idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
239,500
def start_tpot ( automated_run , session , path ) : module = functions . import_string_code_as_module ( automated_run . source ) extraction = session . query ( models . Extraction ) . first ( ) X , y = extraction . return_train_dataset ( ) tpot_learner = module . tpot_learner tpot_learner . fit ( X , y ) temp_filename ...
Starts a TPOT automated run that exports directly to base learner setup
239,501
def start_greedy_ensemble_search ( automated_run , session , path ) : module = functions . import_string_code_as_module ( automated_run . source ) assert module . metric_to_optimize in automated_run . base_learner_origin . metric_generators best_ensemble = [ ] secondary_learner = automated_run . base_learner_origin . r...
Starts an automated ensemble search using greedy forward model selection .
239,502
def extraction_data_statistics ( path ) : with functions . DBContextManager ( path ) as session : extraction = session . query ( models . Extraction ) . first ( ) X , y = extraction . return_main_dataset ( ) functions . verify_dataset ( X , y ) if extraction . test_dataset [ 'method' ] == 'split_from_main' : X , X_test...
Generates data statistics for the given data extraction setup stored in Xcessiv notebook .
239,503
def generate_meta_features ( path , base_learner_id ) : with functions . DBContextManager ( path ) as session : base_learner = session . query ( models . BaseLearner ) . filter_by ( id = base_learner_id ) . first ( ) if not base_learner : raise exceptions . UserError ( 'Base learner {} ' 'does not exist' . format ( bas...
Generates meta - features for specified base learner
239,504
def start_automated_run ( path , automated_run_id ) : with functions . DBContextManager ( path ) as session : automated_run = session . query ( models . AutomatedRun ) . filter_by ( id = automated_run_id ) . first ( ) if not automated_run : raise exceptions . UserError ( 'Automated run {} ' 'does not exist' . format ( ...
Starts automated run . This will automatically create base learners until the run finishes or errors out .
239,505
def hash_file ( path , block_size = 65536 ) : sha256 = hashlib . sha256 ( ) with open ( path , 'rb' ) as f : for block in iter ( lambda : f . read ( block_size ) , b'' ) : sha256 . update ( block ) return sha256 . hexdigest ( )
Returns SHA256 checksum of a file
239,506
def import_object_from_path ( path , object ) : with open ( path ) as f : return import_object_from_string_code ( f . read ( ) , object )
Used to import an object from an absolute path .
239,507
def import_object_from_string_code ( code , object ) : sha256 = hashlib . sha256 ( code . encode ( 'UTF-8' ) ) . hexdigest ( ) module = imp . new_module ( sha256 ) try : exec_ ( code , module . __dict__ ) except Exception as e : raise exceptions . UserError ( 'User code exception' , exception_message = str ( e ) ) sys ...
Used to import an object from arbitrary passed code .
239,508
def import_string_code_as_module ( code ) : sha256 = hashlib . sha256 ( code . encode ( 'UTF-8' ) ) . hexdigest ( ) module = imp . new_module ( sha256 ) try : exec_ ( code , module . __dict__ ) except Exception as e : raise exceptions . UserError ( 'User code exception' , exception_message = str ( e ) ) sys . modules [...
Used to run arbitrary passed code as a module
239,509
def verify_dataset ( X , y ) : X_shape , y_shape = np . array ( X ) . shape , np . array ( y ) . shape if len ( X_shape ) != 2 : raise exceptions . UserError ( "X must be 2-dimensional array" ) if len ( y_shape ) != 1 : raise exceptions . UserError ( "y must be 1-dimensional array" ) if X_shape [ 0 ] != y_shape [ 0 ] :...
Verifies if a dataset is valid for use i . e . scikit - learn format
239,510
def make_serializable ( json ) : new_dict = dict ( ) for key , value in iteritems ( json ) : if is_valid_json ( value ) : new_dict [ key ] = value return new_dict
This function ensures that the dictionary is JSON serializable . If not keys with non - serializable values are removed from the return value .
239,511
def get_sample_dataset ( dataset_properties ) : kwargs = dataset_properties . copy ( ) data_type = kwargs . pop ( 'type' ) if data_type == 'multiclass' : try : X , y = datasets . make_classification ( random_state = 8 , ** kwargs ) splits = model_selection . StratifiedKFold ( n_splits = 2 , random_state = 8 ) . split (...
Returns sample dataset
239,512
def verify_estimator_class ( est , meta_feature_generator , metric_generators , dataset_properties ) : X , y , splits = get_sample_dataset ( dataset_properties ) if not hasattr ( est , "get_params" ) : raise exceptions . UserError ( 'Estimator does not have get_params method' ) if not hasattr ( est , "set_params" ) : r...
Verify if estimator object is valid for use i . e . scikit - learn format
239,513
def get_path_from_query_string ( req ) : if req . args . get ( 'path' ) is None : raise exceptions . UserError ( 'Path not found in query string' ) return req . args . get ( 'path' )
Gets path from query string
239,514
def return_main_dataset ( self ) : if not self . main_dataset [ 'source' ] : raise exceptions . UserError ( 'Source is empty' ) extraction_code = self . main_dataset [ "source" ] extraction_function = functions . import_object_from_string_code ( extraction_code , "extract_main_dataset" ) try : X , y = extraction_functi...
Returns main data set from self
239,515
def return_train_dataset ( self ) : X , y = self . return_main_dataset ( ) if self . test_dataset [ 'method' ] == 'split_from_main' : X , X_test , y , y_test = train_test_split ( X , y , test_size = self . test_dataset [ 'split_ratio' ] , random_state = self . test_dataset [ 'split_seed' ] , stratify = y ) return X , y
Returns train data set
239,516
def return_estimator ( self ) : extraction_code = self . source estimator = functions . import_object_from_string_code ( extraction_code , "base_learner" ) return estimator
Returns estimator from base learner origin
239,517
def export_as_file ( self , filepath , hyperparameters ) : if not filepath . endswith ( '.py' ) : filepath += '.py' file_contents = '' file_contents += self . source file_contents += '\n\nbase_learner.set_params(**{})\n' . format ( hyperparameters ) file_contents += '\nmeta_feature_generator = "{}"\n' . format ( self ....
Generates a Python file with the importable base learner set to hyperparameters
239,518
def return_estimator ( self ) : estimator = self . base_learner_origin . return_estimator ( ) estimator = estimator . set_params ( ** self . hyperparameters ) return estimator
Returns base learner using its origin and the given hyperparameters
239,519
def meta_features_path ( self , path ) : return os . path . join ( path , app . config [ 'XCESSIV_META_FEATURES_FOLDER' ] , str ( self . id ) ) + '.npy'
Returns path for meta - features
239,520
def delete_meta_features ( self , path ) : if os . path . exists ( self . meta_features_path ( path ) ) : os . remove ( self . meta_features_path ( path ) )
Deletes meta - features of base learner if it exists
239,521
def return_secondary_learner ( self ) : estimator = self . base_learner_origin . return_estimator ( ) estimator = estimator . set_params ( ** self . secondary_learner_hyperparameters ) return estimator
Returns secondary learner using its origin and the given hyperparameters
239,522
def export_as_code ( self , cv_source ) : rand_value = '' . join ( random . choice ( string . ascii_uppercase + string . digits ) for _ in range ( 25 ) ) base_learner_code = '' base_learner_code += 'base_learner_list_{} = []\n' . format ( rand_value ) base_learner_code += 'meta_feature_generators_list_{} = []\n\n' . fo...
Returns a string value that contains the Python code for the ensemble
239,523
def export_as_file ( self , file_path , cv_source ) : if os . path . exists ( file_path ) : raise exceptions . UserError ( '{} already exists' . format ( file_path ) ) with open ( file_path , 'wb' ) as f : f . write ( self . export_as_code ( cv_source ) . encode ( 'utf8' ) )
Export the ensemble as a single Python file and saves it to file_path .
239,524
def export_as_package ( self , package_path , cv_source ) : if os . path . exists ( package_path ) : raise exceptions . UserError ( '{} already exists' . format ( package_path ) ) package_name = os . path . basename ( os . path . normpath ( package_path ) ) os . makedirs ( package_path ) with open ( os . path . join ( ...
Exports the ensemble as a Python package and saves it to package_path .
239,525
def verify_full_extraction ( ) : path = functions . get_path_from_query_string ( request ) if request . method == 'POST' : rqtasks . extraction_data_statistics ( path ) with functions . DBContextManager ( path ) as session : extraction = session . query ( models . Extraction ) . first ( ) return jsonify ( extraction . ...
This is an experimental endpoint to simultaneously verify data statistics and extraction for training test and holdout datasets . With this the other three verification methods will no longer be necessary .
239,526
def create_base_learner ( id ) : path = functions . get_path_from_query_string ( request ) with functions . DBContextManager ( path ) as session : base_learner_origin = session . query ( models . BaseLearnerOrigin ) . filter_by ( id = id ) . first ( ) if base_learner_origin is None : raise exceptions . UserError ( 'Bas...
This creates a single base learner from a base learner origin and queues it up
239,527
def search_base_learner ( id ) : path = functions . get_path_from_query_string ( request ) req_body = request . get_json ( ) if req_body [ 'method' ] == 'grid' : param_grid = functions . import_object_from_string_code ( req_body [ 'source' ] , 'param_grid' ) iterator = ParameterGrid ( param_grid ) elif req_body [ 'meth...
Creates a set of base learners from base learner origin using grid search and queues them up
239,528
def get_automated_runs ( ) : path = functions . get_path_from_query_string ( request ) if request . method == 'GET' : with functions . DBContextManager ( path ) as session : automated_runs = session . query ( models . AutomatedRun ) . all ( ) return jsonify ( list ( map ( lambda x : x . serialize , automated_runs ) ) )...
Return all automated runs
239,529
def _process_using_meta_feature_generator ( self , X , meta_feature_generator ) : all_learner_meta_features = [ ] for idx , base_learner in enumerate ( self . base_learners ) : single_learner_meta_features = getattr ( base_learner , self . meta_feature_generators [ idx ] ) ( X ) if len ( single_learner_meta_features . ...
Process using secondary learner meta - feature generator
239,530
def NewEvent ( type : str , id : UUID = None , data : JsonDict = None , metadata : JsonDict = None ) -> NewEventData : return NewEventData ( id or uuid4 ( ) , type , data , metadata )
Build the data structure for a new event .
239,531
def from_bytes ( cls , data ) : len_username = int . from_bytes ( data [ 0 : 2 ] , byteorder = "big" ) offset_username = 2 + len_username username = data [ 2 : offset_username ] . decode ( "UTF-8" ) offset_password = 2 + offset_username len_password = int . from_bytes ( data [ offset_username : offset_password ] , byte...
I am so sorry .
239,532
def connect ( host = "localhost" , port = 1113 , discovery_host = None , discovery_port = 2113 , username = None , password = None , loop = None , name = None , selector = select_random , ) -> Client : discovery = get_discoverer ( host , port , discovery_host , discovery_port , selector ) dispatcher = MessageDispatcher...
Create a new client .
239,533
async def start ( self ) : while True : try : data = await self . reader . read ( 8192 ) if self . _trace_enabled : self . _logger . trace ( "Received %d bytes from remote server:\n%s" , len ( data ) , msg . dump ( data ) , ) await self . process ( data ) except asyncio . CancelledError : return except : logging . exce...
Loop forever reading messages and invoking the operation that caused them
239,534
async def ping ( self , conversation_id : uuid . UUID = None ) -> float : cmd = convo . Ping ( conversation_id = conversation_id or uuid . uuid4 ( ) ) result = await self . dispatcher . start_conversation ( cmd ) return await result
Send a message to the remote server to check liveness .
239,535
async def publish_event ( self , stream : str , type : str , body : Optional [ Any ] = None , id : Optional [ uuid . UUID ] = None , metadata : Optional [ Any ] = None , expected_version : int = - 2 , require_master : bool = False , ) -> None : event = msg . NewEvent ( type , id or uuid . uuid4 ( ) , body , metadata ) ...
Publish a single event to the EventStore .
239,536
async def get_event ( self , stream : str , event_number : int , resolve_links = True , require_master = False , correlation_id : uuid . UUID = None , ) -> msg . Event : correlation_id = correlation_id or uuid . uuid4 ( ) cmd = convo . ReadEvent ( stream , event_number , resolve_links , require_master , conversation_id...
Get a single event by stream and event number .
239,537
async def get ( self , stream : str , direction : msg . StreamDirection = msg . StreamDirection . Forward , from_event : int = 0 , max_count : int = 100 , resolve_links : bool = True , require_master : bool = False , correlation_id : uuid . UUID = None , ) : correlation_id = correlation_id cmd = convo . ReadStreamEvent...
Read a range of events from a stream .
239,538
async def get_all ( self , direction : msg . StreamDirection = msg . StreamDirection . Forward , from_position : Optional [ Union [ msg . Position , msg . _PositionSentinel ] ] = None , max_count : int = 100 , resolve_links : bool = True , require_master : bool = False , correlation_id : uuid . UUID = None , ) : correl...
Read a range of events from the whole database .
239,539
async def iter ( self , stream : str , direction : msg . StreamDirection = msg . StreamDirection . Forward , from_event : int = None , batch_size : int = 100 , resolve_links : bool = True , require_master : bool = False , correlation_id : uuid . UUID = None , ) : correlation_id = correlation_id or uuid . uuid4 ( ) cmd ...
Read through a stream of events until the end and then stop .
239,540
async def iter_all ( self , direction : msg . StreamDirection = msg . StreamDirection . Forward , from_position : Optional [ Union [ msg . Position , msg . _PositionSentinel ] ] = None , batch_size : int = 100 , resolve_links : bool = True , require_master : bool = False , correlation_id : Optional [ uuid . UUID ] = No...
Read through all the events in the database .
239,541
async def subscribe_to ( self , stream , start_from = - 1 , resolve_link_tos = True , batch_size : int = 100 ) : if start_from == - 1 : cmd : convo . Conversation = convo . SubscribeToStream ( stream , resolve_link_tos , credentials = self . credential ) else : cmd = convo . CatchupSubscription ( stream , start_from , ...
Subscribe to receive notifications when a new event is published to a stream .
239,542
def prefer_master ( nodes : List [ DiscoveredNode ] ) -> Optional [ DiscoveredNode ] : return max ( nodes , key = attrgetter ( "state" ) )
Select the master if available otherwise fall back to a replica .
239,543
def prefer_replica ( nodes : List [ DiscoveredNode ] ) -> Optional [ DiscoveredNode ] : masters = [ node for node in nodes if node . state == NodeState . Master ] replicas = [ node for node in nodes if node . state != NodeState . Master ] if replicas : return random . choice ( replicas ) else : return masters [ 0 ]
Select a random replica if any are available or fall back to the master .
239,544
def create_event_handler ( event_type , handler ) : target_name = '{hash}_{event_type}' . format ( hash = hash ( handler ) , event_type = event_type ) def handle_comm_opened ( comm , msg ) : @ comm . on_msg def _handle_msg ( msg ) : data = msg [ 'content' ] [ 'data' ] event = json . loads ( data ) return_value = handle...
Register a comm and return a serializable object with target name
239,545
def to_json ( el , schema = None ) : if type ( el ) is str : json_el = el elif type ( el ) is list : json_el = list ( map ( to_json , el ) ) elif type ( el ) is dict : assert 'tagName' in el json_el = el . copy ( ) if 'attributes' not in el : json_el [ 'attributes' ] = { } if 'children' not in el : json_el [ 'children'...
Convert an element to VDOM JSON
239,546
def create_component ( tag_name , allow_children = True ) : def _component ( * children , ** kwargs ) : if 'children' in kwargs : children = kwargs . pop ( 'children' ) else : if len ( children ) == 1 and isinstance ( children [ 0 ] , list ) : children = tuple ( children [ 0 ] ) style = None event_handlers = None attri...
Create a component for an HTML Tag
239,547
def validate ( self , schema ) : try : validate ( instance = self . to_dict ( ) , schema = schema , cls = Draft4Validator ) except ValidationError as e : raise ValidationError ( _validate_err_template . format ( VDOM_SCHEMA , e ) )
Validate VDOM against given JSON Schema
239,548
def to_dict ( self ) : attributes = dict ( self . attributes . items ( ) ) if self . style : attributes . update ( { "style" : dict ( self . style . items ( ) ) } ) vdom_dict = { 'tagName' : self . tag_name , 'attributes' : attributes } if self . event_handlers : event_handlers = dict ( self . event_handlers . items ( ...
Converts VDOM object to a dictionary that passes our schema
239,549
def _guess_type ( mrz_lines ) : try : if len ( mrz_lines ) == 3 : return 'TD1' elif len ( mrz_lines ) == 2 and len ( mrz_lines [ 0 ] ) < 40 and len ( mrz_lines [ 1 ] ) < 40 : return 'MRVB' if mrz_lines [ 0 ] [ 0 ] . upper ( ) == 'V' else 'TD2' elif len ( mrz_lines ) == 2 : return 'MRVA' if mrz_lines [ 0 ] [ 0 ] . upper...
Guesses the type of the MRZ from given lines . Returns TD1 TD2 TD3 MRVA MRVB or None . The algorithm is basically just counting lines looking at their length and checking whether the first character is a V
239,550
def remove_component ( self , name ) : if name not in self . components : raise Exception ( "No component named %s" % name ) del self . components [ name ] del self . depends [ name ] for p in self . provides [ name ] : del self . whoprovides [ p ] self . invalidate ( p ) del self . provides [ name ]
Removes an existing component with a given name invalidating all the values computed by the previous component .
239,551
def replace_component ( self , name , callable , provides = None , depends = None ) : self . remove_component ( name ) self . add_component ( name , callable , provides , depends )
Changes an existing component with a given name invalidating all the values computed by the previous component and its successors .
239,552
def invalidate ( self , key ) : if key not in self . data : return del self . data [ key ] for cname in self . components : if key in self . depends [ cname ] : for downstream_key in self . provides [ cname ] : self . invalidate ( downstream_key )
Remove the given data item along with all items that depend on it in the graph .
239,553
def ocr ( img , mrz_mode = True , extra_cmdline_params = '' ) : input_file_name = '%s.bmp' % _tempnam ( ) output_file_name_base = '%s' % _tempnam ( ) output_file_name = "%s.txt" % output_file_name_base try : if str ( img . dtype ) . startswith ( 'float' ) and np . nanmin ( img ) >= 0 and np . nanmax ( img ) <= 1 : img ...
Runs Tesseract on a given image . Writes an intermediate tempfile and then runs the tesseract command on the image .
239,554
def approx_equal ( self , center , width , height , angle , tol = 1e-6 ) : "Method mainly useful for testing" return abs ( self . cx - center [ 0 ] ) < tol and abs ( self . cy - center [ 1 ] ) < tol and abs ( self . width - width ) < tol and abs ( self . height - height ) < tol and abs ( self . angle - angle ) < tol
Method mainly useful for testing
239,555
def rotated ( self , rotation_center , angle ) : rot = np . array ( [ [ np . cos ( angle ) , np . sin ( angle ) ] , [ - np . sin ( angle ) , np . cos ( angle ) ] ] ) t = np . asfarray ( rotation_center ) new_c = np . dot ( rot . T , ( self . center - t ) ) + t return RotatedBox ( new_c , self . width , self . height , ...
Returns a RotatedBox that is obtained by rotating this box around a given center by a given angle .
239,556
def as_poly ( self , margin_width = 0 , margin_height = 0 ) : v_hor = ( self . width / 2 + margin_width ) * np . array ( [ np . cos ( self . angle ) , np . sin ( self . angle ) ] ) v_vert = ( self . height / 2 + margin_height ) * np . array ( [ - np . sin ( self . angle ) , np . cos ( self . angle ) ] ) c = np . array ...
Converts this box to a polygon i . e . 4x2 array representing the four corners starting from lower left to upper left counterclockwise .
239,557
def extract_from_image ( self , img , scale = 1.0 , margin_width = 5 , margin_height = 5 ) : rotate_by = ( np . pi / 2 - self . angle ) * 180 / np . pi img_rotated = transform . rotate ( img , angle = rotate_by , center = [ self . center [ 1 ] * scale , self . center [ 0 ] * scale ] , resize = True ) shift_c , shift_r ...
Extracts the contents of this box from a given image . For that the image is unrotated by the appropriate angle and the corresponding part is extracted from it .
239,558
def read_mrz ( file , save_roi = False , extra_cmdline_params = '' ) : p = MRZPipeline ( file , extra_cmdline_params ) mrz = p . result if mrz is not None : mrz . aux [ 'text' ] = p [ 'text' ] if save_roi : mrz . aux [ 'roi' ] = p [ 'roi' ] return mrz
The main interface function to this module encapsulating the recognition pipeline . Given an image filename runs MRZPipeline on it returning the parsed MRZ object .
239,559
def _imread ( self , file ) : img = skimage_io . imread ( file , as_gray = self . as_gray , plugin = 'imageio' ) if img is not None and len ( img . shape ) != 2 : img = skimage_io . imread ( file , as_gray = self . as_gray , plugin = 'matplotlib' ) return img
Proxy to skimage . io . imread with some fixes .
239,560
def _are_aligned_angles ( self , b1 , b2 ) : "Are two boxes aligned according to their angle?" return abs ( b1 - b2 ) <= self . angle_tol or abs ( np . pi - abs ( b1 - b2 ) ) <= self . angle_tol
Are two boxes aligned according to their angle?
239,561
def _are_nearby_parallel_boxes ( self , b1 , b2 ) : "Are two boxes nearby, parallel, and similar in width?" if not self . _are_aligned_angles ( b1 . angle , b2 . angle ) : return False angle = min ( b1 . angle , b2 . angle ) return abs ( np . dot ( b1 . center - b2 . center , [ - np . sin ( angle ) , np . cos ( angle )...
Are two boxes nearby parallel and similar in width?
239,562
def _merge_any_two_boxes ( self , box_list ) : n = len ( box_list ) for i in range ( n ) : for j in range ( i + 1 , n ) : if self . _are_nearby_parallel_boxes ( box_list [ i ] , box_list [ j ] ) : a , b = box_list [ i ] , box_list [ j ] merged_points = np . vstack ( [ a . points , b . points ] ) merged_box = RotatedBox...
Given a list of boxes finds two nearby parallel ones and merges them . Returns false if none found .
239,563
def _try_larger_image ( self , roi , cur_text , cur_mrz , filter_order = 3 ) : if roi . shape [ 1 ] <= 700 : scale_by = int ( 1050.0 / roi . shape [ 1 ] + 0.5 ) roi_lg = transform . rescale ( roi , scale_by , order = filter_order , mode = 'constant' , multichannel = False , anti_aliasing = True ) new_text = ocr ( roi_l...
Attempts to improve the OCR result by scaling the image . If the new mrz is better returns it otherwise returns the old mrz .
239,564
def mrz ( ) : parser = argparse . ArgumentParser ( description = 'Run the MRZ OCR recognition algorithm on the given image.' ) parser . add_argument ( 'filename' ) parser . add_argument ( '--json' , action = 'store_true' , help = 'Produce JSON (rather than tabular) output' ) parser . add_argument ( '--legacy' , action ...
Command - line script for extracting MRZ from a given image
239,565
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
239,566
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
239,567
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 .
239,568
def osPaste ( self ) : from . InputEmulation import Keyboard k = Keyboard ( ) k . keyDown ( "{CTRL}" ) k . type ( "v" ) k . keyUp ( "{CTRL}" )
Triggers the OS paste keyboard shortcut
239,569
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
239,570
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
239,571
def similar ( self , similarity ) : pattern = Pattern ( self . path ) pattern . similarity = similarity return pattern
Returns a new Pattern with the specified similarity threshold
239,572
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
239,573
def debugPreview ( self , title = "Debug" ) : haystack = Image . open ( self . path ) haystack . show ( )
Loads and displays the image at Pattern . path
239,574
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
239,575
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
239,576
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
239,577
def getCenter ( self ) : return Location ( self . x + ( self . w / 2 ) , self . y + ( self . h / 2 ) )
Return the Location of the center of this region
239,578
def getBottomRight ( self ) : return Location ( self . x + self . w , self . y + self . h )
Return the Location of the bottom right corner of this region
239,579
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
239,580
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 .
239,581
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 .
239,582
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 .
239,583
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 .
239,584
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
239,585
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 .
239,586
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
239,587
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 .
239,588
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 .
239,589
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
239,590
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 .
239,591
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
239,592
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 .
239,593
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
239,594
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
239,595
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
239,596
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
239,597
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
239,598
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
239,599
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