idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
50,700
def _check_count ( self , result , func , args ) : if result == 0 : raise ctypes . WinError ( ctypes . get_last_error ( ) ) return args
Private function to return ctypes errors cleanly
50,701
def _getMonitorInfo ( self ) : monitors = [ ] CCHDEVICENAME = 32 def _MonitorEnumProcCallback ( hMonitor , hdcMonitor , lprcMonitor , dwData ) : class MONITORINFOEX ( ctypes . Structure ) : _fields_ = [ ( "cbSize" , ctypes . wintypes . DWORD ) , ( "rcMonitor" , ctypes . wintypes . RECT ) , ( "rcWork" , ctypes . wintypes . RECT ) , ( "dwFlags" , ctypes . wintypes . DWORD ) , ( "szDevice" , ctypes . wintypes . WCHAR * CCHDEVICENAME ) ] lpmi = MONITORINFOEX ( ) lpmi . cbSize = ctypes . sizeof ( MONITORINFOEX ) self . _user32 . GetMonitorInfoW ( hMonitor , ctypes . byref ( lpmi ) ) monitors . append ( { "hmon" : hMonitor , "rect" : ( lprcMonitor . contents . left , lprcMonitor . contents . top , lprcMonitor . contents . right , lprcMonitor . contents . bottom ) , "name" : lpmi . szDevice } ) return True MonitorEnumProc = ctypes . WINFUNCTYPE ( ctypes . c_bool , ctypes . c_ulong , ctypes . c_ulong , ctypes . POINTER ( ctypes . wintypes . RECT ) , ctypes . c_int ) callback = MonitorEnumProc ( _MonitorEnumProcCallback ) if self . _user32 . EnumDisplayMonitors ( 0 , 0 , callback , 0 ) == 0 : raise WindowsError ( "Unable to enumerate monitors" ) monitors . sort ( key = lambda x : ( not ( x [ "rect" ] [ 0 ] == 0 and x [ "rect" ] [ 1 ] == 0 ) , x [ "name" ] ) ) return monitors
Returns info about the attached monitors in device order
50,702
def _getVirtualScreenRect ( self ) : SM_XVIRTUALSCREEN = 76 SM_YVIRTUALSCREEN = 77 SM_CXVIRTUALSCREEN = 78 SM_CYVIRTUALSCREEN = 79 return ( self . _user32 . GetSystemMetrics ( SM_XVIRTUALSCREEN ) , self . _user32 . GetSystemMetrics ( SM_YVIRTUALSCREEN ) , self . _user32 . GetSystemMetrics ( SM_CXVIRTUALSCREEN ) , self . _user32 . GetSystemMetrics ( SM_CYVIRTUALSCREEN ) )
The virtual screen is the bounding box containing all monitors .
50,703
def osPaste ( self ) : from . InputEmulation import Keyboard k = Keyboard ( ) k . keyDown ( "{CTRL}" ) k . type ( "v" ) k . keyUp ( "{CTRL}" )
Triggers the OS paste keyboard shortcut
50,704
def focusWindow ( self , hwnd ) : Debug . log ( 3 , "Focusing window: " + str ( hwnd ) ) SW_RESTORE = 9 if ctypes . windll . user32 . IsIconic ( hwnd ) : ctypes . windll . user32 . ShowWindow ( hwnd , SW_RESTORE ) ctypes . windll . user32 . SetForegroundWindow ( hwnd )
Brings specified window to the front
50,705
def isPIDValid ( self , pid ) : class ExitCodeProcess ( ctypes . Structure ) : _fields_ = [ ( 'hProcess' , ctypes . c_void_p ) , ( 'lpExitCode' , ctypes . POINTER ( ctypes . c_ulong ) ) ] SYNCHRONIZE = 0x100000 PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 process = self . _kernel32 . OpenProcess ( SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION , 0 , pid ) if not process : return False ec = ExitCodeProcess ( ) out = self . _kernel32 . GetExitCodeProcess ( process , ctypes . byref ( ec ) ) if not out : err = self . _kernel32 . GetLastError ( ) if self . _kernel32 . GetLastError ( ) == 5 : logging . warning ( "Access is denied to get pid info." ) self . _kernel32 . CloseHandle ( process ) return False elif bool ( ec . lpExitCode ) : self . _kernel32 . CloseHandle ( process ) return False self . _kernel32 . CloseHandle ( process ) return True
Checks if a PID is associated with a running process
50,706
def similar ( self , similarity ) : pattern = Pattern ( self . path ) pattern . similarity = similarity return pattern
Returns a new Pattern with the specified similarity threshold
50,707
def targetOffset ( self , dx , dy ) : pattern = Pattern ( self . path ) pattern . similarity = self . similarity pattern . offset = Location ( dx , dy ) return pattern
Returns a new Pattern with the given target offset
50,708
def debugPreview ( self , title = "Debug" ) : haystack = Image . open ( self . path ) haystack . show ( )
Loads and displays the image at Pattern . path
50,709
def setLocation ( self , location ) : if not location or not isinstance ( location , Location ) : raise ValueError ( "setLocation expected a Location object" ) self . x = location . x self . y = location . y return self
Change the upper left - hand corner to a new Location
50,710
def contains ( self , point_or_region ) : if isinstance ( point_or_region , Location ) : return ( self . x < point_or_region . x < self . x + self . w ) and ( self . y < point_or_region . y < self . y + self . h ) elif isinstance ( point_or_region , Region ) : return ( ( self . x < point_or_region . getX ( ) < self . x + self . w ) and ( self . y < point_or_region . getY ( ) < self . y + self . h ) and ( self . x < point_or_region . getX ( ) + point_or_region . getW ( ) < self . x + self . w ) and ( self . y < point_or_region . getY ( ) + point_or_region . getH ( ) < self . y + self . h ) ) else : raise TypeError ( "Unrecognized argument type for contains()" )
Checks if point_or_region is within this region
50,711
def morphTo ( self , region ) : if not region or not isinstance ( region , Region ) : raise TypeError ( "morphTo expected a Region object" ) self . setROI ( region ) return self
Change shape of this region to match the given Region object
50,712
def getCenter ( self ) : return Location ( self . x + ( self . w / 2 ) , self . y + ( self . h / 2 ) )
Return the Location of the center of this region
50,713
def getBottomRight ( self ) : return Location ( self . x + self . w , self . y + self . h )
Return the Location of the bottom right corner of this region
50,714
def offset ( self , location , dy = 0 ) : if not isinstance ( location , Location ) : location = Location ( location , dy ) r = Region ( self . x + location . x , self . y + location . y , self . w , self . h ) . clipRegionToScreen ( ) if r is None : raise ValueError ( "Specified region is not visible on any screen" ) return None return r
Returns a new Region offset from this one by location
50,715
def grow ( self , width , height = None ) : if height is None : return self . nearby ( width ) else : return Region ( self . x - width , self . y - height , self . w + ( 2 * width ) , self . h + ( 2 * height ) ) . clipRegionToScreen ( )
Expands the region by width on both sides and height on the top and bottom .
50,716
def nearby ( self , expand = 50 ) : return Region ( self . x - expand , self . y - expand , self . w + ( 2 * expand ) , self . h + ( 2 * expand ) ) . clipRegionToScreen ( )
Returns a new Region that includes the nearby neighbourhood of the the current region .
50,717
def left ( self , expand = None ) : if expand == None : x = 0 y = self . y w = self . x h = self . h else : x = self . x - expand y = self . y w = expand h = self . h return Region ( x , y , w , h ) . clipRegionToScreen ( )
Returns a new Region left of the current region with a width of expand pixels .
50,718
def right ( self , expand = None ) : if expand == None : x = self . x + self . w y = self . y w = self . getScreen ( ) . getBounds ( ) [ 2 ] - x h = self . h else : x = self . x + self . w y = self . y w = expand h = self . h return Region ( x , y , w , h ) . clipRegionToScreen ( )
Returns a new Region right of the current region with a width of expand pixels .
50,719
def getBitmap ( self ) : return PlatformManager . getBitmapFromRect ( self . x , self . y , self . w , self . h )
Captures screen area of this region at least the part that is on the screen
50,720
def debugPreview ( self , title = "Debug" ) : region = self haystack = self . getBitmap ( ) if isinstance ( region , Match ) : cv2 . circle ( haystack , ( region . getTarget ( ) . x - self . x , region . getTarget ( ) . y - self . y ) , 5 , 255 ) if haystack . shape [ 0 ] > ( Screen ( 0 ) . getBounds ( ) [ 2 ] / 2 ) or haystack . shape [ 1 ] > ( Screen ( 0 ) . getBounds ( ) [ 3 ] / 2 ) : haystack = cv2 . resize ( haystack , ( 0 , 0 ) , fx = 0.5 , fy = 0.5 ) Image . fromarray ( haystack ) . show ( )
Displays the region in a preview window .
50,721
def wait ( self , pattern , seconds = None ) : if isinstance ( pattern , ( int , float ) ) : if pattern == FOREVER : while True : time . sleep ( 1 ) time . sleep ( pattern ) return None if seconds is None : seconds = self . autoWaitTimeout findFailedRetry = True timeout = time . time ( ) + seconds while findFailedRetry : while True : match = self . exists ( pattern ) if match : return match if time . time ( ) >= timeout : break path = pattern . path if isinstance ( pattern , Pattern ) else pattern findFailedRetry = self . _raiseFindFailed ( "Could not find pattern '{}'" . format ( path ) ) if findFailedRetry : time . sleep ( self . _repeatWaitTime ) return None
Searches for an image pattern in the given region given a specified timeout period
50,722
def waitVanish ( self , pattern , seconds = None ) : r = self . clipRegionToScreen ( ) if r is None : raise ValueError ( "Region outside all visible screens" ) return None if seconds is None : seconds = self . autoWaitTimeout if not isinstance ( pattern , Pattern ) : if not isinstance ( pattern , basestring ) : raise TypeError ( "find expected a string [image path] or Pattern object" ) pattern = Pattern ( pattern ) needle = cv2 . imread ( pattern . path ) match = True timeout = time . time ( ) + seconds while match and time . time ( ) < timeout : matcher = TemplateMatcher ( r . getBitmap ( ) ) match = matcher . findBestMatch ( needle , pattern . similarity ) time . sleep ( 1 / self . _defaultScanRate if self . _defaultScanRate is not None else 1 / Settings . WaitScanRate ) if match : return False
Waits until the specified pattern is not visible on screen .
50,723
def click ( self , target = None , modifiers = "" ) : if target is None : target = self . _lastMatch or self target_location = None if isinstance ( target , Pattern ) : target_location = self . find ( target ) . getTarget ( ) elif isinstance ( target , basestring ) : target_location = self . find ( target ) . getTarget ( ) elif isinstance ( target , Match ) : target_location = target . getTarget ( ) elif isinstance ( target , Region ) : target_location = target . getCenter ( ) elif isinstance ( target , Location ) : target_location = target else : raise TypeError ( "click expected Pattern, String, Match, Region, or Location object" ) if modifiers != "" : keyboard . keyDown ( modifiers ) Mouse . moveSpeed ( target_location , Settings . MoveMouseDelay ) time . sleep ( 0.1 ) if Settings . ClickDelay > 0 : time . sleep ( min ( 1.0 , Settings . ClickDelay ) ) Settings . ClickDelay = 0.0 Mouse . click ( ) time . sleep ( 0.1 ) if modifiers != 0 : keyboard . keyUp ( modifiers ) Debug . history ( "Clicked at {}" . format ( target_location ) )
Moves the cursor to the target location and clicks the default mouse button .
50,724
def hover ( self , target = None ) : if target is None : target = self . _lastMatch or self target_location = None if isinstance ( target , Pattern ) : target_location = self . find ( target ) . getTarget ( ) elif isinstance ( target , basestring ) : target_location = self . find ( target ) . getTarget ( ) elif isinstance ( target , Match ) : target_location = target . getTarget ( ) elif isinstance ( target , Region ) : target_location = target . getCenter ( ) elif isinstance ( target , Location ) : target_location = target else : raise TypeError ( "hover expected Pattern, String, Match, Region, or Location object" ) Mouse . moveSpeed ( target_location , Settings . MoveMouseDelay )
Moves the cursor to the target location
50,725
def drag ( self , dragFrom = None ) : if dragFrom is None : dragFrom = self . _lastMatch or self dragFromLocation = None if isinstance ( dragFrom , Pattern ) : dragFromLocation = self . find ( dragFrom ) . getTarget ( ) elif isinstance ( dragFrom , basestring ) : dragFromLocation = self . find ( dragFrom ) . getTarget ( ) elif isinstance ( dragFrom , Match ) : dragFromLocation = dragFrom . getTarget ( ) elif isinstance ( dragFrom , Region ) : dragFromLocation = dragFrom . getCenter ( ) elif isinstance ( dragFrom , Location ) : dragFromLocation = dragFrom else : raise TypeError ( "drag expected dragFrom to be Pattern, String, Match, Region, or Location object" ) Mouse . moveSpeed ( dragFromLocation , Settings . MoveMouseDelay ) time . sleep ( Settings . DelayBeforeMouseDown ) Mouse . buttonDown ( ) Debug . history ( "Began drag at {}" . format ( dragFromLocation ) )
Starts a dragDrop operation .
50,726
def dropAt ( self , dragTo = None , delay = None ) : if dragTo is None : dragTo = self . _lastMatch or self if isinstance ( dragTo , Pattern ) : dragToLocation = self . find ( dragTo ) . getTarget ( ) elif isinstance ( dragTo , basestring ) : dragToLocation = self . find ( dragTo ) . getTarget ( ) elif isinstance ( dragTo , Match ) : dragToLocation = dragTo . getTarget ( ) elif isinstance ( dragTo , Region ) : dragToLocation = dragTo . getCenter ( ) elif isinstance ( dragTo , Location ) : dragToLocation = dragTo else : raise TypeError ( "dragDrop expected dragTo to be Pattern, String, Match, Region, or Location object" ) Mouse . moveSpeed ( dragToLocation , Settings . MoveMouseDelay ) time . sleep ( delay if delay is not None else Settings . DelayBeforeDrop ) Mouse . buttonUp ( ) Debug . history ( "Ended drag at {}" . format ( dragToLocation ) )
Completes a dragDrop operation
50,727
def dragDrop ( self , target , target2 = None , modifiers = "" ) : if modifiers != "" : keyboard . keyDown ( modifiers ) if target2 is None : dragFrom = self . _lastMatch dragTo = target else : dragFrom = target dragTo = target2 self . drag ( dragFrom ) time . sleep ( Settings . DelayBeforeDrag ) self . dropAt ( dragTo ) if modifiers != "" : keyboard . keyUp ( modifiers )
Performs a dragDrop operation .
50,728
def mouseMove ( self , PSRML = None , dy = 0 ) : if PSRML is None : PSRML = self . _lastMatch or self if isinstance ( PSRML , Pattern ) : move_location = self . find ( PSRML ) . getTarget ( ) elif isinstance ( PSRML , basestring ) : move_location = self . find ( PSRML ) . getTarget ( ) elif isinstance ( PSRML , Match ) : move_location = PSRML . getTarget ( ) elif isinstance ( PSRML , Region ) : move_location = PSRML . getCenter ( ) elif isinstance ( PSRML , Location ) : move_location = PSRML elif isinstance ( PSRML , int ) : offset = Location ( PSRML , dy ) move_location = Mouse . getPos ( ) . offset ( offset ) else : raise TypeError ( "doubleClick expected Pattern, String, Match, Region, or Location object" ) Mouse . moveSpeed ( move_location )
Low - level mouse actions
50,729
def isRegionValid ( self ) : screens = PlatformManager . getScreenDetails ( ) for screen in screens : s_x , s_y , s_w , s_h = screen [ "rect" ] if self . x + self . w >= s_x and s_x + s_w >= self . x and self . y + self . h >= s_y and s_y + s_h >= self . y : return True return False
Returns false if the whole region is not even partially inside any screen otherwise true
50,730
def clipRegionToScreen ( self ) : if not self . isRegionValid ( ) : return None screens = PlatformManager . getScreenDetails ( ) total_x , total_y , total_w , total_h = Screen ( - 1 ) . getBounds ( ) containing_screen = None for screen in screens : s_x , s_y , s_w , s_h = screen [ "rect" ] if self . x >= s_x and self . x + self . w <= s_x + s_w and self . y >= s_y and self . y + self . h <= s_y + s_h : return self elif self . x + self . w <= s_x or s_x + s_w <= self . x or self . y + self . h <= s_y or s_y + s_h <= self . y : continue elif self . x == total_x and self . y == total_y and self . w == total_w and self . h == total_h : return self else : x = max ( self . x , s_x ) y = max ( self . y , s_y ) w = min ( self . w , s_w ) h = min ( self . h , s_h ) return Region ( x , y , w , h ) return None
Returns the part of the region that is visible on a screen
50,731
def get ( self , part ) : if part == self . MID_VERTICAL : return Region ( self . x + ( self . w / 4 ) , y , self . w / 2 , self . h ) elif part == self . MID_HORIZONTAL : return Region ( self . x , self . y + ( self . h / 4 ) , self . w , self . h / 2 ) elif part == self . MID_BIG : return Region ( self . x + ( self . w / 4 ) , self . y + ( self . h / 4 ) , self . w / 2 , self . h / 2 ) elif isinstance ( part , int ) and part >= 200 and part <= 999 : raster , row , column = str ( part ) self . setRaster ( raster , raster ) if row == raster and column == raster : return self elif row == raster : return self . getCol ( column ) elif column == raster : return self . getRow ( row ) else : return self . getCell ( row , column ) else : return self
Returns a section of the region as a new region
50,732
def setCenter ( self , loc ) : offset = self . getCenter ( ) . getOffset ( loc ) return self . setLocation ( self . getTopLeft ( ) . offset ( offset ) )
Move this region so it is centered on loc
50,733
def setTopRight ( self , loc ) : offset = self . getTopRight ( ) . getOffset ( loc ) return self . setLocation ( self . getTopLeft ( ) . offset ( offset ) )
Move this region so its top right corner is on loc
50,734
def setBottomLeft ( self , loc ) : offset = self . getBottomLeft ( ) . getOffset ( loc ) return self . setLocation ( self . getTopLeft ( ) . offset ( offset ) )
Move this region so its bottom left corner is on loc
50,735
def setBottomRight ( self , loc ) : offset = self . getBottomRight ( ) . getOffset ( loc ) return self . setLocation ( self . getTopLeft ( ) . offset ( offset ) )
Move this region so its bottom right corner is on loc
50,736
def setSize ( self , w , h ) : self . setW ( w ) self . setH ( h ) return self
Sets the new size of the region
50,737
def saveScreenCapture ( self , path = None , name = None ) : bitmap = self . getBitmap ( ) target_file = None if path is None and name is None : _ , target_file = tempfile . mkstemp ( ".png" ) elif name is None : _ , tpath = tempfile . mkstemp ( ".png" ) target_file = os . path . join ( path , tfile ) else : target_file = os . path . join ( path , name + ".png" ) cv2 . imwrite ( target_file , bitmap ) return target_file
Saves the region s bitmap
50,738
def saveLastScreenImage ( self ) : bitmap = self . getLastScreenImage ( ) _ , target_file = tempfile . mkstemp ( ".png" ) cv2 . imwrite ( target_file , bitmap )
Saves the last image taken on this region s screen to a temporary file
50,739
def onChange ( self , min_changed_pixels = None , handler = None ) : if isinstance ( min_changed_pixels , int ) and ( callable ( handler ) or handler is None ) : return self . _observer . register_event ( "CHANGE" , pattern = ( min_changed_pixels , self . getBitmap ( ) ) , handler = handler ) elif ( callable ( min_changed_pixels ) or min_changed_pixels is None ) and ( callable ( handler ) or handler is None ) : handler = min_changed_pixels or handler return self . _observer . register_event ( "CHANGE" , pattern = ( Settings . ObserveMinChangedPixels , self . getBitmap ( ) ) , handler = handler ) else : raise ValueError ( "Unsupported arguments for onChange method" )
Registers an event to call handler when at least min_changed_pixels change in this region .
50,740
def isChanged ( self , min_changed_pixels , screen_state ) : r = self . clipRegionToScreen ( ) current_state = r . getBitmap ( ) diff = numpy . subtract ( current_state , screen_state ) return ( numpy . count_nonzero ( diff ) >= min_changed_pixels )
Returns true if at least min_changed_pixels are different between screen_state and the current state .
50,741
def stopObserver ( self ) : self . _observer . isStopped = True self . _observer . isRunning = False
Stops this region s observer loop .
50,742
def getEvents ( self ) : caught_events = self . _observer . caught_events self . _observer . caught_events = [ ] for event in caught_events : self . _observer . activate_event ( event [ "name" ] ) return caught_events
Returns a list of all events that have occurred .
50,743
def getEvent ( self , name ) : to_return = None for event in self . _observer . caught_events : if event [ "name" ] == name : to_return = event break if to_return : self . _observer . caught_events . remove ( to_return ) self . _observer . activate_event ( to_return [ "name" ] ) return to_return
Returns the named event .
50,744
def setFindFailedResponse ( self , response ) : valid_responses = ( "ABORT" , "SKIP" , "PROMPT" , "RETRY" ) if response not in valid_responses : raise ValueError ( "Invalid response - expected one of ({})" . format ( ", " . join ( valid_responses ) ) ) self . _findFailedResponse = response
Set the response to a FindFailed exception in this region . Can be ABORT SKIP PROMPT or RETRY .
50,745
def setThrowException ( self , setting ) : if setting : self . _throwException = True self . _findFailedResponse = "ABORT" else : self . _throwException = False self . _findFailedResponse = "SKIP"
Defines whether an exception should be thrown for FindFailed operations .
50,746
def register_event ( self , event_type , pattern , handler ) : if event_type not in self . _supported_events : raise ValueError ( "Unsupported event type {}" . format ( event_type ) ) if event_type != "CHANGE" and not isinstance ( pattern , Pattern ) and not isinstance ( pattern , basestring ) : raise ValueError ( "Expected pattern to be a Pattern or string" ) if event_type == "CHANGE" and not ( len ( pattern ) == 2 and isinstance ( pattern [ 0 ] , int ) and isinstance ( pattern [ 1 ] , numpy . ndarray ) ) : raise ValueError ( "For \"CHANGE\" events, ``pattern`` should be a tuple of ``min_changed_pixels`` and the base screen state." ) event = { "pattern" : pattern , "event_type" : event_type , "count" : 0 , "handler" : handler , "name" : uuid . uuid4 ( ) , "active" : True } self . _events [ event [ "name" ] ] = event return event [ "name" ]
When event_type is observed for pattern triggers handler .
50,747
def capture ( self , * args ) : if len ( args ) == 0 : region = self elif isinstance ( args [ 0 ] , Region ) : region = args [ 0 ] elif isinstance ( args [ 0 ] , tuple ) : region = Region ( * args [ 0 ] ) elif isinstance ( args [ 0 ] , basestring ) : raise NotImplementedError ( "Interactive capture mode not defined" ) elif isinstance ( args [ 0 ] , int ) : region = Region ( * args ) self . lastScreenImage = region . getBitmap ( ) return self . lastScreenImage
Captures the region as an image
50,748
def showMonitors ( cls ) : Debug . info ( "*** monitor configuration [ {} Screen(s)] ***" . format ( cls . getNumberScreens ( ) ) ) Debug . info ( "*** Primary is Screen {}" . format ( cls . primaryScreen ) ) for index , screen in enumerate ( PlatformManager . getScreenDetails ( ) ) : Debug . info ( "Screen {}: ({}, {}, {}, {})" . format ( index , * screen [ "rect" ] ) ) Debug . info ( "*** end monitor configuration ***" )
Prints debug information about currently detected screens
50,749
def resetMonitors ( self ) : Debug . error ( "*** BE AWARE: experimental - might not work ***" ) Debug . error ( "Re-evaluation of the monitor setup has been requested" ) Debug . error ( "... Current Region/Screen objects might not be valid any longer" ) Debug . error ( "... Use existing Region/Screen objects only if you know what you are doing!" ) self . __init__ ( self . _screenId ) self . showMonitors ( )
Recalculates screen based on changed monitor setup
50,750
def newRegion ( self , loc , width , height ) : return Region . create ( self . getTopLeft ( ) . offset ( loc ) , width , height )
Creates a new region on the current screen at the specified offset with the specified width and height .
50,751
def history ( self , message ) : if Settings . ActionLogs : self . _write_log ( "action" , Settings . LogTime , message )
Records an Action - level log message
50,752
def error ( self , message ) : if Settings . ErrorLogs : self . _write_log ( "error" , Settings . LogTime , message )
Records an Error - level log message
50,753
def info ( self , message ) : if Settings . InfoLogs : self . _write_log ( "info" , Settings . LogTime , message )
Records an Info - level log message
50,754
def on ( self , level ) : if isinstance ( level , int ) and level >= 0 and level <= 3 : self . _debug_level = level
Turns on all debugging messages up to the specified level
50,755
def setLogFile ( self , filepath ) : if filepath is None : self . _log_file = None return parsed_path = os . path . abspath ( filepath ) if os . path . isdir ( os . path . dirname ( parsed_path ) ) and not os . path . isdir ( parsed_path ) : self . _log_file = parsed_path else : raise IOError ( "File not found: " + filepath )
Defines the file to which output log messages should be sent .
50,756
def _write_log ( self , log_type , log_time , message ) : timestamp = datetime . datetime . now ( ) . strftime ( " %Y-%m-%d %H:%M:%S" ) log_entry = "[{}{}] {}" . format ( log_type , timestamp if log_time else "" , message ) if self . _logger and callable ( getattr ( self . _logger , self . _logger_methods [ log_type ] , None ) ) : getattr ( self . _logger , self . _logger_methods [ log_type ] , None ) ( message if self . _logger_no_prefix else log_entry ) elif self . _log_file : with open ( self . _log_file , 'a' ) as logfile : try : logfile . write ( unicode ( log_entry + "\n" ) ) except NameError : logfile . write ( log_entry + "\n" ) else : print ( log_entry )
Private method to abstract log writing for different types of logs
50,757
def addImagePath ( new_path ) : if os . path . exists ( new_path ) : Settings . ImagePaths . append ( new_path ) elif "http://" in new_path or "https://" in new_path : request = requests . get ( new_path ) if request . status_code < 400 : Settings . ImagePaths . append ( new_path ) else : raise OSError ( "Unable to connect to " + new_path ) else : raise OSError ( "File not found: " + new_path )
Convenience function . Adds a path to the list of paths to search for images .
50,758
def unzip ( from_file , to_folder ) : with ZipFile ( os . path . abspath ( from_file ) , 'r' ) as to_unzip : to_unzip . extractall ( os . path . abspath ( to_folder ) )
Convenience function .
50,759
def popup ( text , title = "Lackey Info" ) : root = tk . Tk ( ) root . withdraw ( ) tkMessageBox . showinfo ( title , text )
Creates an info dialog with the specified text .
50,760
def popError ( text , title = "Lackey Error" ) : root = tk . Tk ( ) root . withdraw ( ) tkMessageBox . showerror ( title , text )
Creates an error dialog with the specified text .
50,761
def popAsk ( text , title = "Lackey Decision" ) : root = tk . Tk ( ) root . withdraw ( ) return tkMessageBox . askyesno ( title , text )
Creates a yes - no dialog with the specified text .
50,762
def input ( msg = "" , default = "" , title = "Lackey Input" , hidden = False ) : root = tk . Tk ( ) input_text = tk . StringVar ( ) input_text . set ( default ) PopupInput ( root , msg , title , hidden , input_text ) root . focus_force ( ) root . mainloop ( ) return str ( input_text . get ( ) )
Creates an input dialog with the specified message and default text .
50,763
def inputText ( message = "" , title = "Lackey Input" , lines = 9 , width = 20 , text = "" ) : root = tk . Tk ( ) input_text = tk . StringVar ( ) input_text . set ( text ) PopupTextarea ( root , message , title , lines , width , input_text ) root . focus_force ( ) root . mainloop ( ) return str ( input_text . get ( ) )
Creates a textarea dialog with the specified message and default text .
50,764
def select ( message = "" , title = "Lackey Input" , options = None , default = None ) : if options is None or len ( options ) == 0 : return "" if default is None : default = options [ 0 ] if default not in options : raise ValueError ( "<<default>> not in options[]" ) root = tk . Tk ( ) input_text = tk . StringVar ( ) input_text . set ( message ) PopupList ( root , message , title , options , default , input_text ) root . focus_force ( ) root . mainloop ( ) return str ( input_text . get ( ) )
Creates a dropdown selection dialog with the specified message and options
50,765
def popFile ( title = "Lackey Open File" ) : root = tk . Tk ( ) root . withdraw ( ) return str ( tkFileDialog . askopenfilename ( title = title ) )
Creates a file selection dialog with the specified message and options .
50,766
def setLocation ( self , x , y ) : self . x = int ( x ) self . y = int ( y ) return self
Set the location of this object to the specified coordinates .
50,767
def offset ( self , dx , dy ) : return Location ( self . x + dx , self . y + dy )
Get a new location which is dx and dy pixels away horizontally and vertically from the current location .
50,768
def getOffset ( self , loc ) : return Location ( loc . x - self . x , loc . y - self . y )
Returns the offset between the given point and this point
50,769
def copyTo ( self , screen ) : from . RegionMatching import Screen if not isinstance ( screen , Screen ) : screen = RegionMatching . Screen ( screen ) return screen . getTopLeft ( ) . offset ( self . getScreen ( ) . getTopLeft ( ) . getOffset ( self ) )
Creates a new point with the same offset on the target screen as this point has on the current screen
50,770
def focusedWindow ( cls ) : x , y , w , h = PlatformManager . getWindowRect ( PlatformManager . getForegroundWindow ( ) ) return Region ( x , y , w , h )
Returns a Region corresponding to whatever window is in the foreground
50,771
def getWindow ( self ) : if self . getPID ( ) != - 1 : return PlatformManager . getWindowTitle ( PlatformManager . getWindowByPID ( self . getPID ( ) ) ) else : return ""
Returns the title of the main window of the currently open app .
50,772
def window ( self , windowNum = 0 ) : if self . _pid == - 1 : return None x , y , w , h = PlatformManager . getWindowRect ( PlatformManager . getWindowByPID ( self . _pid , windowNum ) ) return Region ( x , y , w , h ) . clipRegionToScreen ( )
Returns the region corresponding to the specified window of the app .
50,773
def isRunning ( self , waitTime = 0 ) : waitUntil = time . time ( ) + waitTime while True : if self . getPID ( ) > 0 : return True else : self . _pid = PlatformManager . getWindowPID ( PlatformManager . getWindowByTitle ( re . escape ( self . _title ) ) ) if time . time ( ) > waitUntil : break else : time . sleep ( self . _defaultScanRate ) return self . getPID ( ) > 0
If PID isn t set yet checks if there is a window with the specified title .
50,774
def _getVirtualScreenBitmap ( self ) : filenames = [ ] screen_details = self . getScreenDetails ( ) for screen in screen_details : fh , filepath = tempfile . mkstemp ( '.png' ) filenames . append ( filepath ) os . close ( fh ) subprocess . call ( [ 'screencapture' , '-x' ] + filenames ) min_x , min_y , screen_w , screen_h = self . _getVirtualScreenRect ( ) virtual_screen = Image . new ( "RGB" , ( screen_w , screen_h ) ) for filename , screen in zip ( filenames , screen_details ) : x , y , w , h = screen [ "rect" ] im = Image . open ( filename ) im . load ( ) if im . size [ 0 ] != w or im . size [ 1 ] != h : im = im . resize ( ( int ( w ) , int ( h ) ) , Image . ANTIALIAS ) x = x - min_x y = y - min_y virtual_screen . paste ( im , ( x , y ) ) os . unlink ( filename ) return virtual_screen
Returns a bitmap of all attached screens
50,775
def osCopy ( self ) : k = Keyboard ( ) k . keyDown ( "{CTRL}" ) k . type ( "c" ) k . keyUp ( "{CTRL}" )
Triggers the OS copy keyboard shortcut
50,776
def getForegroundWindow ( self ) : active_app = NSWorkspace . sharedWorkspace ( ) . frontmostApplication ( ) . localizedName ( ) for w in self . _get_window_list ( ) : if "kCGWindowOwnerName" in w and w [ "kCGWindowOwnerName" ] == active_app : return w [ "kCGWindowNumber" ]
Returns a handle to the window in the foreground
50,777
def _get_window_list ( self ) : window_list = Quartz . CGWindowListCopyWindowInfo ( Quartz . kCGWindowListExcludeDesktopElements , Quartz . kCGNullWindowID ) return window_list
Returns a dictionary of details about open windows
50,778
def getProcessName ( self , pid ) : ps = subprocess . check_output ( [ "ps" , "aux" ] ) . decode ( "ascii" ) processes = ps . split ( "\n" ) cols = len ( processes [ 0 ] . split ( ) ) - 1 for row in processes [ 1 : ] : if row != "" : proc = row . split ( None , cols ) if proc [ 1 ] . strip ( ) == str ( pid ) : return proc [ - 1 ]
Searches all processes for the given PID then returns the originating command
50,779
def moveSpeed ( self , location , seconds = 0.3 ) : self . _lock . acquire ( ) original_location = mouse . get_position ( ) mouse . move ( location . x , location . y , duration = seconds ) if mouse . get_position ( ) == original_location and original_location != location . getTuple ( ) : raise IOError ( ) self . _lock . release ( )
Moves cursor to specified Location over seconds .
50,780
def click ( self , loc = None , button = mouse . LEFT ) : if loc is not None : self . moveSpeed ( loc ) self . _lock . acquire ( ) mouse . click ( button ) self . _lock . release ( )
Clicks the specified mouse button .
50,781
def buttonDown ( self , button = mouse . LEFT ) : self . _lock . acquire ( ) mouse . press ( button ) self . _lock . release ( )
Holds down the specified mouse button .
50,782
def buttonUp ( self , button = mouse . LEFT ) : self . _lock . acquire ( ) mouse . release ( button ) self . _lock . release ( )
Releases the specified mouse button .
50,783
def wheel ( self , direction , steps ) : self . _lock . acquire ( ) if direction == 1 : wheel_moved = steps elif direction == 0 : wheel_moved = - 1 * steps else : raise ValueError ( "Expected direction to be 1 or 0" ) self . _lock . release ( ) return mouse . wheel ( wheel_moved )
Clicks the wheel the specified number of steps in the given direction .
50,784
def type ( self , text , delay = 0.1 ) : in_special_code = False special_code = "" modifier_held = False modifier_stuck = False modifier_codes = [ ] for i in range ( 0 , len ( text ) ) : if text [ i ] == "{" : in_special_code = True elif in_special_code and ( text [ i ] == "}" or text [ i ] == " " or i == len ( text ) - 1 ) : in_special_code = False if special_code in self . _SPECIAL_KEYCODES . keys ( ) : keyboard . press_and_release ( self . _SPECIAL_KEYCODES [ special_code ] ) else : keyboard . press ( self . _SPECIAL_KEYCODES [ "SHIFT" ] ) keyboard . press_and_release ( self . _UPPERCASE_KEYCODES [ "{" ] ) keyboard . release ( self . _SPECIAL_KEYCODES [ "SHIFT" ] ) self . type ( special_code ) self . type ( text [ i ] ) special_code = "" elif in_special_code : special_code += text [ i ] elif text [ i ] in self . _REGULAR_KEYCODES . keys ( ) : keyboard . press ( self . _REGULAR_KEYCODES [ text [ i ] ] ) keyboard . release ( self . _REGULAR_KEYCODES [ text [ i ] ] ) elif text [ i ] in self . _UPPERCASE_KEYCODES . keys ( ) : keyboard . press ( self . _SPECIAL_KEYCODES [ "SHIFT" ] ) keyboard . press_and_release ( self . _UPPERCASE_KEYCODES [ text [ i ] ] ) keyboard . release ( self . _SPECIAL_KEYCODES [ "SHIFT" ] ) if delay and not in_special_code : time . sleep ( delay )
Translates a string into a series of keystrokes .
50,785
def findBestMatch ( self , needle , similarity ) : method = cv2 . TM_CCOEFF_NORMED position = None match = cv2 . matchTemplate ( self . haystack , needle , method ) min_val , max_val , min_loc , max_loc = cv2 . minMaxLoc ( match ) if method == cv2 . TM_SQDIFF_NORMED or method == cv2 . TM_SQDIFF : confidence = min_val if min_val <= 1 - similarity : position = min_loc else : confidence = max_val if max_val >= similarity : position = max_loc if not position : return None return ( position , confidence )
Find the best match for needle that has a similarity better than or equal to similarity .
50,786
def findAllMatches ( self , needle , similarity ) : positions = [ ] method = cv2 . TM_CCOEFF_NORMED match = cv2 . matchTemplate ( self . haystack , self . needle , method ) indices = ( - match ) . argpartition ( 100 , axis = None ) [ : 100 ] unraveled_indices = numpy . array ( numpy . unravel_index ( indices , match . shape ) ) . T for location in unraveled_indices : y , x = location confidence = match [ y ] [ x ] if method == cv2 . TM_SQDIFF_NORMED or method == cv2 . TM_SQDIFF : if confidence <= 1 - similarity : positions . append ( ( ( x , y ) , confidence ) ) else : if confidence >= similarity : positions . append ( ( ( x , y ) , confidence ) ) positions . sort ( key = lambda x : ( x [ 0 ] [ 1 ] , x [ 0 ] [ 0 ] ) ) return positions
Find all matches for needle with confidence better than or equal to similarity .
50,787
def findAllMatches ( self , needle , similarity ) : positions = [ ] while True : best_match = self . findBestMatch ( needle , similarity ) if best_match is None : break positions . append ( best_match ) x , y = best_match [ 0 ] w = needle . shape [ 1 ] h = needle . shape [ 0 ] roi = ( x , y , w , h ) roi_slice = ( slice ( roi [ 1 ] , roi [ 1 ] + roi [ 3 ] ) , slice ( roi [ 0 ] , roi [ 0 ] + roi [ 2 ] ) ) self . haystack [ roi_slice ] = 0 positions . sort ( key = lambda x : ( x [ 0 ] [ 1 ] , x [ 0 ] [ 0 ] ) ) return positions
Finds all matches above similarity using a search pyramid to improve efficiency
50,788
def _build_pyramid ( self , image , levels ) : pyramid = [ image ] for l in range ( levels - 1 ) : if any ( x < 20 for x in pyramid [ - 1 ] . shape [ : 2 ] ) : break pyramid . append ( cv2 . pyrDown ( pyramid [ - 1 ] ) ) return list ( reversed ( pyramid ) )
Returns a list of reduced - size images from smallest to original size
50,789
def count_weights ( scope = None , exclude = None , graph = None ) : if scope : scope = scope if scope . endswith ( '/' ) else scope + '/' graph = graph or tf . get_default_graph ( ) vars_ = graph . get_collection ( tf . GraphKeys . TRAINABLE_VARIABLES ) if scope : vars_ = [ var for var in vars_ if var . name . startswith ( scope ) ] if exclude : exclude = re . compile ( exclude ) vars_ = [ var for var in vars_ if not exclude . match ( var . name ) ] shapes = [ var . get_shape ( ) . as_list ( ) for var in vars_ ] return int ( sum ( np . prod ( shape ) for shape in shapes ) )
Count learnable parameters .
50,790
def _custom_diag_normal_kl ( lhs , rhs , name = None ) : with tf . name_scope ( name or 'kl_divergence' ) : mean0 = lhs . mean ( ) mean1 = rhs . mean ( ) logstd0 = tf . log ( lhs . stddev ( ) ) logstd1 = tf . log ( rhs . stddev ( ) ) logstd0_2 , logstd1_2 = 2 * logstd0 , 2 * logstd1 return 0.5 * ( tf . reduce_sum ( tf . exp ( logstd0_2 - logstd1_2 ) , - 1 ) + tf . reduce_sum ( ( mean1 - mean0 ) ** 2 / tf . exp ( logstd1_2 ) , - 1 ) + tf . reduce_sum ( logstd1_2 , - 1 ) - tf . reduce_sum ( logstd0_2 , - 1 ) - mean0 . shape [ - 1 ] . value )
Empirical KL divergence of two normals with diagonal covariance .
50,791
def define_simulation_graph ( batch_env , algo_cls , config ) : step = tf . Variable ( 0 , False , dtype = tf . int32 , name = 'global_step' ) is_training = tf . placeholder ( tf . bool , name = 'is_training' ) should_log = tf . placeholder ( tf . bool , name = 'should_log' ) do_report = tf . placeholder ( tf . bool , name = 'do_report' ) force_reset = tf . placeholder ( tf . bool , name = 'force_reset' ) algo = algo_cls ( batch_env , step , is_training , should_log , config ) done , score , summary = tools . simulate ( batch_env , algo , should_log , force_reset ) message = 'Graph contains {} trainable variables.' tf . logging . info ( message . format ( tools . count_weights ( ) ) ) return tools . AttrDict ( locals ( ) )
Define the algorithm and environment interaction .
50,792
def define_batch_env ( constructor , num_agents , env_processes ) : with tf . variable_scope ( 'environments' ) : if env_processes : envs = [ tools . wrappers . ExternalProcess ( constructor ) for _ in range ( num_agents ) ] else : envs = [ constructor ( ) for _ in range ( num_agents ) ] batch_env = tools . BatchEnv ( envs , blocking = not env_processes ) batch_env = tools . InGraphBatchEnv ( batch_env ) return batch_env
Create environments and apply all desired wrappers .
50,793
def define_saver ( exclude = None ) : variables = [ ] exclude = exclude or [ ] exclude = [ re . compile ( regex ) for regex in exclude ] for variable in tf . global_variables ( ) : if any ( regex . match ( variable . name ) for regex in exclude ) : continue variables . append ( variable ) saver = tf . train . Saver ( variables , keep_checkpoint_every_n_hours = 5 ) return saver
Create a saver for the variables we want to checkpoint .
50,794
def initialize_variables ( sess , saver , logdir , checkpoint = None , resume = None ) : sess . run ( tf . group ( tf . local_variables_initializer ( ) , tf . global_variables_initializer ( ) ) ) if resume and not ( logdir or checkpoint ) : raise ValueError ( 'Need to specify logdir to resume a checkpoint.' ) if logdir : state = tf . train . get_checkpoint_state ( logdir ) if checkpoint : checkpoint = os . path . join ( logdir , checkpoint ) if not checkpoint and state and state . model_checkpoint_path : checkpoint = state . model_checkpoint_path if checkpoint and resume is False : message = 'Found unexpected checkpoint when starting a new run.' raise RuntimeError ( message ) if checkpoint : saver . restore ( sess , checkpoint )
Initialize or restore variables from a checkpoint if available .
50,795
def save_config ( config , logdir = None ) : if logdir : with config . unlocked : config . logdir = logdir message = 'Start a new run and write summaries and checkpoints to {}.' tf . logging . info ( message . format ( config . logdir ) ) tf . gfile . MakeDirs ( config . logdir ) config_path = os . path . join ( config . logdir , 'config.yaml' ) with tf . gfile . FastGFile ( config_path , 'w' ) as file_ : yaml . dump ( config , file_ , default_flow_style = False ) else : message = ( 'Start a new run without storing summaries and checkpoints since no ' 'logging directory was specified.' ) tf . logging . info ( message ) return config
Save a new configuration by name .
50,796
def load_config ( logdir ) : config_path = logdir and os . path . join ( logdir , 'config.yaml' ) if not config_path or not tf . gfile . Exists ( config_path ) : message = ( 'Cannot resume an existing run since the logging directory does not ' 'contain a configuration file.' ) raise IOError ( message ) with tf . gfile . FastGFile ( config_path , 'r' ) as file_ : config = yaml . load ( file_ , Loader = yaml . Loader ) message = 'Resume run and write summaries and checkpoints to {}.' tf . logging . info ( message . format ( config . logdir ) ) return config
Load a configuration from the log directory .
50,797
def set_up_logging ( ) : tf . logging . set_verbosity ( tf . logging . INFO ) logging . getLogger ( 'tensorflow' ) . propagate = False
Configure the TensorFlow logger .
50,798
def _define_loop ( graph , eval_steps ) : loop = tools . Loop ( None , graph . step , graph . should_log , graph . do_report , graph . force_reset ) loop . add_phase ( 'eval' , graph . done , graph . score , graph . summary , eval_steps , report_every = eval_steps , log_every = None , checkpoint_every = None , feed = { graph . is_training : False } ) return loop
Create and configure an evaluation loop .
50,799
def visualize ( logdir , outdir , num_agents , num_episodes , checkpoint = None , env_processes = True ) : config = utility . load_config ( logdir ) with tf . device ( '/cpu:0' ) : batch_env = utility . define_batch_env ( lambda : _create_environment ( config , outdir ) , num_agents , env_processes ) graph = utility . define_simulation_graph ( batch_env , config . algorithm , config ) total_steps = num_episodes * config . max_length loop = _define_loop ( graph , total_steps ) saver = utility . define_saver ( exclude = ( r'.*_temporary.*' , r'global_step' ) ) sess_config = tf . ConfigProto ( allow_soft_placement = True ) sess_config . gpu_options . allow_growth = True with tf . Session ( config = sess_config ) as sess : utility . initialize_variables ( sess , saver , config . logdir , checkpoint , resume = True ) for unused_score in loop . run ( sess , saver , total_steps ) : pass batch_env . close ( )
Recover checkpoint and render videos from it .