idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
33,600
def send_password_reset_notice ( user ) : if config_value ( 'SEND_PASSWORD_RESET_NOTICE_EMAIL' ) : _security . send_mail ( config_value ( 'EMAIL_SUBJECT_PASSWORD_NOTICE' ) , user . email , 'reset_notice' , user = user )
Sends the password reset notice email for the specified user .
33,601
def update_password ( user , password ) : user . password = hash_password ( password ) _datastore . put ( user ) send_password_reset_notice ( user ) password_reset . send ( app . _get_current_object ( ) , user = user )
Update the specified user s password
33,602
def init_app ( self , app , datastore = None , register_blueprint = None , ** kwargs ) : self . app = app if datastore is None : datastore = self . _datastore if register_blueprint is None : register_blueprint = self . _register_blueprint for key , value in self . _kwargs . items ( ) : kwargs . setdefault ( key , value...
Initializes the Flask - Security extension for the specified application and datastore implementation .
33,603
def login ( ) : form_class = _security . login_form if request . is_json : form = form_class ( MultiDict ( request . get_json ( ) ) ) else : form = form_class ( request . form ) if form . validate_on_submit ( ) : login_user ( form . user , remember = form . remember . data ) after_this_request ( _commit ) if not reques...
View function for login view
33,604
def register ( ) : if _security . confirmable or request . is_json : form_class = _security . confirm_register_form else : form_class = _security . register_form if request . is_json : form_data = MultiDict ( request . get_json ( ) ) else : form_data = request . form form = form_class ( form_data ) if form . validate_o...
View function which handles a registration request .
33,605
def send_login ( ) : form_class = _security . passwordless_login_form if request . is_json : form = form_class ( MultiDict ( request . get_json ( ) ) ) else : form = form_class ( ) if form . validate_on_submit ( ) : send_login_instructions ( form . user ) if not request . is_json : do_flash ( * get_message ( 'LOGIN_EMA...
View function that sends login instructions for passwordless login
33,606
def token_login ( token ) : expired , invalid , user = login_token_status ( token ) if invalid : do_flash ( * get_message ( 'INVALID_LOGIN_TOKEN' ) ) if expired : send_login_instructions ( user ) do_flash ( * get_message ( 'LOGIN_EXPIRED' , email = user . email , within = _security . login_within ) ) if invalid or expi...
View function that handles passwordless login via a token
33,607
def send_confirmation ( ) : form_class = _security . send_confirmation_form if request . is_json : form = form_class ( MultiDict ( request . get_json ( ) ) ) else : form = form_class ( ) if form . validate_on_submit ( ) : send_confirmation_instructions ( form . user ) if not request . is_json : do_flash ( * get_message...
View function which sends confirmation instructions .
33,608
def confirm_email ( token ) : expired , invalid , user = confirm_email_token_status ( token ) if not user or invalid : invalid = True do_flash ( * get_message ( 'INVALID_CONFIRMATION_TOKEN' ) ) already_confirmed = user is not None and user . confirmed_at is not None if expired and not already_confirmed : send_confirmat...
View function which handles a email confirmation request .
33,609
def forgot_password ( ) : form_class = _security . forgot_password_form if request . is_json : form = form_class ( MultiDict ( request . get_json ( ) ) ) else : form = form_class ( ) if form . validate_on_submit ( ) : send_reset_password_instructions ( form . user ) if not request . is_json : do_flash ( * get_message (...
View function that handles a forgotten password request .
33,610
def reset_password ( token ) : expired , invalid , user = reset_password_token_status ( token ) if not user or invalid : invalid = True do_flash ( * get_message ( 'INVALID_RESET_PASSWORD_TOKEN' ) ) if expired : send_reset_password_instructions ( user ) do_flash ( * get_message ( 'PASSWORD_RESET_EXPIRED' , email = user ...
View function that handles a reset password request .
33,611
def change_password ( ) : form_class = _security . change_password_form if request . is_json : form = form_class ( MultiDict ( request . get_json ( ) ) ) else : form = form_class ( ) if form . validate_on_submit ( ) : after_this_request ( _commit ) change_user_password ( current_user . _get_current_object ( ) , form . ...
View function which handles a change password request .
33,612
def create_blueprint ( state , import_name ) : bp = Blueprint ( state . blueprint_name , import_name , url_prefix = state . url_prefix , subdomain = state . subdomain , template_folder = 'templates' ) bp . route ( state . logout_url , endpoint = 'logout' ) ( logout ) if state . passwordless : bp . route ( state . login...
Creates the security extension blueprint
33,613
def login_user ( user , remember = None ) : if remember is None : remember = config_value ( 'DEFAULT_REMEMBER_ME' ) if not _login_user ( user , remember ) : return False if _security . trackable : remote_addr = request . remote_addr or None old_current_login , new_current_login = ( user . current_login_at , _security ....
Perform the login routine .
33,614
def logout_user ( ) : for key in ( 'identity.name' , 'identity.auth_type' ) : session . pop ( key , None ) identity_changed . send ( current_app . _get_current_object ( ) , identity = AnonymousIdentity ( ) ) _logout_user ( )
Logs out the current .
33,615
def verify_password ( password , password_hash ) : if use_double_hash ( password_hash ) : password = get_hmac ( password ) return _pwd_context . verify ( password , password_hash )
Returns True if the password matches the supplied hash .
33,616
def find_redirect ( key ) : rv = ( get_url ( session . pop ( key . lower ( ) , None ) ) or get_url ( current_app . config [ key . upper ( ) ] or None ) or '/' ) return rv
Returns the URL to redirect to after a user logs in successfully .
33,617
def send_mail ( subject , recipient , template , ** context ) : context . setdefault ( 'security' , _security ) context . update ( _security . _run_ctx_processor ( 'mail' ) ) sender = _security . email_sender if isinstance ( sender , LocalProxy ) : sender = sender . _get_current_object ( ) msg = Message ( subject , sen...
Send an email via the Flask - Mail extension .
33,618
def capture_registrations ( ) : registrations = [ ] def _on ( app , ** data ) : registrations . append ( data ) user_registered . connect ( _on ) try : yield registrations finally : user_registered . disconnect ( _on )
Testing utility for capturing registrations .
33,619
def capture_reset_password_requests ( reset_password_sent_at = None ) : reset_requests = [ ] def _on ( app , ** data ) : reset_requests . append ( data ) reset_password_instructions_sent . connect ( _on ) try : yield reset_requests finally : reset_password_instructions_sent . disconnect ( _on )
Testing utility for capturing password reset requests .
33,620
def send_login_instructions ( user ) : token = generate_login_token ( user ) login_link = url_for_security ( 'token_login' , token = token , _external = True ) _security . send_mail ( config_value ( 'EMAIL_SUBJECT_PASSWORDLESS' ) , user . email , 'login_instructions' , user = user , login_link = login_link ) login_inst...
Sends the login instructions email for the specified user .
33,621
def roles_add ( user , role ) : user , role = _datastore . _prepare_role_modify_args ( user , role ) if user is None : raise click . UsageError ( 'Cannot find user.' ) if role is None : raise click . UsageError ( 'Cannot find role.' ) if _datastore . add_role_to_user ( user , role ) : click . secho ( 'Role "{0}" added ...
Add user to role .
33,622
def roles_remove ( user , role ) : user , role = _datastore . _prepare_role_modify_args ( user , role ) if user is None : raise click . UsageError ( 'Cannot find user.' ) if role is None : raise click . UsageError ( 'Cannot find role.' ) if _datastore . remove_role_from_user ( user , role ) : click . secho ( 'Role "{0}...
Remove user from role .
33,623
def send_password_changed_notice ( user ) : if config_value ( 'SEND_PASSWORD_CHANGE_EMAIL' ) : subject = config_value ( 'EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE' ) _security . send_mail ( subject , user . email , 'change_notice' , user = user )
Sends the password changed notice email for the specified user .
33,624
def change_user_password ( user , password ) : user . password = hash_password ( password ) _datastore . put ( user ) send_password_changed_notice ( user ) password_changed . send ( current_app . _get_current_object ( ) , user = user )
Change the specified user s password
33,625
def after_log ( logger , log_level , sec_format = "%0.3f" ) : log_tpl = ( "Finished call to '%s' after " + str ( sec_format ) + "(s), " "this was the %s time calling it." ) def log_it ( retry_state ) : logger . log ( log_level , log_tpl , _utils . get_callback_name ( retry_state . fn ) , retry_state . seconds_since_sta...
After call strategy that logs to some logger the finished attempt .
33,626
def retry ( * dargs , ** dkw ) : if len ( dargs ) == 1 and callable ( dargs [ 0 ] ) : return retry ( ) ( dargs [ 0 ] ) else : def wrap ( f ) : if asyncio and asyncio . iscoroutinefunction ( f ) : r = AsyncRetrying ( * dargs , ** dkw ) elif tornado and hasattr ( tornado . gen , 'is_coroutine_function' ) and tornado . ge...
Wrap a function with a new Retrying object .
33,627
def copy ( self , sleep = _unset , stop = _unset , wait = _unset , retry = _unset , before = _unset , after = _unset , before_sleep = _unset , reraise = _unset ) : if before_sleep is _unset : before_sleep = self . before_sleep return self . __class__ ( sleep = self . sleep if sleep is _unset else sleep , stop = self . ...
Copy this object with some parameters changed if needed .
33,628
def statistics ( self ) : try : return self . _local . statistics except AttributeError : self . _local . statistics = { } return self . _local . statistics
Return a dictionary of runtime statistics .
33,629
def wraps ( self , f ) : @ _utils . wraps ( f ) def wrapped_f ( * args , ** kw ) : return self . call ( f , * args , ** kw ) def retry_with ( * args , ** kwargs ) : return self . copy ( * args , ** kwargs ) . wraps ( f ) wrapped_f . retry = self wrapped_f . retry_with = retry_with return wrapped_f
Wrap a function for retrying .
33,630
def construct ( cls , attempt_number , value , has_exception ) : fut = cls ( attempt_number ) if has_exception : fut . set_exception ( value ) else : fut . set_result ( value ) return fut
Construct a new Future object .
33,631
def get_callback_name ( cb ) : segments = [ ] try : segments . append ( cb . __qualname__ ) except AttributeError : try : segments . append ( cb . __name__ ) if inspect . ismethod ( cb ) : try : segments . insert ( 0 , cb . im_class . __name__ ) except AttributeError : pass except AttributeError : pass if not segments ...
Get a callback fully - qualified name .
33,632
def make_retry_state ( previous_attempt_number , delay_since_first_attempt , last_result = None ) : required_parameter_unset = ( previous_attempt_number is _unset or delay_since_first_attempt is _unset ) if required_parameter_unset : raise _make_unset_exception ( 'wait/stop' , previous_attempt_number = previous_attempt...
Construct RetryCallState for given attempt number & delay .
33,633
def func_takes_last_result ( waiter ) : if not six . callable ( waiter ) : return False if not inspect . isfunction ( waiter ) and not inspect . ismethod ( waiter ) : waiter = waiter . __call__ waiter_spec = _utils . getargspec ( waiter ) return 'last_result' in waiter_spec . args
Check if function has a last_result parameter .
33,634
def stop_func_accept_retry_state ( stop_func ) : if not six . callable ( stop_func ) : return stop_func if func_takes_retry_state ( stop_func ) : return stop_func @ _utils . wraps ( stop_func ) def wrapped_stop_func ( retry_state ) : warn_about_non_retry_state_deprecation ( 'stop' , stop_func , stacklevel = 4 ) return ...
Wrap stop function to accept retry_state parameter .
33,635
def wait_func_accept_retry_state ( wait_func ) : if not six . callable ( wait_func ) : return wait_func if func_takes_retry_state ( wait_func ) : return wait_func if func_takes_last_result ( wait_func ) : @ _utils . wraps ( wait_func ) def wrapped_wait_func ( retry_state ) : warn_about_non_retry_state_deprecation ( 'wa...
Wrap wait function to accept retry_state parameter .
33,636
def retry_func_accept_retry_state ( retry_func ) : if not six . callable ( retry_func ) : return retry_func if func_takes_retry_state ( retry_func ) : return retry_func @ _utils . wraps ( retry_func ) def wrapped_retry_func ( retry_state ) : warn_about_non_retry_state_deprecation ( 'retry' , retry_func , stacklevel = 4...
Wrap retry function to accept retry_state parameter .
33,637
def before_func_accept_retry_state ( fn ) : if not six . callable ( fn ) : return fn if func_takes_retry_state ( fn ) : return fn @ _utils . wraps ( fn ) def wrapped_before_func ( retry_state ) : warn_about_non_retry_state_deprecation ( 'before' , fn , stacklevel = 4 ) return fn ( retry_state . fn , retry_state . attem...
Wrap before function to accept retry_state .
33,638
def after_func_accept_retry_state ( fn ) : if not six . callable ( fn ) : return fn if func_takes_retry_state ( fn ) : return fn @ _utils . wraps ( fn ) def wrapped_after_sleep_func ( retry_state ) : warn_about_non_retry_state_deprecation ( 'after' , fn , stacklevel = 4 ) return fn ( retry_state . fn , retry_state . at...
Wrap after function to accept retry_state .
33,639
def before_sleep_func_accept_retry_state ( fn ) : if not six . callable ( fn ) : return fn if func_takes_retry_state ( fn ) : return fn @ _utils . wraps ( fn ) def wrapped_before_sleep_func ( retry_state ) : warn_about_non_retry_state_deprecation ( 'before_sleep' , fn , stacklevel = 4 ) return fn ( retry_state . retry_...
Wrap before_sleep function to accept retry_state .
33,640
def nested ( self , format_callback = None ) : seen = set ( ) roots = [ ] for root in self . edges . get ( None , ( ) ) : roots . extend ( self . _nested ( root , seen , format_callback ) ) return roots
Return the graph as a nested list .
33,641
def get_valid_filename ( s ) : s = get_valid_filename_django ( s ) filename , ext = os . path . splitext ( s ) filename = slugify ( filename ) ext = slugify ( ext ) if ext : return "%s.%s" % ( filename , ext ) else : return "%s" % ( filename , )
like the regular get_valid_filename but also slugifies away umlauts and stuff .
33,642
def walker ( self , path = None , base_folder = None ) : path = path or self . path or '' base_folder = base_folder or self . base_folder path = os . path . normpath ( upath ( path ) ) if base_folder : base_folder = os . path . normpath ( upath ( base_folder ) ) print ( "The directory structure will be imported in %s" ...
This method walk a directory structure and create the Folders and Files as they appear .
33,643
def unzip ( file_obj ) : files = [ ] zip = ZipFile ( file_obj ) bad_file = zip . testzip ( ) if bad_file : raise Exception ( '"%s" in the .zip archive is corrupt.' % bad_file ) infolist = zip . infolist ( ) for zipinfo in infolist : if zipinfo . filename . startswith ( '__' ) : continue file_obj = SimpleUploadedFile ( ...
Take a path to a zipfile and checks if it is a valid zip file and returns ...
33,644
def get_thumbnail_name ( self , thumbnail_options , transparent = False , high_resolution = False ) : path , source_filename = os . path . split ( self . name ) source_extension = os . path . splitext ( source_filename ) [ 1 ] [ 1 : ] if self . thumbnail_preserve_extensions is True or ( self . thumbnail_preserve_extens...
A version of Thumbnailer . get_thumbnail_name that produces a reproducible thumbnail name that can be converted back to the original filename .
33,645
def get_thumbnail_name ( self , thumbnail_options , transparent = False , high_resolution = False ) : path , filename = os . path . split ( self . name ) basedir = self . thumbnail_basedir subdir = self . thumbnail_subdir return os . path . join ( basedir , path , subdir , filename )
A version of Thumbnailer . get_thumbnail_name that returns the original filename to resize .
33,646
def owner_search_fields ( self ) : try : from django . contrib . auth import get_user_model except ImportError : from django . contrib . auth . models import User else : User = get_user_model ( ) return [ field . name for field in User . _meta . fields if isinstance ( field , models . CharField ) and field . name != 'p...
Returns all the fields that are CharFields except for password from the User model . For the built - in User model that means username first_name last_name and email .
33,647
def move_to_clipboard ( self , request , files_queryset , folders_queryset ) : if not self . has_change_permission ( request ) : raise PermissionDenied if request . method != 'POST' : return None clipboard = tools . get_user_clipboard ( request . user ) check_files_edit_permissions ( request , files_queryset ) check_fo...
Action which moves the selected files and files in selected folders to clipboard .
33,648
def admin_url_params ( request , params = None ) : params = params or { } if popup_status ( request ) : params [ IS_POPUP_VAR ] = '1' pick_type = popup_pick_type ( request ) if pick_type : params [ '_pick' ] = pick_type return params
given a request looks at GET and POST values to determine which params should be added . Is used to keep the context of popup and picker mode .
33,649
def clean_subject_location ( self ) : cleaned_data = super ( ImageAdminForm , self ) . clean ( ) subject_location = cleaned_data [ 'subject_location' ] if not subject_location : return subject_location coordinates = normalize_subject_location ( subject_location ) if not coordinates : err_msg = ugettext_lazy ( 'Invalid ...
Validate subject_location preserving last saved value .
33,650
def load_object ( import_path ) : if not isinstance ( import_path , six . string_types ) : return import_path if '.' not in import_path : raise TypeError ( "'import_path' argument to 'django_load.core.load_object' must " "contain at least one dot." ) module_name , object_name = import_path . rsplit ( '.' , 1 ) module =...
Loads an object from an import_path like in MIDDLEWARE_CLASSES and the likes .
33,651
def handle ( self , * args , ** options ) : pks = Image . objects . all ( ) . values_list ( 'id' , flat = True ) total = len ( pks ) for idx , pk in enumerate ( pks ) : image = None try : image = Image . objects . get ( pk = pk ) self . stdout . write ( u'Processing image {0} / {1} {2}' . format ( idx + 1 , total , ima...
Generates image thumbnails
33,652
def upath ( path ) : if six . PY2 and not isinstance ( path , six . text_type ) : return path . decode ( fs_encoding ) return path
Always return a unicode path .
33,653
def get_model_label ( model ) : if isinstance ( model , six . string_types ) : return model else : return "%s.%s" % ( model . _meta . app_label , model . __name__ )
Take a model class or model label and return its model label .
33,654
def ajax_upload ( request , folder_id = None ) : folder = None if folder_id : try : folder = Folder . objects . get ( pk = folder_id ) except Folder . DoesNotExist : return JsonResponse ( { 'error' : NO_FOLDER_ERROR } ) if folder and not folder . has_add_children_permission ( request ) : return JsonResponse ( { 'error'...
Receives an upload from the uploader . Receives only one file at a time .
33,655
def __store_config ( self , args , kwargs ) : signature = ( 'schema' , 'ignore_none_values' , 'allow_unknown' , 'require_all' , 'purge_unknown' , 'purge_readonly' , ) for i , p in enumerate ( signature [ : len ( args ) ] ) : if p in kwargs : raise TypeError ( "__init__ got multiple values for argument " "'%s'" % p ) el...
Assign args to kwargs and store configuration .
33,656
def _error ( self , * args ) : if len ( args ) == 1 : self . _errors . extend ( args [ 0 ] ) self . _errors . sort ( ) for error in args [ 0 ] : self . document_error_tree . add ( error ) self . schema_error_tree . add ( error ) self . error_handler . emit ( error ) elif len ( args ) == 2 and isinstance ( args [ 1 ] , ...
Creates and adds one or multiple errors .
33,657
def __validate_definitions ( self , definitions , field ) : def validate_rule ( rule ) : validator = self . __get_rule_handler ( 'validate' , rule ) return validator ( definitions . get ( rule , None ) , field , value ) definitions = self . _resolve_rules_set ( definitions ) value = self . document [ field ] rules_queu...
Validate a field s value against its defined rules .
33,658
def get_user_from_cookie ( cookies , app_id , app_secret ) : cookie = cookies . get ( "fbsr_" + app_id , "" ) if not cookie : return None parsed_request = parse_signed_request ( cookie , app_secret ) if not parsed_request : return None try : result = GraphAPI ( ) . get_access_token_from_code ( parsed_request [ "code" ]...
Parses the cookie set by the official Facebook JavaScript SDK .
33,659
def parse_signed_request ( signed_request , app_secret ) : try : encoded_sig , payload = map ( str , signed_request . split ( "." , 1 ) ) sig = base64 . urlsafe_b64decode ( encoded_sig + "=" * ( ( 4 - len ( encoded_sig ) % 4 ) % 4 ) ) data = base64 . urlsafe_b64decode ( payload + "=" * ( ( 4 - len ( payload ) % 4 ) % 4...
Return dictionary with signed request data .
33,660
def get_permissions ( self , user_id ) : response = self . request ( "{0}/{1}/permissions" . format ( self . version , user_id ) , { } ) [ "data" ] return { x [ "permission" ] for x in response if x [ "status" ] == "granted" }
Fetches the permissions object from the graph .
33,661
def get_object ( self , id , ** args ) : return self . request ( "{0}/{1}" . format ( self . version , id ) , args )
Fetches the given object from the graph .
33,662
def get_objects ( self , ids , ** args ) : args [ "ids" ] = "," . join ( ids ) return self . request ( self . version + "/" , args )
Fetches all of the given object from the graph .
33,663
def get_connections ( self , id , connection_name , ** args ) : return self . request ( "{0}/{1}/{2}" . format ( self . version , id , connection_name ) , args )
Fetches the connections for given object .
33,664
def get_all_connections ( self , id , connection_name , ** args ) : while True : page = self . get_connections ( id , connection_name , ** args ) for post in page [ "data" ] : yield post next = page . get ( "paging" , { } ) . get ( "next" ) if not next : return args = parse_qs ( urlparse ( next ) . query ) del args [ "...
Get all pages from a get_connections call
33,665
def put_object ( self , parent_object , connection_name , ** data ) : assert self . access_token , "Write operations require an access token" return self . request ( "{0}/{1}/{2}" . format ( self . version , parent_object , connection_name ) , post_args = data , method = "POST" , )
Writes the given object to the graph connected to the given parent .
33,666
def delete_request ( self , user_id , request_id ) : return self . request ( "{0}_{1}" . format ( request_id , user_id ) , method = "DELETE" )
Deletes the Request with the given ID for the given user .
33,667
def get_version ( self ) : args = { "access_token" : self . access_token } try : response = self . session . request ( "GET" , FACEBOOK_GRAPH_URL + self . version + "/me" , params = args , timeout = self . timeout , proxies = self . proxies , ) except requests . HTTPError as e : response = json . loads ( e . read ( ) )...
Fetches the current version number of the Graph API being used .
33,668
def request ( self , path , args = None , post_args = None , files = None , method = None ) : if args is None : args = dict ( ) if post_args is not None : method = "POST" if self . access_token : if post_args and "access_token" not in post_args : post_args [ "access_token" ] = self . access_token elif "access_token" no...
Fetches the given path in the Graph API .
33,669
def get_access_token_from_code ( self , code , redirect_uri , app_id , app_secret ) : args = { "code" : code , "redirect_uri" : redirect_uri , "client_id" : app_id , "client_secret" : app_secret , } return self . request ( "{0}/oauth/access_token" . format ( self . version ) , args )
Get an access token from the code returned from an OAuth dialog .
33,670
def get_auth_url ( self , app_id , canvas_url , perms = None , ** kwargs ) : url = "{0}{1}/{2}" . format ( FACEBOOK_WWW_URL , self . version , FACEBOOK_OAUTH_DIALOG_PATH ) args = { "client_id" : app_id , "redirect_uri" : canvas_url } if perms : args [ "scope" ] = "," . join ( perms ) args . update ( kwargs ) return url...
Build a URL to create an OAuth dialog .
33,671
def get_current_user ( ) : if session . get ( "user" ) : g . user = session . get ( "user" ) return result = get_user_from_cookie ( cookies = request . cookies , app_id = FB_APP_ID , app_secret = FB_APP_SECRET ) if result : user = User . query . filter ( User . id == result [ "uid" ] ) . first ( ) if not user : graph =...
Set g . user to the currently logged in user .
33,672
def build_tree ( self , directory ) : confile = os . path . join ( directory , 'config.yml' ) conf = { } if os . path . exists ( confile ) : conf = yaml . load ( open ( confile ) . read ( ) ) class node ( defaultdict ) : name = '' parent = None tmpl = None rect = None mask = None def __str__ ( self ) : obj = self names...
build scene tree from images
33,673
def pack ( mtype , request , rid = None ) : envelope = wire . Envelope ( ) if rid is not None : envelope . id = rid envelope . type = mtype envelope . message = request . SerializeToString ( ) data = envelope . SerializeToString ( ) data = encoder . _VarintBytes ( len ( data ) ) + data return data
pack request to delimited data
33,674
def unpack ( data ) : size , position = decoder . _DecodeVarint ( data , 0 ) envelope = wire . Envelope ( ) envelope . ParseFromString ( data [ position : position + size ] ) return envelope
unpack from delimited data
33,675
def check_stf_agent ( adbprefix = None , kill = False ) : if adbprefix is None : adbprefix = [ 'adb' ] command = adbprefix + [ 'shell' , 'ps' ] out = subprocess . check_output ( command ) . strip ( ) out = out . splitlines ( ) if len ( out ) > 1 : first , out = out [ 0 ] , out [ 1 : ] idx = first . split ( ) . index ( ...
return True if agent is alive .
33,676
def insert_code ( filename , code , save = True , marker = '# ATX CODE END' ) : content = '' found = False for line in open ( filename , 'rb' ) : if not found and line . strip ( ) == marker : found = True cnt = line . find ( marker ) content += line [ : cnt ] + code content += line if not found : if not content . endsw...
Auto append code
33,677
def find_image_position ( origin = 'origin.png' , query = 'query.png' , outfile = None ) : img1 = cv2 . imread ( query , 0 ) img2 = cv2 . imread ( origin , 0 ) sift = cv2 . SIFT ( ) kp1 , des1 = sift . detectAndCompute ( img1 , None ) kp2 , des2 = sift . detectAndCompute ( img2 , None ) print len ( kp1 ) , len ( kp2 ) ...
find all image positions
33,678
def get ( self , udid ) : timeout = self . get_argument ( 'timeout' , 20.0 ) if timeout is not None : timeout = float ( timeout ) que = self . ques [ udid ] try : item = yield que . get ( timeout = time . time ( ) + timeout ) print 'get from queue:' , item self . write ( item ) que . task_done ( ) except gen . TimeoutE...
get new task
33,679
def post ( self , udid ) : que = self . ques [ udid ] timeout = self . get_argument ( 'timeout' , 10.0 ) if timeout is not None : timeout = float ( timeout ) data = tornado . escape . json_decode ( self . request . body ) data = { 'id' : str ( uuid . uuid1 ( ) ) , 'data' : data } yield que . put ( data , timeout = time...
add new task
33,680
def _process_touch_batch ( self ) : if not self . _touch_batch : return _time = self . _temp_status_time changed = False for ( _time , _device , _type , _code , _value ) in self . _touch_batch : if _code == 'ABS_MT_TRACKING_ID' : if _value == 0xffffffff : self . _temp_status [ self . _curr_slot ] = - INF changed = True...
a batch syncs in about 0 . 001 seconds .
33,681
def process ( self ) : timediff = 0 while True : try : time . sleep ( 0.001 ) event = self . queue . get_nowait ( ) self . handle_event ( event ) if event . msg & HC . KEY_ANY : continue if timediff == 0 : timediff = time . time ( ) - event . time self . touches [ event . slotid ] = event except Queue . Empty : if not ...
handle events and trigger time - related events
33,682
def exists ( self , pattern , ** match_kwargs ) : ret = self . match ( pattern , ** match_kwargs ) if ret is None : return None if not ret . matched : return None return ret
Check if image exists in screen
33,683
def _match_auto ( self , screen , search_img , threshold ) : ret = ac . find_template ( screen , search_img ) if ret and ret [ 'confidence' ] > threshold : return FindPoint ( ret [ 'result' ] , ret [ 'confidence' ] , consts . IMAGE_MATCH_METHOD_TMPL , matched = True ) ret = ac . find_sift ( screen , search_img , min_ma...
Maybe not a good idea
33,684
def match_all ( self , pattern ) : pattern = self . pattern_open ( pattern ) search_img = pattern . image screen = self . region_screenshot ( ) screen = imutils . from_pillow ( screen ) points = ac . find_all_template ( screen , search_img , maxcnt = 10 ) return points
Test method not suggested to use
33,685
def region_screenshot ( self , filename = None ) : screen = self . __last_screen if self . __keep_screen else self . screenshot ( ) if self . bounds : screen = screen . crop ( self . bounds ) if filename : screen . save ( filename ) return screen
Deprecated Take part of the screenshot
33,686
def screenshot ( self , filename = None ) : if self . __keep_screen : return self . __last_screen try : screen = self . _take_screenshot ( ) except IOError : log . warn ( "warning, screenshot failed [2/1], retry again" ) screen = self . _take_screenshot ( ) self . __last_screen = screen if filename : save_dir = os . pa...
Take screen snapshot
33,687
def click_nowait ( self , pattern , action = 'click' , desc = None , ** match_kwargs ) : point = self . match ( pattern , ** match_kwargs ) if not point or not point . matched : return None func = getattr ( self , action ) func ( * point . pos ) return point
Return immediately if no image found
33,688
def click_image ( self , pattern , timeout = 20.0 , action = 'click' , safe = False , desc = None , delay = None , ** match_kwargs ) : pattern = self . pattern_open ( pattern ) log . info ( 'click image:%s %s' , desc or '' , pattern ) start_time = time . time ( ) found = False point = None while time . time ( ) - start...
Simulate click according image position
33,689
def list_images ( path = [ '.' ] ) : for image_dir in set ( path ) : if not os . path . isdir ( image_dir ) : continue for filename in os . listdir ( image_dir ) : bname , ext = os . path . splitext ( filename ) if ext . lower ( ) not in VALID_IMAGE_EXTS : continue filepath = os . path . join ( image_dir , filename ) y...
Return list of image files
33,690
def list_all_image ( path , valid_exts = VALID_IMAGE_EXTS ) : for filename in os . listdir ( path ) : bname , ext = os . path . splitext ( filename ) if ext . lower ( ) not in VALID_IMAGE_EXTS : continue filepath = os . path . join ( path , filename ) yield strutils . decode ( filepath )
List all images under path
33,691
def search_image ( name = None , path = [ '.' ] ) : name = strutils . decode ( name ) for image_dir in path : if not os . path . isdir ( image_dir ) : continue image_dir = strutils . decode ( image_dir ) image_path = os . path . join ( image_dir , name ) if os . path . isfile ( image_path ) : return strutils . encode (...
look for the image real path if name is None then return all images under path .
33,692
def run_cmd ( self , * args , ** kwargs ) : timeout = kwargs . pop ( 'timeout' , None ) p = self . raw_cmd ( * args , ** kwargs ) return p . communicate ( timeout = timeout ) [ 0 ] . decode ( 'utf-8' ) . replace ( '\r\n' , '\n' )
Unix style output already replace \ r \ n to \ n
33,693
def shell ( self , * args , ** kwargs ) : args = [ 'shell' ] + list ( args ) return self . run_cmd ( * args , ** kwargs )
Run command adb shell
33,694
def remove ( self , filename ) : output = self . shell ( 'rm' , filename ) return False if output else True
Remove file from device
33,695
def display ( self ) : w , h = ( 0 , 0 ) for line in self . shell ( 'dumpsys' , 'display' ) . splitlines ( ) : m = _DISPLAY_RE . search ( line , 0 ) if not m : continue w = int ( m . group ( 'width' ) ) h = int ( m . group ( 'height' ) ) o = int ( m . group ( 'orientation' ) ) w , h = min ( w , h ) , max ( w , h ) retu...
Return device width height rotation
33,696
def packages ( self ) : pattern = re . compile ( r'package:(/[^=]+\.apk)=([^\s]+)' ) packages = [ ] for line in self . shell ( 'pm' , 'list' , 'packages' , '-f' ) . splitlines ( ) : m = pattern . match ( line ) if not m : continue path , name = m . group ( 1 ) , m . group ( 2 ) packages . append ( self . Package ( name...
Show all packages
33,697
def _adb_screencap ( self , scale = 1.0 ) : remote_file = tempfile . mktemp ( dir = '/data/local/tmp/' , prefix = 'screencap-' , suffix = '.png' ) local_file = tempfile . mktemp ( prefix = 'atx-screencap-' , suffix = '.png' ) self . shell ( 'screencap' , '-p' , remote_file ) try : self . pull ( remote_file , local_file...
capture screen with adb shell screencap
33,698
def _adb_minicap ( self , scale = 1.0 ) : remote_file = tempfile . mktemp ( dir = '/data/local/tmp/' , prefix = 'minicap-' , suffix = '.jpg' ) local_file = tempfile . mktemp ( prefix = 'atx-minicap-' , suffix = '.jpg' ) ( w , h , r ) = self . display params = '{x}x{y}@{rx}x{ry}/{r}' . format ( x = w , y = h , rx = int ...
capture screen with minicap
33,699
def screenshot ( self , filename = None , scale = 1.0 , method = None ) : image = None method = method or self . _screenshot_method if method == 'minicap' : try : image = self . _adb_minicap ( scale ) except Exception as e : logger . warn ( "use minicap failed, fallback to screencap. error detail: %s" , e ) self . _scr...
Take device screenshot