signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def extract_model_meta ( base_meta : dict , extra_meta : dict , model_url : str ) -> dict : """Merge the metadata from the backend and the extra metadata into a dict which is suitable for ` index . json ` . : param base _ meta : tree [ " meta " ] : class : ` dict ` containing data from the backend . : param ext...
meta = { "default" : { "default" : base_meta [ "uuid" ] , "description" : base_meta [ "description" ] , "code" : extra_meta [ "code" ] } } del base_meta [ "model" ] del base_meta [ "uuid" ] meta [ "model" ] = base_meta meta [ "model" ] . update ( { k : extra_meta [ k ] for k in ( "code" , "datasets" , "references" , "t...
def ArcCos ( input_vertex : vertex_constructor_param_types , label : Optional [ str ] = None ) -> Vertex : """Takes the inverse cosine of a vertex , Arccos ( vertex ) : param input _ vertex : the vertex"""
return Double ( context . jvm_view ( ) . ArcCosVertex , label , cast_to_double_vertex ( input_vertex ) )
def _get_color ( color ) : """Returns a QColor built from a Pygments color string ."""
color = str ( color ) . replace ( "#" , "" ) qcolor = QtGui . QColor ( ) qcolor . setRgb ( int ( color [ : 2 ] , base = 16 ) , int ( color [ 2 : 4 ] , base = 16 ) , int ( color [ 4 : 6 ] , base = 16 ) ) return qcolor
def create ( self , object_type , under = None , attributes = None , ** kwattrs ) : """Create a new automation object . Arguments : object _ type - - Type of object to create . under - - Handle of the parent of the new object . attributes - - Dictionary of attributes ( name - value pairs ) . kwattrs - - O...
data = self . createx ( object_type , under , attributes , ** kwattrs ) return data [ 'handle' ]
def precision ( links_true , links_pred = None ) : """precision ( links _ true , links _ pred ) Compute the precision . The precision is given by TP / ( TP + FP ) . Parameters links _ true : pandas . MultiIndex , pandas . DataFrame , pandas . Series The true ( or actual ) collection of links . links _ p...
if _isconfusionmatrix ( links_true ) : confusion_matrix = links_true v = confusion_matrix [ 0 , 0 ] / ( confusion_matrix [ 0 , 0 ] + confusion_matrix [ 1 , 0 ] ) else : tp = true_positives ( links_true , links_pred ) fp = false_positives ( links_true , links_pred ) v = tp / ( tp + fp ) return float ...
def get_membership_document ( membership_type : str , current_block : dict , identity : Identity , salt : str , password : str ) -> Membership : """Get a Membership document : param membership _ type : " IN " to ask for membership or " OUT " to cancel membership : param current _ block : Current block data : ...
# get current block BlockStamp timestamp = BlockUID ( current_block [ 'number' ] , current_block [ 'hash' ] ) # create keys from credentials key = SigningKey . from_credentials ( salt , password ) # create identity document membership = Membership ( version = 10 , currency = current_block [ 'currency' ] , issuer = key ...
def close ( self ) -> None : """To act as a file ."""
if self . underlying_stream : if self . using_stdout : sys . stdout = self . underlying_stream else : sys . stderr = self . underlying_stream self . underlying_stream = None if self . file : # Do NOT close the file ; we don ' t own it . self . file = None log . debug ( "Finished copy...
def tag_evidence_subtype ( evidence ) : """Returns the type and subtype of an evidence object as a string , typically the extraction rule or database from which the statement was generated . For biopax , this is just the database name . Parameters statement : indra . statements . Evidence The statement ...
source_api = evidence . source_api annotations = evidence . annotations if source_api == 'biopax' : subtype = annotations . get ( 'source_sub_id' ) elif source_api in ( 'reach' , 'eidos' ) : if 'found_by' in annotations : from indra . sources . reach . processor import determine_reach_subtype if...
def perform_job ( self , job ) : """Wraps a job . perform ( ) call with timeout logic and exception handlers . This is the first call happening inside the greenlet ."""
if self . config [ "trace_memory" ] : job . trace_memory_start ( ) set_current_job ( job ) try : job . perform ( ) except MaxConcurrencyInterrupt : self . log . error ( "Max concurrency reached" ) job . _save_status ( "maxconcurrency" , exception = True ) except RetryInterrupt : self . log . error (...
def serialize ( self ) : """Return the string representation of the receiver ."""
res = '<?xml version="1.0" encoding="UTF-8"?>' for ns in self . namespaces : self . top_grammar . attr [ "xmlns:" + self . namespaces [ ns ] ] = ns res += self . top_grammar . start_tag ( ) for ch in self . top_grammar . children : res += ch . serialize ( ) res += self . tree . serialize ( ) for d in self . glo...
def write_measurement ( measurement , root_file = None , xml_path = None , output_path = None , output_suffix = None , write_workspaces = False , apply_xml_patches = True , silence = False ) : """Write a measurement and RooWorkspaces for all contained channels into a ROOT file and write the XML files into a direc...
context = silence_sout_serr if silence else do_nothing output_name = measurement . name if output_suffix is not None : output_name += '_{0}' . format ( output_suffix ) output_name = output_name . replace ( ' ' , '_' ) if xml_path is None : xml_path = 'xml_{0}' . format ( output_name ) if output_path is not ...
def create_user ( self , uid , name , password , channel = None , callback = False , link_auth = True , ipmi_msg = True , privilege_level = 'user' ) : """create / ensure a user is created with provided settings ( helper ) : param privilege _ level : User Privilege Limit . ( Determines the maximum privilege leve...
# current user might be trying to update . . dont disable # set _ user _ password ( uid , password , mode = ' disable ' ) if channel is None : channel = self . get_network_channel ( ) self . set_user_name ( uid , name ) self . set_user_password ( uid , password = password ) self . set_user_password ( uid , mode = '...
def msg_curse ( self , args = None , max_width = None ) : """Return the string to display in the curse interface ."""
# Init the return message ret = [ ] # Build the string message if args . client : # Client mode if args . cs_status . lower ( ) == "connected" : msg = 'Connected to ' ret . append ( self . curse_add_line ( msg , 'OK' ) ) elif args . cs_status . lower ( ) == "snmp" : msg = 'SNMP from ' ...
def access_with_service ( self , service , use_xarray = None ) : """Access the dataset using a particular service . Return an Python object capable of communicating with the server using the particular service . For instance , for ' HTTPServer ' this is a file - like object capable of HTTP communication ; for...
service = CaseInsensitiveStr ( service ) if service == 'CdmRemote' : if use_xarray : from . cdmr . xarray_support import CDMRemoteStore try : import xarray as xr provider = lambda url : xr . open_dataset ( CDMRemoteStore ( url ) ) # noqa : E731 except Impo...
def requires_role ( role_s , logical_operator = all ) : """Requires that the calling Subject be authorized to the extent that is required to satisfy the role _ s specified and the logical operation upon them . : param role _ s : a collection of the role ( s ) required , specified by identifiers ( such as a ...
def outer_wrap ( fn ) : @ functools . wraps ( fn ) def inner_wrap ( * args , ** kwargs ) : subject = Yosai . get_current_subject ( ) subject . check_role ( role_s , logical_operator ) return fn ( * args , ** kwargs ) return inner_wrap return outer_wrap
def setLabels ( self , name ) : """Sets plot labels , according to predefined options : param name : The type of plot to create labels for . Options : calibration , tuning , anything else labels for spike counts : type name : str"""
if name == "calibration" : self . setWindowTitle ( "Calibration Curve" ) self . setTitle ( "Calibration Curve" ) self . setLabel ( 'bottom' , "Frequency" , units = 'Hz' ) self . setLabel ( 'left' , 'Recorded Intensity (dB SPL)' ) elif name == "tuning" : self . setWindowTitle ( "Tuning Curve" ) s...
def estimate_bg ( self , fit_offset = "mean" , fit_profile = "tilt" , border_px = 0 , from_mask = None , ret_mask = False ) : """Estimate image background Parameters fit _ profile : str The type of background profile to fit : - " offset " : offset only - " poly2o " : 2D 2nd order polynomial with mixed ter...
# remove existing bg before accessing imdat . image self . set_bg ( bg = None , key = "fit" ) # compute bg bgimage , mask = bg_estimate . estimate ( data = self . image , fit_offset = fit_offset , fit_profile = fit_profile , border_px = border_px , from_mask = from_mask , ret_mask = True ) attrs = { "fit_offset" : fit_...
def bookmarks ( ) : """Bookmarks ."""
res = None bukudb = getattr ( flask . g , 'bukudb' , get_bukudb ( ) ) page = request . args . get ( get_page_parameter ( ) , type = int , default = 1 ) per_page = request . args . get ( get_per_page_parameter ( ) , type = int , default = int ( current_app . config . get ( 'BUKUSERVER_PER_PAGE' , views . DEFAULT_PER_PAG...
def spiceErrorCheck ( f ) : """Decorator for spiceypy hooking into spice error system . If an error is detected , an output similar to outmsg : type f : builtins . function : return : : rtype :"""
@ functools . wraps ( f ) def with_errcheck ( * args , ** kwargs ) : try : res = f ( * args , ** kwargs ) checkForSpiceError ( f ) return res except : raise return with_errcheck
def parse ( self , text ) : """Parse text to obtain list of Segments"""
text = self . preprocess ( text ) token_stack = [ ] last_pos = 0 # Iterate through all matched tokens for match in self . regex . finditer ( text ) : # Find which token has been matched by regex token , match_type , group = self . get_matched_token ( match ) # Get params from stack of tokens params = self ....
def hook ( * hook_patterns ) : """Register the decorated function to run when the current hook matches any of the ` ` hook _ patterns ` ` . This decorator is generally deprecated and should only be used when absolutely necessary . The hook patterns can use the ` ` { interface : . . . } ` ` and ` ` { A , B ,...
def _register ( action ) : def arg_gen ( ) : # use a generator to defer calling of hookenv . relation _ type , for tests rel = endpoint_from_name ( hookenv . relation_type ( ) ) if rel : yield rel handler = Handler . get ( action ) handler . add_predicate ( partial ( _hook , hook...
def page ( self , course ) : """Get all data and display the page"""
if not self . webdav_host : raise web . notfound ( ) url = self . webdav_host + "/" + course . get_id ( ) username = self . user_manager . session_username ( ) apikey = self . user_manager . session_api_key ( ) return self . template_helper . get_renderer ( ) . course_admin . webdav ( course , url , username , apik...
def connected_outports ( self ) : '''The list of all output ports belonging to this component that are connected to one or more other ports .'''
return [ p for p in self . ports if p . __class__ . __name__ == 'DataOutPort' and p . is_connected ]
def stop ( self ) : """Stop the running task"""
if self . _thread is not None and self . _thread . isAlive ( ) : self . _done . set ( )
def run ( program , * args , ** kwargs ) : """Run ' program ' with ' args '"""
args = flattened ( args , split = SHELL ) full_path = which ( program ) logger = kwargs . pop ( "logger" , LOG . debug ) fatal = kwargs . pop ( "fatal" , True ) dryrun = kwargs . pop ( "dryrun" , is_dryrun ( ) ) include_error = kwargs . pop ( "include_error" , False ) message = "Would run" if dryrun else "Running" mess...
def from_record ( cls , record , crs ) : """Load vector from record ."""
if 'type' not in record : raise TypeError ( "The data isn't a valid record." ) return cls ( to_shape ( record ) , crs )
def schema ( self ) : """List [ : class : ` ~ google . cloud . bigquery . schema . SchemaField ` ] : The schema for the data . See https : / / cloud . google . com / bigquery / docs / reference / rest / v2 / jobs # configuration . query . tableDefinitions . ( key ) . schema https : / / cloud . google . com ...
prop = self . _properties . get ( "schema" , { } ) return [ SchemaField . from_api_repr ( field ) for field in prop . get ( "fields" , [ ] ) ]
def _gather_files ( app , hidden , filepath_filter_regex = None ) : """Gets all files in static folders and returns in dict ."""
dirs = [ ( six . text_type ( app . static_folder ) , app . static_url_path ) ] if hasattr ( app , 'blueprints' ) : blueprints = app . blueprints . values ( ) bp_details = lambda x : ( x . static_folder , _bp_static_url ( x ) ) dirs . extend ( [ bp_details ( x ) for x in blueprints if x . static_folder ] ) v...
def parse ( cls , args ) : """Parse command line arguments to construct a dictionary of command parameters that can be used to create a command Args : ` args ` : sequence of arguments Returns : Dictionary that can be used in create method Raises : ParseError : when the arguments are not correct"""
parsed = { } try : ( options , args ) = cls . optparser . parse_args ( args ) except OptionParsingError as e : raise ParseError ( e . msg , cls . optparser . format_help ( ) ) except OptionParsingExit as e : return None parsed [ 'label' ] = options . label parsed [ 'can_notify' ] = options . can_notify pars...
def iteritems_sorted ( dict_ ) : """change to iteritems ordered"""
if isinstance ( dict_ , OrderedDict ) : return six . iteritems ( dict_ ) else : return iter ( sorted ( six . iteritems ( dict_ ) ) )
def right_shift_blockwise ( x , query_shape , name = None ) : """Right shifts once in every block . Args : x : a tensor of shape [ batch , height , width , depth ] query _ shape : A 2d tuple of ints name : a string Returns : output : a tensor of the same shape as x"""
with tf . variable_scope ( name , default_name = "right_shift_blockwise" , values = [ x ] ) : x_list_shape = x . get_shape ( ) . as_list ( ) x_shape = common_layers . shape_list ( x ) # Add a dummy dimension for heads . x = tf . expand_dims ( x , axis = 1 ) x = pad_to_multiple_2d ( x , query_shape )...
def update_device ( self , device_id , ** kwargs ) : """Update existing device in catalog . . . code - block : : python existing _ device = api . get _ device ( . . . ) updated _ device = api . update _ device ( existing _ device . id , certificate _ fingerprint = " something new " : param str device _ ...
api = self . _get_api ( device_directory . DefaultApi ) device = Device . _create_request_map ( kwargs ) body = DeviceDataPostRequest ( ** device ) return Device ( api . device_update ( device_id , body ) )
def play ( env , transpose = True , fps = 30 , nop_ = 0 ) : """Play the game using the keyboard as a human . Args : env ( gym . Env ) : the environment to use for playing transpose ( bool ) : whether to transpose frame before viewing them fps ( int ) : number of steps of the environment to execute every sec...
# ensure the observation space is a box of pixels assert isinstance ( env . observation_space , gym . spaces . box . Box ) # ensure the observation space is either B & W pixels or RGB Pixels obs_s = env . observation_space is_bw = len ( obs_s . shape ) == 2 is_rgb = len ( obs_s . shape ) == 3 and obs_s . shape [ 2 ] in...
def _xfs_estimate_output ( out ) : '''Parse xfs _ estimate output .'''
spc = re . compile ( r"\s+" ) data = { } for line in [ l for l in out . split ( "\n" ) if l . strip ( ) ] [ 1 : ] : directory , bsize , blocks , megabytes , logsize = spc . sub ( " " , line ) . split ( " " ) data [ directory ] = { 'block _size' : bsize , 'blocks' : blocks , 'megabytes' : megabytes , 'logsize' :...
def is_linear ( self ) : """Tests whether all filters in the list are linear . CascadeFilter and ParallelFilter instances are also linear if all filters they group are linear ."""
return all ( isinstance ( filt , LinearFilter ) or ( hasattr ( filt , "is_linear" ) and filt . is_linear ( ) ) for filt in self . callables )
def replace ( self ) : """Replace index with a new one zero _ downtime _ index for safety and rollback"""
with zero_downtime_index ( self . alias_name , self . index_config ( ) ) as target_index : self . index_all ( target_index )
def connect_to ( self , vertex , weight = 1 ) : """Connect this vertex to another one . Args : vertex ( Vertex ) : vertex to connect to . weight ( int ) : weight of the edge . Returns : Edge : the newly created edge ."""
for edge in self . edges_out : if vertex == edge . vertex_in : return edge return Edge ( self , vertex , weight )
def _search ( self , base , fltr , attrs = None , scope = ldap . SCOPE_SUBTREE ) : """Perform LDAP search"""
try : results = self . _conn . search_s ( base , scope , fltr , attrs ) except Exception as e : log . exception ( self . _get_ldap_msg ( e ) ) results = False return results
def get_raw_counts ( self ) : """Determines counts for unique words , repetitions , etc using the raw text response . Adds the following measures to the self . measures dictionary : - COUNT _ total _ words : count of words ( i . e . utterances with semantic content ) spoken by the subject . Filled pauses , si...
# for making the table at the end words = [ ] labels = [ ] words_said = set ( ) # Words like " polar _ bear " as one semantically but two phonetically # Uncategorizable words are counted as asides for unit in self . parsed_response : word = unit . text test = False if self . type == "PHONETIC" : tes...
def transform ( data , keysToSplit = [ ] ) : """Transform a SPARQL json result by : 1 ) outputing only { key : value } , removing datatype 2 ) for some keys , transform them into array based on SEPARATOR"""
transformed = { } for key in data : if key in keysToSplit : transformed [ key ] = data [ key ] [ 'value' ] . split ( SEPARATOR ) else : transformed [ key ] = data [ key ] [ 'value' ] return transformed
def get_attachment_formset_kwargs ( self ) : """Returns the keyword arguments for instantiating the attachment formset ."""
kwargs = { 'prefix' : 'attachment' , } if self . request . method in ( 'POST' , 'PUT' ) : kwargs . update ( { 'data' : self . request . POST , 'files' : self . request . FILES , } ) else : post = self . get_post ( ) attachment_queryset = Attachment . objects . filter ( post = post ) kwargs . update ( { ...
def _check_and_uninstall_ruby ( ret , ruby , user = None ) : '''Verify that ruby is uninstalled'''
ret = _ruby_installed ( ret , ruby , user = user ) if ret [ 'result' ] : if ret [ 'default' ] : __salt__ [ 'rbenv.default' ] ( 'system' , runas = user ) if __salt__ [ 'rbenv.uninstall_ruby' ] ( ruby , runas = user ) : ret [ 'result' ] = True ret [ 'changes' ] [ ruby ] = 'Uninstalled' ...
def _supervised_evaluation_error_checking ( targets , predictions ) : """Perform basic error checking for the evaluation metrics . Check types and sizes of the inputs ."""
_raise_error_if_not_sarray ( targets , "targets" ) _raise_error_if_not_sarray ( predictions , "predictions" ) if ( len ( targets ) != len ( predictions ) ) : raise _ToolkitError ( "Input SArrays 'targets' and 'predictions' must be of the same length." )
def _handleSmsReceived ( self , notificationLine ) : """Handler for " new SMS " unsolicited notification line"""
self . log . debug ( 'SMS message received' ) cmtiMatch = self . CMTI_REGEX . match ( notificationLine ) if cmtiMatch : msgMemory = cmtiMatch . group ( 1 ) msgIndex = cmtiMatch . group ( 2 ) sms = self . readStoredSms ( msgIndex , msgMemory ) self . deleteStoredSms ( msgIndex ) self . smsReceivedCal...
def fit ( self , matrix , epochs = 5 , no_threads = 2 , verbose = False ) : """Estimate the word embeddings . Parameters : - scipy . sparse . coo _ matrix matrix : coocurrence matrix - int epochs : number of training epochs - int no _ threads : number of training threads - bool verbose : print progress me...
shape = matrix . shape if ( len ( shape ) != 2 or shape [ 0 ] != shape [ 1 ] ) : raise Exception ( 'Coocurrence matrix must be square' ) if not sp . isspmatrix_coo ( matrix ) : raise Exception ( 'Coocurrence matrix must be in the COO format' ) random_state = check_random_state ( self . random_state ) self . wor...
def extend ( self , iterable ) : """Add each item from iterable to the end of the list"""
with self . lock : for item in iterable : self . append ( item )
def list_settings ( self ) : """Get list of all appropriate settings and their default values . The returned list is then used in setup ( ) and get _ setup ( ) methods to setup the widget internal settings ."""
return [ ( self . SETTING_FLAG_PLAIN , False ) , ( self . SETTING_FLAG_ASCII , False ) , ( self . SETTING_WIDTH , 0 ) , ( self . SETTING_ALIGN , '<' ) , ( self . SETTING_TEXT_FORMATING , { } ) , ( self . SETTING_DATA_FORMATING , '{:s}' ) , ( self . SETTING_DATA_TYPE , None ) , ( self . SETTING_PADDING , None ) , ( self...
def delete_namespaced_custom_object ( self , group , version , namespace , plural , name , body , ** kwargs ) : """Deletes the specified namespace scoped custom object This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread =...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . delete_namespaced_custom_object_with_http_info ( group , version , namespace , plural , name , body , ** kwargs ) else : ( data ) = self . delete_namespaced_custom_object_with_http_info ( group , version , namespace , plu...
def _assign_par_snps ( self ) : """Assign PAR SNPs to the X or Y chromosome using SNP position . References . . [ 1 ] National Center for Biotechnology Information , Variation Services , RefSNP , https : / / api . ncbi . nlm . nih . gov / variation / v0/ . . [ 2 ] Yates et . al . ( doi : 10.1093 / bioinform...
rest_client = EnsemblRestClient ( server = "https://api.ncbi.nlm.nih.gov" ) for rsid in self . snps . loc [ self . snps [ "chrom" ] == "PAR" ] . index . values : if "rs" in rsid : try : id = rsid . split ( "rs" ) [ 1 ] response = rest_client . perform_rest_action ( "/variation/v0/bet...
def put ( self , name , values , request = None , process = None , wait = None , get = True ) : """Write a new value of some number of PVs . : param name : A single name string or list of name strings : param values : A single value , a list of values , a dict , a ` Value ` . May be modified by the constructor ...
if request and ( process or wait is not None ) : raise ValueError ( "request= is mutually exclusive to process= or wait=" ) elif process or wait is not None : request = 'field()record[block=%s,process=%s]' % ( 'true' if wait else 'false' , process or 'passive' ) singlepv = isinstance ( name , ( bytes , str ) ) ...
def _check_extension_shape ( self , Y ) : """Private method to check if new data matches ` self . data ` Parameters Y : array - like , shape = [ n _ samples _ y , n _ features _ y ] Input data Returns Y : array - like , shape = [ n _ samples _ y , n _ pca ] ( Potentially transformed ) input data Raise...
if len ( Y . shape ) != 2 : raise ValueError ( "Expected a 2D matrix. Y has shape {}" . format ( Y . shape ) ) if not Y . shape [ 1 ] == self . data_nu . shape [ 1 ] : # try PCA transform if Y . shape [ 1 ] == self . data . shape [ 1 ] : Y = self . transform ( Y ) else : # wrong shape if sel...
def ensure_permissions ( path , user , group , permissions , maxdepth = - 1 ) : """Ensure permissions for path . If path is a file , apply to file and return . If path is a directory , apply recursively ( if required ) to directory contents and return . : param user : user name : param group : group name ...
if not os . path . exists ( path ) : log ( "File '%s' does not exist - cannot set permissions" % ( path ) , level = WARNING ) return _user = pwd . getpwnam ( user ) os . chown ( path , _user . pw_uid , grp . getgrnam ( group ) . gr_gid ) os . chmod ( path , permissions ) if maxdepth == 0 : log ( "Max recurs...
def hexdigest ( self ) : """Terminate and return digest in HEX form . Like digest ( ) except the digest is returned as a string of length 32 , containing only hexadecimal digits . This may be used to exchange the value safely in email or other non - binary environments ."""
d = map ( None , self . digest ( ) ) d = map ( ord , d ) d = map ( lambda x : "%02x" % x , d ) d = string . join ( d , '' ) return d
def _set_syslog_server ( self , v , load = False ) : """Setter method for syslog _ server , mapped from YANG variable / logging / syslog _ server ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ syslog _ server is considered as a private method . Backends look...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "syslogip use_vrf" , syslog_server . syslog_server , yang_name = "syslog-server" , rest_name = "syslog-server" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper ...
def meta ( r ) : """Convert 60 character string ` r ` , the metadata from an image file . Returns a 5 - tuple ( * chan * , * minx * , * miny * , * limx * , * limy * ) . 5 - tuples may settle into lists in transit . As per http : / / plan9 . bell - labs . com / magic / man2html / 6 / image the metadata compr...
r = r . split ( ) # : todo : raise FormatError assert len ( r ) == 5 r = [ r [ 0 ] ] + map ( int , r [ 1 : ] ) return r
async def issuer_create_schema ( issuer_did : str , name : str , version : str , attrs : str ) -> ( str , str ) : """Create credential schema entity that describes credential attributes list and allows credentials interoperability . Schema is public and intended to be shared with all anoncreds workflow actors u...
logger = logging . getLogger ( __name__ ) logger . debug ( "issuer_create_schema: >>> issuer_did: %r, name: %r, version: %r, attrs: %r" , issuer_did , name , version , attrs ) if not hasattr ( issuer_create_schema , "cb" ) : logger . debug ( "issuer_create_schema: Creating callback" ) issuer_create_schema . cb ...
def pub ( self , topic , message ) : '''Publish a message to a topic'''
return self . post ( 'pub' , params = { 'topic' : topic } , data = message )
def message_length ( message ) : '''message _ length returns visual length of message . Ascii chars are counted as 1 , non - asciis are 2. : param str message : random unicode mixed text : rtype : int'''
length = 0 for char in map ( east_asian_width , message ) : if char == 'W' : length += 2 elif char == 'Na' : length += 1 return length
def dvds_current_releases ( self , ** kwargs ) : """Gets the upcoming movies from the API . Args : page _ limit ( optional ) : number of movies to show per page , default = 16 page ( optional ) : results page number , default = 1 country ( optional ) : localized data for selected country , default = " us " ...
path = self . _get_path ( 'dvds_current_releases' ) response = self . _GET ( path , kwargs ) self . _set_attrs_to_values ( response ) return response
def moving_average ( a , n ) : """Moving average over one - dimensional array . Parameters a : np . ndarray One - dimensional array . n : int Number of entries to average over . n = 2 means averaging over the currrent the previous entry . Returns An array view storing the moving average ."""
ret = np . cumsum ( a , dtype = float ) ret [ n : ] = ret [ n : ] - ret [ : - n ] return ret [ n - 1 : ] / n
def get_data_object ( data_id , use_data_config = True ) : """Normalize the data _ id and query the server . If that is unavailable try the raw ID"""
normalized_data_reference = normalize_data_name ( data_id , use_data_config = use_data_config ) client = DataClient ( ) data_obj = client . get ( normalized_data_reference ) # Try with the raw ID if not data_obj and data_id != normalized_data_reference : data_obj = client . get ( data_id ) return data_obj
def markForRebuild ( self , state = True ) : """Sets the rebuild state for this item . : param state | < bool >"""
self . _rebuildRequired = state if ( state ) : self . show ( ) self . update ( )
def base_url ( self , space_id , content_type_id , environment_id = None , ** kwargs ) : """Returns the URI for the editor interface ."""
return "spaces/{0}{1}/content_types/{2}/editor_interface" . format ( space_id , '/environments/{0}' . format ( environment_id ) if environment_id is not None else '' , content_type_id )
def get_callable ( key , dct ) : """Get the callable mapped by a key from a dictionary . This is necessary for pickling ( so we don ' t try to pickle an unbound method ) . Parameters key : str The key for the ` ` dct ` ` dictionary . dct : dict The dictionary of callables ."""
from sklearn . externals import six fun = dct . get ( key , None ) if not isinstance ( key , six . string_types ) or fun is None : # ah , that ' s no fun : ( raise ValueError ( 'key must be a string in one in %r, but got %r' % ( dct , key ) ) return fun
def create ( self , name , path , table = None , create = False ) : """Create a new migration at the given path . : param name : The name of the migration : type name : str : param path : The path of the migrations : type path : str : param table : The table name : type table : str : param create : Wh...
path = self . _get_path ( name , path ) if not os . path . exists ( os . path . dirname ( path ) ) : mkdir_p ( os . path . dirname ( path ) ) parent = os . path . join ( os . path . dirname ( path ) , "__init__.py" ) if not os . path . exists ( parent ) : with open ( parent , "w" ) : pass stub = self . ...
def _mean_prediction ( self , sigma2 , Y , scores , h , t_params ) : """Creates a h - step ahead mean prediction Parameters sigma2 : np . array The past predicted values Y : np . array The past data scores : np . array The past scores h : int How many steps ahead for the prediction t _ params : ...
# Create arrays to iteratre over sigma2_exp = sigma2 . copy ( ) scores_exp = scores . copy ( ) # Loop over h time periods for t in range ( 0 , h ) : new_value = t_params [ 0 ] # ARCH if self . q != 0 : for j in range ( 1 , self . q + 1 ) : new_value += t_params [ j ] * scores_exp [ - j ]...
def verify ( self , obj ) : """Verify that the object conforms to this verifier ' s schema Args : obj ( object ) : A python object to verify Raises : ValidationError : If there is a problem verifying the dictionary , a ValidationError is thrown with at least the reason key set indicating the reason for ...
if len ( self . _options ) == 0 : raise ValidationError ( "No options" , reason = 'no options given in options verifier, matching not possible' , object = obj ) exceptions = { } for i , option in enumerate ( self . _options ) : try : obj = option . verify ( obj ) return obj except Validation...
def extend_parents ( parents ) : """extend _ parents ( parents ) Returns a set containing nearest conditionally stochastic ( Stochastic , not Deterministic ) ancestors ."""
new_parents = set ( ) for parent in parents : new_parents . add ( parent ) if isinstance ( parent , DeterministicBase ) : new_parents . remove ( parent ) new_parents |= parent . extended_parents elif isinstance ( parent , ContainerBase ) : for contained_parent in parent . stochastics...
def initialize_valid_actions ( grammar : Grammar , keywords_to_uppercase : List [ str ] = None ) -> Dict [ str , List [ str ] ] : """We initialize the valid actions with the global actions . These include the valid actions that result from the grammar and also those that result from the tables provided . The ke...
valid_actions : Dict [ str , Set [ str ] ] = defaultdict ( set ) for key in grammar : rhs = grammar [ key ] # Sequence represents a series of expressions that match pieces of the text in order . # Eg . A - > B C if isinstance ( rhs , Sequence ) : valid_actions [ key ] . add ( format_action ( key...
def cursor_blink_mode_changed ( self , settings , key , user_data ) : """Called when cursor blink mode settings has been changed"""
for term in self . guake . notebook_manager . iter_terminals ( ) : term . set_property ( "cursor-blink-mode" , settings . get_int ( key ) )
def _run_external_commands ( self ) : """Post external _ commands to scheduler ( from arbiter ) Wrapper to to app . sched . run _ external _ commands method : return : None"""
commands = cherrypy . request . json with self . app . lock : self . app . sched . run_external_commands ( commands [ 'cmds' ] )
def run ( self , src_project = None , path_to_zip_file = None ) : """Run deploy the lambdas defined in our project . Steps : * Build Artefact * Read file or deploy to S3 . It ' s defined in config [ " deploy " ] [ " deploy _ method " ] * Reload conf with deploy changes * check lambda if exist * Create L...
if path_to_zip_file : code = self . set_artefact_path ( path_to_zip_file ) elif not self . config [ "deploy" ] . get ( "deploy_file" , False ) : code = self . build_artefact ( src_project ) else : code = self . set_artefact_path ( self . config [ "deploy" ] . get ( "deploy_file" ) ) self . set_artefact ( co...
def _array_star ( args ) : """Unpacks the tuple ` args ` and calls _ array . Needed to pass multiple args to a pool . map - ed function"""
fn , cls , genelist , kwargs = args return _array ( fn , cls , genelist , ** kwargs )
def purge_service ( self , service_id ) : """Purge everything from a service ."""
content = self . _fetch ( "/service/%s/purge_all" % service_id , method = "POST" ) return self . _status ( content )
def get_cgi_fieldstorage_from_wsgi_env ( env : Dict [ str , str ] , include_query_string : bool = True ) -> cgi . FieldStorage : """Returns a : class : ` cgi . FieldStorage ` object from the WSGI environment ."""
# http : / / stackoverflow . com / questions / 530526 / accessing - post - data - from - wsgi post_env = env . copy ( ) if not include_query_string : post_env [ 'QUERY_STRING' ] = '' form = cgi . FieldStorage ( fp = env [ 'wsgi.input' ] , environ = post_env , keep_blank_values = True ) return form
def render_partial ( parser , token ) : """Inserts the output of a view , using fully qualified view name , or view name from urls . py . { % render _ partial view _ name arg [ arg2 ] k = v [ k2 = v2 . . . ] % } IMPORTANT : the calling template must receive a context variable called ' request ' containing t...
args = [ ] kwargs = { } tokens = token . split_contents ( ) if len ( tokens ) < 2 : raise TemplateSyntaxError ( '%r tag requires one or more arguments' % token . contents . split ( ) [ 0 ] ) tokens . pop ( 0 ) # tag name view_name = tokens . pop ( 0 ) for token in tokens : equals = token . find ( '=' ) if e...
def parse_name ( cls , name ) : """Parses a name into a dictionary of identified subsections with accompanying information to correctly identify and replace if necessary : param name : str , string to be parsed : return : dict , dictionary with relevant parsed information"""
parse_dict = dict . fromkeys ( cls . PARSABLE , None ) parse_dict [ 'date' ] = cls . get_date ( name ) parse_dict [ 'version' ] = cls . get_version ( name ) parse_dict [ 'udim' ] = cls . get_udim ( name ) parse_dict [ 'side' ] = cls . get_side ( name ) parse_dict [ 'basename' ] = cls . get_base_naive ( cls . _reduce_na...
def resolve ( self , authorization : http . Header ) : """Determine the user associated with a request , using HTTP Basic Authentication ."""
if authorization is None : return None scheme , token = authorization . split ( ) if scheme . lower ( ) != 'basic' : return None username , password = base64 . b64decode ( token ) . decode ( 'utf-8' ) . split ( ':' ) user = authenticate ( username = username , password = password ) return user
def increase_reads_in_units ( current_provisioning , units , max_provisioned_reads , consumed_read_units_percent , log_tag ) : """Increase the current _ provisioning with units units : type current _ provisioning : int : param current _ provisioning : The current provisioning : type units : int : param unit...
units = int ( units ) current_provisioning = float ( current_provisioning ) consumed_read_units_percent = float ( consumed_read_units_percent ) consumption_based_current_provisioning = int ( math . ceil ( current_provisioning * ( consumed_read_units_percent / 100 ) ) ) if consumption_based_current_provisioning > curren...
def _compute_value ( self , pkt ) : # type : ( packet . Packet ) - > int """Computes the value of this field based on the provided packet and the length _ of field and the adjust callback @ param packet . Packet pkt : the packet from which is computed this field value . # noqa : E501 @ return int : the comput...
fld , fval = pkt . getfield_and_val ( self . _length_of ) val = fld . i2len ( pkt , fval ) ret = self . _adjust ( val ) assert ( ret >= 0 ) return ret
def present ( name , mediatype , ** kwargs ) : '''Creates new mediatype . NOTE : This function accepts all standard mediatype properties : keyword argument names differ depending on your zabbix version , see : https : / / www . zabbix . com / documentation / 3.0 / manual / api / reference / host / object # ho...
connection_args = { } if '_connection_user' in kwargs : connection_args [ '_connection_user' ] = kwargs [ '_connection_user' ] if '_connection_password' in kwargs : connection_args [ '_connection_password' ] = kwargs [ '_connection_password' ] if '_connection_url' in kwargs : connection_args [ '_connection_...
def get_chunks ( data , chunks = None ) : """Try to guess a reasonable chunk shape to use for block - wise algorithms operating over ` data ` ."""
if chunks is None : if hasattr ( data , 'chunklen' ) and hasattr ( data , 'shape' ) : # bcolz carray , chunk first dimension only return ( data . chunklen , ) + data . shape [ 1 : ] elif hasattr ( data , 'chunks' ) and hasattr ( data , 'shape' ) and len ( data . chunks ) == len ( data . shape ) : # h5py...
def merge ( self , gdefs ) : """Merge overlapped guides For example : : from plotnine import * gg = ggplot ( mtcars , aes ( y = ' wt ' , x = ' mpg ' , colour = ' factor ( cyl ) ' ) ) gg = gg + stat _ smooth ( aes ( fill = ' factor ( cyl ) ' ) , method = ' lm ' ) gg = gg + geom _ point ( ) gg This woul...
# group guide definitions by hash , and # reduce each group to a single guide # using the guide . merge method df = pd . DataFrame ( { 'gdef' : gdefs , 'hash' : [ g . hash for g in gdefs ] } ) grouped = df . groupby ( 'hash' , sort = False ) gdefs = [ ] for name , group in grouped : # merge gdef = group [ 'gdef' ] ...
def destroy_elb ( app = '' , env = 'dev' , region = 'us-east-1' , ** _ ) : """Destroy ELB Resources . Args : app ( str ) : Spinnaker Application name . env ( str ) : Deployment environment . region ( str ) : AWS region . Returns : True upon successful completion ."""
task_json = get_template ( template_file = 'destroy/destroy_elb.json.j2' , app = app , env = env , region = region , vpc = get_vpc_id ( account = env , region = region ) ) wait_for_task ( task_json ) return True
def insert_state_into_selected_state ( state , as_template = False ) : """Adds a State to the selected state : param state : the state which is inserted : param as _ template : If a state is a library state can be insert as template : return : boolean : success of the insertion"""
smm_m = rafcon . gui . singleton . state_machine_manager_model if not isinstance ( state , State ) : logger . warning ( "A state is needed to be insert not {0}" . format ( state ) ) return False if not smm_m . selected_state_machine_id : logger . warning ( "Please select a container state within a state mac...
def high_frequency_cutoff_from_config ( cp ) : """Gets the high frequency cutoff from the given config file . This looks for ` ` high - frequency - cutoff ` ` in the ` ` [ model ] ` ` section and casts it to float . If none is found , will just return ` ` None ` ` . Parameters cp : WorkflowConfigParser Co...
if cp . has_option ( 'model' , 'high-frequency-cutoff' ) : high_frequency_cutoff = float ( cp . get ( 'model' , 'high-frequency-cutoff' ) ) else : high_frequency_cutoff = None return high_frequency_cutoff
def inspect ( self , mrf = True ) : """Inspects a Packer Templates file ( ` packer inspect - machine - readable ` ) To return the output in a readable form , the ` - machine - readable ` flag is appended automatically , afterwhich the output is parsed and returned as a dict of the following format : " varia...
self . packer_cmd = self . packer . inspect self . _add_opt ( '-machine-readable' if mrf else None ) self . _add_opt ( self . packerfile ) result = self . packer_cmd ( ) if mrf : result . parsed_output = self . _parse_inspection_output ( result . stdout . decode ( ) ) else : result . parsed_output = None return...
def start_all_linking ( self , link_type , group_id ) : """Start all linking"""
self . logger . info ( "Start_all_linking for device %s type %s group %s" , self . device_id , link_type , group_id ) self . hub . direct_command ( self . device_id , '02' , '64' + link_type + group_id )
def inspect_axes ( ax ) : """Inspect an axes or subplot to get the initialization parameters"""
ret = { 'fig' : ax . get_figure ( ) . number } if mpl . __version__ < '2.0' : ret [ 'axisbg' ] = ax . get_axis_bgcolor ( ) else : # axisbg is depreceated ret [ 'facecolor' ] = ax . get_facecolor ( ) proj = getattr ( ax , 'projection' , None ) if proj is not None and not isinstance ( proj , six . string_types ) ...
def evaluate ( self , env ) : """Evaluate the function call in the environment , returning a Unicode string ."""
if self . ident in env . functions : arg_vals = [ expr . evaluate ( env ) for expr in self . args ] try : out = env . functions [ self . ident ] ( * arg_vals ) except Exception as exc : # Function raised exception ! Maybe inlining the name of # the exception will help debug . return u'<%...
def kill ( self , id , signal = signal . SIGTERM ) : """Kill a job with given id : WARNING : beware of what u kill , if u killed redis for example core0 or coreX won ' t be reachable : param id : job id to kill"""
args = { 'id' : id , 'signal' : int ( signal ) , } self . _kill_chk . check ( args ) return self . _client . json ( 'job.kill' , args )
def get_next_want_file ( self , byte_index , block ) : '''Returns the leftmost file in the user ' s list of wanted files ( want _ file _ pos ) . If the first file it finds isn ' t in the list , it will keep searching until the length of ' block ' is exceeded .'''
while block : rightmost = get_rightmost_index ( byte_index = byte_index , file_starts = self . file_starts ) if rightmost in self . want_file_pos : return rightmost , byte_index , block else : file_start = ( self . file_starts [ rightmost ] ) file_length = self . file_list [ rightmos...
def decode_base64_and_inflate ( value , ignore_zip = False ) : """base64 decodes and then inflates according to RFC1951 : param value : a deflated and encoded string : type value : string : param ignore _ zip : ignore zip errors : returns : the string after decoding and inflating : rtype : string"""
encoded = OneLogin_Saml2_Utils . b64decode ( value ) try : return zlib . decompress ( encoded , - 15 ) except zlib . error : if not ignore_zip : raise return encoded
def _diagnostic ( self , event ) : """This method is employed instead of _ tap ( ) if the PyKeyboardEvent is initialized with diagnostic = True . This makes some basic testing quickly and easily available . It will print out information regarding the event instead of passing information along to self . tap ( ...
print ( '\n---Keyboard Event Diagnostic---' ) print ( 'MessageName:' , event . MessageName ) print ( 'Message:' , event . Message ) print ( 'Time:' , event . Time ) print ( 'Window:' , event . Window ) print ( 'WindowName:' , event . WindowName ) print ( 'Ascii:' , event . Ascii , ',' , chr ( event . Ascii ) ) print ( ...
def mjd2gmst ( mjd ) : """Convert Modfied Juian Date ( JD = 2400000.5 ) to GMST Taken from P . T . Walace routines ."""
tu = ( mjd - MJD0 ) / ( 100 * DPY ) st = math . fmod ( mjd , 1.0 ) * D2PI + ( 24110.54841 + ( 8640184.812866 + ( 0.093104 - 6.2e-6 * tu ) * tu ) * tu ) * DS2R w = math . fmod ( st , D2PI ) if w >= 0.0 : return w else : return w + D2PI
def hex_encode_abi_type ( abi_type , value , force_size = None ) : """Encodes value into a hex string in format of abi _ type"""
validate_abi_type ( abi_type ) validate_abi_value ( abi_type , value ) data_size = force_size or size_of_type ( abi_type ) if is_array_type ( abi_type ) : sub_type = sub_type_of_array_type ( abi_type ) return "" . join ( [ remove_0x_prefix ( hex_encode_abi_type ( sub_type , v , 256 ) ) for v in value ] ) elif i...
def sample_tmatrix ( C , nsample = 1 , nsteps = None , reversible = False , mu = None , T0 = None , return_statdist = False ) : r"""samples transition matrices from the posterior distribution Parameters C : ( M , M ) ndarray or scipy . sparse matrix Count matrix nsample : int number of samples to be drawn...
if issparse ( C ) : _showSparseConversionWarning ( ) C = C . toarray ( ) sampler = tmatrix_sampler ( C , reversible = reversible , mu = mu , T0 = T0 , nsteps = nsteps ) return sampler . sample ( nsamples = nsample , return_statdist = return_statdist )
def delete_archive ( self , archive_id ) : """Deletes an OpenTok archive . You can only delete an archive which has a status of " available " or " uploaded " . Deleting an archive removes its record from the list of archives . For an " available " archive , it also removes the archive file , making it unavail...
response = requests . delete ( self . endpoints . archive_url ( archive_id ) , headers = self . json_headers ( ) , proxies = self . proxies , timeout = self . timeout ) if response . status_code < 300 : pass elif response . status_code == 403 : raise AuthError ( ) elif response . status_code == 404 : raise ...
def log_metrics ( metrics , summ_writer , log_prefix , step , history = None ) : """Log metrics to summary writer and history ."""
rjust_len = max ( [ len ( name ) for name in metrics ] ) for name , value in six . iteritems ( metrics ) : step_log ( step , "%s %s | % .8f" % ( log_prefix . ljust ( 5 ) , name . rjust ( rjust_len ) , value ) ) full_name = "metrics/" + name if history : history . append ( log_prefix , full_name , st...
def create_table ( self , table_name , obj = None , ** kwargs ) : """Dispatch to ImpalaClient . create _ table . See that function ' s docstring for more"""
return self . client . create_table ( table_name , obj = obj , database = self . name , ** kwargs )