idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
43,400 | def coords_intersect ( self ) : return set . intersection ( * map ( set , ( getattr ( arr , 'coords_intersect' , arr . coords ) for arr in self ) ) ) | Coordinates of the arrays in this list that are used in all arrays |
43,401 | def with_plotter ( self ) : return self . __class__ ( ( arr for arr in self if arr . psy . plotter is not None ) , auto_update = bool ( self . auto_update ) ) | The arrays in this instance that are visualized with a plotter |
43,402 | def rename ( self , arr , new_name = True ) : name_in_me = arr . psy . arr_name in self . arr_names if not name_in_me : return arr , False elif name_in_me and not self . _contains_array ( arr ) : if new_name is False : raise ValueError ( "Array name %s is already in use! Set the `new_name` " "parameter to None for renaming!" % arr . psy . arr_name ) elif new_name is True : new_name = new_name if isstring ( new_name ) else 'arr{0}' arr . psy . arr_name = self . next_available_name ( new_name ) return arr , True return arr , None | Rename an array to find a name that isn t already in the list |
43,403 | def copy ( self , deep = False ) : if not deep : return self . __class__ ( self [ : ] , attrs = self . attrs . copy ( ) , auto_update = not bool ( self . no_auto_update ) ) else : return self . __class__ ( [ arr . psy . copy ( deep ) for arr in self ] , attrs = self . attrs . copy ( ) , auto_update = not bool ( self . auto_update ) ) | Returns a copy of the list |
43,404 | def _get_tnames ( self ) : tnames = set ( ) for arr in self : if isinstance ( arr , InteractiveList ) : tnames . update ( arr . get_tnames ( ) ) else : tnames . add ( arr . psy . decoder . get_tname ( next ( arr . psy . iter_base_variables ) , arr . coords ) ) return tnames - { None } | Get the name of the time coordinate of the objects in this list |
43,405 | def _register_update ( self , method = 'isel' , replot = False , dims = { } , fmt = { } , force = False , todefault = False ) : for arr in self : arr . psy . _register_update ( method = method , replot = replot , dims = dims , fmt = fmt , force = force , todefault = todefault ) | Register new dimensions and formatoptions for updating . The keywords are the same as for each single array |
43,406 | def draw ( self ) : for fig in set ( chain ( * map ( lambda arr : arr . psy . plotter . figs2draw , self . with_plotter ) ) ) : self . logger . debug ( "Drawing figure %s" , fig . number ) fig . canvas . draw ( ) for arr in self : if arr . psy . plotter is not None : arr . psy . plotter . _figs2draw . clear ( ) self . logger . debug ( "Done drawing." ) | Draws all the figures in this instance |
43,407 | def _contains_array ( self , val ) : arr = self ( arr_name = val . psy . arr_name ) [ 0 ] is_not_list = any ( map ( lambda a : not isinstance ( a , InteractiveList ) , [ arr , val ] ) ) is_list = any ( map ( lambda a : isinstance ( a , InteractiveList ) , [ arr , val ] ) ) if is_list and is_not_list : return False if is_list : return all ( a in arr for a in val ) and all ( a in val for a in arr ) return arr is val | Checks whether exactly this array is in the list |
43,408 | def next_available_name ( self , fmt_str = 'arr{0}' , counter = None ) : names = self . arr_names counter = counter or iter ( range ( 1000 ) ) try : new_name = next ( filter ( lambda n : n not in names , map ( fmt_str . format , counter ) ) ) except StopIteration : raise ValueError ( "{0} already in the list" . format ( fmt_str ) ) return new_name | Create a new array out of the given format string |
43,409 | def append ( self , value , new_name = False ) : arr , renamed = self . rename ( value , new_name ) if renamed is not None : super ( ArrayList , self ) . append ( value ) | Append a new array to the list |
43,410 | def extend ( self , iterable , new_name = False ) : super ( ArrayList , self ) . extend ( t [ 0 ] for t in filter ( lambda t : t [ 1 ] is not None , ( self . rename ( arr , new_name ) for arr in iterable ) ) ) | Add further arrays from an iterable to this list |
43,411 | def remove ( self , arr ) : name = arr if isinstance ( arr , six . string_types ) else arr . psy . arr_name if arr not in self : raise ValueError ( "Array {0} not in the list" . format ( name ) ) for i , arr in enumerate ( self ) : if arr . psy . arr_name == name : del self [ i ] return raise ValueError ( "No array found with name {0}" . format ( name ) ) | Removes an array from the list |
43,412 | def _register_update ( self , method = 'isel' , replot = False , dims = { } , fmt = { } , force = False , todefault = False ) : ArrayList . _register_update ( self , method = method , dims = dims ) InteractiveBase . _register_update ( self , fmt = fmt , todefault = todefault , replot = bool ( dims ) or replot , force = force ) | Register new dimensions and formatoptions for updating |
43,413 | def from_dataset ( cls , * args , ** kwargs ) : plotter = kwargs . pop ( 'plotter' , None ) make_plot = kwargs . pop ( 'make_plot' , True ) instance = super ( InteractiveList , cls ) . from_dataset ( * args , ** kwargs ) if plotter is not None : plotter . initialize_plot ( instance , make_plot = make_plot ) return instance | Create an InteractiveList instance from the given base dataset |
43,414 | def capture_guest ( userid ) : ret = sdk_client . send_request ( 'guest_get_power_state' , userid ) power_status = ret [ 'output' ] if power_status == 'off' : sdk_client . send_request ( 'guest_start' , userid ) time . sleep ( 1 ) image_name = 'image_captured_%03d' % ( time . time ( ) % 1000 ) sdk_client . send_request ( 'guest_capture' , userid , image_name , capture_type = 'rootonly' , compress_level = 6 ) return image_name | Caputre a virtual machine image . |
43,415 | def import_image ( image_path , os_version ) : image_name = os . path . basename ( image_path ) print ( "Checking if image %s exists or not, import it if not exists" % image_name ) image_info = sdk_client . send_request ( 'image_query' , imagename = image_name ) if 'overallRC' in image_info and image_info [ 'overallRC' ] : print ( "Importing image %s ..." % image_name ) url = 'file://' + image_path ret = sdk_client . send_request ( 'image_import' , image_name , url , { 'os_version' : os_version } ) else : print ( "Image %s already exists" % image_name ) | Import image . |
43,416 | def _run_guest ( userid , image_path , os_version , profile , cpu , memory , network_info , disks_list ) : import_image ( image_path , os_version ) spawn_start = time . time ( ) print ( "Creating userid %s ..." % userid ) ret = sdk_client . send_request ( 'guest_create' , userid , cpu , memory , disk_list = disks_list , user_profile = profile ) if ret [ 'overallRC' ] : print 'guest_create error:%s' % ret return - 1 image_name = os . path . basename ( image_path ) print ( "Deploying %s to %s ..." % ( image_name , userid ) ) ret = sdk_client . send_request ( 'guest_deploy' , userid , image_name ) if ret [ 'overallRC' ] : print 'guest_deploy error:%s' % ret return - 2 print ( "Configuring network interface for %s ..." % userid ) ret = sdk_client . send_request ( 'guest_create_network_interface' , userid , os_version , [ network_info ] ) if ret [ 'overallRC' ] : print 'guest_create_network error:%s' % ret return - 3 ret = sdk_client . send_request ( 'guest_nic_couple_to_vswitch' , userid , '1000' , network_info [ 'vswitch_name' ] ) if ret [ 'overallRC' ] : print 'guest_nic_couple error:%s' % ret return - 4 ret = sdk_client . send_request ( 'vswitch_grant_user' , network_info [ 'vswitch_name' ] , userid ) if ret [ 'overallRC' ] : print 'vswitch_grant_user error:%s' % ret return - 5 print ( "Starting guest %s" % userid ) ret = sdk_client . send_request ( 'guest_start' , userid ) if ret [ 'overallRC' ] : print 'guest_start error:%s' % ret return - 6 spawn_time = time . time ( ) - spawn_start print "Instance-%s pawned succeeded in %s seconds" % ( userid , spawn_time ) | Deploy and provision a virtual machine . |
43,417 | def run_guest ( ) : global GUEST_USERID global GUEST_PROFILE global GUEST_VCPUS global GUEST_MEMORY global GUEST_ROOT_DISK_SIZE global DISK_POOL global IMAGE_PATH global IMAGE_OS_VERSION global GUEST_IP_ADDR global GATEWAY global CIDR global VSWITCH_NAME network_info = { 'ip_addr' : GUEST_IP_ADDR , 'gateway_addr' : GATEWAY , 'cidr' : CIDR , 'vswitch_name' : VSWITCH_NAME } disks_list = [ { 'size' : '%ig' % GUEST_ROOT_DISK_SIZE , 'is_boot_disk' : True , 'disk_pool' : DISK_POOL } ] _run_guest ( GUEST_USERID , IMAGE_PATH , IMAGE_OS_VERSION , GUEST_PROFILE , GUEST_VCPUS , GUEST_MEMORY , network_info , disks_list ) | A sample for quick deploy and start a virtual guest . |
43,418 | def _remove_unexpected_query_parameters ( schema , req ) : additional_properties = schema . get ( 'addtionalProperties' , True ) if additional_properties : pattern_regexes = [ ] patterns = schema . get ( 'patternProperties' , None ) if patterns : for regex in patterns : pattern_regexes . append ( re . compile ( regex ) ) for param in set ( req . GET . keys ( ) ) : if param not in schema [ 'properties' ] . keys ( ) : if not ( list ( regex for regex in pattern_regexes if regex . match ( param ) ) ) : del req . GET [ param ] | Remove unexpected properties from the req . GET . |
43,419 | def query_schema ( query_params_schema , min_version = None , max_version = None ) : def add_validator ( func ) : @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : if 'req' in kwargs : req = kwargs [ 'req' ] else : req = args [ 1 ] if req . environ [ 'wsgiorg.routing_args' ] [ 1 ] : if _schema_validation_helper ( query_params_schema , req . environ [ 'wsgiorg.routing_args' ] [ 1 ] , args , kwargs , is_body = False ) : _remove_unexpected_query_parameters ( query_params_schema , req ) else : if _schema_validation_helper ( query_params_schema , req . GET . dict_of_lists ( ) , args , kwargs , is_body = False ) : _remove_unexpected_query_parameters ( query_params_schema , req ) return func ( * args , ** kwargs ) return wrapper return add_validator | Register a schema to validate request query parameters . |
43,420 | def _close_after_stream ( self , response , chunk_size ) : for chunk in response . iter_content ( chunk_size = chunk_size ) : yield chunk response . close ( ) | Iterate over the content and ensure the response is closed after . |
43,421 | def process_docstring ( app , what , name , obj , options , lines ) : result_lines = lines if app . config . napoleon_numpy_docstring : docstring = ExtendedNumpyDocstring ( result_lines , app . config , app , what , name , obj , options ) result_lines = docstring . lines ( ) if app . config . napoleon_google_docstring : docstring = ExtendedGoogleDocstring ( result_lines , app . config , app , what , name , obj , options ) result_lines = docstring . lines ( ) lines [ : ] = result_lines [ : ] | Process the docstring for a given python object . |
43,422 | def setup ( app ) : from sphinx . application import Sphinx if not isinstance ( app , Sphinx ) : return app . connect ( 'autodoc-process-docstring' , process_docstring ) return napoleon_setup ( app ) | Sphinx extension setup function |
43,423 | def format_time ( x ) : if isinstance ( x , ( datetime64 , datetime ) ) : return format_timestamp ( x ) elif isinstance ( x , ( timedelta64 , timedelta ) ) : return format_timedelta ( x ) elif isinstance ( x , ndarray ) : return list ( x ) if x . ndim else x [ ( ) ] return x | Formats date values |
43,424 | def is_data_dependent ( fmto , data ) : if callable ( fmto . data_dependent ) : return fmto . data_dependent ( data ) return fmto . data_dependent | Check whether a formatoption is data dependent |
43,425 | def ax ( self ) : if self . _ax is None : import matplotlib . pyplot as plt plt . figure ( ) self . _ax = plt . axes ( projection = self . _get_sample_projection ( ) ) return self . _ax | Axes instance of the plot |
43,426 | def _fmto_groups ( self ) : ret = defaultdict ( set ) for key in self : ret [ getattr ( self , key ) . group ] . add ( getattr ( self , key ) ) return dict ( ret ) | Mapping from group to a set of formatoptions |
43,427 | def _try2set ( self , fmto , * args , ** kwargs ) : try : fmto . set_value ( * args , ** kwargs ) except Exception as e : critical ( "Error while setting %s!" % fmto . key , logger = getattr ( self , 'logger' , None ) ) raise e | Sets the value in fmto and gives additional informations when fail |
43,428 | def check_key ( self , key , raise_error = True , * args , ** kwargs ) : return check_key ( key , possible_keys = list ( self ) , raise_error = raise_error , name = 'formatoption keyword' , * args , ** kwargs ) | Checks whether the key is a valid formatoption |
43,429 | def initialize_plot ( self , data = None , ax = None , make_plot = True , clear = False , draw = False , remove = False , priority = None ) : if data is None and self . data is not None : data = self . data else : self . data = data self . ax = ax if data is None : return self . no_auto_update = not ( not self . no_auto_update or not data . psy . no_auto_update ) data . psy . plotter = self if not make_plot : return self . logger . debug ( "Initializing plot..." ) if remove : self . logger . debug ( " Removing old formatoptions..." ) for fmto in self . _fmtos : try : fmto . remove ( ) except Exception : self . logger . debug ( "Could not remove %s while initializing" , fmto . key , exc_info = True ) if clear : self . logger . debug ( " Clearing axes..." ) self . ax . clear ( ) self . cleared = True fmto_groups = self . _grouped_fmtos ( self . _sorted_by_priority ( sorted ( self . _fmtos , key = lambda fmto : fmto . key ) ) ) self . plot_data = self . data self . _updating = True for fmto_priority , grouper in fmto_groups : if priority is None or fmto_priority == priority : self . _plot_by_priority ( fmto_priority , grouper , initializing = True ) self . _release_all ( True ) self . cleared = False self . replot = False self . _initialized = True self . _updating = False if draw is None : draw = rcParams [ 'auto_draw' ] if draw : self . draw ( ) if rcParams [ 'auto_show' ] : self . show ( ) | Initialize the plot for a data array |
43,430 | def _register_update ( self , fmt = { } , replot = False , force = False , todefault = False ) : if self . disabled : return self . replot = self . replot or replot self . _todefault = self . _todefault or todefault if force is True : force = list ( fmt ) self . _force . update ( [ ret [ 0 ] for ret in map ( self . check_key , force or [ ] ) ] ) list ( map ( self . check_key , fmt ) ) self . _registered_updates . update ( fmt ) | Register formatoptions for the update |
43,431 | def reinit ( self , draw = None , clear = False ) : self . initialize_plot ( self . data , self . _ax , draw = draw , clear = clear or any ( fmto . requires_clearing for fmto in self . _fmtos ) , remove = True ) | Reinitializes the plot with the same data and on the same axes . |
43,432 | def draw ( self ) : for fig in self . figs2draw : fig . canvas . draw ( ) self . _figs2draw . clear ( ) | Draw the figures and those that are shared and have been changed |
43,433 | def _set_and_filter ( self ) : fmtos = [ ] seen = set ( ) for key in self . _force : self . _registered_updates . setdefault ( key , getattr ( self , key ) . value ) for key , value in chain ( six . iteritems ( self . _registered_updates ) , six . iteritems ( { key : getattr ( self , key ) . default for key in self } ) if self . _todefault else ( ) ) : if key in seen : continue seen . add ( key ) fmto = getattr ( self , key ) if key in self . _shared and key not in self . _force : if not self . _shared [ key ] . plotter . _updating : warn ( ( "%s formatoption is shared with another plotter." " Use the unshare method to enable the updating" ) % ( fmto . key ) , logger = self . logger ) changed = False else : try : changed = fmto . check_and_set ( value , todefault = self . _todefault , validate = not self . no_validation ) except Exception as e : self . _registered_updates . pop ( key , None ) self . logger . debug ( 'Failed to set %s' , key ) raise e changed = changed or key in self . _force if changed : fmtos . append ( fmto ) fmtos = self . _insert_additionals ( fmtos , seen ) for fmto in fmtos : fmto . lock . acquire ( ) self . _todefault = False self . _registered_updates . clear ( ) self . _force . clear ( ) return fmtos | Filters the registered updates and sort out what is not needed |
43,434 | def _insert_additionals ( self , fmtos , seen = None ) : def get_dependencies ( fmto ) : if fmto is None : return [ ] return fmto . dependencies + list ( chain ( * map ( lambda key : get_dependencies ( getattr ( self , key , None ) ) , fmto . dependencies ) ) ) seen = seen or { fmto . key for fmto in fmtos } keys = { fmto . key for fmto in fmtos } self . replot = self . replot or any ( fmto . requires_replot for fmto in fmtos ) if self . replot or any ( fmto . priority >= START for fmto in fmtos ) : self . replot = True self . plot_data = self . data new_fmtos = dict ( ( f . key , f ) for f in self . _fmtos if ( ( f not in fmtos and is_data_dependent ( f , self . data ) ) ) ) seen . update ( new_fmtos ) keys . update ( new_fmtos ) fmtos += list ( new_fmtos . values ( ) ) if any ( fmto . priority >= BEFOREPLOTTING for fmto in fmtos ) : new_fmtos = dict ( ( f . key , f ) for f in self . _fmtos if ( ( f not in fmtos and f . update_after_plot ) ) ) fmtos += list ( new_fmtos . values ( ) ) for fmto in set ( self . _fmtos ) . difference ( fmtos ) : all_dependencies = get_dependencies ( fmto ) if keys . intersection ( all_dependencies ) : fmtos . append ( fmto ) if any ( fmto . requires_clearing for fmto in fmtos ) : self . cleared = True return list ( self . _fmtos ) return fmtos | Insert additional formatoptions into fmtos . |
43,435 | def _sorted_by_priority ( self , fmtos , changed = None ) : def pop_fmto ( key ) : idx = fmtos_keys . index ( key ) del fmtos_keys [ idx ] return fmtos . pop ( idx ) def get_children ( fmto , parents_keys ) : all_fmtos = fmtos_keys + parents_keys for key in fmto . children + fmto . dependencies : if key not in fmtos_keys : continue child_fmto = pop_fmto ( key ) for childs_child in get_children ( child_fmto , parents_keys + [ child_fmto . key ] ) : yield childs_child if ( any ( key in all_fmtos for key in child_fmto . parents ) or fmto . key in child_fmto . parents ) : continue yield child_fmto fmtos . sort ( key = lambda fmto : fmto . priority , reverse = True ) fmtos_keys = [ fmto . key for fmto in fmtos ] self . _last_update = changed or fmtos_keys [ : ] self . logger . debug ( "Update the formatoptions %s" , fmtos_keys ) while fmtos : del fmtos_keys [ 0 ] fmto = fmtos . pop ( 0 ) for child_fmto in get_children ( fmto , [ fmto . key ] ) : yield child_fmto if any ( key in fmtos_keys for key in fmto . parents ) : continue yield fmto | Sort the formatoption objects by their priority and dependency |
43,436 | def _get_formatoptions ( cls , include_bases = True ) : def base_fmtos ( base ) : return filter ( lambda key : isinstance ( getattr ( cls , key ) , Formatoption ) , getattr ( base , '_get_formatoptions' , empty ) ( False ) ) def empty ( * args , ** kwargs ) : return list ( ) fmtos = ( attr for attr , obj in six . iteritems ( cls . __dict__ ) if isinstance ( obj , Formatoption ) ) if not include_bases : return fmtos return unique_everseen ( chain ( fmtos , * map ( base_fmtos , cls . __mro__ ) ) ) | Iterator over formatoptions |
43,437 | def _enhance_keys ( cls , keys = None , * args , ** kwargs ) : all_keys = list ( cls . _get_formatoptions ( ) ) if isinstance ( keys , six . string_types ) : keys = [ keys ] else : keys = list ( keys or sorted ( all_keys ) ) fmto_groups = defaultdict ( list ) for key in all_keys : fmto_groups [ getattr ( cls , key ) . group ] . append ( key ) new_i = 0 for i , key in enumerate ( keys [ : ] ) : if key in fmto_groups : del keys [ new_i ] for key2 in fmto_groups [ key ] : if key2 not in keys : keys . insert ( new_i , key2 ) new_i += 1 else : valid , similar , message = check_key ( key , all_keys , False , 'formatoption keyword' , * args , ** kwargs ) if not valid : keys . remove ( key ) new_i -= 1 warn ( message ) new_i += 1 return keys | Enhance the given keys by groups |
43,438 | def show_keys ( cls , keys = None , indent = 0 , grouped = False , func = None , include_links = False , * args , ** kwargs ) : def titled_group ( groupname ) : bars = str_indent + '*' * len ( groupname ) + '\n' return bars + str_indent + groupname + '\n' + bars keys = cls . _enhance_keys ( keys , * args , ** kwargs ) str_indent = " " * indent func = func or default_print_func if grouped : grouped_keys = DefaultOrderedDict ( list ) for fmto in map ( lambda key : getattr ( cls , key ) , keys ) : grouped_keys [ fmto . groupname ] . append ( fmto . key ) text = "" for group , keys in six . iteritems ( grouped_keys ) : text += titled_group ( group ) + cls . show_keys ( keys , indent = indent , grouped = False , func = six . text_type , include_links = include_links ) + '\n\n' return func ( text . rstrip ( ) ) if not keys : return n = len ( keys ) ncols = min ( [ 4 , n ] ) ncells = n + ( ( ncols - ( n % ncols ) ) if n != ncols else 0 ) if include_links or ( include_links is None and cls . include_links ) : long_keys = list ( map ( lambda key : ':attr:`~%s.%s.%s`' % ( cls . __module__ , cls . __name__ , key ) , keys ) ) else : long_keys = keys maxn = max ( map ( len , long_keys ) ) long_keys . extend ( [ ' ' * maxn ] * ( ncells - n ) ) bars = ( str_indent + '+-' + ( "-" * ( maxn ) + "-+-" ) * ncols ) [ : - 1 ] lines = ( '| %s |\n%s' % ( ' | ' . join ( key . ljust ( maxn ) for key in long_keys [ i : i + ncols ] ) , bars ) for i in range ( 0 , n , ncols ) ) text = bars + "\n" + str_indent + ( "\n" + str_indent ) . join ( lines ) if six . PY2 : text = text . encode ( 'utf-8' ) return func ( text ) | Classmethod to return a nice looking table with the given formatoptions |
43,439 | def _show_doc ( cls , fmt_func , keys = None , indent = 0 , grouped = False , func = None , include_links = False , * args , ** kwargs ) : def titled_group ( groupname ) : bars = str_indent + '*' * len ( groupname ) + '\n' return bars + str_indent + groupname + '\n' + bars func = func or default_print_func keys = cls . _enhance_keys ( keys , * args , ** kwargs ) str_indent = " " * indent if grouped : grouped_keys = DefaultOrderedDict ( list ) for fmto in map ( lambda key : getattr ( cls , key ) , keys ) : grouped_keys [ fmto . groupname ] . append ( fmto . key ) text = "\n\n" . join ( titled_group ( group ) + cls . _show_doc ( fmt_func , keys , indent = indent , grouped = False , func = str , include_links = include_links ) for group , keys in six . iteritems ( grouped_keys ) ) return func ( text . rstrip ( ) ) if include_links or ( include_links is None and cls . include_links ) : long_keys = list ( map ( lambda key : ':attr:`~%s.%s.%s`' % ( cls . __module__ , cls . __name__ , key ) , keys ) ) else : long_keys = keys text = '\n' . join ( str_indent + long_key + '\n' + fmt_func ( key , long_key , getattr ( cls , key ) . __doc__ ) for long_key , key in zip ( long_keys , keys ) ) return func ( text ) | Classmethod to print the formatoptions and their documentation |
43,440 | def show_summaries ( cls , keys = None , indent = 0 , * args , ** kwargs ) : def find_summary ( key , key_txt , doc ) : return '\n' . join ( wrapper . wrap ( doc [ : doc . find ( '\n\n' ) ] ) ) str_indent = " " * indent wrapper = TextWrapper ( width = 80 , initial_indent = str_indent + ' ' * 4 , subsequent_indent = str_indent + ' ' * 4 ) return cls . _show_doc ( find_summary , keys = keys , indent = indent , * args , ** kwargs ) | Classmethod to print the summaries of the formatoptions |
43,441 | def show_docs ( cls , keys = None , indent = 0 , * args , ** kwargs ) : def full_doc ( key , key_txt , doc ) : return ( '=' * len ( key_txt ) ) + '\n' + doc + '\n' return cls . _show_doc ( full_doc , keys = keys , indent = indent , * args , ** kwargs ) | Classmethod to print the full documentations of the formatoptions |
43,442 | def _get_rc_strings ( cls ) : return list ( unique_everseen ( chain ( * map ( lambda base : getattr ( base , '_rcparams_string' , [ ] ) , cls . __mro__ ) ) ) ) | Recursive method to get the base strings in the rcParams dictionary . |
43,443 | def _set_rc ( self ) : base_str = self . _get_rc_strings ( ) pattern_base = map ( lambda s : s . replace ( '.' , '\.' ) , base_str ) pattern = '(%s)(?=$)' % '|' . join ( self . _get_formatoptions ( ) ) self . _rc = rcParams . find_and_replace ( base_str , pattern = pattern , pattern_base = pattern_base ) user_rc = SubDict ( rcParams [ 'plotter.user' ] , base_str , pattern = pattern , pattern_base = pattern_base ) self . _rc . update ( user_rc . data ) self . _defaultParams = SubDict ( rcParams . defaultParams , base_str , pattern = pattern , pattern_base = pattern_base ) | Method to set the rcparams and defaultParams for this plotter |
43,444 | def update ( self , fmt = { } , replot = False , auto_update = False , draw = None , force = False , todefault = False , ** kwargs ) : if self . disabled : return fmt = dict ( fmt ) if kwargs : fmt . update ( kwargs ) if not self . _initialized : for key , val in six . iteritems ( fmt ) : self [ key ] = val return self . _register_update ( fmt = fmt , replot = replot , force = force , todefault = todefault ) if not self . no_auto_update or auto_update : self . start_update ( draw = draw ) | Update the formatoptions and the plot |
43,445 | def _set_sharing_keys ( self , keys ) : if isinstance ( keys , str ) : keys = { keys } keys = set ( self ) if keys is None else set ( keys ) fmto_groups = self . _fmto_groups keys . update ( chain ( * ( map ( lambda fmto : fmto . key , fmto_groups [ key ] ) for key in keys . intersection ( fmto_groups ) ) ) ) keys . difference_update ( fmto_groups ) return keys | Set the keys to share or unshare |
43,446 | def share ( self , plotters , keys = None , draw = None , auto_update = False ) : auto_update = auto_update or not self . no_auto_update if isinstance ( plotters , Plotter ) : plotters = [ plotters ] keys = self . _set_sharing_keys ( keys ) for plotter in plotters : for key in keys : fmto = self . _shared . get ( key , getattr ( self , key ) ) if not getattr ( plotter , key ) == fmto : plotter . _shared [ key ] = getattr ( self , key ) fmto . shared . add ( getattr ( plotter , key ) ) if self . _initialized : self . update ( force = keys , auto_update = auto_update , draw = draw ) for plotter in plotters : if not plotter . _initialized : continue old_registered = plotter . _registered_updates . copy ( ) plotter . _registered_updates . clear ( ) try : plotter . update ( force = keys , auto_update = auto_update , draw = draw ) except : raise finally : plotter . _registered_updates . clear ( ) plotter . _registered_updates . update ( old_registered ) if draw is None : draw = rcParams [ 'auto_draw' ] if draw : self . draw ( ) if rcParams [ 'auto_show' ] : self . show ( ) | Share the formatoptions of this plotter with others |
43,447 | def has_changed ( self , key , include_last = True ) : if self . _initializing or key not in self : return fmto = getattr ( self , key ) if self . _old_fmt and key in self . _old_fmt [ - 1 ] : old_val = self . _old_fmt [ - 1 ] [ key ] else : old_val = fmto . default if ( fmto . diff ( old_val ) or ( include_last and fmto . key in self . _last_update ) ) : return [ old_val , fmto . value ] | Determine whether a formatoption changed in the last update |
43,448 | def convert_to_mb ( s ) : s = s . upper ( ) try : if s . endswith ( 'G' ) : return float ( s [ : - 1 ] . strip ( ) ) * 1024 elif s . endswith ( 'T' ) : return float ( s [ : - 1 ] . strip ( ) ) * 1024 * 1024 else : return float ( s [ : - 1 ] . strip ( ) ) except ( IndexError , ValueError , KeyError , TypeError ) : errmsg = ( "Invalid memory format: %s" ) % s raise exception . SDKInternalError ( msg = errmsg ) | Convert memory size from GB to MB . |
43,449 | def check_input_types ( * types , ** validkeys ) : def decorator ( function ) : @ functools . wraps ( function ) def wrap_func ( * args , ** kwargs ) : if args [ 0 ] . _skip_input_check : return function ( * args , ** kwargs ) inputs = args [ 1 : ] if ( len ( inputs ) > len ( types ) ) : msg = ( "Too many parameters provided: %(specified)d specified," "%(expected)d expected." % { 'specified' : len ( inputs ) , 'expected' : len ( types ) } ) LOG . info ( msg ) raise exception . SDKInvalidInputNumber ( function . __name__ , len ( types ) , len ( inputs ) ) argtypes = tuple ( map ( type , inputs ) ) match_types = types [ 0 : len ( argtypes ) ] invalid_type = False invalid_userid_idx = - 1 for idx in range ( len ( argtypes ) ) : _mtypes = match_types [ idx ] if not isinstance ( _mtypes , tuple ) : _mtypes = ( _mtypes , ) argtype = argtypes [ idx ] if constants . _TUSERID in _mtypes : userid_type = True for _tmtype in _mtypes : if ( ( argtype == _tmtype ) and ( _tmtype != constants . _TUSERID ) ) : userid_type = False if ( userid_type and ( not valid_userid ( inputs [ idx ] ) ) ) : invalid_userid_idx = idx break elif argtype not in _mtypes : invalid_type = True break if invalid_userid_idx != - 1 : msg = ( "Invalid string value found at the #%d parameter, " "length should be less or equal to 8 and should not be " "null or contain spaces." % ( invalid_userid_idx + 1 ) ) LOG . info ( msg ) raise exception . SDKInvalidInputFormat ( msg = msg ) if invalid_type : msg = ( "Invalid input types: %(argtypes)s; " "Expected types: %(types)s" % { 'argtypes' : str ( argtypes ) , 'types' : str ( types ) } ) LOG . info ( msg ) raise exception . SDKInvalidInputTypes ( function . __name__ , str ( types ) , str ( argtypes ) ) valid_keys = validkeys . get ( 'valid_keys' ) if valid_keys : for k in kwargs . keys ( ) : if k not in valid_keys : msg = ( "Invalid keyword: %(key)s; " "Expected keywords are: %(keys)s" % { 'key' : k , 'keys' : str ( valid_keys ) } ) LOG . info ( msg ) raise exception . SDKInvalidInputFormat ( msg = msg ) return function ( * args , ** kwargs ) return wrap_func return decorator | This is a function decorator to check all input parameters given to decorated function are in expected types . |
43,450 | def expect_and_reraise_internal_error ( modID = 'SDK' ) : try : yield except exception . SDKInternalError as err : msg = err . format_message ( ) raise exception . SDKInternalError ( msg , modID = modID ) | Catch all kinds of zvm client request failure and reraise . |
43,451 | def log_and_reraise_smt_request_failed ( action = None ) : try : yield except exception . SDKSMTRequestFailed as err : msg = '' if action is not None : msg = "Failed to %s. " % action msg += "SMT error: %s" % err . format_message ( ) LOG . error ( msg ) raise exception . SDKSMTRequestFailed ( err . results , msg ) | Catch SDK base exception and print error log before reraise exception . |
43,452 | def get_smt_userid ( ) : cmd = [ "sudo" , "/sbin/vmcp" , "query userid" ] try : userid = subprocess . check_output ( cmd , close_fds = True , stderr = subprocess . STDOUT ) userid = bytes . decode ( userid ) userid = userid . split ( ) [ 0 ] return userid except Exception as err : msg = ( "Could not find the userid of the smt server: %s" ) % err raise exception . SDKInternalError ( msg = msg ) | Get the userid of smt server |
43,453 | def get_namelist ( ) : if CONF . zvm . namelist is not None : if len ( CONF . zvm . namelist ) <= 8 : return CONF . zvm . namelist userid = get_smt_userid ( ) return 'NL' + userid . rjust ( 6 , '0' ) [ - 6 : ] | Generate namelist . |
43,454 | def generate_iucv_authfile ( fn , client ) : lines = [ '#!/bin/bash\n' , 'echo -n %s > /etc/iucv_authorized_userid\n' % client ] with open ( fn , 'w' ) as f : f . writelines ( lines ) | Generate the iucv_authorized_userid file |
43,455 | def translate_response_to_dict ( rawdata , dirt ) : data_list = rawdata . split ( "\n" ) data = { } for ls in data_list : for k in list ( dirt . keys ( ) ) : if ls . __contains__ ( dirt [ k ] ) : data [ k ] = ls [ ( ls . find ( dirt [ k ] ) + len ( dirt [ k ] ) ) : ] . strip ( ) break if data == { } : msg = ( "Invalid smt response data. Error: No value matched with " "keywords. Raw Data: %(raw)s; Keywords: %(kws)s" % { 'raw' : rawdata , 'kws' : str ( dirt ) } ) raise exception . SDKInternalError ( msg = msg ) return data | Translate SMT response to a python dictionary . |
43,456 | def delete_guest ( userid ) : guest_list_info = client . send_request ( 'guest_list' ) userid_1 = ( unicode ( userid , "utf-8" ) if sys . version [ 0 ] == '2' else userid ) if userid_1 not in guest_list_info [ 'output' ] : RuntimeError ( "Userid %s does not exist!" % userid ) guest_delete_info = client . send_request ( 'guest_delete' , userid ) if guest_delete_info [ 'overallRC' ] : print ( "\nFailed to delete guest %s!" % userid ) else : print ( "\nSucceeded to delete guest %s!" % userid ) | Destroy a virtual machine . |
43,457 | def describe_guest ( userid ) : guest_list_info = client . send_request ( 'guest_list' ) userid_1 = ( unicode ( userid , "utf-8" ) if sys . version [ 0 ] == '2' else userid ) if userid_1 not in guest_list_info [ 'output' ] : raise RuntimeError ( "Guest %s does not exist!" % userid ) guest_describe_info = client . send_request ( 'guest_get_definition_info' , userid ) print ( "\nThe created guest %s's info are: \n%s\n" % ( userid , guest_describe_info ) ) | Get the basic information of virtual machine . |
43,458 | def import_image ( image_path , os_version ) : image_name = os . path . basename ( image_path ) print ( "\nChecking if image %s exists ..." % image_name ) image_query_info = client . send_request ( 'image_query' , imagename = image_name ) if image_query_info [ 'overallRC' ] : print ( "Importing image %s ..." % image_name ) url = "file://" + image_path image_import_info = client . send_request ( 'image_import' , image_name , url , { 'os_version' : os_version } ) if image_import_info [ 'overallRC' ] : raise RuntimeError ( "Failed to import image %s!\n%s" % ( image_name , image_import_info ) ) else : print ( "Succeeded to import image %s!" % image_name ) else : print ( "Image %s already exists!" % image_name ) | Import the specific image . |
43,459 | def create_guest ( userid , cpu , memory , disks_list , profile ) : guest_list_info = client . send_request ( 'guest_list' ) userid_1 = ( unicode ( userid , "utf-8" ) if sys . version [ 0 ] == '2' else userid ) if userid_1 in guest_list_info [ 'output' ] : raise RuntimeError ( "Guest %s already exists!" % userid ) print ( "\nCreating guest: %s ..." % userid ) guest_create_info = client . send_request ( 'guest_create' , userid , cpu , memory , disk_list = disks_list , user_profile = profile ) if guest_create_info [ 'overallRC' ] : raise RuntimeError ( "Failed to create guest %s!\n%s" % ( userid , guest_create_info ) ) else : print ( "Succeeded to create guest %s!" % userid ) | Create the userid . |
43,460 | def deploy_guest ( userid , image_name ) : print ( "\nDeploying %s to %s ..." % ( image_name , userid ) ) guest_deploy_info = client . send_request ( 'guest_deploy' , userid , image_name ) if guest_deploy_info [ 'overallRC' ] : print ( "\nFailed to deploy guest %s!\n%s" % ( userid , guest_deploy_info ) ) print ( "\nDeleting the guest %s that failed to deploy..." % userid ) delete_guest ( userid ) os . _exit ( 0 ) else : print ( "Succeeded to deploy %s!" % userid ) | Deploy image to root disk . |
43,461 | def create_network ( userid , os_version , network_info ) : print ( "\nConfiguring network interface for %s ..." % userid ) network_create_info = client . send_request ( 'guest_create_network_interface' , userid , os_version , network_info ) if network_create_info [ 'overallRC' ] : raise RuntimeError ( "Failed to create network for guest %s!\n%s" % ( userid , network_create_info ) ) else : print ( "Succeeded to create network for guest %s!" % userid ) | Create network device and configure network interface . |
43,462 | def coupleTo_vswitch ( userid , vswitch_name ) : print ( "\nCoupleing to vswitch for %s ..." % userid ) vswitch_info = client . send_request ( 'guest_nic_couple_to_vswitch' , userid , '1000' , vswitch_name ) if vswitch_info [ 'overallRC' ] : raise RuntimeError ( "Failed to couple to vswitch for guest %s!\n%s" % ( userid , vswitch_info ) ) else : print ( "Succeeded to couple to vswitch for guest %s!" % userid ) | Couple to vswitch . |
43,463 | def grant_user ( userid , vswitch_name ) : print ( "\nGranting user %s ..." % userid ) user_grant_info = client . send_request ( 'vswitch_grant_user' , vswitch_name , userid ) if user_grant_info [ 'overallRC' ] : raise RuntimeError ( "Failed to grant user %s!" % userid ) else : print ( "Succeeded to grant user %s!" % userid ) | Grant user . |
43,464 | def start_guest ( userid ) : power_state_info = client . send_request ( 'guest_get_power_state' , userid ) print ( "\nPower state is: %s." % power_state_info [ 'output' ] ) guest_start_info = client . send_request ( 'guest_start' , userid ) if guest_start_info [ 'overallRC' ] : raise RuntimeError ( 'Failed to start guest %s!\n%s' % ( userid , guest_start_info ) ) else : print ( "Succeeded to start guest %s!" % userid ) power_state_info = client . send_request ( 'guest_get_power_state' , userid ) print ( "Power state is: %s." % power_state_info [ 'output' ] ) if guest_start_info [ 'overallRC' ] : print ( "Guest_start error: %s" % guest_start_info ) | Power on the vm . |
43,465 | def _run_guest ( userid , image_path , os_version , profile , cpu , memory , network_info , vswitch_name , disks_list ) : print ( "Start deploying a virtual machine:" ) import_image ( image_path , os_version ) spawn_start = time . time ( ) create_guest ( userid , cpu , memory , disks_list , profile ) image_name = os . path . basename ( image_path ) deploy_guest ( userid , image_name ) create_network ( userid , os_version , network_info ) coupleTo_vswitch ( userid , vswitch_name ) grant_user ( userid , vswitch_name ) start_guest ( userid ) spawn_time = time . time ( ) - spawn_start print ( "Instance-%s spawned succeeded in %s seconds!" % ( userid , spawn_time ) ) describe_guest ( userid ) | Deploy and provide a virtual machine . |
43,466 | def _user_input_properties ( ) : global GUEST_USERID global GUEST_PROFILE global GUEST_VCPUS global GUEST_MEMORY global GUEST_ROOT_DISK_SIZE global DISK_POOL global IMAGE_PATH global IMAGE_OS_VERSION global GUEST_IP_ADDR global GATEWAY global CIDR global VSWITCH_NAME global NETWORK_INFO global DISKS_LIST pythonVersion = sys . version [ 0 ] print ( "Your python interpreter's version is %s." % pythonVersion ) if pythonVersion == '2' : print ( "Input properties with string type in ''." ) else : print ( "Input properties without ''." ) print ( "Please input guest properties:" ) GUEST_USERID = input ( "guest_userid = " ) GUEST_PROFILE = input ( "guest_profile = " ) GUEST_VCPUS = int ( input ( "guest_vcpus = " ) ) GUEST_MEMORY = int ( input ( "guest_memory (in Megabytes) = " ) ) GUEST_ROOT_DISK_SIZE = int ( input ( "guest_root_disk_size (in Gigabytes) = " ) ) GUEST_POOL = input ( "disk_pool = " ) print ( "\n" ) IMAGE_PATH = input ( "image_path = " ) IMAGE_OS_VERSION = input ( "image_os_version = " ) print ( "\n" ) GUEST_IP_ADDR = input ( "guest_ip_addr = " ) GATEWAY = input ( "gateway = " ) CIDR = input ( "cidr = " ) VSWITCH_NAME = input ( "vswitch_name = " ) NETWORK_INFO = [ { 'ip_addr' : GUEST_IP_ADDR , 'gateway_addr' : GATEWAY , 'cidr' : CIDR } ] DISKS_LIST = [ { 'size' : '%dg' % GUEST_ROOT_DISK_SIZE , 'is_boot_disk' : True , 'disk_pool' : GUEST_POOL } ] | User input the properties of guest image and network . |
43,467 | def run_guest ( ) : _user_input_properties ( ) _run_guest ( GUEST_USERID , IMAGE_PATH , IMAGE_OS_VERSION , GUEST_PROFILE , GUEST_VCPUS , GUEST_MEMORY , NETWORK_INFO , VSWITCH_NAME , DISKS_LIST ) | A sample for quickly deploy and start a virtual guest . |
43,468 | def package_version ( filename , varname ) : _locals = { } with open ( filename ) as fp : exec ( fp . read ( ) , None , _locals ) return _locals [ varname ] | Return package version string by reading filename and retrieving its module - global variable varnam . |
43,469 | def invokeSmapiApi ( rh ) : rh . printSysLog ( "Enter smapi.invokeSmapiApi" ) if rh . userid != 'HYPERVISOR' : userid = rh . userid else : userid = 'dummy' parms = [ "-T" , userid ] if 'operands' in rh . parms : parms . extend ( rh . parms [ 'operands' ] ) results = invokeSMCLI ( rh , rh . parms [ 'apiName' ] , parms ) if results [ 'overallRC' ] == 0 : rh . printLn ( "N" , results [ 'response' ] ) else : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) rh . printSysLog ( "Exit smapi.invokeCmd, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ] | Invoke a SMAPI API . |
43,470 | def init_fcp ( self , assigner_id ) : fcp_list = CONF . volume . fcp_list if fcp_list == '' : errmsg = ( "because CONF.volume.fcp_list is empty, " "no volume functions available" ) LOG . info ( errmsg ) return self . _fcp_info = self . _init_fcp_pool ( fcp_list , assigner_id ) self . _sync_db_fcp_list ( ) | init_fcp to init the FCP managed by this host |
43,471 | def _expand_fcp_list ( fcp_list ) : LOG . debug ( "Expand FCP list %s" % fcp_list ) if not fcp_list : return set ( ) range_pattern = '[0-9a-fA-F]{1,4}(-[0-9a-fA-F]{1,4})?' match_pattern = "^(%(range)s)(;%(range)s)*$" % { 'range' : range_pattern } if not re . match ( match_pattern , fcp_list ) : errmsg = ( "Invalid FCP address %s" ) % fcp_list raise exception . SDKInternalError ( msg = errmsg ) fcp_devices = set ( ) for _range in fcp_list . split ( ';' ) : if '-' not in _range : fcp_addr = int ( _range , 16 ) fcp_devices . add ( "%04x" % fcp_addr ) else : ( _min , _max ) = _range . split ( '-' ) _min = int ( _min , 16 ) _max = int ( _max , 16 ) for fcp_addr in range ( _min , _max + 1 ) : fcp_devices . add ( "%04x" % fcp_addr ) return fcp_devices | Expand fcp list string into a python list object which contains each fcp devices in the list string . A fcp list is composed of fcp device addresses range indicator - and split indicator ; . |
43,472 | def _add_fcp ( self , fcp ) : try : LOG . info ( "fcp %s found in CONF.volume.fcp_list, add it to db" % fcp ) self . db . new ( fcp ) except Exception : LOG . info ( "failed to add fcp %s into db" , fcp ) | add fcp to db if it s not in db but in fcp list and init it |
43,473 | def _sync_db_fcp_list ( self ) : fcp_db_list = self . db . get_all ( ) for fcp_rec in fcp_db_list : if not fcp_rec [ 0 ] . lower ( ) in self . _fcp_pool : self . _report_orphan_fcp ( fcp_rec [ 0 ] ) for fcp_conf_rec , v in self . _fcp_pool . items ( ) : res = self . db . get_from_fcp ( fcp_conf_rec ) if len ( res ) == 0 : self . _add_fcp ( fcp_conf_rec ) | sync db records from given fcp list for example you need warn if some FCP already removed while it s still in use or info about the new FCP added |
43,474 | def find_and_reserve_fcp ( self , assigner_id ) : fcp_list = self . db . get_from_assigner ( assigner_id ) if not fcp_list : new_fcp = self . db . find_and_reserve ( ) if new_fcp is None : LOG . info ( "no more fcp to be allocated" ) return None LOG . debug ( "allocated %s fcp for %s assigner" % ( new_fcp , assigner_id ) ) return new_fcp else : old_fcp = fcp_list [ 0 ] [ 0 ] self . db . reserve ( fcp_list [ 0 ] [ 0 ] ) return old_fcp | reserve the fcp to assigner_id |
43,475 | def increase_fcp_usage ( self , fcp , assigner_id = None ) : connections = self . db . get_connections_from_assigner ( assigner_id ) new = False if connections == 0 : self . db . assign ( fcp , assigner_id ) new = True else : self . db . increase_usage ( fcp ) return new | Incrase fcp usage of given fcp |
43,476 | def get_available_fcp ( self ) : available_list = [ ] free_unreserved = self . db . get_all_free_unreserved ( ) for item in free_unreserved : available_list . append ( item [ 0 ] ) return available_list | get all the fcps not reserved |
43,477 | def _attach ( self , fcp , assigner_id , target_wwpn , target_lun , multipath , os_version , mount_point ) : LOG . info ( 'Start to attach device to %s' % assigner_id ) self . fcp_mgr . init_fcp ( assigner_id ) new = self . fcp_mgr . increase_fcp_usage ( fcp , assigner_id ) try : if new : self . _dedicate_fcp ( fcp , assigner_id ) self . _add_disk ( fcp , assigner_id , target_wwpn , target_lun , multipath , os_version , mount_point ) except exception . SDKBaseException as err : errmsg = 'rollback attach because error:' + err . format_message ( ) LOG . error ( errmsg ) connections = self . fcp_mgr . decrease_fcp_usage ( fcp , assigner_id ) if not connections : with zvmutils . ignore_errors ( ) : self . _undedicate_fcp ( fcp , assigner_id ) raise exception . SDKBaseException ( msg = errmsg ) LOG . info ( 'Attaching device to %s is done.' % assigner_id ) | Attach a volume |
43,478 | def get_volume_connector ( self , assigner_id ) : empty_connector = { 'zvm_fcp' : [ ] , 'wwpns' : [ ] , 'host' : '' } self . fcp_mgr . init_fcp ( assigner_id ) fcp_list = self . fcp_mgr . get_available_fcp ( ) if not fcp_list : errmsg = "No available FCP device found." LOG . warning ( errmsg ) return empty_connector wwpns = [ ] for fcp_no in fcp_list : wwpn = self . fcp_mgr . get_wwpn ( fcp_no ) if not wwpn : errmsg = "FCP device %s has no available WWPN." % fcp_no LOG . warning ( errmsg ) else : wwpns . append ( wwpn ) if not wwpns : errmsg = "No available WWPN found." LOG . warning ( errmsg ) return empty_connector inv_info = self . _smtclient . get_host_info ( ) zvm_host = inv_info [ 'zvm_host' ] if zvm_host == '' : errmsg = "zvm host not specified." LOG . warning ( errmsg ) return empty_connector connector = { 'zvm_fcp' : fcp_list , 'wwpns' : wwpns , 'host' : zvm_host } LOG . debug ( 'get_volume_connector returns %s for %s' % ( connector , assigner_id ) ) return connector | Get connector information of the instance for attaching to volumes . |
43,479 | def blockmix_salsa8 ( BY , Yi , r ) : start = ( 2 * r - 1 ) * 16 X = BY [ start : start + 16 ] tmp = [ 0 ] * 16 for i in xrange ( 2 * r ) : salsa20_8 ( X , tmp , BY , i * 16 , BY , Yi + i * 16 ) for i in xrange ( r ) : BY [ i * 16 : ( i * 16 ) + ( 16 ) ] = BY [ Yi + ( i * 2 ) * 16 : ( Yi + ( i * 2 ) * 16 ) + ( 16 ) ] BY [ ( i + r ) * 16 : ( ( i + r ) * 16 ) + ( 16 ) ] = BY [ Yi + ( i * 2 + 1 ) * 16 : ( Yi + ( i * 2 + 1 ) * 16 ) + ( 16 ) ] | Blockmix ; Used by SMix |
43,480 | def multiple_subplots ( rows = 1 , cols = 1 , maxplots = None , n = 1 , delete = True , for_maps = False , * args , ** kwargs ) : import matplotlib . pyplot as plt axes = np . array ( [ ] ) maxplots = maxplots or rows * cols kwargs . setdefault ( 'figsize' , [ min ( 8. * cols , 16 ) , min ( 6.5 * rows , 12 ) ] ) if for_maps : import cartopy . crs as ccrs subplot_kw = kwargs . setdefault ( 'subplot_kw' , { } ) subplot_kw [ 'projection' ] = ccrs . PlateCarree ( ) for i in range ( 0 , n , maxplots ) : fig , ax = plt . subplots ( rows , cols , * args , ** kwargs ) try : axes = np . append ( axes , ax . ravel ( ) [ : maxplots ] ) if delete : for iax in range ( maxplots , rows * cols ) : fig . delaxes ( ax . ravel ( ) [ iax ] ) except AttributeError : axes = np . append ( axes , [ ax ] ) if i + maxplots > n and delete : for ax2 in axes [ n : ] : fig . delaxes ( ax2 ) axes = axes [ : n ] return axes | Function to create subplots . |
43,481 | def _only_main ( func ) : @ wraps ( func ) def wrapper ( self , * args , ** kwargs ) : if not self . is_main : return getattr ( self . main , func . __name__ ) ( * args , ** kwargs ) return func ( self , * args , ** kwargs ) return wrapper | Call the given func only from the main project |
43,482 | def gcp ( main = False ) : if main : return project ( ) if _current_project is None else _current_project else : return gcp ( True ) if _current_subproject is None else _current_subproject | Get the current project |
43,483 | def _scp ( p , main = False ) : global _current_subproject global _current_project if p is None : mp = project ( ) if main or _current_project is None else _current_project _current_subproject = Project ( main = mp ) elif not main : _current_subproject = p else : _current_project = p | scp version that allows a bit more control over whether the project is a main project or not |
43,484 | def close ( num = None , figs = True , data = True , ds = True , remove_only = False ) : kws = dict ( figs = figs , data = data , ds = ds , remove_only = remove_only ) cp_num = gcp ( True ) . num got_cp = False if num is None : project = gcp ( ) scp ( None ) project . close ( ** kws ) elif num == 'all' : for project in _open_projects [ : ] : project . close ( ** kws ) got_cp = got_cp or project . main . num == cp_num del _open_projects [ 0 ] else : if isinstance ( num , Project ) : project = num else : project = [ project for project in _open_projects if project . num == num ] [ 0 ] project . close ( ** kws ) try : _open_projects . remove ( project ) except ValueError : pass got_cp = got_cp or project . main . num == cp_num if got_cp : if _open_projects : scp ( _open_projects [ - 1 ] ) else : _scp ( None , True ) | Close the project |
43,485 | def _fmtos ( self ) : plotters = self . plotters if len ( plotters ) == 0 : return { } p0 = plotters [ 0 ] if len ( plotters ) == 1 : return p0 . _fmtos return ( getattr ( p0 , key ) for key in set ( p0 ) . intersection ( * map ( set , plotters [ 1 : ] ) ) ) | An iterator over formatoption objects |
43,486 | def figs ( self ) : ret = utils . DefaultOrderedDict ( lambda : self [ 1 : 0 ] ) for arr in self : if arr . psy . plotter is not None : ret [ arr . psy . plotter . ax . get_figure ( ) ] . append ( arr ) return OrderedDict ( ret ) | A mapping from figures to data objects with the plotter in this figure |
43,487 | def axes ( self ) : ret = utils . DefaultOrderedDict ( lambda : self [ 1 : 0 ] ) for arr in self : if arr . psy . plotter is not None : ret [ arr . psy . plotter . ax ] . append ( arr ) return OrderedDict ( ret ) | A mapping from axes to data objects with the plotter in this axes |
43,488 | def datasets ( self ) : return { key : val [ 'ds' ] for key , val in six . iteritems ( self . _get_ds_descriptions ( self . array_info ( ds_description = [ 'ds' ] ) ) ) } | A mapping from dataset numbers to datasets in this list |
43,489 | def disable ( self ) : for arr in self : if arr . psy . plotter : arr . psy . plotter . disabled = True | Disables the plotters in this list |
43,490 | def close ( self , figs = True , data = False , ds = False , remove_only = False ) : import matplotlib . pyplot as plt close_ds = ds for arr in self [ : ] : if figs and arr . psy . plotter is not None : if remove_only : for fmto in arr . psy . plotter . _fmtos : try : fmto . remove ( ) except Exception : pass else : plt . close ( arr . psy . plotter . ax . get_figure ( ) . number ) arr . psy . plotter = None if data : self . remove ( arr ) if not self . is_main : try : self . main . remove ( arr ) except ValueError : pass if close_ds : if isinstance ( arr , InteractiveList ) : for ds in [ val [ 'ds' ] for val in six . itervalues ( arr . _get_ds_descriptions ( arr . array_info ( ds_description = [ 'ds' ] , standardize_dims = False ) ) ) ] : ds . close ( ) else : arr . psy . base . close ( ) if self . is_main and self is gcp ( True ) and data : scp ( None ) elif self . is_main and self . is_cmp : self . oncpchange . emit ( self ) elif self . main . is_cmp : self . oncpchange . emit ( self . main ) | Close this project instance |
43,491 | def _add_data ( self , plotter_cls , filename_or_obj , fmt = { } , make_plot = True , draw = False , mf_mode = False , ax = None , engine = None , delete = True , share = False , clear = False , enable_post = None , concat_dim = _concat_dim_default , load = False , * args , ** kwargs ) : if not isinstance ( filename_or_obj , xarray . Dataset ) : if mf_mode : filename_or_obj = open_mfdataset ( filename_or_obj , engine = engine , concat_dim = concat_dim ) else : filename_or_obj = open_dataset ( filename_or_obj , engine = engine ) if load : old = filename_or_obj filename_or_obj = filename_or_obj . load ( ) old . close ( ) fmt = dict ( fmt ) possible_fmts = list ( plotter_cls . _get_formatoptions ( ) ) additional_fmt , kwargs = utils . sort_kwargs ( kwargs , possible_fmts ) fmt . update ( additional_fmt ) if enable_post is None : enable_post = bool ( fmt . get ( 'post' ) ) sub_project = self . from_dataset ( filename_or_obj , ** kwargs ) sub_project . main = self sub_project . no_auto_update = not ( not sub_project . no_auto_update or not self . no_auto_update ) proj = plotter_cls . _get_sample_projection ( ) if isinstance ( ax , tuple ) : axes = iter ( multiple_subplots ( * ax , n = len ( sub_project ) , subplot_kw = { 'projection' : proj } ) ) elif ax is None or isinstance ( ax , ( mpl . axes . SubplotBase , mpl . axes . Axes ) ) : axes = repeat ( ax ) else : axes = iter ( ax ) clear = clear or ( isinstance ( ax , tuple ) and proj is not None ) for arr in sub_project : plotter_cls ( arr , make_plot = ( not bool ( share ) and make_plot ) , draw = False , ax = next ( axes ) , clear = clear , project = self , enable_post = enable_post , ** fmt ) if share : if share is True : share = possible_fmts elif isinstance ( share , six . string_types ) : share = [ share ] else : share = list ( share ) sub_project [ 0 ] . psy . plotter . share ( [ arr . psy . plotter for arr in sub_project [ 1 : ] ] , keys = share , draw = False ) if make_plot : for arr in sub_project : arr . psy . plotter . reinit ( draw = False , clear = clear ) if draw is None : draw = rcParams [ 'auto_draw' ] if draw : sub_project . draw ( ) if rcParams [ 'auto_show' ] : self . show ( ) self . extend ( sub_project , new_name = True ) if self is gcp ( True ) : scp ( sub_project ) return sub_project | Extract data from a dataset and visualize it with the given plotter |
43,492 | def joined_attrs ( self , delimiter = ', ' , enhanced = True , plot_data = False , keep_all = True ) : if enhanced : all_attrs = [ plotter . get_enhanced_attrs ( getattr ( plotter , 'plot_data' if plot_data else 'data' ) ) for plotter in self . plotters ] else : if plot_data : all_attrs = [ plotter . plot_data . attrs for plotter in self . plotters ] else : all_attrs = [ arr . attrs for arr in self ] return utils . join_dicts ( all_attrs , delimiter = delimiter , keep_all = keep_all ) | Join the attributes of the arrays in this project |
43,493 | def export ( self , output , tight = False , concat = True , close_pdf = None , use_time = False , ** kwargs ) : from matplotlib . backends . backend_pdf import PdfPages if tight : kwargs [ 'bbox_inches' ] = 'tight' if use_time : def insert_time ( s , attrs ) : time = attrs [ tname ] try : s = pd . to_datetime ( time ) . strftime ( s ) except ValueError : pass return s tnames = self . _get_tnames ( ) tname = next ( iter ( tnames ) ) if len ( tnames ) == 1 else None else : def insert_time ( s , attrs ) : return s tname = None if isinstance ( output , six . string_types ) : out_fmt = kwargs . pop ( 'format' , os . path . splitext ( output ) ) [ 1 ] [ 1 : ] if out_fmt . lower ( ) == 'pdf' and concat : attrs = self . joined_attrs ( '-' ) if tname is not None and tname in attrs : output = insert_time ( output , attrs ) pdf = PdfPages ( safe_modulo ( output , attrs ) ) def save ( fig ) : pdf . savefig ( fig , ** kwargs ) def close ( ) : if close_pdf is None or close_pdf : pdf . close ( ) return return pdf else : def save ( fig ) : attrs = self . figs [ fig ] . joined_attrs ( '-' ) out = output if tname is not None and tname in attrs : out = insert_time ( out , attrs ) try : out = safe_modulo ( out , i , print_warning = False ) except TypeError : pass fig . savefig ( safe_modulo ( out , attrs ) , ** kwargs ) def close ( ) : pass elif isinstance ( output , Iterable ) : output = cycle ( output ) def save ( fig ) : attrs = self . figs [ fig ] . joined_attrs ( '-' ) out = next ( output ) if tname is not None and tname in attrs : out = insert_time ( out , attrs ) try : out = safe_modulo ( next ( output ) , i , print_warning = False ) except TypeError : pass fig . savefig ( safe_modulo ( out , attrs ) , ** kwargs ) def close ( ) : pass else : def save ( fig ) : output . savefig ( fig , ** kwargs ) def close ( ) : if close_pdf : output . close ( ) for i , fig in enumerate ( self . figs , 1 ) : save ( fig ) return close ( ) | Exports the figures of the project to one or more image files |
43,494 | def share ( self , base = None , keys = None , by = None , ** kwargs ) : if by is not None : if base is not None : if hasattr ( base , 'psy' ) or isinstance ( base , Plotter ) : base = [ base ] if by . lower ( ) in [ 'ax' , 'axes' ] : bases = { ax : p [ 0 ] for ax , p in six . iteritems ( Project ( base ) . axes ) } elif by . lower ( ) in [ 'fig' , 'figure' ] : bases = { fig : p [ 0 ] for fig , p in six . iteritems ( Project ( base ) . figs ) } else : raise ValueError ( "*by* must be out of {'fig', 'figure', 'ax', 'axes'}. " "Not %s" % ( by , ) ) else : bases = { } projects = self . axes if by == 'axes' else self . figs for obj , p in projects . items ( ) : p . share ( bases . get ( obj ) , keys , ** kwargs ) else : plotters = self . plotters if not plotters : return if base is None : if len ( plotters ) == 1 : return base = plotters [ 0 ] plotters = plotters [ 1 : ] elif not isinstance ( base , Plotter ) : base = getattr ( getattr ( base , 'psy' , base ) , 'plotter' , base ) base . share ( plotters , keys = keys , ** kwargs ) | Share the formatoptions of one plotter with all the others |
43,495 | def keys ( self , * args , ** kwargs ) : class TmpClass ( Plotter ) : pass for fmto in self . _fmtos : setattr ( TmpClass , fmto . key , type ( fmto ) ( fmto . key ) ) return TmpClass . show_keys ( * args , ** kwargs ) | Show the available formatoptions in this project |
43,496 | def summaries ( self , * args , ** kwargs ) : class TmpClass ( Plotter ) : pass for fmto in self . _fmtos : setattr ( TmpClass , fmto . key , type ( fmto ) ( fmto . key ) ) return TmpClass . show_summaries ( * args , ** kwargs ) | Show the available formatoptions and their summaries in this project |
43,497 | def docs ( self , * args , ** kwargs ) : class TmpClass ( Plotter ) : pass for fmto in self . _fmtos : setattr ( TmpClass , fmto . key , type ( fmto ) ( fmto . key ) ) return TmpClass . show_docs ( * args , ** kwargs ) | Show the available formatoptions in this project and their full docu |
43,498 | def scp ( cls , project ) : if project is None : _scp ( None ) cls . oncpchange . emit ( gcp ( ) ) elif not project . is_main : if project . main is not _current_project : _scp ( project . main , True ) cls . oncpchange . emit ( project . main ) _scp ( project ) cls . oncpchange . emit ( project ) else : _scp ( project , True ) cls . oncpchange . emit ( project ) sp = project [ : ] _scp ( sp ) cls . oncpchange . emit ( sp ) | Set the current project |
43,499 | def inspect_axes ( ax ) : ret = { 'fig' : ax . get_figure ( ) . number } if mpl . __version__ < '2.0' : ret [ 'axisbg' ] = ax . get_axis_bgcolor ( ) else : ret [ 'facecolor' ] = ax . get_facecolor ( ) proj = getattr ( ax , 'projection' , None ) if proj is not None and not isinstance ( proj , six . string_types ) : proj = ( proj . __class__ . __module__ , proj . __class__ . __name__ ) ret [ 'projection' ] = proj ret [ 'visible' ] = ax . get_visible ( ) ret [ 'spines' ] = { } ret [ 'zorder' ] = ax . get_zorder ( ) ret [ 'yaxis_inverted' ] = ax . yaxis_inverted ( ) ret [ 'xaxis_inverted' ] = ax . xaxis_inverted ( ) for key , val in ax . spines . items ( ) : ret [ 'spines' ] [ key ] = { } for prop in [ 'linestyle' , 'edgecolor' , 'linewidth' , 'facecolor' , 'visible' ] : ret [ 'spines' ] [ key ] [ prop ] = getattr ( val , 'get_' + prop ) ( ) if isinstance ( ax , mfig . SubplotBase ) : sp = ax . get_subplotspec ( ) . get_topmost_subplotspec ( ) ret [ 'grid_spec' ] = sp . get_geometry ( ) [ : 2 ] ret [ 'subplotspec' ] = [ sp . num1 , sp . num2 ] ret [ 'is_subplot' ] = True else : ret [ 'args' ] = [ ax . get_position ( True ) . bounds ] ret [ 'is_subplot' ] = False return ret | Inspect an axes or subplot to get the initialization parameters |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.