idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
28,600
def _render_mail ( self , rebuild , success , auto_canceled , manual_canceled ) : subject_template = '%(endstate)s building image %(image_name)s' body_template = '\n' . join ( [ 'Image Name: %(image_name)s' , 'Repositories: %(repositories)s' , 'Status: %(endstate)s' , 'Submitted by: %(user)s' , ] ) if self . session an...
Render and return subject and body of the mail to send .
28,601
def _send_mail ( self , receivers_list , subject , body , log_files = None ) : if not receivers_list : self . log . info ( 'no valid addresses in requested addresses. Doing nothing' ) return self . log . info ( 'sending notification to %s ...' , receivers_list ) if log_files : msg = MIMEMultipart ( ) msg . attach ( MIM...
Actually sends the mail with subject and body and optionanl log_file attachements to all members of receivers_list .
28,602
def get_platform_metadata ( self , platform , build_annotations ) : build_info = get_worker_build_info ( self . workflow , platform ) osbs = build_info . osbs kind = "configmap/" cmlen = len ( kind ) cm_key_tmp = build_annotations [ 'metadata_fragment' ] cm_frag_key = build_annotations [ 'metadata_fragment_key' ] if no...
Return the metadata for the given platform .
28,603
def get_output ( self , worker_metadatas ) : outputs = [ ] has_pulp_pull = PLUGIN_PULP_PULL_KEY in self . workflow . exit_results try : pulp_sync_results = self . workflow . postbuild_results [ PLUGIN_PULP_SYNC_KEY ] crane_registry = pulp_sync_results [ 0 ] except ( KeyError , IndexError ) : crane_registry = None for p...
Build the output entry of the metadata .
28,604
def handle_401 ( self , response , repo , ** kwargs ) : if response . status_code != requests . codes . unauthorized : return response auth_info = response . headers . get ( 'www-authenticate' , '' ) if 'bearer' not in auth_info . lower ( ) : return response self . _token_cache [ repo ] = self . _get_token ( auth_info ...
Fetch Bearer token and retry .
28,605
def remove_plugins_without_parameters ( self ) : self . remove_plugin ( 'prebuild_plugins' , PLUGIN_DOCKERFILE_CONTENT_KEY , 'dockerfile_content is deprecated, please remove from config' ) if not self . reactor_env : return self . remove_koji_plugins ( ) self . remove_pulp_plugins ( ) if not self . get_value ( 'odcs' )...
This used to be handled in BuildRequest but with REACTOR_CONFIG osbs - client doesn t have enough information .
28,606
def adjust_for_autorebuild ( self ) : if not is_rebuild ( self . workflow ) : return if self . signing_intent : self . log . info ( 'Autorebuild detected: Ignoring signing_intent plugin parameter' ) self . signing_intent = None if self . compose_ids : self . log . info ( 'Autorebuild detected: Ignoring compose_ids plug...
Ignore pre - filled signing_intent and compose_ids for autorebuids
28,607
def resolve_signing_intent ( self ) : all_signing_intents = [ self . odcs_config . get_signing_intent_by_keys ( compose_info . get ( 'sigkeys' , [ ] ) ) for compose_info in self . composes_info ] if self . _parent_signing_intent : all_signing_intents . append ( self . _parent_signing_intent ) signing_intent = min ( all...
Determine the correct signing intent
28,608
def validate_for_request ( self ) : if not self . use_packages and not self . modules and not self . pulp : raise ValueError ( "Nothing to compose (no packages, modules, or enabled pulp repos)" ) if self . packages and not self . koji_tag : raise ValueError ( 'koji_tag is required when packages are used' )
Verify enough information is available for requesting compose .
28,609
def run ( self ) : path = self . path or CONTAINER_BUILD_JSON_PATH try : with open ( path , 'r' ) as build_cfg_fd : build_cfg_json = json . load ( build_cfg_fd ) except ValueError : self . log . error ( "couldn't decode json from file '%s'" , path ) return None except IOError : self . log . error ( "couldn't read json ...
get json with build config from path
28,610
def has_operator_manifest ( self ) : dockerfile = df_parser ( self . workflow . builder . df_path , workflow = self . workflow ) labels = Labels ( dockerfile . labels ) try : _ , operator_label = labels . get_name_and_value ( Labels . LABEL_TYPE_OPERATOR_MANIFESTS ) except KeyError : operator_label = 'false' return ope...
Check if Dockerfile sets the operator manifest label
28,611
def should_run ( self ) : if self . is_orchestrator ( ) : self . log . warning ( "%s plugin set to run on orchestrator. Skipping" , self . key ) return False if self . operator_manifests_extract_platform != self . platform : self . log . info ( "Only platform [%s] will upload operators metadata. Skipping" , self . oper...
Check if the plugin should run or skip execution .
28,612
def _read ( self ) : data = b'' for chunk in self . _event_source : for line in chunk . splitlines ( True ) : data += line if data . endswith ( ( b'\r\r' , b'\n\n' , b'\r\n\r\n' ) ) : yield data data = b'' if data : yield data
Read the incoming event source stream and yield event chunks .
28,613
def check ( wants , has ) : if wants & has == 0 : return False if wants & has < wants : return False return True
Check if a desired scope wants is part of an available scope has .
28,614
def to_int ( * names , ** kwargs ) : return reduce ( lambda prev , next : ( prev | SCOPE_NAME_DICT . get ( next , 0 ) ) , names , kwargs . pop ( 'default' , 0 ) )
Turns a list of scope names into an integer value .
28,615
def get_data ( self , request , key = 'params' ) : return request . session . get ( '%s:%s' % ( constants . SESSION_KEY , key ) )
Return stored data from the session store .
28,616
def cache_data ( self , request , data , key = 'params' ) : request . session [ '%s:%s' % ( constants . SESSION_KEY , key ) ] = data
Cache data in the session store .
28,617
def clear_data ( self , request ) : for key in request . session . keys ( ) : if key . startswith ( constants . SESSION_KEY ) : del request . session [ key ]
Clear all OAuth related data from the session store .
28,618
def error_response ( self , request , error , ** kwargs ) : ctx = { } ctx . update ( error ) if error [ 'error' ] in [ 'redirect_uri' , 'unauthorized_client' ] : ctx . update ( next = '/' ) return self . render_to_response ( ctx , ** kwargs ) ctx . update ( next = self . get_redirect_url ( request ) ) return self . ren...
Return an error to be displayed to the resource owner if anything goes awry . Errors can include invalid clients authorization denials and other edge cases such as a wrong redirect_uri in the authorization request .
28,619
def get_handler ( self , grant_type ) : if grant_type == 'authorization_code' : return self . authorization_code elif grant_type == 'refresh_token' : return self . refresh_token elif grant_type == 'password' : return self . password return None
Return a function or method that is capable handling the grant_type requested by the client or return None to indicate that this type of grant type is not supported resulting in an error response .
28,620
def get_expire_delta ( self , reference = None ) : if reference is None : reference = now ( ) expiration = self . expires if timezone : if timezone . is_aware ( reference ) and timezone . is_naive ( expiration ) : expiration = timezone . make_aware ( expiration , timezone . utc ) elif timezone . is_naive ( reference ) ...
Return the number of seconds until this token expires .
28,621
def _clean_fields ( self ) : try : super ( OAuthForm , self ) . _clean_fields ( ) except OAuthValidationError , e : self . _errors . update ( e . args [ 0 ] )
Overriding the default cleaning behaviour to exit early on errors instead of validating each field .
28,622
def rfclink ( name , rawtext , text , lineno , inliner , options = { } , content = [ ] ) : node = nodes . reference ( rawtext , "Section " + text , refuri = "%s#section-%s" % ( base_url , text ) ) return [ node ] , [ ]
Link to the OAuth2 draft .
28,623
def validate ( self , value ) : if self . required and not value : raise OAuthValidationError ( { 'error' : 'invalid_request' } ) for val in value : if not self . valid_value ( val ) : raise OAuthValidationError ( { 'error' : 'invalid_request' , 'error_description' : _ ( "'%s' is not a valid scope." ) % val } )
Validates that the input is a list or tuple .
28,624
def clean_scope ( self ) : default = SCOPES [ 0 ] [ 0 ] flags = self . cleaned_data . get ( 'scope' , [ ] ) return scope . to_int ( default = default , * flags )
The scope is assembled by combining all the set flags into a single integer value which we can later check again for set bits .
28,625
def clean ( self ) : data = self . cleaned_data want_scope = data . get ( 'scope' ) or 0 refresh_token = data . get ( 'refresh_token' ) access_token = getattr ( refresh_token , 'access_token' , None ) if refresh_token else None has_scope = access_token . scope if access_token else 0 if want_scope is not 0 and not scope...
Make sure that the scope is less or equal to the previous scope!
28,626
def clean ( self ) : data = self . cleaned_data want_scope = data . get ( 'scope' ) or 0 grant = data . get ( 'grant' ) has_scope = grant . scope if grant else 0 if want_scope is not 0 and not scope . check ( want_scope , has_scope ) : raise OAuthValidationError ( { 'error' : 'invalid_scope' } ) return data
Make sure that the scope is less or equal to the scope allowed on the grant!
28,627
def short_token ( ) : hash = hashlib . sha1 ( shortuuid . uuid ( ) ) hash . update ( settings . SECRET_KEY ) return hash . hexdigest ( ) [ : : 2 ]
Generate a hash that can be used as an application identifier
28,628
def deserialize_instance ( model , data = { } ) : "Translate raw data into a model instance." ret = model ( ) for k , v in data . items ( ) : if v is not None : try : f = model . _meta . get_field ( k ) if isinstance ( f , DateTimeField ) : v = dateparse . parse_datetime ( v ) elif isinstance ( f , TimeField ) : v = da...
Translate raw data into a model instance .
28,629
def get_media_urls ( tweet ) : media = get_media_entities ( tweet ) urls = [ m . get ( "media_url_https" ) for m in media ] if media else [ ] return urls
Gets the https links to each media entity in the tweet .
28,630
def get_hashtags ( tweet ) : entities = get_entities ( tweet ) hashtags = entities . get ( "hashtags" ) hashtags = [ tag [ "text" ] for tag in hashtags ] if hashtags else [ ] return hashtags
Get a list of hashtags in the Tweet Note that in the case of a quote - tweet this does not return the hashtags in the quoted status .
28,631
def get_embedded_tweet ( tweet ) : if tweet . retweeted_tweet is not None : return tweet . retweeted_tweet elif tweet . quoted_tweet is not None : return tweet . quoted_tweet else : return None
Get the retweeted Tweet OR the quoted Tweet and return it as a dictionary
28,632
def get_bio ( tweet ) : if is_original_format ( tweet ) : bio_or_none = tweet [ "user" ] . get ( "description" , "" ) else : bio_or_none = tweet [ "actor" ] . get ( "summary" , "" ) if bio_or_none is None : return "" else : return bio_or_none
Get the bio text of the user who posted the Tweet
28,633
def is_original_format ( tweet ) : if "created_at" in tweet : original_format = True elif "postedTime" in tweet : original_format = False else : raise NotATweetError ( "This dict has neither 'created_at' or 'postedTime' as keys" ) return original_format
Simple checker to flag the format of a tweet .
28,634
def get_all_keys ( tweet , parent_key = '' ) : items = [ ] for k , v in tweet . items ( ) : new_key = parent_key + " " + k if isinstance ( v , dict ) : items . extend ( get_all_keys ( v , parent_key = new_key ) ) else : items . append ( new_key . strip ( " " ) ) return items
Takes a tweet object and recursively returns a list of all keys contained in this level and all nexstted levels of the tweet .
28,635
def key_validation_check ( tweet_keys_list , superset_keys , minset_keys ) : tweet_keys = set ( tweet_keys_list ) minset_overlap = tweet_keys & minset_keys if minset_overlap != minset_keys : raise UnexpectedFormatError ( "keys ({}) missing from Tweet (Public API data is not supported)" . format ( minset_keys - tweet_ke...
Validates the keys present in a Tweet .
28,636
def check_tweet ( tweet , validation_checking = False ) : if "id" not in tweet : raise NotATweetError ( "This text has no 'id' key" ) original_format = is_original_format ( tweet ) if original_format : _check_original_format_tweet ( tweet , validation_checking = validation_checking ) else : _check_activity_streams_twee...
Ensures a tweet is valid and determines the type of format for the tweet .
28,637
def get_lang ( tweet ) : if is_original_format ( tweet ) : lang_field = "lang" else : lang_field = "twitter_lang" if tweet [ lang_field ] is not None and tweet [ lang_field ] != "und" : return tweet [ lang_field ] else : return None
Get the language that the Tweet is written in .
28,638
def get_poll_options ( tweet ) : if is_original_format ( tweet ) : try : poll_options_text = [ ] for p in tweet [ "entities" ] [ "polls" ] : for o in p [ "options" ] : poll_options_text . append ( o [ "text" ] ) return poll_options_text except KeyError : return [ ] else : raise NotAvailableError ( "Gnip activity-stream...
Get the text in the options of a poll as a list - If there is no poll in the Tweet return an empty list - If the Tweet is in activity - streams format raise NotAvailableError
28,639
def remove_links ( text ) : tco_link_regex = re . compile ( "https?://t.co/[A-z0-9].*" ) generic_link_regex = re . compile ( "(https?://)?(\w*[.]\w+)+([/?=&]+\w+)*" ) remove_tco = re . sub ( tco_link_regex , " " , text ) remove_generic = re . sub ( generic_link_regex , " " , remove_tco ) return remove_generic
Helper function to remove the links from the input text
28,640
def get_matching_rules ( tweet ) : if is_original_format ( tweet ) : rules = tweet . get ( "matching_rules" ) else : gnip = tweet . get ( "gnip" ) rules = gnip . get ( "matching_rules" ) if gnip else None return rules
Retrieves the matching rules for a tweet with a gnip field enrichment .
28,641
def get_profile_location ( tweet ) : if is_original_format ( tweet ) : try : return tweet [ "user" ] [ "derived" ] [ "locations" ] [ 0 ] except KeyError : return None else : try : location = tweet [ "gnip" ] [ "profileLocations" ] [ 0 ] reconstructed_original_format = { } if location [ "address" ] . get ( "country" , N...
Get user s derived location data from the profile location enrichment If unavailable returns None .
28,642
def get_generator ( tweet ) : if is_original_format ( tweet ) : if sys . version_info [ 0 ] == 3 and sys . version_info [ 1 ] >= 4 : parser = GeneratorHTMLParser ( convert_charrefs = True ) else : parser = GeneratorHTMLParser ( ) parser . feed ( tweet [ "source" ] ) return { "link" : parser . generator_link , "name" : ...
Get information about the application that generated the Tweet
28,643
def lazy_property ( fn ) : attr_name = '_lazy_' + fn . __name__ @ property @ wraps ( fn ) def _lazy_property ( self ) : if not hasattr ( self , attr_name ) : setattr ( self , attr_name , fn ( self ) ) return getattr ( self , attr_name ) return _lazy_property
Decorator that makes a property lazy - evaluated whilst preserving docstrings .
28,644
def quoted_tweet ( self ) : quote_tweet = tweet_embeds . get_quoted_tweet ( self ) if quote_tweet is not None : try : return Tweet ( quote_tweet ) except NotATweetError as nate : raise ( NotATweetError ( "The quote-tweet payload appears malformed." + " Failed with '{}'" . format ( nate ) ) ) else : return None
The quoted Tweet as a Tweet object If the Tweet is not a quote Tweet return None If the quoted Tweet payload cannot be loaded as a Tweet this will raise a NotATweetError
28,645
def retweeted_tweet ( self ) : retweet = tweet_embeds . get_retweeted_tweet ( self ) if retweet is not None : try : return Tweet ( retweet ) except NotATweetError as nate : raise ( NotATweetError ( "The retweet payload appears malformed." + " Failed with '{}'" . format ( nate ) ) ) else : return None
The retweeted Tweet as a Tweet object If the Tweet is not a Retweet return None If the Retweet payload cannot be loaded as a Tweet this will raise a NotATweetError
28,646
def embedded_tweet ( self ) : embedded_tweet = tweet_embeds . get_embedded_tweet ( self ) if embedded_tweet is not None : try : return Tweet ( embedded_tweet ) except NotATweetError as nate : raise ( NotATweetError ( "The embedded tweet payload {} appears malformed." + " Failed with '{}'" . format ( embedded_tweet , na...
Get the retweeted Tweet OR the quoted Tweet and return it as a Tweet object
28,647
def is_applicable ( cls , conf ) : return all ( ( URLPromoter . is_applicable ( conf ) , not cls . needs_firefox ( conf ) , ) )
Return whether this promoter is applicable for given conf
28,648
def xpath_selector ( selector , html , select_all ) : from defusedxml import lxml as dlxml from lxml import etree import re encoded = html . encode ( 'utf-8' ) root = dlxml . fromstring ( encoded , parser = etree . HTMLParser ( ) ) xpath_results = root . xpath ( selector ) if not xpath_results : logger . warning ( 'XPa...
Returns Xpath match for selector within html .
28,649
def register ( ) : registry = { key : bake_html ( key ) for key in ( 'css' , 'css-all' , 'tag' , 'text' ) } registry [ 'xpath' ] = bake_parametrized ( xpath_selector , select_all = False ) registry [ 'xpath-all' ] = bake_parametrized ( xpath_selector , select_all = True ) return registry
Return dictionary of tranform factories
28,650
def reread ( self ) : logger . debug ( "Loading settings from %s" , os . path . abspath ( self . filename ) ) conf = self . read_conf ( ) changed = self . creds . reread ( ) checks = self . parser . parse_checks ( conf ) if self . checks != checks : self . checks = checks return True else : return changed
Read configuration file and substitute references into checks conf
28,651
def reread ( self ) : logger . debug ( "Loading credentials from %s" , os . path . abspath ( self . creds_filename ) ) creds = { } try : with self . open_creds ( ) as fp : creds = yaml . safe_load ( fp ) except IOError : logger . info ( "No credentials file found at %s" , os . path . abspath ( self . creds_filename ) )...
Read and parse credentials file . If something goes wrong log exception and continue .
28,652
def parse_checks ( self , conf ) : checks = conf . get ( 'checks' , conf . get ( 'pages' , [ ] ) ) checks = list ( self . unpack_batches ( checks ) ) checks = list ( self . unpack_templates ( checks , conf . get ( 'templates' , { } ) ) ) self . inject_missing_names ( checks ) for check in checks : self . inject_scenari...
Unpack configuration from human - friendly form to strict check definitions .
28,653
def create_boilerplate ( ) : if not os . path . exists ( 'kibitzr.yml' ) : with open ( 'kibitzr.yml' , 'wt' ) as fp : logger . info ( "Saving sample check in kibitzr.yml" ) fp . write ( KIBITZR_YML ) else : logger . info ( "kibitzr.yml already exists. Skipping" ) if not os . path . exists ( 'kibitzr-creds.yml' ) : with...
Create kibitzr . yml and kibitzr - creds . yml in current directory if they do not exist .
28,654
def cleanup ( ) : temp_dirs = [ ] for key in ( 'headless' , 'headed' ) : if FIREFOX_INSTANCE [ key ] is not None : if FIREFOX_INSTANCE [ key ] . profile : temp_dirs . append ( FIREFOX_INSTANCE [ key ] . profile . profile_dir ) try : FIREFOX_INSTANCE [ key ] . quit ( ) FIREFOX_INSTANCE [ key ] = None except : logger . e...
Must be called before exit
28,655
def firefox ( headless = True ) : from selenium import webdriver from selenium . webdriver . firefox . options import Options if headless : driver_key = 'headless' firefox_options = Options ( ) firefox_options . add_argument ( '-headless' ) else : driver_key = 'headed' firefox_options = None if os . path . isdir ( PROF...
Context manager returning Selenium webdriver . Instance is reused and must be cleaned up on exit .
28,656
def fetcher_factory ( conf ) : global PROMOTERS applicable = [ ] if not PROMOTERS : PROMOTERS = load_promoters ( ) for promoter in PROMOTERS : if promoter . is_applicable ( conf ) : applicable . append ( ( promoter . PRIORITY , promoter ) ) if applicable : best_match = sorted ( applicable , reverse = True ) [ 0 ] [ 1 ]...
Return initialized fetcher capable of processing given conf .
28,657
def fetch ( self , conf ) : url = conf [ 'url' ] self . driver . set_window_size ( 1366 , 800 ) self . driver . implicitly_wait ( 2 ) self . driver . get ( url ) try : self . _run_automation ( conf ) html = self . _get_html ( ) except : logger . exception ( "Exception occurred while fetching" ) return False , traceback...
1 . Fetch URL 2 . Run automation . 3 . Return HTML . 4 . Close the tab .
28,658
def _run_automation ( self , conf ) : self . _fill_form ( self . _find_form ( conf ) ) self . _run_scenario ( conf ) self . _delay ( conf )
1 . Fill form . 2 . Run scenario . 3 . Delay .
28,659
def _fill_form ( form ) : clicked = False last_element = None for field in form : if field [ 'text' ] : field [ 'element' ] . clear ( ) field [ 'element' ] . send_keys ( field [ 'text' ] ) if field [ 'click' ] : field [ 'element' ] . click ( ) clicked = True last_element = field [ 'element' ] if last_element : if not c...
Fill all inputs with provided Jinja2 templates . If no field had click key submit last element .
28,660
def _find_element ( self , selector , selector_type , check_displayed = False ) : if selector_type == 'css' : elements = self . driver . find_elements_by_css_selector ( selector ) elif selector_type == 'xpath' : elements = self . driver . find_elements_by_xpath ( selector ) elif selector_type == 'id' : elements = self ...
Return first matching displayed element of non - zero size or None if nothing found
28,661
def _close_tab ( self ) : old_tab = self . driver . current_window_handle self . driver . execute_script ( ) self . driver . switch_to . window ( old_tab ) self . driver . close ( ) self . driver . switch_to . window ( self . driver . window_handles [ 0 ] )
Create a new tab and close the old one to avoid idle page resource usage
28,662
def write ( self , content ) : with io . open ( self . target , 'w' , encoding = 'utf-8' ) as fp : fp . write ( content ) if not content . endswith ( u'\n' ) : fp . write ( u'\n' )
Save content on disk
28,663
def commit ( self ) : self . git . add ( '-A' , '.' ) try : self . git . commit ( '-m' , self . commit_msg ) return True except sh . ErrorReturnCode_1 : return False
git commit and return whether there were changes
28,664
def ensure_repo_exists ( self ) : if not os . path . isdir ( self . cwd ) : os . makedirs ( self . cwd ) if not os . path . isdir ( os . path . join ( self . cwd , ".git" ) ) : self . git . init ( ) self . git . config ( "user.email" , "you@example.com" ) self . git . config ( "user.name" , "Your Name" )
Create git repo if one does not exist yet
28,665
def word ( self ) : try : output = ensure_unicode ( self . git . diff ( '--no-color' , '--word-diff=plain' , 'HEAD~1:content' , 'HEAD:content' , ) . stdout ) except sh . ErrorReturnCode_128 : result = ensure_unicode ( self . git . show ( "HEAD:content" ) . stdout ) else : ago = ensure_unicode ( self . git . log ( '-2' ...
Return last changes with word diff
28,666
def default ( self ) : output = ensure_unicode ( self . git . log ( '-1' , '-p' , '--no-color' , '--format=%s' , ) . stdout ) lines = output . splitlines ( ) return u'\n' . join ( itertools . chain ( lines [ : 1 ] , itertools . islice ( itertools . dropwhile ( lambda x : not x . startswith ( '+++' ) , lines [ 1 : ] , )...
Return last changes in truncated unified diff format
28,667
def temp_file ( self ) : with tempfile . NamedTemporaryFile ( suffix = '.bat' , delete = False ) as fp : try : logger . debug ( "Saving code to %r" , fp . name ) fp . write ( self . code . encode ( 'utf-8' ) ) fp . close ( ) yield fp . name finally : os . remove ( fp . name )
Create temporary file with code and yield its path . Works both on Windows and Linux
28,668
def once ( ctx , name ) : from kibitzr . app import Application app = Application ( ) sys . exit ( app . run ( once = True , log_level = ctx . obj [ 'log_level' ] , names = name ) )
Run kibitzr checks once and exit
28,669
def subtract_and_intersect_circle ( self , center , radius ) : center = np . asarray ( center , float ) d = np . linalg . norm ( center - self . center ) if d > ( radius + self . radius - tol ) : return [ self , VennEmptyRegion ( ) ] elif d < tol : if radius > self . radius - tol : return [ VennEmptyRegion ( ) , self ]...
Will throw a VennRegionException if the circle to be subtracted is completely inside and not touching the given region .
28,670
def size ( self ) : polygon_area = 0 for a in self . arcs : polygon_area += box_product ( a . start_point ( ) , a . end_point ( ) ) polygon_area /= 2.0 return polygon_area + sum ( [ a . sign * a . segment_area ( ) for a in self . arcs ] )
Return the area of the patch . The area can be computed using the standard polygon area formula + signed segment areas of each arc .
28,671
def make_patch ( self ) : path = [ self . arcs [ 0 ] . start_point ( ) ] for a in self . arcs : if a . direction : vertices = Path . arc ( a . from_angle , a . to_angle ) . vertices else : vertices = Path . arc ( a . to_angle , a . from_angle ) . vertices vertices = vertices [ np . arange ( len ( vertices ) - 1 , - 1 ,...
Retuns a matplotlib PathPatch representing the current region .
28,672
def label_position ( self ) : reg_sizes = [ ( r . size ( ) , r ) for r in self . pieces ] reg_sizes . sort ( ) return reg_sizes [ - 1 ] [ 1 ] . label_position ( )
Find the largest region and position the label in that .
28,673
def make_patch ( self ) : paths = [ p . make_patch ( ) . get_path ( ) for p in self . pieces ] vertices = np . concatenate ( [ p . vertices for p in paths ] ) codes = np . concatenate ( [ p . codes for p in paths ] ) return PathPatch ( Path ( vertices , codes ) )
Currently only works if all the pieces are Arcgons . In this case returns a multiple - piece path . Otherwise throws an exception .
28,674
def mid_point ( self ) : midpoint_angle = self . from_angle + self . sign * self . length_degrees ( ) / 2 return self . angle_as_point ( midpoint_angle )
Returns the midpoint of the arc as a 1x2 numpy array .
28,675
def hide_zeroes ( self ) : for v in self . subset_labels : if v is not None and v . get_text ( ) == '0' : v . set_visible ( False )
Sometimes it makes sense to hide the labels for subsets whose size is zero . This utility method does this .
28,676
def calculate_dict_diff ( old_params : dict , new_params : dict ) : old_params = remove_None ( old_params ) new_params = remove_None ( new_params ) params_diff = { } for key , value in old_params . items ( ) : if key in new_params : if value != new_params [ key ] : params_diff [ key ] = new_params [ key ] else : params...
Return the parameters based on the difference .
28,677
def validate_file ( parser , arg ) : if not os . path . isfile ( arg ) : parser . error ( "%s is not a file." % arg ) return arg
Validates that arg is a valid file .
28,678
def register ( parser ) : cmd_machines . register ( parser ) cmd_machine . register ( parser ) cmd_allocate . register ( parser ) cmd_deploy . register ( parser ) cmd_commission . register ( parser ) cmd_release . register ( parser ) cmd_abort . register ( parser ) cmd_mark_fixed . register ( parser ) cmd_mark_broken ....
Register commands with the given parser .
28,679
def perform_action ( self , action , machines , params , progress_title , success_title ) : if len ( machines ) == 0 : return 0 with utils . Spinner ( ) as context : return self . _async_perform_action ( context , action , list ( machines ) , params , progress_title , success_title )
Perform the action on the set of machines .
28,680
def get_machines ( self , origin , hostnames ) : hostnames = { hostname : True for hostname in hostnames } machines = origin . Machines . read ( hostnames = hostnames ) machines = [ machine for machine in machines if hostnames . pop ( machine . hostname , False ) ] if len ( hostnames ) > 0 : raise CommandError ( "Unabl...
Return a set of machines based on hostnames .
28,681
def add_ssh_options ( self , parser ) : parser . add_argument ( "--username" , metavar = 'USER' , help = ( "Username for the SSH connection." ) ) parser . add_argument ( "--boot-only" , action = "store_true" , help = ( "Only use the IP addresses on the machine's boot interface." ) )
Add the SSH arguments to the parser .
28,682
def get_ip_addresses ( self , machine , * , boot_only = False , discovered = False ) : boot_ips = [ link . ip_address for link in machine . boot_interface . links if link . ip_address ] if boot_only : if boot_ips : return boot_ips elif discovered : return [ link . ip_address for link in machine . boot_interface . disco...
Return all IP address for machine .
28,683
async def _async_get_sshable_ips ( self , ip_addresses ) : async def _async_ping ( ip_address ) : try : reader , writer = await asyncio . wait_for ( asyncio . open_connection ( ip_address , 22 ) , timeout = 5 ) except ( OSError , TimeoutError ) : return None try : line = await reader . readline ( ) finally : writer . c...
Return list of all IP address that could be pinged .
28,684
def _check_ssh ( self , * args ) : ssh = subprocess . Popen ( args , stdin = subprocess . DEVNULL , stdout = subprocess . DEVNULL , stderr = subprocess . DEVNULL ) ssh . wait ( ) return ssh . returncode == 0
Check if SSH connection can be made to IP with username .
28,685
def _determine_username ( self , ip ) : ssh = subprocess . Popen ( [ "ssh" , "-o" , "UserKnownHostsFile=/dev/null" , "-o" , "StrictHostKeyChecking=no" , "root@%s" % ip ] , stdin = subprocess . DEVNULL , stdout = subprocess . PIPE , stderr = subprocess . DEVNULL ) first_line = ssh . stdout . readline ( ) ssh . kill ( ) ...
SSH in as root and determine the username .
28,686
def ssh ( self , machine , * , username = None , command = None , boot_only = False , discovered = False , wait = 300 ) : start_time = time . monotonic ( ) with utils . Spinner ( ) as context : context . msg = colorized ( "{autoblue}Determining{/autoblue} best IP for %s" % ( machine . hostname ) ) ip_addresses = self ....
SSH into machine .
28,687
def _get_deploy_options ( self , options ) : user_data = None if options . user_data and options . b64_user_data : raise CommandError ( "Cannot provide both --user-data and --b64-user-data." ) if options . b64_user_data : user_data = options . b64_user_data if options . user_data : user_data = base64_file ( options . u...
Return the deployment options based on command line .
28,688
def _handle_abort ( self , machine , allocated ) : abort = yes_or_no ( "Abort deployment?" ) if abort : with utils . Spinner ( ) as context : if allocated : context . msg = colorized ( "{autoblue}Releasing{/autoblue} %s" ) % ( machine . hostname ) machine . release ( ) context . print ( colorized ( "{autoblue}Released{...
Handle the user aborting mid deployment .
28,689
def register ( parser ) : cmd_login . register ( parser ) cmd_logout . register ( parser ) cmd_switch . register ( parser ) cmd_profiles . register ( parser )
Register profile commands with the given parser .
28,690
def print_whats_next ( profile ) : what_next = [ "{{autogreen}}Congratulations!{{/autogreen}} You are logged in " "to the MAAS server at {{autoblue}}{profile.url}{{/autoblue}} " "with the profile name {{autoblue}}{profile.name}{{/autoblue}}." , "For help with the available commands, try:" , " maas help" , ] for messag...
Explain what to do next .
28,691
def obtain_credentials ( credentials ) : if credentials == "-" : credentials = sys . stdin . readline ( ) . strip ( ) elif credentials is None : credentials = try_getpass ( "API key (leave empty for anonymous access): " ) if credentials and not credentials . isspace ( ) : return Credentials . parse ( credentials ) else...
Prompt for credentials if possible .
28,692
async def fromURL ( cls , url , * , credentials = None , insecure = False ) : try : description = await helpers . fetch_api_description ( url , insecure = insecure ) except helpers . RemoteError as error : raise SessionError ( str ( error ) ) else : session = cls ( description , credentials ) session . insecure = insec...
Return a SessionAPI for a given MAAS instance .
28,693
def fromProfileName ( cls , name ) : with profiles . ProfileStore . open ( ) as config : return cls . fromProfile ( config . load ( name ) )
Return a SessionAPI from a given configuration profile name .
28,694
async def login ( cls , url , * , username = None , password = None , insecure = False ) : profile = await helpers . login ( url = url , username = username , password = password , insecure = insecure ) session = cls ( profile . description , profile . credentials ) session . insecure = insecure return profile , sessio...
Make a SessionAPI by logging - in with a username and password .
28,695
async def connect ( cls , url , * , apikey = None , insecure = False ) : profile = await helpers . connect ( url = url , apikey = apikey , insecure = insecure ) session = cls ( profile . description , profile . credentials ) session . insecure = insecure return profile , session
Make a SessionAPI by connecting with an apikey .
28,696
def rebind ( self , ** params ) : new_params = self . __params . copy ( ) new_params . update ( params ) return self . __class__ ( new_params , self . __action )
Rebind the parameters into the URI .
28,697
def call ( self , ** data ) : uri , body , headers = self . prepare ( data ) return self . dispatch ( uri , body , headers )
Issue the call .
28,698
def prepare ( self , data ) : def expand ( data ) : for name , value in data . items ( ) : if isinstance ( value , Iterable ) : for value in value : yield name , value else : yield name , value if self . action . method in ( "GET" , "DELETE" ) : data = expand ( data ) else : data = data . items ( ) uri , body , headers...
Prepare the call payload .
28,699
async def dispatch ( self , uri , body , headers ) : insecure = self . action . handler . session . insecure connector = aiohttp . TCPConnector ( verify_ssl = ( not insecure ) ) session = aiohttp . ClientSession ( connector = connector ) async with session : response = await session . request ( self . action . method ,...
Dispatch the call via HTTP .