idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
30,700
async def observer_poll ( self , message ) : await asyncio . sleep ( message [ 'interval' ] ) await self . channel_layer . send ( CHANNEL_WORKER , { 'type' : TYPE_EVALUATE , 'observer' : message [ 'observer' ] } )
Poll observer after a delay .
30,701
async def observer_evaluate ( self , message ) : observer_id = message [ 'observer' ] throttle_rate = get_queryobserver_settings ( ) [ 'throttle_rate' ] if throttle_rate <= 0 : await self . _evaluate ( observer_id ) return cache_key = throttle_cache_key ( observer_id ) try : count = cache . incr ( cache_key ) if count ...
Execute observer evaluation on the worker or throttle .
30,702
def websocket_connect ( self , message ) : self . session_id = self . scope [ 'url_route' ] [ 'kwargs' ] [ 'subscriber_id' ] super ( ) . websocket_connect ( message ) Subscriber . objects . get_or_create ( session_id = self . session_id )
Called when WebSocket connection is established .
30,703
def disconnect ( self , code ) : Subscriber . objects . filter ( session_id = self . session_id ) . delete ( )
Called when WebSocket connection is closed .
30,704
def observer_update ( self , message ) : for action in ( 'added' , 'changed' , 'removed' ) : for item in message [ action ] : self . send_json ( { 'msg' : action , 'observer' : message [ 'observer' ] , 'primary_key' : message [ 'primary_key' ] , 'order' : item [ 'order' ] , 'item' : item [ 'data' ] , } )
Called when update from observer is received .
30,705
def remove_subscriber ( session_id , observer_id ) : models . Observer . subscribers . through . objects . filter ( subscriber_id = session_id , observer_id = observer_id ) . delete ( )
Remove subscriber from the given observer .
30,706
def _get_logging_extra ( self , duration = None , results = None ) : return { 'duration' : duration , 'results' : results , 'observer_id' : self . id , 'viewset' : '{}.{}' . format ( self . _request . viewset_class . __module__ , self . _request . viewset_class . __name__ , ) , 'method' : self . _request . viewset_meth...
Extra information for logger .
30,707
def _get_logging_id ( self ) : return "{}.{}/{}" . format ( self . _request . viewset_class . __module__ , self . _request . viewset_class . __name__ , self . _request . viewset_method , )
Get logging identifier .
30,708
def _warning ( self , msg , duration = None , results = None ) : logger . warning ( "{} ({})" . format ( msg , self . _get_logging_id ( ) ) , extra = self . _get_logging_extra ( duration = duration , results = results ) , )
Log warnings .
30,709
async def evaluate ( self ) : @ database_sync_to_async def remove_subscribers ( ) : models . Observer . subscribers . through . objects . filter ( observer_id = self . id ) . delete ( ) @ database_sync_to_async def get_subscriber_sessions ( ) : return list ( models . Observer . subscribers . through . objects . filter ...
Evaluate the query observer .
30,710
def _viewset_results ( self ) : results = [ ] try : response = self . _viewset_method ( self . _viewset . request , * self . _request . args , ** self . _request . kwargs ) if response . status_code == 200 : results = response . data if not isinstance ( results , list ) : if isinstance ( results , dict ) : if 'results'...
Parse results from the viewset response .
30,711
def _evaluate ( self , viewset_results = None ) : if viewset_results is None : viewset_results = self . _viewset_results ( ) try : observer = models . Observer . objects . get ( id = self . id ) if observer . subscribers . count ( ) == 0 : return ( None , None , None ) models . Observer . objects . filter ( id = self ....
Evaluate query observer .
30,712
def observable ( _method_or_viewset = None , poll_interval = None , primary_key = None , dependencies = None ) : if poll_interval and dependencies : raise ValueError ( 'Only one of poll_interval and dependencies arguments allowed' ) def decorator_observable ( method_or_viewset ) : if inspect . isclass ( method_or_views...
Make ViewSet or ViewSet method observable .
30,713
def set_is_valid_rss ( self ) : if self . title and self . link and self . description : self . is_valid_rss = True else : self . is_valid_rss = False
Check to if this is actually a valid RSS feed
30,714
def set_extended_elements ( self ) : self . set_creative_commons ( ) self . set_owner ( ) self . set_subtitle ( ) self . set_summary ( )
Parses and sets non required elements
30,715
def set_itunes ( self ) : self . set_itunes_author_name ( ) self . set_itunes_block ( ) self . set_itunes_complete ( ) self . set_itunes_explicit ( ) self . set_itune_image ( ) self . set_itunes_keywords ( ) self . set_itunes_new_feed_url ( ) self . set_itunes_categories ( ) self . set_items ( )
Sets elements related to itunes
30,716
def set_optional_elements ( self ) : self . set_categories ( ) self . set_copyright ( ) self . set_generator ( ) self . set_image ( ) self . set_language ( ) self . set_last_build_date ( ) self . set_managing_editor ( ) self . set_published_date ( ) self . set_pubsubhubbub ( ) self . set_ttl ( ) self . set_web_master (...
Sets elements considered option by RSS spec
30,717
def set_soup ( self ) : self . soup = BeautifulSoup ( self . feed_content , "html.parser" ) for item in self . soup . findAll ( 'item' ) : item . decompose ( ) for image in self . soup . findAll ( 'image' ) : image . decompose ( )
Sets soup and strips items
30,718
def set_categories ( self ) : self . categories = [ ] temp_categories = self . soup . findAll ( 'category' ) for category in temp_categories : category_text = category . string self . categories . append ( category_text )
Parses and set feed categories
30,719
def count_items ( self ) : soup_items = self . soup . findAll ( 'item' ) full_soup_items = self . full_soup . findAll ( 'item' ) return len ( soup_items ) , len ( full_soup_items )
Counts Items in full_soup and soup . For debugging
30,720
def set_copyright ( self ) : try : self . copyright = self . soup . find ( 'copyright' ) . string except AttributeError : self . copyright = None
Parses copyright and set value
30,721
def set_creative_commons ( self ) : try : self . creative_commons = self . soup . find ( 'creativecommons:license' ) . string except AttributeError : self . creative_commons = None
Parses creative commons for item and sets value
30,722
def set_description ( self ) : try : self . description = self . soup . find ( 'description' ) . string except AttributeError : self . description = None
Parses description and sets value
30,723
def set_generator ( self ) : try : self . generator = self . soup . find ( 'generator' ) . string except AttributeError : self . generator = None
Parses feed generator and sets value
30,724
def set_image ( self ) : temp_soup = self . full_soup for item in temp_soup . findAll ( 'item' ) : item . decompose ( ) image = temp_soup . find ( 'image' ) try : self . image_title = image . find ( 'title' ) . string except AttributeError : self . image_title = None try : self . image_url = image . find ( 'url' ) . st...
Parses image element and set values
30,725
def set_itunes_author_name ( self ) : try : self . itunes_author_name = self . soup . find ( 'itunes:author' ) . string except AttributeError : self . itunes_author_name = None
Parses author name from itunes tags and sets value
30,726
def set_itunes_block ( self ) : try : block = self . soup . find ( 'itunes:block' ) . string . lower ( ) except AttributeError : block = "" if block == "yes" : self . itunes_block = True else : self . itunes_block = False
Check and see if podcast is blocked from iTunes and sets value
30,727
def set_itunes_categories ( self ) : self . itunes_categories = [ ] temp_categories = self . soup . findAll ( 'itunes:category' ) for category in temp_categories : category_text = category . get ( 'text' ) self . itunes_categories . append ( category_text )
Parses and set itunes categories
30,728
def set_itunes_complete ( self ) : try : self . itunes_complete = self . soup . find ( 'itunes:complete' ) . string self . itunes_complete = self . itunes_complete . lower ( ) except AttributeError : self . itunes_complete = None
Parses complete from itunes tags and sets value
30,729
def set_itunes_explicit ( self ) : try : self . itunes_explicit = self . soup . find ( 'itunes:explicit' ) . string self . itunes_explicit = self . itunes_explicit . lower ( ) except AttributeError : self . itunes_explicit = None
Parses explicit from itunes tags and sets value
30,730
def set_itune_image ( self ) : try : self . itune_image = self . soup . find ( 'itunes:image' ) . get ( 'href' ) except AttributeError : self . itune_image = None
Parses itunes images and set url as value
30,731
def set_itunes_keywords ( self ) : try : keywords = self . soup . find ( 'itunes:keywords' ) . string except AttributeError : keywords = None try : self . itunes_keywords = [ keyword . strip ( ) for keyword in keywords . split ( ',' ) ] self . itunes_keywords = list ( set ( self . itunes_keywords ) ) except AttributeEr...
Parses itunes keywords and set value
30,732
def set_itunes_new_feed_url ( self ) : try : self . itunes_new_feed_url = self . soup . find ( 'itunes:new-feed-url' ) . string except AttributeError : self . itunes_new_feed_url = None
Parses new feed url from itunes tags and sets value
30,733
def set_language ( self ) : try : self . language = self . soup . find ( 'language' ) . string except AttributeError : self . language = None
Parses feed language and set value
30,734
def set_last_build_date ( self ) : try : self . last_build_date = self . soup . find ( 'lastbuilddate' ) . string except AttributeError : self . last_build_date = None
Parses last build date and set value
30,735
def set_link ( self ) : try : self . link = self . soup . find ( 'link' ) . string except AttributeError : self . link = None
Parses link to homepage and set value
30,736
def set_managing_editor ( self ) : try : self . managing_editor = self . soup . find ( 'managingeditor' ) . string except AttributeError : self . managing_editor = None
Parses managing editor and set value
30,737
def set_published_date ( self ) : try : self . published_date = self . soup . find ( 'pubdate' ) . string except AttributeError : self . published_date = None
Parses published date and set value
30,738
def set_pubsubhubbub ( self ) : self . pubsubhubbub = None atom_links = self . soup . findAll ( 'atom:link' ) for atom_link in atom_links : rel = atom_link . get ( 'rel' ) if rel == "hub" : self . pubsubhubbub = atom_link . get ( 'href' )
Parses pubsubhubbub and email then sets value
30,739
def set_owner ( self ) : owner = self . soup . find ( 'itunes:owner' ) try : self . owner_name = owner . find ( 'itunes:name' ) . string except AttributeError : self . owner_name = None try : self . owner_email = owner . find ( 'itunes:email' ) . string except AttributeError : self . owner_email = None
Parses owner name and email then sets value
30,740
def set_subtitle ( self ) : try : self . subtitle = self . soup . find ( 'itunes:subtitle' ) . string except AttributeError : self . subtitle = None
Parses subtitle and sets value
30,741
def set_web_master ( self ) : try : self . web_master = self . soup . find ( 'webmaster' ) . string except AttributeError : self . web_master = None
Parses the feed s webmaster and sets value
30,742
def set_rss_element ( self ) : self . set_author ( ) self . set_categories ( ) self . set_comments ( ) self . set_creative_commons ( ) self . set_description ( ) self . set_enclosure ( ) self . set_guid ( ) self . set_link ( ) self . set_published_date ( ) self . set_title ( )
Set each of the basic rss elements .
30,743
def set_author ( self ) : try : self . author = self . soup . find ( 'author' ) . string except AttributeError : self . author = None
Parses author and set value .
30,744
def set_comments ( self ) : try : self . comments = self . soup . find ( 'comments' ) . string except AttributeError : self . comments = None
Parses comments and set value .
30,745
def set_enclosure ( self ) : try : self . enclosure_url = self . soup . find ( 'enclosure' ) [ 'url' ] except : self . enclosure_url = None try : self . enclosure_type = self . soup . find ( 'enclosure' ) [ 'type' ] except : self . enclosure_type = None try : self . enclosure_length = self . soup . find ( 'enclosure' )...
Parses enclosure_url enclosure_type then set values .
30,746
def set_guid ( self ) : try : self . guid = self . soup . find ( 'guid' ) . string except AttributeError : self . guid = None
Parses guid and set value
30,747
def set_title ( self ) : try : self . title = self . soup . find ( 'title' ) . string except AttributeError : self . title = None
Parses title and set value .
30,748
def set_itunes_element ( self ) : self . set_itunes_author_name ( ) self . set_itunes_block ( ) self . set_itunes_closed_captioned ( ) self . set_itunes_duration ( ) self . set_itunes_explicit ( ) self . set_itune_image ( ) self . set_itunes_order ( ) self . set_itunes_subtitle ( ) self . set_itunes_summary ( )
Set each of the itunes elements .
30,749
def set_itunes_closed_captioned ( self ) : try : self . itunes_closed_captioned = self . soup . find ( 'itunes:isclosedcaptioned' ) . string self . itunes_closed_captioned = self . itunes_closed_captioned . lower ( ) except AttributeError : self . itunes_closed_captioned = None
Parses isClosedCaptioned from itunes tags and sets value
30,750
def set_itunes_duration ( self ) : try : self . itunes_duration = self . soup . find ( 'itunes:duration' ) . string except AttributeError : self . itunes_duration = None
Parses duration from itunes tags and sets value
30,751
def set_itunes_order ( self ) : try : self . itunes_order = self . soup . find ( 'itunes:order' ) . string self . itunes_order = self . itunes_order . lower ( ) except AttributeError : self . itunes_order = None
Parses episode order and set url as value
30,752
def set_itunes_subtitle ( self ) : try : self . itunes_subtitle = self . soup . find ( 'itunes:subtitle' ) . string except AttributeError : self . itunes_subtitle = None
Parses subtitle from itunes tags and sets value
30,753
def set_itunes_summary ( self ) : try : self . itunes_summary = self . soup . find ( 'itunes:summary' ) . string except AttributeError : self . itunes_summary = None
Parses summary from itunes tags and sets value
30,754
def _apply_updates ( self , gradients ) : if not hasattr ( self , 'optimizers' ) : self . optimizers = { obj : AdaGradOptimizer ( self . learning_rate ) for obj in [ 'W' , 'C' , 'bw' , 'bc' ] } self . W -= self . optimizers [ 'W' ] . get_step ( gradients [ 'W' ] ) self . C -= self . optimizers [ 'C' ] . get_step ( grad...
Apply AdaGrad update to parameters .
30,755
def get_step ( self , grad ) : if self . _momentum is None : self . _momentum = self . initial_accumulator_value * np . ones_like ( grad ) self . _momentum += grad ** 2 return self . learning_rate * grad / np . sqrt ( self . _momentum )
Computes the step to take for the next gradient descent update .
30,756
def _format_param_value ( key , value ) : if isinstance ( value , str ) : value = "'{}'" . format ( value ) return "{}={}" . format ( key , value )
Wraps string values in quotes and returns as key = value .
30,757
def randmatrix ( m , n , random_seed = None ) : val = np . sqrt ( 6.0 / ( m + n ) ) np . random . seed ( random_seed ) return np . random . uniform ( - val , val , size = ( m , n ) )
Creates an m x n matrix of random values drawn using the Xavier Glorot method .
30,758
def _progressbar ( self , msg , iter_num ) : if self . display_progress and ( iter_num + 1 ) % self . display_progress == 0 : sys . stderr . write ( '\r' ) sys . stderr . write ( "Iteration {}: {}" . format ( iter_num + 1 , msg ) ) sys . stderr . flush ( )
Display a progress bar with current loss .
30,759
def _build_graph ( self , vocab , initial_embedding_dict ) : self . ones = tf . ones ( [ self . n_words , 1 ] ) if initial_embedding_dict is None : self . W = self . _weight_init ( self . n_words , self . n , 'W' ) self . C = self . _weight_init ( self . n_words , self . n , 'C' ) else : self . n = len ( next ( iter ( ...
Builds the computatation graph .
30,760
def _get_cost_function ( self ) : self . weights = tf . placeholder ( tf . float32 , shape = [ self . n_words , self . n_words ] ) self . log_coincidence = tf . placeholder ( tf . float32 , shape = [ self . n_words , self . n_words ] ) self . diffs = tf . subtract ( self . model , self . log_coincidence ) cost = tf . r...
Compute the cost of the Mittens objective function .
30,761
def _tf_squared_euclidean ( X , Y ) : return tf . reduce_sum ( tf . pow ( tf . subtract ( X , Y ) , 2 ) , axis = 1 )
Squared Euclidean distance between the rows of X and Y .
30,762
def _weight_init ( self , m , n , name ) : x = np . sqrt ( 6.0 / ( m + n ) ) with tf . name_scope ( name ) as scope : return tf . Variable ( tf . random_uniform ( [ m , n ] , minval = - x , maxval = x ) , name = name )
Uses the Xavier Glorot method for initializing weights . This is built in to TensorFlow as tf . contrib . layers . xavier_initializer but it s nice to see all the details .
30,763
def round_robin ( self , x , y , n_keep ) : vals = y . unique ( ) scores = { } for cls in vals : scores [ cls ] = self . rank ( x , np . equal ( cls , y ) . astype ( 'Int64' ) ) scores [ cls ] . reverse ( ) keepers = set ( ) while len ( keepers ) < n_keep : for cls in vals : keepers . add ( scores [ cls ] . pop ( ) [ 1...
Ensures all classes get representative features not just those with strong features
30,764
def dumppickle ( obj , fname , protocol = - 1 ) : with open ( fname , 'wb' ) as fout : pickle . dump ( obj , fout , protocol = protocol )
Pickle object obj to file fname .
30,765
def predict_maxprob ( self , x , ** kwargs ) : return self . base_estimator_ . predict ( x . values , ** kwargs )
Most likely value . Generally equivalent to predict .
30,766
def _pprint ( params ) : params_list = list ( ) line_sep = ',' for i , ( k , v ) in enumerate ( sorted ( params . iteritems ( ) ) ) : if type ( v ) is float : this_repr = '%s=%.10f' % ( k , v ) else : this_repr = '%s=%r' % ( k , v ) params_list . append ( this_repr ) lines = ',' . join ( params_list ) return lines
prints object state in stable manner
30,767
def cross_validate ( data = None , folds = 5 , repeat = 1 , metrics = None , reporters = None , model_def = None , ** kwargs ) : md_kwargs = { } if model_def is None : for arg in ModelDefinition . params : if arg in kwargs : md_kwargs [ arg ] = kwargs . pop ( arg ) model_def = ModelDefinition ( ** md_kwargs ) if metric...
Shortcut to cross - validate a single configuration .
30,768
def cv_factory ( data = None , folds = 5 , repeat = 1 , reporters = [ ] , metrics = None , cv_runner = None , ** kwargs ) : cv_runner = cv_runner or cross_validate md_kwargs = { } for arg in ModelDefinition . params : if arg in kwargs : md_kwargs [ arg ] = kwargs . pop ( arg ) model_def_fact = model_definition_factory ...
Shortcut to iterate and cross - validate models .
30,769
def build_report ( self ) : thresholds = self . thresholds lower_quantile = self . config [ 'lower_quantile' ] upper_quantile = self . config [ 'upper_quantile' ] if self . n_current_results > self . n_cached_curves : colnames = [ '_' . join ( [ metric , stat ] ) for metric in [ self . metric1 . name , self . metric2 ....
Calculates the pair of metrics for each threshold for each result .
30,770
def model_definition_factory ( base_model_definition , ** kwargs ) : if not kwargs : yield config else : for param in kwargs : if not hasattr ( base_model_definition , param ) : raise ValueError ( "'%s' is not a valid configuration parameter" % param ) for raw_params in itertools . product ( * kwargs . values ( ) ) : n...
Provides an iterator over passed - in configuration values allowing for easy exploration of models .
30,771
def summary ( self ) : if self . features is not None : feature_count = len ( self . features ) else : feature_count = 0 feature_hash = 'feathash:' + str ( hash ( tuple ( self . features ) ) ) return ( str ( self . estimator ) , feature_count , feature_hash , self . target )
Summary of model definition for labeling . Intended to be somewhat readable but unique to a given model definition .
30,772
def column_rename ( self , existing_name , hsh = None ) : try : existing_name = str ( existing_name ) except UnicodeEncodeError : pass if hsh is None : hsh = self . _hash ( ) if self . _name : return '%s(%s) [%s]' % ( self . _name , self . _remove_hashes ( existing_name ) , hsh ) return '%s [%s]' % ( self . _remove_has...
Like unique_name but in addition must be unique to each column of this feature . accomplishes this by prepending readable string to existing column name and replacing unique hash at end of column name .
30,773
def ecdsa_signature_normalize ( self , raw_sig , check_only = False ) : if check_only : sigout = ffi . NULL else : sigout = ffi . new ( 'secp256k1_ecdsa_signature *' ) result = lib . secp256k1_ecdsa_signature_normalize ( self . ctx , sigout , raw_sig ) return ( bool ( result ) , sigout if sigout != ffi . NULL else None...
Check and optionally convert a signature to a normalized lower - S form . If check_only is True then the normalized signature is not returned .
30,774
def schnorr_partial_combine ( self , schnorr_sigs ) : if not HAS_SCHNORR : raise Exception ( "secp256k1_schnorr not enabled" ) assert len ( schnorr_sigs ) > 0 sig64 = ffi . new ( 'char [64]' ) sig64sin = [ ] for sig in schnorr_sigs : if not isinstance ( sig , bytes ) : raise TypeError ( 'expected bytes, got {}' . forma...
Combine multiple Schnorr partial signatures .
30,775
def combine ( self , pubkeys ) : assert len ( pubkeys ) > 0 outpub = ffi . new ( 'secp256k1_pubkey *' ) for item in pubkeys : assert ffi . typeof ( item ) is ffi . typeof ( 'secp256k1_pubkey *' ) res = lib . secp256k1_ec_pubkey_combine ( self . ctx , outpub , pubkeys , len ( pubkeys ) ) if not res : raise Exception ( '...
Add a number of public keys together .
30,776
def schnorr_generate_nonce_pair ( self , msg , raw = False , digest = hashlib . sha256 ) : if not HAS_SCHNORR : raise Exception ( "secp256k1_schnorr not enabled" ) msg32 = _hash32 ( msg , raw , digest ) pubnonce = ffi . new ( 'secp256k1_pubkey *' ) privnonce = ffi . new ( 'char [32]' ) valid = lib . secp256k1_schnorr_g...
Generate a nonce pair deterministically for use with schnorr_partial_sign .
30,777
def schnorr_partial_sign ( self , msg , privnonce , pubnonce_others , raw = False , digest = hashlib . sha256 ) : if not HAS_SCHNORR : raise Exception ( "secp256k1_schnorr not enabled" ) msg32 = _hash32 ( msg , raw , digest ) sig64 = ffi . new ( 'char [64]' ) res = lib . secp256k1_schnorr_partial_sign ( self . ctx , si...
Produce a partial Schnorr signature which can be combined using schnorr_partial_combine to end up with a full signature that is verifiable using PublicKey . schnorr_verify .
30,778
def build_flags ( library , type_ , path ) : pkg_config_path = [ path ] if "PKG_CONFIG_PATH" in os . environ : pkg_config_path . append ( os . environ [ 'PKG_CONFIG_PATH' ] ) if "LIB_DIR" in os . environ : pkg_config_path . append ( os . environ [ 'LIB_DIR' ] ) pkg_config_path . append ( os . path . join ( os . environ...
Return separated build flags from pkg - config output
30,779
def command ( self , group = None , help = "" , name = None ) : def decorator ( func ) : return self . add_command ( func , group = group , help = help , name = name ) return decorator
Decorator for adding a command to this manager .
30,780
def parse_args ( cliargs ) : largs = [ ] for arg in cliargs : if "=" in arg : key , arg = arg . split ( "=" ) largs . append ( key ) largs . append ( arg ) args = [ ] flags = [ ] kwargs = { } key = None for sarg in largs : if is_key ( sarg ) : if key is not None : flags . append ( key ) key = sarg . strip ( "-" ) conti...
Parse the command line arguments and return a list of the positional arguments and a dictionary with the named ones .
30,781
def param ( name , help = "" ) : def decorator ( func ) : params = getattr ( func , "params" , [ ] ) _param = Param ( name , help ) params . insert ( 0 , _param ) func . params = params return func return decorator
Decorator that add a parameter to the wrapped command or function .
30,782
def option ( name , help = "" ) : def decorator ( func ) : options = getattr ( func , "options" , [ ] ) _option = Param ( name , help ) options . insert ( 0 , _option ) func . options = options return func return decorator
Decorator that add an option to the wrapped command or function .
30,783
def _open_file_obj ( f , mode = "r" ) : if isinstance ( f , six . string_types ) : if f . startswith ( ( "http://" , "https://" ) ) : file_obj = _urlopen ( f ) yield file_obj file_obj . close ( ) else : with open ( f , mode ) as file_obj : yield file_obj else : yield f
A context manager that provides access to a file .
30,784
def split_version ( version ) : if re . match ( "^[^0-9].*" , version ) : return [ version ] return [ int ( i ) for i in version . split ( "." ) ]
Split version to a list of integers that can be easily compared .
30,785
def get_major_version ( version , remove = None ) : if remove : warnings . warn ( "remove argument is deprecated" , DeprecationWarning ) version_split = version . split ( "." ) return version_split [ 0 ]
Return major version of a provided version string . Major version is the first component of the dot - separated version string . For non - version - like strings this function returns the argument unchanged .
30,786
def get_minor_version ( version , remove = None ) : if remove : warnings . warn ( "remove argument is deprecated" , DeprecationWarning ) version_split = version . split ( "." ) try : return version_split [ 1 ] except IndexError : return None
Return minor version of a provided version string . Minor version is the second component in the dot - separated version string . For non - version - like strings this function returns None .
30,787
def create_release_id ( short , version , type , bp_short = None , bp_version = None , bp_type = None ) : if not is_valid_release_short ( short ) : raise ValueError ( "Release short name is not valid: %s" % short ) if not is_valid_release_version ( version ) : raise ValueError ( "Release short version is not valid: %s"...
Create release_id from given parts .
30,788
def _assert_matches_re ( self , field , expected_patterns ) : value = getattr ( self , field ) for pattern in expected_patterns : try : if pattern . match ( value ) : return except AttributeError : if re . match ( pattern , value ) : return raise ValueError ( "%s: Field '%s' has invalid value: %s. It does not match any...
The list of patterns can contain either strings or compiled regular expressions .
30,789
def loads ( self , s ) : io = six . StringIO ( ) io . write ( s ) io . seek ( 0 ) self . load ( io ) self . validate ( )
Load data from a string .
30,790
def dump ( self , f ) : self . validate ( ) with _open_file_obj ( f , "w" ) as f : parser = self . _get_parser ( ) self . serialize ( parser ) self . build_file ( parser , f )
Dump data to a file .
30,791
def dumps ( self ) : io = six . StringIO ( ) self . dump ( io ) io . seek ( 0 ) return io . read ( )
Dump data to a string .
30,792
def _validate_version ( self ) : self . _assert_type ( "version" , list ( six . string_types ) ) self . _assert_matches_re ( "version" , [ RELEASE_VERSION_RE ] )
If the version starts with a digit it must be a sematic - versioning style string .
30,793
def type_suffix ( self ) : if not self . type or self . type . lower ( ) == 'ga' : return '' return '-%s' % self . type . lower ( )
This is used in compose ID .
30,794
def get_variants ( self , arch = None , types = None , recursive = False ) : types = types or [ ] result = [ ] if "self" in types : result . append ( self ) for variant in six . itervalues ( self . variants ) : if types and variant . type not in types : continue if arch and arch not in variant . arches . union ( [ "src...
Return all variants of given arch and types .
30,795
def add ( self , variant , arch , nevra , path , sigkey , category , srpm_nevra = None ) : if arch not in productmd . common . RPM_ARCHES : raise ValueError ( "Arch not found in RPM_ARCHES: %s" % arch ) if arch in [ "src" , "nosrc" ] : raise ValueError ( "Source arch is not allowed. Map source files under binary arches...
Map RPM to to variant and arch .
30,796
def album_to_ref ( album ) : name = '' for artist in album . artists : if len ( name ) > 0 : name += ', ' name += artist . name if ( len ( name ) ) > 0 : name += ' - ' if album . name : name += album . name else : name += 'Unknown Album' return Ref . directory ( uri = album . uri , name = name )
Convert a mopidy album to a mopidy ref .
30,797
def artist_to_ref ( artist ) : if artist . name : name = artist . name else : name = 'Unknown artist' return Ref . directory ( uri = artist . uri , name = name )
Convert a mopidy artist to a mopidy ref .
30,798
def track_to_ref ( track , with_track_no = False ) : if with_track_no and track . track_no > 0 : name = '%d - ' % track . track_no else : name = '' for artist in track . artists : if len ( name ) > 0 : name += ', ' name += artist . name if ( len ( name ) ) > 0 : name += ' - ' name += track . name return Ref . track ( u...
Convert a mopidy track to a mopidy ref .
30,799
def user ( self , user : str ) -> "ChildHTTPAPI" : if self . is_real_user : raise ValueError ( "Can't get child of real user" ) try : return self . children [ user ] except KeyError : child = ChildHTTPAPI ( user , self ) self . children [ user ] = child return child
Get a child HTTPAPI instance .