def RightClick(self, x: int = None, y: int = None, ratioX: float = <NUM_LIT:0.5>, ratioY: float = <NUM_LIT:0.5>, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:

point = self.MoveCursorToInnerPos(x, y, ratioX, ratioY, simulateMove)<EOL>if point:<EOL><INDENT>RightClick(point[<NUM_LIT:0>], point[<NUM_LIT:1>], waitTime)<EOL><DEDENT>

x: int, if < 0, right click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, right click self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
ratioX: float.
ratioY: float.
simulateMove: bool, if True, first move cursor to control smoothly.
waitTime: float.

RightClick(), RightClick(ratioX=0.5, ratioY=0.5): right click center.
RightClick(10, 10): right click left+10, top+10.
RightClick(-10, -10): right click right-10, bottom-10.


def FromControl(self, control: '<STR_LIT>', x: int = <NUM_LIT:0>, y: int = <NUM_LIT:0>, width: int = <NUM_LIT:0>, height: int = <NUM_LIT:0>) -> bool:

rect = control.BoundingRectangle<EOL>while rect.width() == <NUM_LIT:0> or rect.height() == <NUM_LIT:0>:<EOL><INDENT>control = control.GetParentControl()<EOL>if not control:<EOL><INDENT>return False<EOL><DEDENT>rect = control.BoundingRectangle<EOL><DEDENT>if width <= <NUM_LIT:0>:<EOL><INDENT>width = rect.width() + width<EOL><DEDENT>if height <= <NUM_LIT:0>:<EOL><INDENT>height = rect.height() + height<EOL><DEDENT>handle = control.NativeWindowHandle<EOL>if handle:<EOL><INDENT>left = x<EOL>top = y<EOL>right = left + width<EOL>bottom = top + height<EOL><DEDENT>else:<EOL><INDENT>while True:<EOL><INDENT>control = control.GetParentControl()<EOL>handle = control.NativeWindowHandle<EOL>if handle:<EOL><INDENT>pRect = control.BoundingRectangle<EOL>left = rect.left - pRect.left + x<EOL>top = rect.top - pRect.top + y<EOL>right = left + width<EOL>bottom = top + height<EOL>break<EOL><DEDENT><DEDENT><DEDENT>return self.FromHandle(handle, left, top, right, bottom)<EOL>

Capture a control to Bitmap.
control: `Control` or its subclass.
x: int.
y: int.
width: int.
height: int.
x, y: the point in control's internal position(from 0,0)
width, height: image's width and height from x, y, use 0 for entire area,
If width(or height) < 0, image size will be control's width(or height) - width(or height).
Return bool, True if succeed otherwise False.


self.pattern = pattern<EOL>


def GetGridItemPattern(self) -> GridItemPattern:

return self.GetPattern(PatternId.GridItemPattern)<EOL>

Return `GridItemPattern` if it supports the pattern else None(Conditional support according to MSDN).


def GetPixelColor(x: int, y: int, handle: int = <NUM_LIT:0>) -> int:

hdc = ctypes.windll.user32.GetWindowDC(ctypes.c_void_p(handle))<EOL>bgr = ctypes.windll.gdi32.GetPixel(hdc, x, y)<EOL>ctypes.windll.user32.ReleaseDC(ctypes.c_void_p(handle), hdc)<EOL>return bgr<EOL>

Get pixel color of a native window.
x: int.
y: int.
handle: int, the handle of a native window.
Return int, the bgr value of point (x,y).
r = bgr & 0x0000FF
g = (bgr & 0x00FF00) >> 8
b = (bgr & 0xFF0000) >> 16
If handle is 0, get pixel from Desktop window(root control).
Note:
Not all devices support GetPixel.
An application should call GetDeviceCaps to determine whether a specified device supports this function.
For example, console window doesn't support.


def EnumAndLogControl(control: Control, maxDepth: int = <NUM_LIT>, showAllName: bool = True, startDepth: int = <NUM_LIT:0>) -> None:

for c, d in WalkControl(control, True, maxDepth):<EOL><INDENT>LogControl(c, d + startDepth, showAllName)<EOL><DEDENT>

Print and log control and its descendants' propertyies.
control: `Control` or its subclass.
maxDepth: int, enum depth.
showAllName: bool, if False, print the first 30 characters of control.Name.
startDepth: int, control's current depth.


def GetExpandCollapsePattern(self) -> ExpandCollapsePattern:

return self.GetPattern(PatternId.ExpandCollapsePattern)<EOL>

Return `ExpandCollapsePattern` if it supports the pattern else None(Must support according to MSDN).


def SetTopmost(self, isTopmost: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> bool:

if self.IsTopLevel():<EOL><INDENT>ret = SetWindowTopmost(self.NativeWindowHandle, isTopmost)<EOL>time.sleep(waitTime)<EOL>return ret<EOL><DEDENT>return False<EOL>

Set top level window topmost.
isTopmost: bool.
waitTime: float.


def Toggle(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:

ret = self.pattern.Toggle() == S_OK<EOL>time.sleep(waitTime)<EOL>return ret<EOL>

Call IUIAutomationTogglePattern::Toggle.
Cycle through the toggle states of the control.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtogglepattern-toggle


@property<EOL><INDENT>def Role(self) -> int:<DEDENT>

return self.pattern.CurrentRole<EOL>

Property Role.
Call IUIAutomationLegacyIAccessiblePattern::get_CurrentRole.
Return int, a value in calss `AccessibleRole`, the Microsoft Active Accessibility role identifier.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-get_currentrole


def GetParentControl(self) -> '<STR_LIT>':

ele = _AutomationClient.instance().ViewWalker.GetParentElement(self.Element)<EOL>return Control.CreateControlFromElement(ele)<EOL>


def Navigate(self, direction: int) -> '<STR_LIT>':

ele = self.pattern.Navigate(direction)<EOL>return Control.CreateControlFromElement(ele)<EOL>

Call IUIAutomationCustomNavigationPattern::Navigate.
Get the next control in the specified direction within the logical UI tree.
direction: int, a value in class `NavigateDirection`.
Return `Control` subclass or None.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationcustomnavigationpattern-navigate


def RemoveFromSelection(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:

ret = self.textRange.RemoveFromSelection() == S_OK<EOL>time.sleep(waitTime)<EOL>return ret<EOL>

Call IUIAutomationTextRange::RemoveFromSelection.
Remove the text range from an existing collection of selected text in a text container that supports multiple, disjoint selections.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-removefromselection


@property<EOL><INDENT>def Help(self) -> str:<DEDENT>

return self.pattern.CurrentHelp<EOL>

Property Help.
Call IUIAutomationLegacyIAccessiblePattern::get_CurrentHelp.
Return str, the Microsoft Active Accessibility help string for the element.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-get_currenthelp


def GetSelectionPattern(self) -> SelectionPattern:

return self.GetPattern(PatternId.SelectionPattern)<EOL>

Return `SelectionPattern` if it supports the pattern else None(Conditional support according to MSDN).


@property<EOL><INDENT>def IsReadOnly(self) -> bool:<DEDENT>

return self.pattern.CurrentIsReadOnly<EOL>

Property IsReadOnly.
Call IUIAutomationRangeValuePattern::get_CurrentIsReadOnly.
Return bool, indicates whether the value of the element can be changed.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationrangevaluepattern-get_currentisreadonly


@property<EOL><INDENT>def ZoomMinimum(self) -> float:<DEDENT>

return self.pattern.CurrentZoomMinimum<EOL>

Property ZoomMinimum.
Call IUIAutomationTransformPattern2::get_CurrentZoomMinimum.
Return float, the minimum zoom level of the control's viewport.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtransformpattern2-get_currentzoomminimum


def GetTablePattern(self) -> TablePattern:

return self.GetPattern(PatternId.TablePattern)<EOL>

Return `TablePattern` if it supports the pattern else None(Conditional support according to MSDN).


def FromFile(self, filePath: str) -> bool:

self.Release()<EOL>self._bitmap = _DllClient.instance().dll.BitmapFromFile(ctypes.c_wchar_p(filePath))<EOL>self._getsize()<EOL>return self._bitmap > <NUM_LIT:0><EOL>

Load image from a file.
filePath: str.
Return bool, True if succeed otherwise False.


def ToFile(self, savePath: str) -> bool:

name, ext = os.path.splitext(savePath)<EOL>extMap = {'<STR_LIT>': '<STR_LIT>'<EOL>, '<STR_LIT>': '<STR_LIT>'<EOL>, '<STR_LIT>': '<STR_LIT>'<EOL>, '<STR_LIT>': '<STR_LIT>'<EOL>, '<STR_LIT>': '<STR_LIT>'<EOL>, '<STR_LIT>': '<STR_LIT>'<EOL>, '<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>gdiplusImageFormat = extMap.get(ext.lower(), '<STR_LIT>')<EOL>return bool(_DllClient.instance().dll.BitmapToFile(self._bitmap, ctypes.c_wchar_p(savePath), ctypes.c_wchar_p(gdiplusImageFormat)))<EOL>

Save to a file.
savePath: str, should end with .bmp, .jpg, .jpeg, .png, .gif, .tif, .tiff.
Return bool, True if succeed otherwise False.


def GetSubBitmap(self, x: int, y: int, width: int, height: int) -> '<STR_LIT>':

colors = self.GetPixelColorsOfRect(x, y, width, height)<EOL>bitmap = Bitmap(width, height)<EOL>bitmap.SetPixelColorsOfRect(<NUM_LIT:0>, <NUM_LIT:0>, width, height, colors)<EOL>return bitmap<EOL>

x: int.
y: int.
width: int.
height: int.
Return `Bitmap`, a sub bitmap of the input rect.


return self.Element.SetFocus() == S_OK<EOL>


@property<EOL><INDENT>def WindowInteractionState(self) -> int:<DEDENT>

return self.pattern.CurrentWindowInteractionState<EOL>

Property WindowInteractionState.
Call IUIAutomationWindowPattern::get_CurrentWindowInteractionState.
Return int, a value in class `WindowInteractionState`,
            the current state of the window for the purposes of user interaction.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationwindowpattern-get_currentwindowinteractionstate


def GetInvokePattern(self) -> InvokePattern:

return self.GetPattern(PatternId.InvokePattern)<EOL>

Return `InvokePattern` if it supports the pattern else None(Must support according to MSDN).


def SetGlobalSearchTimeout(seconds: float) -> None:

global TIME_OUT_SECOND<EOL>TIME_OUT_SECOND = seconds<EOL>

seconds: float.
To make this available, you need explicitly import uiautomation:
    from uiautomation import uiautomation as auto
    auto.SetGlobalSearchTimeout(10)


@property<EOL><INDENT>def ChildId(self) -> int:<DEDENT>

return self.pattern.CurrentChildId<EOL>

Property ChildId.
Call IUIAutomationLegacyIAccessiblePattern::get_CurrentChildId.
Return int, the Microsoft Active Accessibility child identifier for the element.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-get_currentchildid


def SetWindowVisualState(self, state: int, waitTime: float = OPERATION_WAIT_TIME) -> bool:

ret = self.pattern.SetWindowVisualState(state) == S_OK<EOL>time.sleep(waitTime)<EOL>return ret<EOL>

Call IUIAutomationWindowPattern::SetWindowVisualState.
Minimize, maximize, or restore the window.
state: int, a value in class `WindowVisualState`.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationwindowpattern-setwindowvisualstate


def SetValue(self, value: str, waitTime: float = OPERATION_WAIT_TIME) -> bool:

ret = self.pattern.SetValue(value) == S_OK<EOL>time.sleep(waitTime)<EOL>return ret<EOL>

Call IUIAutomationLegacyIAccessiblePattern::SetValue.
Set the Microsoft Active Accessibility value property for the element.
value: str.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-setvalue


Return `InvokePattern` if it supports the pattern else None(Conditional support according to MSDN).


@property<EOL><INDENT>def ExtendedProperties(self) -> str:<DEDENT>

return self.pattern.CurrentExtendedProperties<EOL>

Property ExtendedProperties.
Call IUIAutomationStylesPattern::get_CurrentExtendedProperties.
Return str, a localized string that contains the list of extended properties for an element in a document.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationstylespattern-get_currentextendedproperties


@property<EOL><INDENT>def DocumentRange(self) -> TextRange:<DEDENT>

return TextRange(self.pattern.DocumentRange)<EOL>

Property DocumentRange.
Call IUIAutomationTextPattern::get_DocumentRange.
Return `TextRange`, a text range that encloses the main text of a document.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextpattern-get_documentrange


def WalkControl(control: Control, includeTop: bool = False, maxDepth: int = <NUM_LIT>):

if includeTop:<EOL><INDENT>yield control, <NUM_LIT:0><EOL><DEDENT>if maxDepth <= <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>depth = <NUM_LIT:0><EOL>child = control.GetFirstChildControl()<EOL>controlList = [child]<EOL>while depth >= <NUM_LIT:0>:<EOL><INDENT>lastControl = controlList[-<NUM_LIT:1>]<EOL>if lastControl:<EOL><INDENT>yield lastControl, depth + <NUM_LIT:1><EOL>child = lastControl.GetNextSiblingControl()<EOL>controlList[depth] = child<EOL>if depth + <NUM_LIT:1> < maxDepth:<EOL><INDENT>child = lastControl.GetFirstChildControl()<EOL>if child:<EOL><INDENT>depth += <NUM_LIT:1><EOL>controlList.append(child)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>del controlList[depth]<EOL>depth -= <NUM_LIT:1><EOL><DEDENT><DEDENT>

control: `Control` or its subclass.
includeTop: bool, if True, yield (control, 0) first.
maxDepth: int, enum depth.
Yield 2 items tuple(control: Control, depth: int).


def GetPixelColorsOfRects(self, rects: list) -> list:

rects2 = [(x, y, x + width, y + height) for x, y, width, height in rects]<EOL>left, top, right, bottom = zip(*rects2)<EOL>left, top, right, bottom = min(left), min(top), max(right), max(bottom)<EOL>width, height = right - left, bottom - top<EOL>allColors = self.GetPixelColorsOfRect(left, top, width, height)<EOL>colorsOfRects = []<EOL>for x, y, w, h in rects:<EOL><INDENT>x -= left<EOL>y -= top<EOL>colors = []<EOL>for row in range(h):<EOL><INDENT>colors.extend(allColors[(y + row) * width + x:(y + row) * width + x + w])<EOL><DEDENT>colorsOfRects.append(colors)<EOL><DEDENT>return colorsOfRects<EOL>

rects: a list of rects, such as [(0,0,10,10), (10,10,20,20),(x,y,width,height)].
Return list, a list whose elements are ctypes.Array which is an iterable array of int values in argb.


def GetScrollItemPattern(self) -> ScrollItemPattern:

return self.GetPattern(PatternId.ScrollItemPattern)<EOL>

Return `ScrollItemPattern` if it supports the pattern else None(Conditional support according to MSDN).


@property<EOL><INDENT>def AutomationId(self) -> str:<DEDENT>

return self.Element.CurrentAutomationId<EOL>


def GetTogglePattern(self) -> TogglePattern:

return self.GetPattern(PatternId.TogglePattern)<EOL>

Return `TogglePattern` if it supports the pattern else None(Conditional support according to MSDN).


def GetGridPattern(self) -> GridPattern:

return self.GetPattern(PatternId.GridPattern)<EOL>

Return `GridPattern` if it supports the pattern else None(Conditional support according to MSDN).


def GetPixelColorsHorizontally(self, x: int, y: int, count: int) -> ctypes.Array:

arrayType = ctypes.c_uint32 * count<EOL>values = arrayType()<EOL>_DllClient.instance().dll.BitmapGetPixelsHorizontally(ctypes.c_size_t(self._bitmap), x, y, values, count)<EOL>return values<EOL>

x: int.
y: int.
count: int.
Return `ctypes.Array`, an iterable array of int values in argb form point x,y horizontally.


def GetSelectionItemPattern(self) -> SelectionItemPattern:

return self.GetPattern(PatternId.SelectionItemPattern)<EOL>

Return `SelectionItemPattern` if it supports the pattern else None(Must support according to MSDN).


@property<EOL><INDENT>def SupportedTextSelection(self) -> bool:<DEDENT>

return bool(self.pattern.SupportedTextSelection)<EOL>

Property SupportedTextSelection.
Call IUIAutomationTextPattern::get_SupportedTextSelection.
Return bool, specifies the type of text selection that is supported by the control.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextpattern-get_supportedtextselection


def Hide(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:

return self.ShowWindow(SW.Hide, waitTime)<EOL>

Call native `ShowWindow(SW.Hide)`.
waitTime: float
Return bool, True if succeed otherwise False.


def GetDockPattern(self) -> DockPattern:

return self.GetPattern(PatternId.DockPattern)<EOL>

Return `DockPattern` if it supports the pattern else None(Conditional support according to MSDN).


def GetExpandCollapsePattern(self) -> ExpandCollapsePattern:

return self.GetPattern(PatternId.ExpandCollapsePattern)<EOL>

Return `ExpandCollapsePattern` if it supports the pattern else None(Conditional support according to MSDN).


self.textRange = textRange<EOL>


self.pattern = pattern<EOL>


def FindText(self, text: str, backward: bool, ignoreCase: bool) -> '<STR_LIT>':

textRange = self.textRange.FindText(text, int(backward), int(ignoreCase))<EOL>if textRange:<EOL><INDENT>return TextRange(textRange=textRange)<EOL><DEDENT>

Call IUIAutomationTextRange::FindText.
text: str,
backward: bool, True if the last occurring text range should be returned instead of the first; otherwise False.
ignoreCase: bool, True if case should be ignored; otherwise False.
return `TextRange` or None, a text range subset that contains the specified text.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-findtext


def GetWindowPattern(self) -> WindowPattern:

return self.GetPattern(PatternId.WindowPattern)<EOL>

Return `WindowPattern` if it supports the pattern else None(Conditional support according to MSDN).


def ToBitmap(self, x: int = <NUM_LIT:0>, y: int = <NUM_LIT:0>, width: int = <NUM_LIT:0>, height: int = <NUM_LIT:0>) -> Bitmap:

bitmap = Bitmap()<EOL>bitmap.FromControl(self, x, y, width, height)<EOL>return bitmap<EOL>

Capture control to a Bitmap object.
x, y: int, the point in control's internal position(from 0,0).
width, height: int, image's width and height from x, y, use 0 for entire area.
               If width(or height) < 0, image size will be control's width(or height) - width(or height).


def __init__(self, width: int = <NUM_LIT:0>, height: int = <NUM_LIT:0>):

self._width = width<EOL>self._height = height<EOL>self._bitmap = <NUM_LIT:0><EOL>if width > <NUM_LIT:0> and height > <NUM_LIT:0>:<EOL><INDENT>self._bitmap = _DllClient.instance().dll.BitmapCreate(width, height)<EOL><DEDENT>

Create a black bimap of size(width, height).


def keybd_event(bVk: int, bScan: int, dwFlags: int, dwExtraInfo: int) -> None:

ctypes.windll.user32.keybd_event(bVk, bScan, dwFlags, dwExtraInfo)<EOL>


def Select(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:

ret = self.pattern.Select() == S_OK<EOL>time.sleep(waitTime)<EOL>return ret<EOL>

Call IUIAutomationSelectionItemPattern::Select.
Clear any selected items and then select the current element.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationselectionitempattern-select


def GetFirstChildControl(self) -> '<STR_LIT>':

ele = _AutomationClient.instance().ViewWalker.GetFirstChildElement(self.Element)<EOL>return Control.CreateControlFromElement(ele)<EOL>


def Click(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None:

SetCursorPos(x, y)<EOL>screenWidth, screenHeight = GetScreenSize()<EOL>mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.Absolute, x * <NUM_LIT> // screenWidth, y * <NUM_LIT> // screenHeight, <NUM_LIT:0>, <NUM_LIT:0>)<EOL>time.sleep(<NUM_LIT>)<EOL>mouse_event(MouseEventFlag.LeftUp | MouseEventFlag.Absolute, x * <NUM_LIT> // screenWidth, y * <NUM_LIT> // screenHeight, <NUM_LIT:0>, <NUM_LIT:0>)<EOL>time.sleep(waitTime)<EOL>

Simulate mouse click at point x, y.
x: int.
y: int.
waitTime: float.


def FindAttribute(self, textAttributeId: int, val, backward: bool) -> '<STR_LIT>':

textRange = self.textRange.FindAttribute(textAttributeId, val, int(backward))<EOL>if textRange:<EOL><INDENT>return TextRange(textRange=textRange)<EOL><DEDENT>

Call IUIAutomationTextRange::FindAttribute.
textAttributeID: int, a value in class `TextAttributeId`.
val: COM VARIANT according to textAttributeId? todo.
backward: bool, True if the last occurring text range should be returned instead of the first; otherwise False.
return `TextRange` or None, a text range subset that has the specified text attribute value.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-findattribute


if self.IsTopLevel():<EOL><INDENT>rect = self.BoundingRectangle<EOL>screenWidth, screenHeight = GetScreenSize()<EOL>x, y = (screenWidth - rect.width()) // <NUM_LIT:2>, (screenHeight - rect.height()) // <NUM_LIT:2><EOL>if x < <NUM_LIT:0>: x = <NUM_LIT:0><EOL>if y < <NUM_LIT:0>: y = <NUM_LIT:0><EOL>return SetWindowPos(self.NativeWindowHandle, SWP.HWND_Top, x, y, <NUM_LIT:0>, <NUM_LIT:0>, SWP.SWP_NoSize)<EOL><DEDENT>return False<EOL>


def Disappears(self, maxSearchSeconds: float = <NUM_LIT:5>, searchIntervalSeconds: float = SEARCH_INTERVAL, printIfNotDisappear: bool = False) -> bool:

global DEBUG_EXIST_DISAPPEAR<EOL>start = ProcessTime()<EOL>while True:<EOL><INDENT>temp = DEBUG_EXIST_DISAPPEAR<EOL>DEBUG_EXIST_DISAPPEAR = False  <EOL>if not self.Exists(<NUM_LIT:0>, <NUM_LIT:0>, False):<EOL><INDENT>DEBUG_EXIST_DISAPPEAR = temp<EOL>return True<EOL><DEDENT>DEBUG_EXIST_DISAPPEAR = temp<EOL>remain = start + maxSearchSeconds - ProcessTime()<EOL>if remain > <NUM_LIT:0>:<EOL><INDENT>time.sleep(min(remain, searchIntervalSeconds))<EOL><DEDENT>else:<EOL><INDENT>if printIfNotDisappear or DEBUG_EXIST_DISAPPEAR:<EOL><INDENT>Logger.ColorfullyWriteLine(self.GetColorfulSearchPropertiesStr() + '<STR_LIT>')<EOL><DEDENT>return False<EOL><DEDENT><DEDENT>

maxSearchSeconds: float
searchIntervalSeconds: float
Check if control disappears every searchIntervalSeconds seconds in maxSearchSeconds seconds.
Return bool, True if control disappears.


def WaitForInputIdle(self, milliseconds: int) -> bool:

return self.pattern.WaitForInputIdle(milliseconds) == S_OK<EOL>

Call IUIAutomationWindowPattern::WaitForInputIdle.
Cause the calling code to block for the specified time or
    until the associated process enters an idle state, whichever completes first.
milliseconds: int.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationwindowpattern-waitforinputidle


@property<EOL><INDENT>def Author(self) -> str:<DEDENT>

return self.pattern.CurrentAuthor<EOL>


@property<EOL><INDENT>def LocalizedControlType(self) -> str:<DEDENT>

return self.Element.CurrentLocalizedControlType<EOL>


return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.GetRootElement())<EOL>

Get root control, the Desktop window.
Return `PaneControl`.


def WindowFromPoint(x: int, y: int) -> int:

return ctypes.windll.user32.WindowFromPoint(ctypes.wintypes.POINT(x, y))<EOL>

WindowFromPoint from Win32.
Return int, a native window handle.


@property<EOL><INDENT>def HelpText(self) -> str:<DEDENT>

return self.Element.CurrentHelpText<EOL>


@property<EOL><INDENT>def ProcessId(self) -> int:<DEDENT>

return self.Element.CurrentProcessId<EOL>


def GetConsoleWindow() -> WindowControl:

return ControlFromHandle(ctypes.windll.kernel32.GetConsoleWindow())<EOL>

Return `WindowControl`, a console window that runs python.


@staticmethod<EOL><INDENT>def ColorfullyWrite(log: str, consoleColor: int = -<NUM_LIT:1>, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None:<DEDENT>

text = []<EOL>start = <NUM_LIT:0><EOL>while True:<EOL><INDENT>index1 = log.find('<STR_LIT>', start)<EOL>if index1 >= <NUM_LIT:0>:<EOL><INDENT>if index1 > start:<EOL><INDENT>text.append((log[start:index1], consoleColor))<EOL><DEDENT>index2 = log.find('<STR_LIT:>>', index1)<EOL>colorName = log[index1+<NUM_LIT:7>:index2]<EOL>index3 = log.find('<STR_LIT>', index2 + <NUM_LIT:1>)<EOL>text.append((log[index2 + <NUM_LIT:1>:index3], Logger.ColorNames[colorName]))<EOL>start = index3 + <NUM_LIT:8><EOL><DEDENT>else:<EOL><INDENT>if start < len(log):<EOL><INDENT>text.append((log[start:], consoleColor))<EOL><DEDENT>break<EOL><DEDENT><DEDENT>for t, c in text:<EOL><INDENT>Logger.Write(t, c, writeToFile, printToStdout, logFile)<EOL><DEDENT>

log: str.
consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`.
writeToFile: bool.
printToStdout: bool.
logFile: str, log file path.
ColorfullyWrite('Hello <Color=Green>Green</Color> !!!'), color name must be in Logger.ColorNames.


eleArray = self.pattern.GetCurrentAnnotationObjects()<EOL>if eleArray:<EOL><INDENT>controls = []<EOL>for i in range(eleArray.Length):<EOL><INDENT>ele = eleArray.GetElement(i)<EOL>con = Control.CreateControlFromElement(element=ele)<EOL>if con:<EOL><INDENT>controls.append(con)<EOL><DEDENT><DEDENT>return controls<EOL><DEDENT>return []<EOL>

Call IUIAutomationSelectionPattern::GetCurrentAnnotationObjects.
Return list, a list of `Control` subclasses representing the annotations associated with this spreadsheet cell.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationspreadsheetitempattern-getcurrentannotationobjects


def GetActiveComposition(self) -> TextRange:

textRange = self.pattern.GetActiveComposition()<EOL>if textRange:<EOL><INDENT>return TextRange(textRange=textRange)<EOL><DEDENT>

Call IUIAutomationTextEditPattern::GetActiveComposition.
Return `TextRange` or None, the active composition.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtexteditpattern-getactivecomposition


def GetTableItemPattern(self) -> TableItemPattern:

return self.GetPattern(PatternId.TableItemPattern)<EOL>

Return `TableItemPattern` if it supports the pattern else None(Conditional support according to MSDN).


def ControlFromPoint(x: int, y: int) -> Control:

element = _AutomationClient.instance().IUIAutomation.ElementFromPoint(ctypes.wintypes.POINT(x, y))<EOL>return Control.CreateControlFromElement(element)<EOL>

Call IUIAutomation ElementFromPoint x,y. May return None if mouse is over cmd's title bar icon.
Return `Control` subclass or None.


def SetWindowLong(handle: int, index: int, value: int) -> int:

return ctypes.windll.user32.SetWindowLongW(ctypes.c_void_p(handle), index, value)<EOL>

SetWindowLong from Win32.
handle: int, the handle of a native window.
index: int.
value: int.
Return int, the previous value before set.


def ShowDesktop(waitTime: float = <NUM_LIT:1>) -> None:

SendKeys('<STR_LIT>')<EOL>time.sleep(waitTime)<EOL>


def Move(self, unit: int, count: int, waitTime: float = OPERATION_WAIT_TIME) -> int:

ret = self.textRange.Move(unit, count)<EOL>time.sleep(waitTime)<EOL>return ret<EOL>

Call IUIAutomationTextRange::Move.
Move the text range forward or backward by the specified number of text units.
unit: int, a value in class `TextUnit`.
count: int, the number of text units to move.
       A positive value moves the text range forward.
       A negative value moves the text range backward. Zero has no effect.
waitTime: float.
Return: int, the number of text units actually moved.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-move


def Move(self, x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> bool:

ret = self.pattern.Move(x, y) == S_OK<EOL>time.sleep(waitTime)<EOL>return ret<EOL>

Call IUIAutomationTransformPattern::Move.
Move the UI Automation element.
x: int.
y: int.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtransformpattern-move


eleArray = self.pattern.GetCurrentGrabbedItems()<EOL>if eleArray:<EOL><INDENT>controls = []<EOL>for i in range(eleArray.Length):<EOL><INDENT>ele = eleArray.GetElement(i)<EOL>con = Control.CreateControlFromElement(element=ele)<EOL>if con:<EOL><INDENT>controls.append(con)<EOL><DEDENT><DEDENT>return controls<EOL><DEDENT>return []<EOL>

Call IUIAutomationDragPattern::GetCurrentGrabbedItems.
Return list, a list of `Control` subclasses that represent the full set of items
             that the user is dragging as part of a drag operation.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationdragpattern-getcurrentgrabbeditems


self.pattern = pattern<EOL>


@property<EOL><INDENT>def CanMaximize(self) -> bool:<DEDENT>

return bool(self.pattern.CurrentCanMaximize)<EOL>

Property CanMaximize.
Call IUIAutomationWindowPattern::get_CurrentCanMaximize.
Return bool, indicates whether the window can be maximized.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationwindowpattern-get_currentcanmaximize


def WalkTree(top, getChildren: Callable = None, getFirstChild: Callable = None, getNextSibling: Callable = None, yieldCondition: Callable = None, includeTop: bool = False, maxDepth: int = <NUM_LIT>):

if maxDepth <= <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>depth = <NUM_LIT:0><EOL>if getChildren:<EOL><INDENT>if includeTop:<EOL><INDENT>if not yieldCondition or yieldCondition(top, <NUM_LIT:0>):<EOL><INDENT>yield top, <NUM_LIT:0>, <NUM_LIT:0><EOL><DEDENT><DEDENT>children = getChildren(top)<EOL>childList = [children]<EOL>while depth >= <NUM_LIT:0>:   <EOL><INDENT>lastItems = childList[-<NUM_LIT:1>]<EOL>if lastItems:<EOL><INDENT>if not yieldCondition or yieldCondition(lastItems[<NUM_LIT:0>], depth + <NUM_LIT:1>):<EOL><INDENT>yield lastItems[<NUM_LIT:0>], depth + <NUM_LIT:1>, len(lastItems) - <NUM_LIT:1><EOL><DEDENT>if depth + <NUM_LIT:1> < maxDepth:<EOL><INDENT>children = getChildren(lastItems[<NUM_LIT:0>])<EOL>if children:<EOL><INDENT>depth += <NUM_LIT:1><EOL>childList.append(children)<EOL><DEDENT><DEDENT>del lastItems[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>del childList[depth]<EOL>depth -= <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>elif getFirstChild and getNextSibling:<EOL><INDENT>if includeTop:<EOL><INDENT>if not yieldCondition or yieldCondition(top, <NUM_LIT:0>):<EOL><INDENT>yield top, <NUM_LIT:0><EOL><DEDENT><DEDENT>child = getFirstChild(top)<EOL>childList = [child]<EOL>while depth >= <NUM_LIT:0>:  <EOL><INDENT>lastItem = childList[-<NUM_LIT:1>]<EOL>if lastItem:<EOL><INDENT>if not yieldCondition or yieldCondition(lastItem, depth + <NUM_LIT:1>):<EOL><INDENT>yield lastItem, depth + <NUM_LIT:1><EOL><DEDENT>child = getNextSibling(lastItem)<EOL>childList[depth] = child<EOL>if depth + <NUM_LIT:1> < maxDepth:<EOL><INDENT>child = getFirstChild(lastItem)<EOL>if child:<EOL><INDENT>depth += <NUM_LIT:1><EOL>childList.append(child)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>del childList[depth]<EOL>depth -= <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>

Walk a tree not using recursive algorithm.
top: a tree node.
getChildren: function(treeNode) -> list.
getNextSibling: function(treeNode) -> treeNode.
getNextSibling: function(treeNode) -> treeNode.
yieldCondition: function(treeNode, depth) -> bool.
includeTop: bool, if True yield top first.
maxDepth: int, enum depth.

If getChildren is valid, ignore getFirstChild and getNextSibling,
    yield 3 items tuple: (treeNode, depth, remain children count in current depth).
If getChildren is not valid, using getFirstChild and getNextSibling,
    yield 2 items tuple: (treeNode, depth).
If yieldCondition is not None, only yield tree nodes that yieldCondition(treeNode, depth)->bool returns True.

For example:
def GetDirChildren(dir_):
    if os.path.isdir(dir_):
        return [os.path.join(dir_, it) for it in os.listdir(dir_)]
for it, depth, leftCount in WalkTree('D:\\', getChildren= GetDirChildren):
    print(it, depth, leftCount)


@property<EOL><INDENT>def ExpandCollapseState(self) -> int:<DEDENT>

return self.pattern.CurrentExpandCollapseState<EOL>

Property ExpandCollapseState.
Call IUIAutomationExpandCollapsePattern::get_CurrentExpandCollapseState.
Return int, a value in class ExpandCollapseState.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationexpandcollapsepattern-get_currentexpandcollapsestate


def GetValuePattern(self) -> ValuePattern:

return self.GetPattern(PatternId.ValuePattern)<EOL>

Return `ValuePattern` if it supports the pattern else None(Conditional support according to MSDN).


def GetLastChildControl(self) -> '<STR_LIT>':

ele = _AutomationClient.instance().ViewWalker.GetLastChildElement(self.Element)<EOL>return Control.CreateControlFromElement(ele)<EOL>


return self.pattern.GetCurrentSupportedViews()<EOL>

Call IUIAutomationMultipleViewPattern::GetCurrentSupportedViews, todo.
Return list, a list of int, control-specific view identifiers.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationmultipleviewpattern-getcurrentsupportedviews


@property<EOL><INDENT>def ContainingGrid(self) -> '<STR_LIT>':<DEDENT>

return Control.CreateControlFromElement(self.pattern.CurrentContainingGrid)<EOL>

Property ContainingGrid.
Call IUIAutomationGridItemPattern::get_CurrentContainingGrid.
Return `Control` subclass, the element that contains the grid item.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationgriditempattern-get_currentcontaininggrid


def RangeFromChild(self, child) -> TextRange:

textRange = self.pattern.RangeFromChild(Control.Element)<EOL>if textRange:<EOL><INDENT>return TextRange(textRange=textRange)<EOL><DEDENT>

Call IUIAutomationTextPattern::RangeFromChild.
child: `Control` or its subclass.
Return `TextRange` or None, a text range enclosing a child element such as an image,
    hyperlink, Microsoft Excel spreadsheet, or other embedded object.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextpattern-rangefromchild


@property<EOL><INDENT>def Minimum(self) -> float:<DEDENT>

return self.pattern.CurrentMinimum<EOL>

Property Minimum.
Call IUIAutomationRangeValuePattern::get_CurrentMinimum.
Return float, the minimum value of the control.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationrangevaluepattern-get_currentminimum


def GetSelectionPattern(self) -> SelectionPattern:

return self.GetPattern(PatternId.SelectionPattern)<EOL>

Return `SelectionPattern` if it supports the pattern else None(Conditional support according to MSDN).


@property<EOL><INDENT>def AriaProperties(self) -> str:<DEDENT>

return self.Element.CurrentAriaProperties<EOL>


def Resize(self, width: int, height: int, waitTime: float = OPERATION_WAIT_TIME) -> bool:

ret = self.pattern.Resize(width, height) == S_OK<EOL>time.sleep(waitTime)<EOL>return ret<EOL>

Call IUIAutomationTransformPattern::Resize.
Resize the UI Automation element.
width: int.
height: int.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtransformpattern-resize


@staticmethod<EOL><INDENT>def Write(log: Any, consoleColor: int = ConsoleColor.Default, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None, printTruncateLen: int = <NUM_LIT:0>) -> None:<DEDENT>

if not isinstance(log, str):<EOL><INDENT>log = str(log)<EOL><DEDENT>if printToStdout and sys.stdout:<EOL><INDENT>isValidColor = (consoleColor >= ConsoleColor.Black and consoleColor <= ConsoleColor.White)<EOL>if isValidColor:<EOL><INDENT>SetConsoleColor(consoleColor)<EOL><DEDENT>try:<EOL><INDENT>if printTruncateLen > <NUM_LIT:0> and len(log) > printTruncateLen:<EOL><INDENT>sys.stdout.write(log[:printTruncateLen] + '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>sys.stdout.write(log)<EOL><DEDENT><DEDENT>except Exception as ex:<EOL><INDENT>SetConsoleColor(ConsoleColor.Red)<EOL>isValidColor = True<EOL>sys.stdout.write(ex.__class__.__name__ + '<STR_LIT>')<EOL>if log.endswith('<STR_LIT:\n>'):<EOL><INDENT>sys.stdout.write('<STR_LIT:\n>')<EOL><DEDENT><DEDENT>if isValidColor:<EOL><INDENT>ResetConsoleColor()<EOL><DEDENT>sys.stdout.flush()<EOL><DEDENT>if not writeToFile:<EOL><INDENT>return<EOL><DEDENT>fileName = logFile if logFile else Logger.FileName<EOL>try:<EOL><INDENT>fout = open(fileName, '<STR_LIT>', encoding='<STR_LIT:utf-8>')<EOL>fout.write(log)<EOL><DEDENT>except Exception as ex:<EOL><INDENT>if sys.stdout:<EOL><INDENT>sys.stdout.write(ex.__class__.__name__ + '<STR_LIT>')<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>if fout:<EOL><INDENT>fout.close()<EOL><DEDENT><DEDENT>

log: any type.
consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`.
writeToFile: bool.
printToStdout: bool.
logFile: str, log file path.
printTruncateLen: int, if <= 0, log is not truncated when print.


def GetRangeValuePattern(self) -> RangeValuePattern:

return self.GetPattern(PatternId.RangeValuePattern)<EOL>

Return `RangeValuePattern` if it supports the pattern else None(Conditional support according to MSDN).


def Select(self, flagsSelect: int, waitTime: float = OPERATION_WAIT_TIME) -> bool:

ret = self.pattern.Select(flagsSelect) == S_OK<EOL>time.sleep(waitTime)<EOL>return ret<EOL>

Call IUIAutomationLegacyIAccessiblePattern::Select.
Perform a Microsoft Active Accessibility selection.
flagsSelect: int, a value in `AccessibleSelection`.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-select


def GetTransformPattern(self) -> TransformPattern:

return self.GetPattern(PatternId.TransformPattern)<EOL>

Return `TransformPattern` if it supports the pattern else None(Conditional support according to MSDN).


def MetroClose(self, waitTime: float = OPERATION_WAIT_TIME) -> None:

if self.ClassName == METRO_WINDOW_CLASS_NAME:<EOL><INDENT>screenWidth, screenHeight = GetScreenSize()<EOL>MoveTo(screenWidth // <NUM_LIT:2>, <NUM_LIT:0>, waitTime=<NUM_LIT:0>)<EOL>DragDrop(screenWidth // <NUM_LIT:2>, <NUM_LIT:0>, screenWidth // <NUM_LIT:2>, screenHeight, waitTime=waitTime)<EOL><DEDENT>else:<EOL><INDENT>Logger.WriteLine('<STR_LIT>', ConsoleColor.Yellow)<EOL><DEDENT>

Only work on Windows 8/8.1, if current window is Metro UI.
waitTime: float.


def GetGridItemPattern(self) -> GridItemPattern:

return self.GetPattern(PatternId.GridItemPattern)<EOL>

Return `GridItemPattern` if it supports the pattern else None(Conditional support according to MSDN).


def ControlsAreSame(control1: Control, control2: Control) -> bool:

return bool(_AutomationClient.instance().IUIAutomation.CompareElements(control1.Element, control2.Element))<EOL>

control1: `Control` or its subclass.
control2: `Control` or its subclass.
Return bool, True if control1 and control2 represent the same control otherwise False.


@property<EOL><INDENT>def Value(self) -> float:<DEDENT>

return self.pattern.CurrentValue<EOL>

Property Value.
Call IUIAutomationRangeValuePattern::get_CurrentValue.
Return float, the value of the control.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationrangevaluepattern-get_currentvalue


@property<EOL><INDENT>def IsGrabbed(self) -> bool:<DEDENT>

return bool(self.pattern.CurrentIsGrabbed)<EOL>

Property IsGrabbed.
Call IUIAutomationDragPattern::get_CurrentIsGrabbed.
Return bool, indicates whether the user has grabbed this element as part of a drag-and-drop operation.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationdragpattern-get_currentisgrabbed


@property<EOL><INDENT>def HorizontalScrollPercent(self) -> float:<DEDENT>

return self.pattern.CurrentHorizontalScrollPercent<EOL>

Property HorizontalScrollPercent.
Call IUIAutomationScrollPattern::get_CurrentHorizontalScrollPercent.
Return float, the horizontal scroll position.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationscrollpattern-get_currenthorizontalscrollpercent


@classmethod<EOL><INDENT>def instance(cls) -> '<STR_LIT>':<DEDENT>

if cls._instance is None:<EOL><INDENT>cls._instance = cls()<EOL><DEDENT>return cls._instance<EOL>

Singleton instance (this prevents com creation on import).


def Maximize(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:

if self.IsTopLevel():<EOL><INDENT>return self.ShowWindow(SW.ShowMaximized, waitTime)<EOL><DEDENT>return False<EOL>


@property<EOL><INDENT>def DefaultAction(self) -> str:<DEDENT>

return self.pattern.CurrentDefaultAction<EOL>

Property DefaultAction.
Call IUIAutomationLegacyIAccessiblePattern::get_CurrentDefaultAction.
Return str, the Microsoft Active Accessibility current default action for the element.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-get_currentdefaultaction


self.pattern = pattern<EOL>


def ExpandToEnclosingUnit(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:

ret = self.textRange.ExpandToEnclosingUnit() == S_OK<EOL>time.sleep(waitTime)<EOL>return ret<EOL>

Call IUIAutomationTextRange::ExpandToEnclosingUnit.
Normalize the text range by the specified text unit.
    The range is expanded if it is smaller than the specified unit,
    or shortened if it is longer than the specified unit.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-expandtoenclosingunit


@property<EOL><INDENT>def Description(self) -> str:<DEDENT>

return self.pattern.CurrentDescription<EOL>

Property Description.
Call IUIAutomationLegacyIAccessiblePattern::get_CurrentDescription.
Return str, the Microsoft Active Accessibility description of the element.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-get_currentdescription


@property<EOL><INDENT>def HorizontalViewSize(self) -> float:<DEDENT>

return self.pattern.CurrentHorizontalViewSize<EOL>

Property HorizontalViewSize.
Call IUIAutomationScrollPattern::get_CurrentHorizontalViewSize.
Return float, the horizontal size of the viewable region of a scrollable element.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationscrollpattern-get_currenthorizontalviewsize


def GetExpandCollapsePattern(self) -> ExpandCollapsePattern:

return self.GetPattern(PatternId.ExpandCollapsePattern)<EOL>

Return `ExpandCollapsePattern` if it supports the pattern else None(Conditional support according to MSDN).


Return `TransformPattern` if it supports the pattern else None(Must support according to MSDN).


@property<EOL><INDENT>def IsPassword(self) -> bool:<DEDENT>

return self.Element.CurrentIsPassword<EOL>


if IsNT6orHigher:<EOL><INDENT>arrayType = ctypes.c_wchar * MAX_PATH<EOL>values = arrayType()<EOL>ctypes.windll.kernel32.GetConsoleOriginalTitleW(values, MAX_PATH)<EOL>return values.value<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>

GetConsoleOriginalTitle from Win32.
Return str.
Only available on Windows Vista or higher.


@property<EOL><INDENT>def ClassName(self) -> str:<DEDENT>

return self.Element.CurrentClassName<EOL>


nInputs = len(inputs)<EOL>LPINPUT = INPUT * nInputs<EOL>pInputs = LPINPUT(*inputs)<EOL>cbSize = ctypes.c_int(ctypes.sizeof(INPUT))<EOL>return ctypes.windll.user32.SendInput(nInputs, pInputs, cbSize)<EOL>

SendInput from Win32.
input: `INPUT`.
Return int, the number of events that it successfully inserted into the keyboard or mouse input stream.
            If the function returns zero, the input was already blocked by another thread.


def GetItemByName(self, name: str) -> '<STR_LIT>':

ele = self.pattern.GetItemByName(name)<EOL>return Control.CreateControlFromElement(element=ele)<EOL>

Call IUIAutomationSpreadsheetPattern::GetItemByName.
name: str.
Return `Control` subclass or None, represents the spreadsheet cell that has the specified name..
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationspreadsheetpattern-getitembyname


def PressMouse(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None:

SetCursorPos(x, y)<EOL>screenWidth, screenHeight = GetScreenSize()<EOL>mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.Absolute, x * <NUM_LIT> // screenWidth, y * <NUM_LIT> // screenHeight, <NUM_LIT:0>, <NUM_LIT:0>)<EOL>time.sleep(waitTime)<EOL>

Press left mouse.
x: int.
y: int.
waitTime: float.


@property<EOL><INDENT>def DropEffects(self) -> list:<DEDENT>

return self.pattern.CurrentDropEffects<EOL>

Property DropEffects.
Call IUIAutomationDragPattern::get_CurrentDropEffects, todo SAFEARRAY.
Return list, a list of localized strings that enumerate the full set of effects
             that can happen when this element as part of a drag-and-drop operation.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationdragpattern-get_currentdropeffects


def GetTablePattern(self) -> TablePattern:

return self.GetPattern(PatternId.TablePattern)<EOL>

Return `TablePattern` if it supports the pattern else None(Must support according to MSDN).


@property<EOL><INDENT>def AccessKey(self) -> str:<DEDENT>

return self.Element.CurrentAccessKey<EOL>


def GetTransformPattern(self) -> TransformPattern:

return self.GetPattern(PatternId.TransformPattern)<EOL>


return bool(ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(text)))<EOL>

SetConsoleTitle from Win32.
text: str.
Return bool, True if succeed otherwise False.


@property<EOL><INDENT>def Row(self) -> int:<DEDENT>

return self.pattern.CurrentRow<EOL>

Property Row.
Call IUIAutomationGridItemPattern::get_CurrentRow.
Return int, the zero-based index of the row that contains the grid item.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationgriditempattern-get_currentrow


return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.GetFocusedElement())<EOL>


def ControlFromHandle(handle: int) -> Control:

return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(handle))<EOL>

Call IUIAutomation.ElementFromHandle with a native handle.
handle: int, a native window handle.
Return `Control` subclass.


def Restore(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:

if self.IsTopLevel():<EOL><INDENT>return self.ShowWindow(SW.Restore, waitTime)<EOL><DEDENT>return False<EOL>

Restore window to normal state.
Similar to SwitchToThisWindow.


def GetSelectionPattern(self) -> SelectionPattern:

return self.GetPattern(PatternId.SelectionPattern)<EOL>

Return `SelectionPattern` if it supports the pattern else None(Must support according to MSDN).


@property<EOL><INDENT>def VerticallyScrollable(self) -> bool:<DEDENT>

return bool(self.pattern.CurrentVerticallyScrollable)<EOL>

Property VerticallyScrollable.
Call IUIAutomationScrollPattern::get_CurrentVerticallyScrollable.
Return bool, indicates whether the element can scroll vertically.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationscrollpattern-get_currentverticallyscrollable


def SetPixelColorsVertically(self, x: int, y: int, colors: Iterable) -> bool:

count = len(colors)<EOL>arrayType = ctypes.c_uint32 * count<EOL>values = arrayType(*colors)<EOL>return _DllClient.instance().dll.BitmapSetPixelsVertically(ctypes.c_size_t(self._bitmap), x, y, values, count)<EOL>

Set pixel colors form x,y vertically.
x: int.
y: int.
colors: Iterable, an iterable list of int color values in argb.
Return bool, True if succeed otherwise False.


self.pattern = pattern<EOL>


def WheelUp(self, wheelTimes: int = <NUM_LIT:1>, interval: float = <NUM_LIT>, waitTime: float = OPERATION_WAIT_TIME) -> None:

x, y = GetCursorPos()<EOL>self.SetFocus()<EOL>self.MoveCursorToMyCenter(False)<EOL>WheelUp(wheelTimes, interval, waitTime)<EOL>SetCursorPos(x, y)<EOL>

Make control have focus first, move cursor to center and mouse wheel up.
wheelTimes: int.
interval: float.
waitTime: float.


def WaitHotKeyReleased(hotkey: tuple) -> None:

mod = {ModifierKey.Alt: Keys.VK_MENU,<EOL>ModifierKey.Control: Keys.VK_CONTROL,<EOL>ModifierKey.Shift: Keys.VK_SHIFT,<EOL>ModifierKey.Win: Keys.VK_LWIN<EOL>}<EOL>while True:<EOL><INDENT>time.sleep(<NUM_LIT>)<EOL>if IsKeyPressed(hotkey[<NUM_LIT:1>]):<EOL><INDENT>continue<EOL><DEDENT>for k, v in mod.items():<EOL><INDENT>if k & hotkey[<NUM_LIT:0>]:<EOL><INDENT>if IsKeyPressed(v):<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>

hotkey: tuple, two ints tuple(modifierKey, key)


def AddToSelection(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:

ret = self.textRange.AddToSelection() == S_OK<EOL>time.sleep(waitTime)<EOL>return ret<EOL>

Call IUIAutomationTextRange::AddToSelection.
Add the text range to the collection of selected text ranges in a control that supports multiple, disjoint spans of selected text.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-addtoselection


def MiddleClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None:

SetCursorPos(x, y)<EOL>screenWidth, screenHeight = GetScreenSize()<EOL>mouse_event(MouseEventFlag.MiddleDown | MouseEventFlag.Absolute, x * <NUM_LIT> // screenWidth, y * <NUM_LIT> // screenHeight, <NUM_LIT:0>, <NUM_LIT:0>)<EOL>time.sleep(<NUM_LIT>)<EOL>mouse_event(MouseEventFlag.MiddleUp | MouseEventFlag.Absolute, x * <NUM_LIT> // screenWidth, y * <NUM_LIT> // screenHeight, <NUM_LIT:0>, <NUM_LIT:0>)<EOL>time.sleep(waitTime)<EOL>

Simulate mouse middle click at point x, y.
x: int.
y: int.
waitTime: float.


@property<EOL><INDENT>def DockPosition(self) -> int:<DEDENT>

return self.pattern.CurrentDockPosition<EOL>

Property DockPosition.
Call IUIAutomationDockPattern::get_CurrentDockPosition.
Return int, a value in class `DockPosition`.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationdockpattern-get_currentdockposition


@property<EOL><INDENT>def IsTopmost(self) -> bool:<DEDENT>

return bool(self.pattern.CurrentIsTopmost)<EOL>

Property IsTopmost.
Call IUIAutomationWindowPattern::get_CurrentIsTopmost.
Return bool, indicates whether the window is the topmost element in the z-order.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationwindowpattern-get_currentistopmost


@property<EOL><INDENT>def Shape(self) -> str:<DEDENT>

return self.pattern.CurrentShape<EOL>

Property Shape.
Call IUIAutomationStylesPattern::get_CurrentShape.
Return str, the shape of an element in a document.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationstylespattern-get_currentshape


def GetPixelColor(self, x: int, y: int) -> int:

handle = self.NativeWindowHandle<EOL>if handle:<EOL><INDENT>return GetPixelColor(x, y, handle)<EOL><DEDENT>

Call native `GetPixelColor` if control has a valid native handle.
Use `self.ToBitmap` if control doesn't have a valid native handle or you get many pixels.
x: int, internal x position.
y: int, internal y position.
Return int, a color value in bgr.
r = bgr & 0x0000FF
g = (bgr & 0x00FF00) >> 8
b = (bgr & 0xFF0000) >> 16


def ReleaseMouse(waitTime: float = OPERATION_WAIT_TIME) -> None:

x, y = GetCursorPos()<EOL>screenWidth, screenHeight = GetScreenSize()<EOL>mouse_event(MouseEventFlag.LeftUp | MouseEventFlag.Absolute, x * <NUM_LIT> // screenWidth, y * <NUM_LIT> // screenHeight, <NUM_LIT:0>, <NUM_LIT:0>)<EOL>time.sleep(waitTime)<EOL>


@staticmethod<EOL><INDENT>def CreateControlFromControl(control: '<STR_LIT>') -> '<STR_LIT>':<DEDENT>

newControl = Control.CreateControlFromElement(control.Element)<EOL>return newControl<EOL>

Create a concreate `Control` from a control instance, copy it.
control: `Control` or its subclass.
Return a subclass of `Control`, an instance of the control's real type.
For example: if control's ControlType is EditControl, return an EditControl.


@property<EOL><INDENT>def ControlTypeName(self) -> str:<DEDENT>

return ControlTypeNames[self.ControlType]<EOL>


def GetTransformPattern(self) -> TransformPattern:

return self.GetPattern(PatternId.TransformPattern)<EOL>

Return `TransformPattern` if it supports the pattern else None(Conditional support according to MSDN).


def GetTogglePattern(self) -> TogglePattern:

return self.GetPattern(PatternId.TogglePattern)<EOL>

Return `TogglePattern` if it supports the pattern else None(Conditional support according to MSDN).


eleArray = self.pattern.GetCurrentRowHeaderItems()<EOL>if eleArray:<EOL><INDENT>controls = []<EOL>for i in range(eleArray.Length):<EOL><INDENT>ele = eleArray.GetElement(i)<EOL>con = Control.CreateControlFromElement(element=ele)<EOL>if con:<EOL><INDENT>controls.append(con)<EOL><DEDENT><DEDENT>return controls<EOL><DEDENT>return []<EOL>

Call IUIAutomationTableItemPattern::GetCurrentRowHeaderItems.
Return list, a list of `Control` subclasses, the row headers associated with a table item or cell.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtableitempattern-getcurrentrowheaderitems


def MoveWindow(self, x: int, y: int, width: int, height: int, repaint: bool = True) -> bool:

handle = self.NativeWindowHandle<EOL>if handle:<EOL><INDENT>return MoveWindow(handle, x, y, width, height, int(repaint))<EOL><DEDENT>return False<EOL>

Call native MoveWindow if control has a valid native handle.
x: int.
y: int.
width: int.
height: int.
repaint: bool.
Return bool, True if succeed otherwise False.


def GetPropertyValue(self, propertyId: int) -> Any:

return self.Element.GetCurrentPropertyValue(propertyId)<EOL>

Call IUIAutomationElement::GetCurrentPropertyValue.
propertyId: int, a value in class `PropertyId`.
Return Any, corresponding type according to propertyId.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-getcurrentpropertyvalue


def GetExpandCollapsePattern(self) -> ExpandCollapsePattern:

return self.GetPattern(PatternId.ExpandCollapsePattern)<EOL>

Return `ExpandCollapsePattern` if it supports the pattern else None(Must support according to MSDN).


@classmethod<EOL><INDENT>def instance(cls) -> '<STR_LIT>':<DEDENT>

if cls._instance is None:<EOL><INDENT>cls._instance = cls()<EOL><DEDENT>return cls._instance<EOL>

Singleton instance (this prevents com creation on import).


return self.pattern.Cancel() == S_OK<EOL>

Call IUIAutomationSynchronizedInputPattern::Cancel.
Cause the Microsoft UI Automation provider to stop listening for mouse or keyboard input.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationsynchronizedinputpattern-cancel


def GetSelectionItemPattern(self) -> SelectionItemPattern:

return self.GetPattern(PatternId.SelectionItemPattern)<EOL>

Return `SelectionItemPattern` if it supports the pattern else None(Must support according to MSDN).


state = ctypes.windll.user32.GetAsyncKeyState(key)<EOL>return bool(state & <NUM_LIT>)<EOL>

key: int, a value in class `Keys`.
Return bool.


def ShowWindow(self, cmdShow: int, waitTime: float = OPERATION_WAIT_TIME) -> bool:

handle = self.NativeWindowHandle<EOL>if not handle:<EOL><INDENT>control = self<EOL>while not handle:<EOL><INDENT>control = control.GetParentControl()<EOL>handle = control.NativeWindowHandle<EOL><DEDENT><DEDENT>if handle:<EOL><INDENT>ret = ShowWindow(handle, cmdShow)<EOL>time.sleep(waitTime)<EOL>return ret<EOL><DEDENT>

Get a native handle from self or ancestors until valid and call native `ShowWindow` with cmdShow.
cmdShow: int, a value in in class `SW`.
waitTime: float.
Return bool, True if succeed otherwise False.


@property<EOL><INDENT>def CanZoom(self) -> bool:<DEDENT>

return bool(self.pattern.CurrentCanZoom)<EOL>

Property CanZoom.
Call IUIAutomationTransformPattern2::get_CurrentCanZoom.
Return bool, indicates whether the control supports zooming of its viewport.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtransformpattern2-get_CurrentCanZoom


@property<EOL><INDENT>def BoundingRectangle(self) -> Rect:<DEDENT>

rect = self.Element.CurrentBoundingRectangle<EOL>return Rect(rect.left, rect.top, rect.right, rect.bottom)<EOL>

Property BoundingRectangle.
Call IUIAutomationElement::get_CurrentBoundingRectangle.
Return `Rect`.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-get_currentboundingrectangle

rect = control.BoundingRectangle
print(rect.left, rect.top, rect.right, rect.bottom, rect.width(), rect.height(), rect.xcenter(), rect.ycenter())


def MiddleClick(self, x: int = None, y: int = None, ratioX: float = <NUM_LIT:0.5>, ratioY: float = <NUM_LIT:0.5>, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:

point = self.MoveCursorToInnerPos(x, y, ratioX, ratioY, simulateMove)<EOL>if point:<EOL><INDENT>MiddleClick(point[<NUM_LIT:0>], point[<NUM_LIT:1>], waitTime)<EOL><DEDENT>

x: int, if < 0, middle click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, middle click self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
ratioX: float.
ratioY: float.
simulateMove: bool, if True, first move cursor to control smoothly.
waitTime: float.

MiddleClick(), MiddleClick(ratioX=0.5, ratioY=0.5): middle click center.
MiddleClick(10, 10): middle click left+10, top+10.
MiddleClick(-10, -10): middle click right-10, bottom-10.


return self.pattern.GetIAccessible()<EOL>

Call IUIAutomationLegacyIAccessiblePattern::GetIAccessible, todo.
Return an IAccessible object that corresponds to the Microsoft UI Automation element.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-getiaccessible
Refer https://docs.microsoft.com/en-us/windows/desktop/api/oleacc/nn-oleacc-iaccessible


self.pattern = pattern<EOL>


def GetTableItemPattern(self) -> TableItemPattern:

return self.GetPattern(PatternId.TableItemPattern)<EOL>

Return `TableItemPattern` if it supports the pattern else None(Conditional support according to MSDN).


@property<EOL><INDENT>def Maximum(self) -> float:<DEDENT>

return self.pattern.CurrentMaximum<EOL>

Property Maximum.
Call IUIAutomationRangeValuePattern::get_CurrentMaximum.
Return float, the maximum value of the control.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationrangevaluepattern-get_currentmaximum


def ShowWindow(handle: int, cmdShow: int) -> bool:

return ctypes.windll.user32.ShowWindow(ctypes.c_void_p(handle), cmdShow)<EOL>

ShowWindow from Win32.
handle: int, the handle of a native window.
cmdShow: int, a value in clas `SW`.
Return bool, True if succeed otherwise False.


def GetTopLevelControl(self) -> '<STR_LIT>':

handle = self.NativeWindowHandle<EOL>if handle:<EOL><INDENT>topHandle = GetAncestor(handle, GAFlag.Root)<EOL>if topHandle:<EOL><INDENT>if topHandle == handle:<EOL><INDENT>return self<EOL><DEDENT>else:<EOL><INDENT>return ControlFromHandle(topHandle)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>control = self<EOL>while True:<EOL><INDENT>control = control.GetParentControl()<EOL>handle = control.NativeWindowHandle<EOL>if handle:<EOL><INDENT>topHandle = GetAncestor(handle, GAFlag.Root)<EOL>return ControlFromHandle(topHandle)<EOL><DEDENT><DEDENT><DEDENT>

Get the top level control which current control lays.
If current control is top level, return self.
If current control is root control, return None.
Return `PaneControl` or `WindowControl` or None.


@staticmethod<EOL><INDENT>def WriteLine(log: Any, consoleColor: int = -<NUM_LIT:1>, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None:<DEDENT>

Logger.Write('<STR_LIT>'.format(log), consoleColor, writeToFile, printToStdout, logFile)<EOL>

log: any type.
consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`.
writeToFile: bool.
printToStdout: bool.
logFile: str, log file path.


def SetConsoleColor(color: int) -> bool:

global _ConsoleOutputHandle<EOL>global _DefaultConsoleColor<EOL>if not _DefaultConsoleColor:<EOL><INDENT>if not _ConsoleOutputHandle:<EOL><INDENT>_ConsoleOutputHandle = ctypes.windll.kernel32.GetStdHandle(_StdOutputHandle)<EOL><DEDENT>bufferInfo = ConsoleScreenBufferInfo()<EOL>ctypes.windll.kernel32.GetConsoleScreenBufferInfo(_ConsoleOutputHandle, ctypes.byref(bufferInfo))<EOL>_DefaultConsoleColor = int(bufferInfo.wAttributes & <NUM_LIT>)<EOL><DEDENT>if sys.stdout:<EOL><INDENT>sys.stdout.flush()<EOL><DEDENT>bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, color))<EOL>

Change the text color on console window.
color: int, a value in class `ConsoleColor`.
Return bool, True if succeed otherwise False.


def PlayWaveFile(filePath: str = r'<STR_LIT>', isAsync: bool = False, isLoop: bool = False) -> bool:

if filePath:<EOL><INDENT>SND_ASYNC = <NUM_LIT><EOL>SND_NODEFAULT = <NUM_LIT><EOL>SND_LOOP = <NUM_LIT><EOL>SND_FILENAME = <NUM_LIT><EOL>flags = SND_NODEFAULT | SND_FILENAME<EOL>if isAsync:<EOL><INDENT>flags |= SND_ASYNC<EOL><DEDENT>if isLoop:<EOL><INDENT>flags |= SND_LOOP<EOL>flags |= SND_ASYNC<EOL><DEDENT>return bool(ctypes.windll.winmm.PlaySoundW(ctypes.c_wchar_p(filePath), ctypes.c_void_p(<NUM_LIT:0>), flags))<EOL><DEDENT>else:<EOL><INDENT>return bool(ctypes.windll.winmm.PlaySoundW(ctypes.c_wchar_p(<NUM_LIT:0>), ctypes.c_void_p(<NUM_LIT:0>), <NUM_LIT:0>))<EOL><DEDENT>

Call PlaySound from Win32.
filePath: str, if emtpy, stop playing the current sound.
isAsync: bool, if True, the sound is played asynchronously and returns immediately.
isLoop: bool, if True, the sound plays repeatedly until PlayWaveFile(None) is called again, must also set isAsync to True.
Return bool, True if succeed otherwise False.


return self.pattern.GetCurrentAnnotationTypes()<EOL>

Call IUIAutomationSelectionPattern::GetCurrentAnnotationTypes.
Return list, a list of int values in class `AnnotationType`,
             indicating the types of annotations that are associated with this spreadsheet cell.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationselectionpattern-getcurrentannotationtypes


@property<EOL><INDENT>def Column(self) -> int:<DEDENT>

return self.pattern.CurrentColumn<EOL>

Property Column.
Call IUIAutomationGridItemPattern::get_CurrentColumn.
Return int, the zero-based index of the column that contains the item.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationgriditempattern-get_currentcolumn


try:<EOL><INDENT>pattern = self.Element.GetCurrentPattern(patternId)<EOL>if pattern:<EOL><INDENT>subPattern = CreatePattern(patternId, pattern)<EOL>self._supportedPatterns[patternId] = subPattern<EOL>return subPattern<EOL><DEDENT><DEDENT>except comtypes.COMError as ex:<EOL><INDENT>pass<EOL><DEDENT>

Call IUIAutomationElement::GetCurrentPattern.
Get a new pattern by pattern id if it supports the pattern.
patternId: int, a value in class `PatternId`.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-getcurrentpattern


def SetWindowPos(handle: int, hWndInsertAfter: int, x: int, y: int, width: int, height: int, flags: int) -> bool:

return ctypes.windll.user32.SetWindowPos(ctypes.c_void_p(handle), ctypes.c_void_p(hWndInsertAfter), x, y, width, height, flags)<EOL>

SetWindowPos from Win32.
handle: int, the handle of a native window.
hWndInsertAfter: int, a value whose name starts with 'HWND' in class SWP.
x: int.
y: int.
width: int.
height: int.
flags: int, values whose name starts with 'SWP' in class `SWP`.
Return bool, True if succeed otherwise False.


def GetTransformPattern(self) -> TransformPattern:

return self.GetPattern(PatternId.TransformPattern)<EOL>

Return `TransformPattern` if it supports the pattern else None(Conditional support according to MSDN).


eleArray = self.pattern.GetCurrentColumnHeaderItems()<EOL>if eleArray:<EOL><INDENT>controls = []<EOL>for i in range(eleArray.Length):<EOL><INDENT>ele = eleArray.GetElement(i)<EOL>con = Control.CreateControlFromElement(element=ele)<EOL>if con:<EOL><INDENT>controls.append(con)<EOL><DEDENT><DEDENT>return controls<EOL><DEDENT>return []<EOL>

Call IUIAutomationTableItemPattern::GetCurrentColumnHeaderItems.
Return list, a list of `Control` subclasses, the column headers associated with a table item or cell.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtableitempattern-getcurrentcolumnheaderitems


@property<EOL><INDENT>def RowCount(self) -> int:<DEDENT>

return self.pattern.CurrentRowCount<EOL>

Property RowCount.
Call IUIAutomationGridPattern::get_CurrentRowCount.
Return int, the number of rows in the grid.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationgridpattern-get_currentrowcount


@property<EOL><INDENT>def CanMinimize(self) -> bool:<DEDENT>

return bool(self.pattern.CurrentCanMinimize)<EOL>

Property CanMinimize.
Call IUIAutomationWindowPattern::get_CurrentCanMinimize.
Return bool, indicates whether the window can be minimized.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationwindowpattern-get_currentismodal


def RightDragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = <NUM_LIT:1>, waitTime: float = OPERATION_WAIT_TIME) -> None:

RightPressMouse(x1, y1, <NUM_LIT>)<EOL>MoveTo(x2, y2, moveSpeed, <NUM_LIT>)<EOL>RightReleaseMouse(waitTime)<EOL>

Simulate mouse right button drag from point x1, y1 drop to point x2, y2.
x1: int.
y1: int.
x2: int.
y2: int.
moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster.
waitTime: float.


def EnumAndLogControlAncestors(control: Control, showAllName: bool = True) -> None:

lists = []<EOL>while control:<EOL><INDENT>lists.insert(<NUM_LIT:0>, control)<EOL>control = control.GetParentControl()<EOL><DEDENT>for i, control in enumerate(lists):<EOL><INDENT>LogControl(control, i, showAllName)<EOL><DEDENT>

Print and log control and its ancestors' propertyies.
control: `Control` or its subclass.
showAllName: bool, if False, print the first 30 characters of control.Name.


def FindItemByProperty(control: '<STR_LIT>', propertyId: int, propertyValue) -> '<STR_LIT>':

ele = self.pattern.FindItemByProperty(control.Element, propertyId, propertyValue)<EOL>return Control.CreateControlFromElement(ele)<EOL>

Call IUIAutomationItemContainerPattern::FindItemByProperty.
control: `Control` or its subclass.
propertyValue: COM VARIANT according to propertyId? todo.
propertyId: int, a value in class `PropertyId`.
Return `Control` subclass, a control within a containing element, based on a specified property value.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationitemcontainerpattern-finditembyproperty


def GetTogglePattern(self) -> TogglePattern:

return self.GetPattern(PatternId.TogglePattern)<EOL>

Return `TogglePattern` if it supports the pattern else None(Conditional support according to MSDN).


self.pattern = pattern<EOL>


def RangeFromPoint(self, x: int, y: int) -> TextRange:

textRange = self.pattern.RangeFromPoint(ctypes.wintypes.POINT(x, y))<EOL>if textRange:<EOL><INDENT>return TextRange(textRange=textRange)<EOL><DEDENT>

Call IUIAutomationTextPattern::RangeFromPoint.
child: `Control` or its subclass.
Return `TextRange` or None, the degenerate (empty) text range nearest to the specified screen coordinates.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextpattern-rangefrompoint


def SetClipboardText(text: str) -> bool:

if ctypes.windll.user32.OpenClipboard(<NUM_LIT:0>):<EOL><INDENT>ctypes.windll.user32.EmptyClipboard()<EOL>textByteLen = (len(text) + <NUM_LIT:1>) * <NUM_LIT:2><EOL>hClipboardData = ctypes.windll.kernel32.GlobalAlloc(<NUM_LIT:0>, textByteLen)  <EOL>hDestText = ctypes.windll.kernel32.GlobalLock(hClipboardData)<EOL>ctypes.cdll.msvcrt.wcsncpy(ctypes.c_wchar_p(hDestText), ctypes.c_wchar_p(text), textByteLen // <NUM_LIT:2>)<EOL>ctypes.windll.kernel32.GlobalUnlock(hClipboardData)<EOL>ctypes.windll.user32.SetClipboardData(<NUM_LIT>, hClipboardData)  <EOL>ctypes.windll.user32.CloseClipboard()<EOL>return True<EOL><DEDENT>return False<EOL>

Return bool, True if succeed otherwise False.


def GetAncestorControl(self, condition: Callable) -> '<STR_LIT>':

ancestor = self<EOL>depth = <NUM_LIT:0><EOL>while True:<EOL><INDENT>ancestor = ancestor.GetParentControl()<EOL>depth -= <NUM_LIT:1><EOL>if ancestor:<EOL><INDENT>if condition(ancestor, depth):<EOL><INDENT>return ancestor<EOL><DEDENT><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>

Get a ancestor control that matches the condition.
condition: Callable, function (control: Control, depth: int)->bool,
           depth starts with -1 and decreses when search goes up.
Return `Control` subclass or None.


def RightReleaseMouse(waitTime: float = OPERATION_WAIT_TIME) -> None:

x, y = GetCursorPos()<EOL>screenWidth, screenHeight = GetScreenSize()<EOL>mouse_event(MouseEventFlag.RightUp | MouseEventFlag.Absolute, x * <NUM_LIT> // screenWidth, y * <NUM_LIT> // screenHeight, <NUM_LIT:0>, <NUM_LIT:0>)<EOL>time.sleep(waitTime)<EOL>


@property<EOL><INDENT>def CanMove(self) -> bool:<DEDENT>

return bool(self.pattern.CurrentCanMove)<EOL>

Property CanMove.
Call IUIAutomationTransformPattern::get_CurrentCanMove.
Return bool, indicates whether the element can be moved.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtransformpattern-get_currentcanmove


@property<EOL><INDENT>def IsSelected(self) -> bool:<DEDENT>

return bool(self.pattern.CurrentIsSelected)<EOL>

Property IsSelected.
Call IUIAutomationScrollPattern::get_CurrentIsSelected.
Return bool, indicates whether this item is selected.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationscrollpattern-get_currentisselected


@property<EOL><INDENT>def IsKeyboardFocusable(self) -> bool:<DEDENT>

return self.Element.CurrentIsKeyboardFocusable<EOL>


@property<EOL><INDENT>def IsOffscreen(self) -> bool:<DEDENT>

return self.Element.CurrentIsOffscreen<EOL>


@property<EOL><INDENT>def Target(self) -> '<STR_LIT>':<DEDENT>

ele = self.pattern.CurrentTarget<EOL>return Control.CreateControlFromElement(ele)<EOL>

Property Target.
Call IUIAutomationAnnotationPattern::get_CurrentTarget.
Return `Control` subclass, the element that is being annotated.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationannotationpattern-get_currenttarget


def AddSearchProperties(self, **searchProperties) -> None:

self.searchProperties.update(searchProperties)<EOL>if '<STR_LIT>' in searchProperties:<EOL><INDENT>self.searchDepth = searchProperties['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in searchProperties:<EOL><INDENT>regName = searchProperties['<STR_LIT>']<EOL>self.regexName = re.compile(regName) if regName else None<EOL><DEDENT>

Add search properties using `dict.update`.
searchProperties: dict, same as searchProperties in `Control.__init__`.


def SwitchToThisWindow(handle: int) -> None:

ctypes.windll.user32.SwitchToThisWindow(ctypes.c_void_p(handle), <NUM_LIT:1>)<EOL>

SwitchToThisWindow from Win32.
handle: int, the handle of a native window.


return bool(ctypes.windll.shell32.IsUserAnAdmin())<EOL>

IsUserAnAdmin from Win32.
Return bool.
Minimum supported OS: Windows XP, Windows Server 2003


def Realize(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:

ret = self.pattern.Realize() == S_OK<EOL>time.sleep(waitTime)<EOL>return ret<EOL>

Call IUIAutomationVirtualizedItemPattern::Realize.
Create a full UI Automation element for a virtualized item.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationvirtualizeditempattern-realize


def SendKey(self, key: int, waitTime: float = OPERATION_WAIT_TIME) -> None:

self.SetFocus()<EOL>SendKey(key, waitTime)<EOL>

Make control have focus first and type a key.
`self.SetFocus` may not work for some controls, you may need to click it to make it have focus.
key: int, a key code value in class Keys.
waitTime: float.


def GetInvokePattern(self) -> InvokePattern:

return self.GetPattern(PatternId.InvokePattern)<EOL>

Return `InvokePattern` if it supports the pattern else None(Must support according to MSDN).


def SetActive(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:

if self.IsTopLevel():<EOL><INDENT>handle = self.NativeWindowHandle<EOL>if IsIconic(handle):<EOL><INDENT>ret = ShowWindow(handle, SW.Restore)<EOL><DEDENT>elif not IsWindowVisible(handle):<EOL><INDENT>ret = ShowWindow(handle, SW.Show)<EOL><DEDENT>ret = SetForegroundWindow(handle)  <EOL>time.sleep(waitTime)<EOL>return ret<EOL><DEDENT>return False<EOL>


def SetPixelColor(self, x: int, y: int, argb: int) -> bool:

return _DllClient.instance().dll.BitmapSetPixel(self._bitmap, x, y, argb)<EOL>

Set color value of a pixel.
x: int.
y: int.
argb: int, color value.
Return bool, True if succeed otherwise False.


def GetTableItemPattern(self) -> TableItemPattern:

return self.GetPattern(PatternId.TableItemPattern)<EOL>

Return `TableItemPattern` if it supports the pattern else None(Conditional support according to MSDN).


self.pattern = pattern<EOL>


def Click(self, x: int = None, y: int = None, ratioX: float = <NUM_LIT:0.5>, ratioY: float = <NUM_LIT:0.5>, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:

point = self.MoveCursorToInnerPos(x, y, ratioX, ratioY, simulateMove)<EOL>if point:<EOL><INDENT>Click(point[<NUM_LIT:0>], point[<NUM_LIT:1>], waitTime)<EOL><DEDENT>

x: int, if < 0, click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, click self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
ratioX: float.
ratioY: float.
simulateMove: bool, if True, first move cursor to control smoothly.
waitTime: float.

Click(), Click(ratioX=0.5, ratioY=0.5): click center.
Click(10, 10): click left+10, top+10.
Click(-10, -10): click right-10, bottom-10.


@property<EOL><INDENT>def CanSelectMultiple(self) -> bool:<DEDENT>

return bool(self.pattern.CurrentCanSelectMultiple)<EOL>

Property CanSelectMultiple.
Call IUIAutomationSelectionPattern::get_CurrentCanSelectMultiple.
Return bool, indicates whether more than one item in the container can be selected at one time.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationselectionpattern-get_currentcanselectmultiple


if not self._element:<EOL><INDENT>self.Refind(maxSearchSeconds=TIME_OUT_SECOND, searchIntervalSeconds=self.searchWaitTime)<EOL><DEDENT>return self._element<EOL>

Property Element.
Return `ctypes.POINTER(IUIAutomationElement)`.


@staticmethod<EOL><INDENT>def ColorfullyLog(log: str = '<STR_LIT>', consoleColor: int = -<NUM_LIT:1>, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None:<DEDENT>

t = datetime.datetime.now()<EOL>frame = sys._getframe(<NUM_LIT:1>)<EOL>log = '<STR_LIT>'.format(t.year, t.month, t.day,<EOL>t.hour, t.minute, t.second, t.microsecond // <NUM_LIT:1000>, frame.f_code.co_name, frame.f_lineno, log)<EOL>Logger.ColorfullyWrite(log, consoleColor, writeToFile, printToStdout, logFile)<EOL>

log: any type.
consoleColor: int, a value in class ConsoleColor, such as ConsoleColor.DarkGreen.
writeToFile: bool.
printToStdout: bool.
logFile: str, log file path.

ColorfullyLog('Hello <Color=Green>Green</Color> !!!'), color name must be in Logger.ColorNames


def BringWindowToTop(handle: int) -> bool:

return bool(ctypes.windll.user32.BringWindowToTop(ctypes.c_void_p(handle)))<EOL>

BringWindowToTop from Win32.
handle: int, the handle of a native window.
Return bool, True if succeed otherwise False.


@property<EOL><INDENT>def ControlType(self) -> int:<DEDENT>

return self.Element.CurrentControlType<EOL>

Property ControlType.
Return int, a value in class `ControlType`.
Call IUIAutomationElement::get_CurrentControlType.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-get_currentcontroltype


return TextRange(textRange=self.textRange.Clone())<EOL>

Call IUIAutomationTextRange::Clone.
return `TextRange`, identical to the original and inheriting all properties of the original.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-clone


def GetScrollPattern(self) -> ScrollPattern:

return self.GetPattern(PatternId.ScrollPattern)<EOL>

Return `ScrollPattern` if it supports the pattern else None(Conditional support according to MSDN).


def GetTextPattern(self) -> TextPattern:

return self.GetPattern(PatternId.TextPattern)<EOL>

Return `TextPattern` if it supports the pattern else None(Conditional support according to MSDN).


def GetTogglePattern(self) -> TogglePattern:

return self.GetPattern(PatternId.TogglePattern)<EOL>

Return `TogglePattern` if it supports the pattern else None(Conditional support according to MSDN).


@property<EOL><INDENT>def FrameworkId(self) -> str:<DEDENT>

return self.Element.CurrentFrameworkId<EOL>

Property FrameworkId.
Call IUIAutomationElement::get_CurrentFrameworkId.
Return str, such as Win32, WPF...
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-get_currentframeworkid


@property<EOL><INDENT>def Name(self) -> str:<DEDENT>

return self.Element.CurrentName or '<STR_LIT>'<EOL>

Property Name.
Call IUIAutomationElement::get_CurrentName.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-get_currentname


return ctypes.windll.user32.GetDoubleClickTime()<EOL>

GetDoubleClickTime from Win32.
Return int, in milliseconds.


def SetDockPosition(self, dockPosition: int, waitTime: float = OPERATION_WAIT_TIME) -> int:

ret = self.pattern.SetDockPosition(dockPosition)<EOL>time.sleep(waitTime)<EOL>return ret<EOL>

Call IUIAutomationDockPattern::SetDockPosition.
dockPosition: int, a value in class `DockPosition`.
waitTime: float.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationdockpattern-setdockposition


@property<EOL><INDENT>def Culture(self) -> int:<DEDENT>

return self.Element.CurrentCulture<EOL>


def Collapse(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:

ret = self.pattern.Collapse() == S_OK<EOL>time.sleep(waitTime)<EOL>return ret<EOL>

Call IUIAutomationExpandCollapsePattern::Collapse.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationexpandcollapsepattern-collapse


@property<EOL><INDENT>def TextContainer(self) -> '<STR_LIT>':<DEDENT>

return Control.CreateControlFromElement(self.pattern.TextContainer)<EOL>

Property TextContainer.
Call IUIAutomationSelectionContainer::get_TextContainer.
Return `Control` subclass, the nearest ancestor element that supports the Text control pattern.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextchildpattern-get_textcontainer


data = record._raw.copy()<EOL>data['<STR_LIT:time>'] = data['<STR_LIT:time>'].isoformat()<EOL>if data.get('<STR_LIT>'):<EOL><INDENT>data['<STR_LIT>'] = self.formatException(data['<STR_LIT>'])<EOL><DEDENT>return json.dumps(data)<EOL>

JSON-encode a record for serializing through redis.

Convert date to iso format, and stringify any exceptions.


try:<EOL><INDENT>if self.max_messages:<EOL><INDENT>p = self.redis_client.pipeline()<EOL>p.rpush(self.key, self.format(record))<EOL>p.ltrim(self.key, -self.max_messages, -<NUM_LIT:1>)<EOL>p.execute()<EOL><DEDENT>else:<EOL><INDENT>self.redis_client.rpush(self.key, self.format(record))<EOL><DEDENT><DEDENT>except redis.RedisError:<EOL><INDENT>pass<EOL><DEDENT>


frames = inspect.stack()<EOL>if len(frames) > <NUM_LIT:4>:<EOL><INDENT>context = frames[<NUM_LIT:5>]<EOL><DEDENT>else:<EOL><INDENT>context = frames[<NUM_LIT:0>]<EOL><DEDENT>modname = context[<NUM_LIT:1>]<EOL>lineno = context[<NUM_LIT:2>]<EOL>if context[<NUM_LIT:3>]:<EOL><INDENT>funcname = context[<NUM_LIT:3>]<EOL><DEDENT>else:<EOL><INDENT>funcname = "<STR_LIT>"<EOL><DEDENT>del context<EOL>del frames<EOL>return modname, funcname, lineno<EOL>

Utility function for the RedisLogRecord.

Returns the module, function, and lineno of the function
that called the logger.

We look way up in the stack.  The stack at this point is:
[0] logger.py _getCallingContext (hey, that's me!)
[1] logger.py __init__
[2] logger.py makeRecord
[3] _log
[4] <logging method>
[5] caller of logging method


for encoding in ['<STR_LIT:utf-8>', '<STR_LIT>']:<EOL><INDENT>try:<EOL><INDENT>result = unicode(string, encoding)<EOL>return result<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>result = unicode(string, '<STR_LIT:utf-8>', '<STR_LIT:replace>')<EOL>return result<EOL>

Try to convert a string to unicode using different encodings


def request(key, features, query, timeout=<NUM_LIT:5>):

data = {}<EOL>data['<STR_LIT:key>'] = key<EOL>data['<STR_LIT>'] = '<STR_LIT:/>'.join([f for f in features if f in FEATURES])<EOL>data['<STR_LIT>'] = quote(query)<EOL>data['<STR_LIT>'] = '<STR_LIT>'<EOL>r = requests.get(API_URL.format(**data), timeout=timeout)<EOL>results = json.loads(_unicode(r.content))<EOL>return results<EOL>

Make an API request

    :param string key: API key to use
    :param list features: features to request. It must be a subset of :data:`FEATURES`
    :param string query: query to send
    :param integer timeout: timeout of the request
    :returns: result of the API request
    :rtype: dict


req_man = RequirementsManager([req])<EOL>return any(req_man.check(*checked) for checked in self.checked)<EOL>

Check if requirement is already satisfied by what was previously checked

:param Requirement req: Requirement to check


raise NotImplementedError<EOL>

Update/persist requirements from `self.bumps`


@classmethod<EOL><INDENT>def parse(cls, s, required=False):<DEDENT>

req = pkg_resources.Requirement.parse(s)<EOL>return cls(req, required=required)<EOL>

Parse string to create an instance

:param str s: String with requirement to parse
:param bool required: Is this requirement required to be fulfilled? If not, then it is a filter.


@classmethod<EOL><INDENT>def bump_message(self, bumps, include_changes=False):<DEDENT>

raise NotImplementedError<EOL>

Compose a bump message for the given bumps

:param list bumps: List of :class:`Bump` instances
:param bool include_changes: Indicate if the message should include detailed changes.


if self._original_target_content:<EOL><INDENT>with open(self.target, '<STR_LIT:w>') as fp:<EOL><INDENT>fp.write(self._original_target_content)<EOL><DEDENT><DEDENT>

Restore content in target file to be before any changes


raise NotImplementedError<EOL>

Return a list of existing requirements (as :class:`pkg_resources.Requirement`)


def bump(self, filter_requirements, required=False, show_summary=True, show_detail=False, **kwargs):

found_targets = [target for target in self.targets if os.path.exists(target)]<EOL>if not found_targets:<EOL><INDENT>raise BumpAccident('<STR_LIT>' % '<STR_LIT:U+002CU+0020>'.join(self.targets))<EOL><DEDENT>bump_reqs = RequirementsManager()<EOL>if filter_requirements:<EOL><INDENT>requirements = parse_requirements(filter_requirements)<EOL>bump_reqs.add(requirements, required=required)<EOL><DEDENT>try:<EOL><INDENT>for target in found_targets:<EOL><INDENT>log.debug('<STR_LIT>', target)<EOL>target_bumpers = []<EOL>target_bump_reqs = RequirementsManager(bump_reqs)<EOL>loops = <NUM_LIT:0><EOL>while True:<EOL><INDENT>loops += <NUM_LIT:1><EOL>if loops > <NUM_LIT:5>:<EOL><INDENT>log.debug('<STR_LIT>')<EOL>break<EOL><DEDENT>if not target_bumpers:<EOL><INDENT>target_bumpers = [model(target, detail=self.detail, test_drive=self.test_drive)<EOL>for model in self.bumper_models if model.likes(target)]<EOL>if not target_bumpers:<EOL><INDENT>log.debug('<STR_LIT>', target, self.default_model)<EOL>target_bumpers = [self.default_model(target, detail=self.detail,<EOL>test_drive=self.test_drive)]<EOL><DEDENT>self.bumpers.extend(target_bumpers)<EOL><DEDENT>new_target_bump_reqs = RequirementsManager()<EOL>for bumper in target_bumpers:<EOL><INDENT>target_bumps = bumper.bump(target_bump_reqs)<EOL>self.bumps.update(dict((b.name, b) for b in target_bumps))<EOL>for bump in target_bumps:<EOL><INDENT>for new_req in bump.requirements:<EOL><INDENT>if not (bump_reqs.satisfied_by_checked(new_req) or<EOL>target_bump_reqs.satisfied_by_checked(new_req)):<EOL><INDENT>new_target_bump_reqs.add(new_req)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>bump_reqs.matched_name |= target_bump_reqs.matched_name<EOL>bump_reqs.checked.extend(target_bump_reqs.checked)<EOL>if new_target_bump_reqs:<EOL><INDENT>bump_reqs.add(new_target_bump_reqs)<EOL><DEDENT>target_bump_reqs = RequirementsManager(list(<EOL>r for r in new_target_bump_reqs if r.project_name not in self.bumps))<EOL>if not target_bump_reqs:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>if not self.bumpers:<EOL><INDENT>raise BumpAccident('<STR_LIT>' % '<STR_LIT:U+002CU+0020>'.join(found_targets))<EOL><DEDENT>if bump_reqs and not bump_reqs.matched_name:<EOL><INDENT>raise BumpAccident('<STR_LIT>' % '<STR_LIT:U+002CU+0020>'.join(found_targets))<EOL><DEDENT>if self.bumps:<EOL><INDENT>for bump in self.bumps.values():<EOL><INDENT>bump_reqs.check(bump)<EOL><DEDENT>for reqs in bump_reqs.required_requirements().values():<EOL><INDENT>for req in reqs:<EOL><INDENT>if not self.full_throttle:<EOL><INDENT>use_force = '<STR_LIT>' if req.required_by else '<STR_LIT>'<EOL>raise BumpAccident('<STR_LIT>'<EOL>'<STR_LIT>' % (req, use_force))<EOL><DEDENT><DEDENT><DEDENT>if self.test_drive:<EOL><INDENT>log.info("<STR_LIT>")<EOL><DEDENT>messages = {}<EOL>for bumper in self.bumpers:<EOL><INDENT>if bumper.bumps:<EOL><INDENT>if not self.test_drive:<EOL><INDENT>bumper.update_requirements()<EOL><DEDENT>if self.test_drive or show_summary:<EOL><INDENT>msg = bumper.bump_message(self.test_drive or show_detail)<EOL>if self.test_drive:<EOL><INDENT>print(msg)<EOL><DEDENT>else:<EOL><INDENT>rewords = [('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>')]<EOL>for word, new_word in rewords:<EOL><INDENT>if msg.startswith(word):<EOL><INDENT>msg = msg.replace(word, new_word, <NUM_LIT:1>)<EOL>break<EOL><DEDENT><DEDENT>log.info(msg)<EOL><DEDENT><DEDENT>messages[bumper.target] = bumper.bump_message(True)<EOL><DEDENT><DEDENT>return messages, self.bumps<EOL><DEDENT>else:<EOL><INDENT>log.info('<STR_LIT>')<EOL>return {}, []<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>if not self.test_drive and self.bumps:<EOL><INDENT>map(lambda b: b.reverse(), self.bumpers)<EOL><DEDENT>raise<EOL><DEDENT>

Bump dependency requirements using filter.

:param list filter_requirements: List of dependency filter requirements.
:param bool required: Require the filter_requirements to be met (by adding if possible).
:param bool show_summary: Show summary for each bump made.
:param bool show_detail: Show detail for each bump made if available.
:return: Tuple with two elements: Dict of target file to bump message, List of :class:`Bump`
:raise BumpAccident: for any bump errors


if not self.test_drive and self.bumps:<EOL><INDENT>map(lambda b: b.reverse(), self.bumpers)<EOL><DEDENT>


parser = argparse.ArgumentParser(description=bump.__doc__)<EOL>parser.add_argument('<STR_LIT>', nargs='<STR_LIT:*>', help="""<STR_LIT>""")<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', action='<STR_LIT:store_true>',<EOL>help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', action='<STR_LIT:store_true>',<EOL>help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', action='<STR_LIT:store_true>',<EOL>help='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', action='<STR_LIT:store_true>', help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', action='<STR_LIT:store_true>', help='<STR_LIT>')<EOL>args = parser.parse_args()<EOL>targets = [args.file] if args.file else ['<STR_LIT>', '<STR_LIT>']<EOL>level = logging.DEBUG if args.debug else logging.INFO<EOL>logging.basicConfig(level=level, format='<STR_LIT>')<EOL>try:<EOL><INDENT>bumper = BumperDriver(targets, full_throttle=args.force, detail=args.detail, test_drive=args.dry_run)<EOL>bumper.bump(args.names, required=args.add, show_detail=args.detail)<EOL><DEDENT>except Exception as e:<EOL><INDENT>if args.debug:<EOL><INDENT>raise<EOL><DEDENT>else:<EOL><INDENT>log.error(e)<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>

CLI entry point to bump requirements in requirements.txt or pinned.txt


data = super(IndexBuilder, self).freeze()<EOL>try:<EOL><INDENT>base_file_names = data['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>base_file_names = data['<STR_LIT>']<EOL><DEDENT>store = {}<EOL>c = itertools.count()<EOL>for prefix, items in iteritems(data['<STR_LIT>']):<EOL><INDENT>for name, (index, typeindex, _, shortanchor) in iteritems(items):<EOL><INDENT>objtype = data['<STR_LIT>'][typeindex]<EOL>if objtype.startswith('<STR_LIT>'):<EOL><INDENT>split =  name.rsplit('<STR_LIT>', <NUM_LIT:1>)<EOL>if len(split) != <NUM_LIT:2>:<EOL><INDENT>warnings.warn("<STR_LIT>" % str((prefix, name, objtype)))<EOL>continue<EOL><DEDENT>prefix, name = split<EOL>last_prefix = prefix.split('<STR_LIT>')[-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>last_prefix = prefix.split('<STR_LIT:.>')[-<NUM_LIT:1>]<EOL><DEDENT>store[next(c)] = {<EOL>'<STR_LIT:filename>': base_file_names[index],<EOL>'<STR_LIT>': objtype,<EOL>'<STR_LIT>': prefix,<EOL>'<STR_LIT>': last_prefix,<EOL>'<STR_LIT:name>': name,<EOL>'<STR_LIT>': shortanchor,<EOL>}<EOL><DEDENT><DEDENT>data.update({'<STR_LIT:store>': store})<EOL>return data<EOL>

Create a usable data structure for serializing.


<EOL>if self.stop_words is not None:<EOL><INDENT>tokens = [w for w in tokens if w not in self.stop_words]<EOL><DEDENT>min_n, max_n = self.ngram_range<EOL>if max_n != <NUM_LIT:1>:<EOL><INDENT>original_tokens = tokens<EOL>if min_n == <NUM_LIT:1>:<EOL><INDENT>tokens = list(original_tokens)<EOL>min_n += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>tokens = []<EOL><DEDENT>n_original_tokens = len(original_tokens)<EOL>tokens_append = tokens.append<EOL>space_join = "<STR_LIT:U+0020>".join<EOL>for n in range(min_n,<EOL>min(max_n + <NUM_LIT:1>, n_original_tokens + <NUM_LIT:1>)):<EOL><INDENT>for i in range(n_original_tokens - n + <NUM_LIT:1>):<EOL><INDENT>tokens_append(space_join(original_tokens[i: i + n]))<EOL><DEDENT><DEDENT><DEDENT>return tokens<EOL>

Turn tokens into a tokens of n-grams

ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153


if sp.isspmatrix_csr(X):<EOL><INDENT>return np.bincount(X.indices, minlength=X.shape[<NUM_LIT:1>])<EOL><DEDENT>return np.diff(sp.csc_matrix(X, copy=False).indptr)<EOL>

Count the number of non-zero values for each feature in sparse X.


if stop == "<STR_LIT>":<EOL><INDENT>return THAI_STOP_WORDS<EOL><DEDENT>elif isinstance(stop, six.string_types):<EOL><INDENT>raise ValueError("<STR_LIT>" % stop)<EOL><DEDENT>elif stop is None:<EOL><INDENT>return None<EOL><DEDENT>return frozenset(stop)<EOL>

Check stop words list
ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95


x_test_char, x_test_type, y_test = prepare_feature(best_processed_path, option='<STR_LIT:test>')<EOL>y_predict = model.predict([x_test_char, x_test_type])<EOL>y_predict = (y_predict.ravel() > <NUM_LIT:0.5>).astype(int)<EOL>f1score = f1_score(y_test, y_predict)<EOL>precision = precision_score(y_test, y_predict)<EOL>recall = recall_score(y_test, y_predict)<EOL>return f1score, precision, recall<EOL>

Evaluate model on splitted 10 percent testing set


def generate_best_dataset(best_path, output_path='<STR_LIT>', create_val=False):

if not os.path.isdir(output_path):<EOL><INDENT>os.mkdir(output_path)<EOL><DEDENT>if not os.path.isdir(os.path.join(output_path, '<STR_LIT:train>')):<EOL><INDENT>os.makedirs(os.path.join(output_path, '<STR_LIT:train>'))<EOL><DEDENT>if not os.path.isdir(os.path.join(output_path, '<STR_LIT:test>')):<EOL><INDENT>os.makedirs(os.path.join(output_path, '<STR_LIT:test>'))<EOL><DEDENT>if not os.path.isdir(os.path.join(output_path, '<STR_LIT>')) and create_val:<EOL><INDENT>os.makedirs(os.path.join(output_path, '<STR_LIT>'))<EOL><DEDENT>for article_type in article_types:<EOL><INDENT>files = glob(os.path.join(best_path, article_type, '<STR_LIT>'))<EOL>files_train, files_test = train_test_split(files, random_state=<NUM_LIT:0>, test_size=<NUM_LIT:0.1>)<EOL>if create_val:<EOL><INDENT>files_train, files_val = train_test_split(files_train, random_state=<NUM_LIT:0>, test_size=<NUM_LIT:0.1>)<EOL>val_words = generate_words(files_val)<EOL>val_df = create_char_dataframe(val_words)<EOL>val_df.to_csv(os.path.join(output_path, '<STR_LIT>', '<STR_LIT>'.format(article_type)), index=False)<EOL><DEDENT>train_words = generate_words(files_train)<EOL>test_words = generate_words(files_test)<EOL>train_df = create_char_dataframe(train_words)<EOL>test_df = create_char_dataframe(test_words)<EOL>train_df.to_csv(os.path.join(output_path, '<STR_LIT:train>', '<STR_LIT>'.format(article_type)), index=False)<EOL>test_df.to_csv(os.path.join(output_path, '<STR_LIT:test>', '<STR_LIT>'.format(article_type)), index=False)<EOL>print("<STR_LIT>".format(article_type))<EOL><DEDENT>

Generate CSV file for training and testing data

Input
=====
best_path: str, path to BEST folder which contains unzipped subfolder
    'article', 'encyclopedia', 'news', 'novel'

cleaned_data: str, path to output folder, the cleaned data will be saved
    in the given folder name where training set will be stored in `train` folder
    and testing set will be stored on `test` folder

create_val: boolean, True or False, if True, divide training set into training set and
    validation set in `val` folder


<EOL>n_pad = <NUM_LIT><EOL>n_pad_2 = int((n_pad - <NUM_LIT:1>)/<NUM_LIT:2>)<EOL>pad = [{'<STR_LIT>': '<STR_LIT:U+0020>', '<STR_LIT:type>': '<STR_LIT:p>', '<STR_LIT:target>': True}]<EOL>df_pad = pd.DataFrame(pad * n_pad_2)<EOL>df = []<EOL>for article_type in article_types:<EOL><INDENT>df.append(pd.read_csv(os.path.join(best_processed_path, option, '<STR_LIT>'.format(article_type, option))))<EOL><DEDENT>df = pd.concat(df)<EOL>df = pd.concat((df_pad, df, df_pad)) <EOL>df['<STR_LIT>'] = df['<STR_LIT>'].map(lambda x: CHARS_MAP.get(x, <NUM_LIT>))<EOL>df['<STR_LIT:type>'] = df['<STR_LIT:type>'].map(lambda x: CHAR_TYPES_MAP.get(x, <NUM_LIT:4>))<EOL>df_pad = create_n_gram_df(df, n_pad=n_pad)<EOL>char_row = ['<STR_LIT>' + str(i + <NUM_LIT:1>) for i in range(n_pad_2)] +['<STR_LIT>' + str(i + <NUM_LIT:1>) for i in range(n_pad_2)] + ['<STR_LIT>']<EOL>type_row = ['<STR_LIT:type>' + str(i + <NUM_LIT:1>) for i in range(n_pad_2)] +['<STR_LIT>' + str(i + <NUM_LIT:1>) for i in range(n_pad_2)] + ['<STR_LIT:type>']<EOL>x_char = df_pad[char_row].as_matrix()<EOL>x_type = df_pad[type_row].as_matrix()<EOL>y = df_pad['<STR_LIT:target>'].astype(int).as_matrix()<EOL>return x_char, x_type, y<EOL>

Transform processed path into feature matrix and output array

Input
=====
best_processed_path: str, path to processed BEST dataset

option: str, 'train' or 'test'


n_pad_2 = int((n_pad - <NUM_LIT:1>)/<NUM_LIT:2>)<EOL>for i in range(n_pad_2):<EOL><INDENT>df['<STR_LIT>'.format(i+<NUM_LIT:1>)] = df['<STR_LIT>'].shift(i + <NUM_LIT:1>)<EOL>df['<STR_LIT>'.format(i+<NUM_LIT:1>)] = df['<STR_LIT:type>'].shift(i + <NUM_LIT:1>)<EOL>df['<STR_LIT>'.format(i+<NUM_LIT:1>)] = df['<STR_LIT>'].shift(-i - <NUM_LIT:1>)<EOL>df['<STR_LIT>'.format(i+<NUM_LIT:1>)] = df['<STR_LIT:type>'].shift(-i - <NUM_LIT:1>)<EOL><DEDENT>return df[n_pad_2: -n_pad_2]<EOL>

Given input dataframe, create feature dataframe of shifted characters


run('<STR_LIT>')<EOL>run('<STR_LIT>')<EOL>


Looks for errors in source code of your blog


config = context.obj<EOL>pelican(config, '<STR_LIT>', '<STR_LIT>')<EOL>server_proc = None<EOL>os.chdir(config['<STR_LIT>'])<EOL>try:<EOL><INDENT>try:<EOL><INDENT>command = '<STR_LIT>' + str(PORT)<EOL>server_proc = run(command, bg=True)<EOL>time.sleep(<NUM_LIT:3>)<EOL>click.launch('<STR_LIT>')<EOL>time.sleep(<NUM_LIT:5>)<EOL>pelican(config, '<STR_LIT>')<EOL><DEDENT>except Exception:<EOL><INDENT>if server_proc is not None:<EOL><INDENT>server_proc.kill()<EOL><DEDENT>raise<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>abort(context)<EOL><DEDENT>

Opens local preview of your blog website


<EOL>LEN_TYPE = {<EOL><NUM_LIT:7>: '<STR_LIT>',<EOL><NUM_LIT:4>: '<STR_LIT>',<EOL><NUM_LIT:2>: '<STR_LIT>',<EOL>}<EOL>for ja in orm.JednostkaAdministracyjna.objects.all():<EOL><INDENT>ja.typ = LEN_TYPE[len(ja.id)]<EOL>ja.save()<EOL><DEDENT>


def do_filter(qs, keywords, exclude=False):

and_q = Q()<EOL>for keyword, value in iteritems(keywords):<EOL><INDENT>try:<EOL><INDENT>values = value.split("<STR_LIT:U+002C>")<EOL>if len(values) > <NUM_LIT:0>:<EOL><INDENT>or_q = Q()<EOL>for value in values:<EOL><INDENT>or_q |= Q(**{keyword: value})<EOL><DEDENT>and_q &= or_q<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>and_q &= Q(**{keyword: value})<EOL><DEDENT><DEDENT>if exclude:<EOL><INDENT>qs = qs.exclude(and_q)<EOL><DEDENT>else:<EOL><INDENT>qs = qs.filter(and_q)<EOL><DEDENT>return qs<EOL>

Filter queryset based on keywords.
Support for multiple-selected parent values.