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 . wintype...
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 ...
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_Q...
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...
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" ) ...
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...
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...
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 T...
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...
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 isinsta...
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 ...
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 ( dra...
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...
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 )...
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 ....
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 ....
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_fil...
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_chan...
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 ( "Exp...
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" ) ...
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 {}: ({}, {}...
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 y...
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: " + fil...
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 ] ...
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 con...
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 ( ) ...
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 ( sel...
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 , scree...
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 p...
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...
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 ) ...
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 i...
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 . ...
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 = ( slic...
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 . startsw...
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 ...
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 , ...
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 ( ...
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 ( v...
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...
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...
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 ...
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 = {...
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 . ...
Recover checkpoint and render videos from it .