INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Creates the TensorFlow operations for performing an optimization step.
def tf_step( self, time, variables, arguments, fn_loss, **kwargs ): """ Creates the TensorFlow operations for performing an optimization step. Args: time: Time tensor. variables: List of variables to optimize. ...
Keyword Args: global_variables: List of global variables to apply the proposed optimization step to.
def tf_step(self, time, variables, **kwargs): """ Keyword Args: global_variables: List of global variables to apply the proposed optimization step to. Returns: List of delta tensors corresponding to the updates for each optimized variable. """ global_var...
compute the eigen decomp using copied var stats to avoid concurrent read/ write from other queue
def computeStatsEigen(self): """ compute the eigen decomp using copied var stats to avoid concurrent read/write from other queue """ # TO-DO: figure out why this op has delays (possibly moving # eigenvectors around?) with tf.device('/cpu:0'): def removeNone(tensor_list): ...
Creates the TensorFlow operations for performing an optimization step on the given variables including actually changing the values of the variables.
def tf_step(self, time, variables, **kwargs): """ Creates the TensorFlow operations for performing an optimization step on the given variables, including actually changing the values of the variables. Args: time: Time tensor. Not used for this optimizer. variable...
Applies the given ( and already calculated ) step deltas to the variable values.
def apply_step(self, variables, deltas, loss_sampled): """ Applies the given (and already calculated) step deltas to the variable values. Args: variables: List of variables. deltas: List of deltas of same length. loss_sampled : the sampled loss Retur...
Performs an optimization step.
def minimize(self, time, variables, **kwargs): """ Performs an optimization step. Args: time: Time tensor. Not used for this variables: List of variables to optimize. **kwargs: fn_loss : loss function tensor that is differentiated ...
Constructs the extra Replay memory.
def setup_components_and_tf_funcs(self, custom_getter=None): """ Constructs the extra Replay memory. """ custom_getter = super(QDemoModel, self).setup_components_and_tf_funcs(custom_getter) self.demo_memory = Replay( states=self.states_spec, internals=sel...
Imports a single experience to memory.
def tf_import_demo_experience(self, states, internals, actions, terminal, reward): """ Imports a single experience to memory. """ return self.demo_memory.store( states=states, internals=internals, actions=actions, terminal=terminal, ...
Extends the q - model loss via the dqfd large - margin loss.
def tf_demo_loss(self, states, actions, terminal, reward, internals, update, reference=None): """ Extends the q-model loss via the dqfd large-margin loss. """ embedding = self.network.apply(x=states, internals=internals, update=update) deltas = list() for name in sorted(...
Combines Q - loss and demo loss.
def tf_combined_loss(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None): """ Combines Q-loss and demo loss. """ q_model_loss = self.fn_loss( states=states, internals=internals, actions=actions, ...
Returns the TensorFlow variables used by the model.
def get_variables(self, include_submodules=False, include_nontrainable=False): """ Returns the TensorFlow variables used by the model. Returns: List of variables. """ model_variables = super(QDemoModel, self).get_variables( include_submodules=include_subm...
Stores demonstrations in the demo memory.
def import_demo_experience(self, states, internals, actions, terminal, reward): """ Stores demonstrations in the demo memory. """ fetches = self.import_demo_experience_output feed_dict = self.get_feed_dict( states=states, internals=internals, ...
Performs a demonstration update by calling the demo optimization operation. Note that the batch data does not have to be fetched from the demo memory as this is now part of the TensorFlow operation of the demo update.
def demo_update(self): """ Performs a demonstration update by calling the demo optimization operation. Note that the batch data does not have to be fetched from the demo memory as this is now part of the TensorFlow operation of the demo update. """ fetches = self.demo_opt...
Creates a solver from a specification dict.
def from_config(config, kwargs=None): """ Creates a solver from a specification dict. """ return util.get_object( obj=config, predefined=tensorforce.core.optimizers.solvers.solvers, kwargs=kwargs )
Keyword Args: arguments: Dict of arguments for passing to fn_loss as ** kwargs. fn_loss: A callable taking arguments as kwargs and returning the loss op of the current model.
def tf_step(self, time, variables, **kwargs): """ Keyword Args: arguments: Dict of arguments for passing to fn_loss as **kwargs. fn_loss: A callable taking arguments as kwargs and returning the loss op of the current model. """ arguments = kwargs["arguments"] ...
Return bool True if succeed otherwise False.
def SetClipboardText(text: str) -> bool: """ Return bool, True if succeed otherwise False. """ if ctypes.windll.user32.OpenClipboard(0): ctypes.windll.user32.EmptyClipboard() textByteLen = (len(text) + 1) * 2 hClipboardData = ctypes.windll.kernel32.GlobalAlloc(0, textByteLen) # ...
Change the text color on console window. color: int a value in class ConsoleColor. Return bool True if succeed otherwise False.
def SetConsoleColor(color: int) -> bool: """ Change the text color on console window. color: int, a value in class `ConsoleColor`. Return bool, True if succeed otherwise False. """ global _ConsoleOutputHandle global _DefaultConsoleColor if not _DefaultConsoleColor: if not _Consol...
Reset to the default text color on console window. Return bool True if succeed otherwise False.
def ResetConsoleColor() -> bool: """ Reset to the default text color on console window. Return bool, True if succeed otherwise False. """ if sys.stdout: sys.stdout.flush() bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor))
WindowFromPoint from Win32. Return int a native window handle.
def WindowFromPoint(x: int, y: int) -> int: """ WindowFromPoint from Win32. Return int, a native window handle. """ return ctypes.windll.user32.WindowFromPoint(ctypes.wintypes.POINT(x, y))
GetCursorPos from Win32. Get current mouse cursor positon. Return tuple two ints tuple ( x y ).
def GetCursorPos() -> tuple: """ GetCursorPos from Win32. Get current mouse cursor positon. Return tuple, two ints tuple (x, y). """ point = ctypes.wintypes.POINT(0, 0) ctypes.windll.user32.GetCursorPos(ctypes.byref(point)) return point.x, point.y
SetCursorPos from Win32. Set mouse cursor to point x y. x: int. y: int. Return bool True if succeed otherwise False.
def SetCursorPos(x: int, y: int) -> bool: """ SetCursorPos from Win32. Set mouse cursor to point x, y. x: int. y: int. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.SetCursorPos(x, y))
mouse_event from Win32.
def mouse_event(dwFlags: int, dx: int, dy: int, dwData: int, dwExtraInfo: int) -> None: """mouse_event from Win32.""" ctypes.windll.user32.mouse_event(dwFlags, dx, dy, dwData, dwExtraInfo)
keybd_event from Win32.
def keybd_event(bVk: int, bScan: int, dwFlags: int, dwExtraInfo: int) -> None: """keybd_event from Win32.""" ctypes.windll.user32.keybd_event(bVk, bScan, dwFlags, dwExtraInfo)
PostMessage from Win32. Return bool True if succeed otherwise False.
def PostMessage(handle: int, msg: int, wParam: int, lParam: int) -> bool: """ PostMessage from Win32. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.PostMessageW(ctypes.c_void_p(handle), msg, wParam, lParam))
SendMessage from Win32. Return int the return value specifies the result of the message processing ; it depends on the message sent.
def SendMessage(handle: int, msg: int, wParam: int, lParam: int) -> int: """ SendMessage from Win32. Return int, the return value specifies the result of the message processing; it depends on the message sent. """ return ctypes.windll.user32.SendMessageW(ctypes.c_void_p(handle), msg,...
Simulate mouse click at point x y. x: int. y: int. waitTime: float.
def Click(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse click at point x, y. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.Absolute, x * 655...
Simulate mouse middle click at point x y. x: int. y: int. waitTime: float.
def MiddleClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse middle click at point x, y. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.MiddleDown | MouseEventFlag.Ab...
Simulate mouse right click at point x y. x: int. y: int. waitTime: float.
def RightClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse right click at point x, y. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.RightDown | MouseEventFlag.Absol...
Press left mouse. x: int. y: int. waitTime: float.
def PressMouse(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Press left mouse. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.Absolute, x * 65535 // screenW...
Release left mouse. waitTime: float.
def ReleaseMouse(waitTime: float = OPERATION_WAIT_TIME) -> None: """ Release left mouse. waitTime: float. """ x, y = GetCursorPos() screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.LeftUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0,...
Press right mouse. x: int. y: int. waitTime: float.
def RightPressMouse(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Press right mouse. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.RightDown | MouseEventFlag.Absolute, x * 65535 // ...
Release right mouse. waitTime: float.
def RightReleaseMouse(waitTime: float = OPERATION_WAIT_TIME) -> None: """ Release right mouse. waitTime: float. """ x, y = GetCursorPos() screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.RightUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHei...
Simulate mouse move to point x y from current cursor. x: int. y: int. moveSpeed: float 1 normal speed < 1 move slower > 1 move faster. waitTime: float.
def MoveTo(x: int, y: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse move to point x, y from current cursor. x: int. y: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float. """ if moveSpeed <= 0: ...
Simulate mouse left 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 DragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse left 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 f...
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 RightDragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None: """ 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 ...
Simulate mouse wheel up. wheelTimes: int. interval: float. waitTime: float.
def WheelUp(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse wheel up. wheelTimes: int. interval: float. waitTime: float. """ for i in range(wheelTimes): mouse_event(MouseEventFlag.Wheel, 0, 0, 120, 0) #WHEEL_DELTA=120 ...
Return tuple two ints tuple ( width height ).
def GetScreenSize() -> tuple: """Return tuple, two ints tuple (width, height).""" SM_CXSCREEN = 0 SM_CYSCREEN = 1 w = ctypes.windll.user32.GetSystemMetrics(SM_CXSCREEN) h = ctypes.windll.user32.GetSystemMetrics(SM_CYSCREEN) return w, h
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 ...
def GetPixelColor(x: int, y: int, handle: int = 0) -> int: """ 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 hand...
MessageBox from Win32. content: str. title: str. flags: int a value or some combined values in class MB. Return int a value in MB whose name starts with Id such as MB. IdOk
def MessageBox(content: str, title: str, flags: int = MB.Ok) -> int: """ MessageBox from Win32. content: str. title: str. flags: int, a value or some combined values in class `MB`. Return int, a value in MB whose name starts with Id, such as MB.IdOk """ return ctypes.windll.user32.Messag...
SetForegroundWindow from Win32. handle: int the handle of a native window. Return bool True if succeed otherwise False.
def SetForegroundWindow(handle: int) -> bool: """ SetForegroundWindow from Win32. handle: int, the handle of a native window. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.SetForegroundWindow(ctypes.c_void_p(handle)))
BringWindowToTop from Win32. handle: int the handle of a native window. Return bool True if succeed otherwise False.
def BringWindowToTop(handle: int) -> bool: """ BringWindowToTop from Win32. handle: int, the handle of a native window. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.BringWindowToTop(ctypes.c_void_p(handle)))
SwitchToThisWindow from Win32. handle: int the handle of a native window.
def SwitchToThisWindow(handle: int) -> None: """ SwitchToThisWindow from Win32. handle: int, the handle of a native window. """ ctypes.windll.user32.SwitchToThisWindow(ctypes.c_void_p(handle), 1)
GetAncestor from Win32. handle: int the handle of a native window. index: int a value in class GAFlag. Return int a native window handle.
def GetAncestor(handle: int, flag: int) -> int: """ GetAncestor from Win32. handle: int, the handle of a native window. index: int, a value in class `GAFlag`. Return int, a native window handle. """ return ctypes.windll.user32.GetAncestor(ctypes.c_void_p(handle), flag)
IsTopLevelWindow from Win32. handle: int the handle of a native window. Return bool. Only available on Windows 7 or Higher.
def IsTopLevelWindow(handle: int) -> bool: """ IsTopLevelWindow from Win32. handle: int, the handle of a native window. Return bool. Only available on Windows 7 or Higher. """ return bool(ctypes.windll.user32.IsTopLevelWindow(ctypes.c_void_p(handle)))
GetWindowLong from Win32. handle: int the handle of a native window. index: int.
def GetWindowLong(handle: int, index: int) -> int: """ GetWindowLong from Win32. handle: int, the handle of a native window. index: int. """ return ctypes.windll.user32.GetWindowLongW(ctypes.c_void_p(handle), index)
SetWindowLong from Win32. handle: int the handle of a native window. index: int. value: int. Return int the previous value before set.
def SetWindowLong(handle: int, index: int, value: int) -> int: """ SetWindowLong from Win32. handle: int, the handle of a native window. index: int. value: int. Return int, the previous value before set. """ return ctypes.windll.user32.SetWindowLongW(ctypes.c_void_p(handle), index, value...
IsIconic from Win32. Determine whether a native window is minimized. handle: int the handle of a native window. Return bool.
def IsIconic(handle: int) -> bool: """ IsIconic from Win32. Determine whether a native window is minimized. handle: int, the handle of a native window. Return bool. """ return bool(ctypes.windll.user32.IsIconic(ctypes.c_void_p(handle)))
IsZoomed from Win32. Determine whether a native window is maximized. handle: int the handle of a native window. Return bool.
def IsZoomed(handle: int) -> bool: """ IsZoomed from Win32. Determine whether a native window is maximized. handle: int, the handle of a native window. Return bool. """ return bool(ctypes.windll.user32.IsZoomed(ctypes.c_void_p(handle)))
IsWindowVisible from Win32. handle: int the handle of a native window. Return bool.
def IsWindowVisible(handle: int) -> bool: """ IsWindowVisible from Win32. handle: int, the handle of a native window. Return bool. """ return bool(ctypes.windll.user32.IsWindowVisible(ctypes.c_void_p(handle)))
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 ShowWindow(handle: int, cmdShow: int) -> bool: """ 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. """ return ctypes.windll.user32.ShowWindow(ctypes.c_void_p(handle), cmdShow)
MoveWindow from Win32. handle: int the handle of a native window. x: int. y: int. width: int. height: int. repaint: int use 1 or 0. Return bool True if succeed otherwise False.
def MoveWindow(handle: int, x: int, y: int, width: int, height: int, repaint: int = 1) -> bool: """ MoveWindow from Win32. handle: int, the handle of a native window. x: int. y: int. width: int. height: int. repaint: int, use 1 or 0. Return bool, True if succeed otherwise False. ...
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 SetWindowPos(handle: int, hWndInsertAfter: int, x: int, y: int, width: int, height: int, flags: int) -> bool: """ 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. ...
handle: int the handle of a native window. isTopmost: bool Return bool True if succeed otherwise False.
def SetWindowTopmost(handle: int, isTopmost: bool) -> bool: """ handle: int, the handle of a native window. isTopmost: bool Return bool, True if succeed otherwise False. """ topValue = SWP.HWND_Topmost if isTopmost else SWP.HWND_NoTopmost return bool(SetWindowPos(handle, topValue, 0, 0, 0, 0...
GetWindowText from Win32. handle: int the handle of a native window. Return str.
def GetWindowText(handle: int) -> str: """ GetWindowText from Win32. handle: int, the handle of a native window. Return str. """ arrayType = ctypes.c_wchar * MAX_PATH values = arrayType() ctypes.windll.user32.GetWindowTextW(ctypes.c_void_p(handle), values, MAX_PATH) return values.val...
SetWindowText from Win32. handle: int the handle of a native window. text: str. Return bool True if succeed otherwise False.
def SetWindowText(handle: int, text: str) -> bool: """ SetWindowText from Win32. handle: int, the handle of a native window. text: str. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.SetWindowTextW(ctypes.c_void_p(handle), ctypes.c_wchar_p(text)))
Get text of a native Win32 Edit. handle: int the handle of a native window. Return str.
def GetEditText(handle: int) -> str: """ Get text of a native Win32 Edit. handle: int, the handle of a native window. Return str. """ textLen = SendMessage(handle, 0x000E, 0, 0) + 1 #WM_GETTEXTLENGTH arrayType = ctypes.c_wchar * textLen values = arrayType() SendMessage(handle, 0x000...
GetConsoleOriginalTitle from Win32. Return str. Only available on Windows Vista or higher.
def GetConsoleOriginalTitle() -> str: """ GetConsoleOriginalTitle from Win32. Return str. Only available on Windows Vista or higher. """ if IsNT6orHigher: arrayType = ctypes.c_wchar * MAX_PATH values = arrayType() ctypes.windll.kernel32.GetConsoleOriginalTitleW(values, MA...
GetConsoleTitle from Win32. Return str.
def GetConsoleTitle() -> str: """ GetConsoleTitle from Win32. Return str. """ arrayType = ctypes.c_wchar * MAX_PATH values = arrayType() ctypes.windll.kernel32.GetConsoleTitleW(values, MAX_PATH) return values.value
SetConsoleTitle from Win32. text: str. Return bool True if succeed otherwise False.
def SetConsoleTitle(text: str) -> bool: """ SetConsoleTitle from Win32. text: str. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(text)))
Check if desktop is locked. Return bool. Desktop is locked if press Win + L Ctrl + Alt + Del or in remote desktop mode.
def IsDesktopLocked() -> bool: """ Check if desktop is locked. Return bool. Desktop is locked if press Win+L, Ctrl+Alt+Del or in remote desktop mode. """ isLocked = False desk = ctypes.windll.user32.OpenDesktopW(ctypes.c_wchar_p('Default'), 0, 0, 0x0100) # DESKTOP_SWITCHDESKTOP = 0x0100 ...
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 other...
def PlayWaveFile(filePath: str = r'C:\Windows\Media\notify.wav', isAsync: bool = False, isLoop: bool = False) -> bool: """ 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: b...
Return True if process is 64 bit. Return False if process is 32 bit. Return None if unknown maybe caused by having no acess right to the process.
def IsProcess64Bit(processId: int) -> bool: """ Return True if process is 64 bit. Return False if process is 32 bit. Return None if unknown, maybe caused by having no acess right to the process. """ try: func = ctypes.windll.ntdll.ZwWow64ReadVirtualMemory64 #only 64 bit OS has this func...
Run a python script as administrator. System will show a popup dialog askes you whether to elevate as administrator if UAC is enabled. argv: list a str list like sys. argv argv [ 0 ] is the script file argv [ 1: ] are other arguments. workingDirectory: str the working directory for the script file. showFlag: int a valu...
def RunScriptAsAdmin(argv: list, workingDirectory: str = None, showFlag: int = SW.ShowNormal) -> bool: """ Run a python script as administrator. System will show a popup dialog askes you whether to elevate as administrator if UAC is enabled. argv: list, a str list like sys.argv, argv[0] is the script fi...
Simulate typing a key. key: int a value in class Keys.
def SendKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate typing a key. key: int, a value in class `Keys`. """ keybd_event(key, 0, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey, 0) keybd_event(key, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0...
Simulate a key down for key. key: int a value in class Keys. waitTime: float.
def PressKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate a key down for key. key: int, a value in class `Keys`. waitTime: float. """ keybd_event(key, 0, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey, 0) time.sleep(waitTime)
Simulate a key up for key. key: int a value in class Keys. waitTime: float.
def ReleaseKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate a key up for key. key: int, a value in class `Keys`. waitTime: float. """ keybd_event(key, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) time.sleep(waitTime)
key: int a value in class Keys. Return bool.
def IsKeyPressed(key: int) -> bool: """ key: int, a value in class `Keys`. Return bool. """ state = ctypes.windll.user32.GetAsyncKeyState(key) return bool(state & 0x8000)
Create Win32 struct INPUT for SendInput. Return INPUT.
def _CreateInput(structure) -> INPUT: """ Create Win32 struct `INPUT` for `SendInput`. Return `INPUT`. """ if isinstance(structure, MOUSEINPUT): return INPUT(InputType.Mouse, _INPUTUnion(mi=structure)) if isinstance(structure, KEYBDINPUT): return INPUT(InputType.Keyboard, _INPUTU...
Create Win32 struct MOUSEINPUT for SendInput. Return INPUT.
def MouseInput(dx: int, dy: int, mouseData: int = 0, dwFlags: int = MouseEventFlag.LeftDown, time_: int = 0) -> INPUT: """ Create Win32 struct `MOUSEINPUT` for `SendInput`. Return `INPUT`. """ return _CreateInput(MOUSEINPUT(dx, dy, mouseData, dwFlags, time_, None))
Create Win32 struct KEYBDINPUT for SendInput.
def KeyboardInput(wVk: int, wScan: int, dwFlags: int = KeyboardEventFlag.KeyDown, time_: int = 0) -> INPUT: """Create Win32 struct `KEYBDINPUT` for `SendInput`.""" return _CreateInput(KEYBDINPUT(wVk, wScan, dwFlags, time_, None))
Create Win32 struct HARDWAREINPUT for SendInput.
def HardwareInput(uMsg: int, param: int = 0) -> INPUT: """Create Win32 struct `HARDWAREINPUT` for `SendInput`.""" return _CreateInput(HARDWAREINPUT(uMsg, param & 0xFFFF, param >> 16 & 0xFFFF))
Type a single unicode char. char: str len ( char ) must equal to 1. 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 SendUnicodeChar(char: str) -> int: """ Type a single unicode char. char: str, len(char) must equal to 1. 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 thre...
This function is only for internal use in SendKeys. key: int a value in class Keys. Return int.
def _VKtoSC(key: int) -> int: """ This function is only for internal use in SendKeys. key: int, a value in class `Keys`. Return int. """ if key in _SCKeys: return _SCKeys[key] scanCode = ctypes.windll.user32.MapVirtualKeyA(key, 0) if not scanCode: return 0 keyList = [...
Simulate typing keys on keyboard. text: str keys to type. interval: float seconds between keys. waitTime: float. debug: bool if True print the keys. Examples: { Ctrl } { Delete }... are special keys name in SpecialKeyNames. SendKeys ( { Ctrl } a { Delete } { Ctrl } v { Ctrl } s { Ctrl } { Shift } s { Win } e { PageDown...
def SendKeys(text: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT_TIME, debug: bool = False) -> None: """ Simulate typing keys on keyboard. text: str, keys to type. interval: float, seconds between keys. waitTime: float. debug: bool, if True, print the keys. Examples: {Ctr...
Get pattern COM interface by pattern id. patternId: int a value in class PatternId. Return comtypes. _cominterface_meta.
def GetPatternIdInterface(patternId: int): """ Get pattern COM interface by pattern id. patternId: int, a value in class `PatternId`. Return comtypes._cominterface_meta. """ global _PatternIdInterfaces if not _PatternIdInterfaces: _PatternIdInterfaces = { # PatternId.Anno...
Create a concreate pattern by pattern id and pattern ( POINTER ( IUnknown )).
def CreatePattern(patternId: int, pattern: ctypes.POINTER(comtypes.IUnknown)): """Create a concreate pattern by pattern id and pattern(POINTER(IUnknown)).""" subPattern = pattern.QueryInterface(GetPatternIdInterface(patternId)) if subPattern: return PatternConstructors[patternId](pattern=subPattern)
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 ...
def WalkTree(top, getChildren: Callable = None, getFirstChild: Callable = None, getNextSibling: Callable = None, yieldCondition: Callable = None, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF): """ Walk a tree not using recursive algorithm. top: a tree node. getChildren: function(treeNode) -> lis...
Call IUIAutomation ElementFromPoint x y. May return None if mouse is over cmd s title bar icon. Return Control subclass or None.
def ControlFromPoint(x: int, y: int) -> Control: """ Call IUIAutomation ElementFromPoint x,y. May return None if mouse is over cmd's title bar icon. Return `Control` subclass or None. """ element = _AutomationClient.instance().IUIAutomation.ElementFromPoint(ctypes.wintypes.POINT(x, y)) return Co...
Get a native handle from point x y and call IUIAutomation. ElementFromHandle. Return Control subclass.
def ControlFromPoint2(x: int, y: int) -> Control: """ Get a native handle from point x,y and call IUIAutomation.ElementFromHandle. Return `Control` subclass. """ return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(WindowFromPoint(x, y)))
Call IUIAutomation. ElementFromHandle with a native handle. handle: int a native window handle. Return Control subclass.
def ControlFromHandle(handle: int) -> Control: """ Call IUIAutomation.ElementFromHandle with a native handle. handle: int, a native window handle. Return `Control` subclass. """ return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(handle))
control1: Control or its subclass. control2: Control or its subclass. Return bool True if control1 and control2 represent the same control otherwise False.
def ControlsAreSame(control1: Control, control2: Control) -> bool: """ control1: `Control` or its subclass. control2: `Control` or its subclass. Return bool, True if control1 and control2 represent the same control otherwise False. """ return bool(_AutomationClient.instance().IUIAutomation.Compa...
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 WalkControl(control: Control, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF): """ 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). """ if includeTop: yield...
Print and log control s properties. control: Control or its subclass. depth: int current depth. showAllName: bool if False print the first 30 characters of control. Name.
def LogControl(control: Control, depth: int = 0, showAllName: bool = True) -> None: """ Print and log control's properties. control: `Control` or its subclass. depth: int, current depth. showAllName: bool, if False, print the first 30 characters of control.Name. """ def getKeyName(theDict, t...
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 EnumAndLogControl(control: Control, maxDepth: int = 0xFFFFFFFF, showAllName: bool = True, startDepth: int = 0) -> None: """ 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 chara...
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 EnumAndLogControlAncestors(control: Control, showAllName: bool = True) -> None: """ 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. """ lists = [] while control: ...
control: Control or its subclass. compare: compare function with parameters ( control: Control depth: int ) which returns bool. maxDepth: int enum depth. findFromSelf: bool if False do not compare self. foundIndex: int starts with 1 > = 1. Return Control subclass or None if not find.
def FindControl(control: Control, compare: Callable, maxDepth: int = 0xFFFFFFFF, findFromSelf: bool = False, foundIndex: int = 1) -> Control: """ control: `Control` or its subclass. compare: compare function with parameters (control: Control, depth: int) which returns bool. maxDepth: int, enum depth. ...
hotkey: tuple two ints tuple ( modifierKey key )
def WaitHotKeyReleased(hotkey: tuple) -> None: """hotkey: tuple, two ints tuple(modifierKey, key)""" mod = {ModifierKey.Alt: Keys.VK_MENU, ModifierKey.Control: Keys.VK_CONTROL, ModifierKey.Shift: Keys.VK_SHIFT, ModifierKey.Win: Keys.VK_LWIN } while Tru...
Bind functions with hotkeys the function will be run or stopped in another thread when the hotkey is pressed. keyFunctions: hotkey function dict like { ( uiautomation. ModifierKey. Control uiautomation. Keys. VK_1 ): func } stopHotKey: hotkey tuple exitHotKey: hotkey tuple waitHotKeyReleased: bool if True hotkey functi...
def RunByHotKey(keyFunctions: dict, stopHotKey: tuple = None, exitHotKey: tuple = (ModifierKey.Control, Keys.VK_D), waitHotKeyReleased: bool = True) -> None: """ Bind functions with hotkeys, the function will be run or stopped in another thread when the hotkey is pressed. keyFunctions: hotkey function dict,...
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 Write(log: Any, consoleColor: int = ConsoleColor.Default, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None, printTruncateLen: int = 0) -> None: """ log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFil...
log: any type. consoleColor: int a value in class ConsoleColor such as ConsoleColor. DarkGreen. writeToFile: bool. printToStdout: bool. logFile: str log file path.
def WriteLine(log: Any, consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. ...
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.
def ColorfullyWrite(log: str, consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: str. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. ...
log: str. consoleColor: int a value in class ConsoleColor such as ConsoleColor. DarkGreen. writeToFile: bool. printToStdout: bool. logFile: str log file path.
def ColorfullyWriteLine(log: str, consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: str. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool...
log: any type. consoleColor: int a value in class ConsoleColor such as ConsoleColor. DarkGreen. writeToFile: bool. printToStdout: bool. logFile: str log file path.
def Log(log: Any = '', consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. ...
Delete log file.
def DeleteLog() -> None: """Delete log file.""" if os.path.exists(Logger.FileName): os.remove(Logger.FileName)
Capture a native window to Bitmap by its handle. hwnd: int the handle of a native window. left: int. top: int. right: int. bottom: int. left top right and bottom are control s internal postion ( from 0 0 ). Return bool True if succeed otherwise False.
def FromHandle(self, hwnd: int, left: int = 0, top: int = 0, right: int = 0, bottom: int = 0) -> bool: """ Capture a native window to Bitmap by its handle. hwnd: int, the handle of a native window. left: int. top: int. right: int. bottom: int. left, top, r...
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 ( o...
def FromControl(self, control: 'Control', x: int = 0, y: int = 0, width: int = 0, height: int = 0) -> bool: """ 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 ...
Load image from a file. filePath: str. Return bool True if succeed otherwise False.
def FromFile(self, filePath: str) -> bool: """ Load image from a file. filePath: str. Return bool, True if succeed otherwise False. """ self.Release() self._bitmap = _DllClient.instance().dll.BitmapFromFile(ctypes.c_wchar_p(filePath)) self._getsize() ...
Save to a file. savePath: str should end with. bmp. jpg. jpeg. png. gif. tif. tiff. Return bool True if succeed otherwise False.
def ToFile(self, savePath: str) -> bool: """ Save to a file. savePath: str, should end with .bmp, .jpg, .jpeg, .png, .gif, .tif, .tiff. Return bool, True if succeed otherwise False. """ name, ext = os.path.splitext(savePath) extMap = {'.bmp': 'image/bmp' ...
Get color value of a pixel. x: int. y: int. Return int argb color. b = argb & 0x0000FF g = ( argb & 0x00FF00 ) >> 8 r = ( argb & 0xFF0000 ) >> 16 a = ( argb & 0xFF0000 ) >> 24
def GetPixelColor(self, x: int, y: int) -> int: """ Get color value of a pixel. x: int. y: int. Return int, argb color. b = argb & 0x0000FF g = (argb & 0x00FF00) >> 8 r = (argb & 0xFF0000) >> 16 a = (argb & 0xFF0000) >> 24 """ retur...
Set color value of a pixel. x: int. y: int. argb: int color value. Return bool True if succeed otherwise False.
def SetPixelColor(self, x: int, y: int, argb: int) -> bool: """ Set color value of a pixel. x: int. y: int. argb: int, color value. Return bool, True if succeed otherwise False. """ return _DllClient.instance().dll.BitmapSetPixel(self._bitmap, x, y, argb)