signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def run_filter_query ( self , resource_name , filter_clause ) : """run a query ( get ) against the CLUE api , using the API and user key fields of self and the fitler _ clause provided Args : resource _ name : str - name of the resource / collection to query - e . g . genes , perts , cells etc . filter _ clau...
url = self . base_url + "/" + resource_name params = { "filter" : json . dumps ( filter_clause ) } r = requests . get ( url , headers = self . headers , params = params ) logger . debug ( "requests.get result r.status_code: {}" . format ( r . status_code ) ) ClueApiClient . _check_request_response ( r ) return r . jso...
def get ( self , word , default = nil ) : """Retrieves output value associated with word . If there is no word returns default value , and if default is not given rises KeyError ."""
node = self . __get_node ( word ) output = nil if node : output = node . output if output is nil : if default is nil : raise KeyError ( "no key '%s'" % word ) else : return default else : return output
def get ( cls , name ) : """returns the time of the timer . : param name : the name of the timer : type name : string : rtype : the elapsed time"""
if name in cls . timer_end : cls . timer_elapsed [ name ] = cls . timer_end [ name ] - cls . timer_start [ name ] return cls . timer_elapsed [ name ] else : return "undefined"
def get_rows ( self , indexes , column , as_list = False ) : """For a list of indexes and a single column name return the values of the indexes in that column . : param indexes : either a list of index values or a list of booleans with same length as all indexes : param column : single column name : param as ...
c = self . _columns . index ( column ) if all ( [ isinstance ( i , bool ) for i in indexes ] ) : # boolean list if len ( indexes ) != len ( self . _index ) : raise ValueError ( 'boolean index list must be same size of existing index' ) if all ( indexes ) : # the entire column data = self . _data...
def report_factory ( app , report_name , ** kwargs ) : """Report instance factory populating boilerplate raw data Args : app ( App ) : Swimlane App instance report _ name ( str ) : Generated Report name Keyword Args * * kwargs : Kwargs to pass to the Report class"""
# pylint : disable = protected - access created = pendulum . now ( ) . to_rfc3339_string ( ) user_model = app . _swimlane . user . as_usergroup_selection ( ) return Report ( app , { "$type" : Report . _type , "groupBys" : [ ] , "aggregates" : [ ] , "applicationIds" : [ app . id ] , "columns" : [ ] , "sorts" : { "$type"...
def add_port_fwd ( zone , src , dest , proto = 'tcp' , dstaddr = '' , permanent = True ) : '''Add port forwarding . . . versionadded : : 2015.8.0 CLI Example : . . code - block : : bash salt ' * ' firewalld . add _ port _ fwd public 80 443 tcp'''
cmd = '--zone={0} --add-forward-port=port={1}:proto={2}:toport={3}:toaddr={4}' . format ( zone , src , proto , dest , dstaddr ) if permanent : cmd += ' --permanent' return __firewall_cmd ( cmd )
def _get_desired_deployment_id ( self ) : '''Helper method to return the deployment id matching the desired deployment label for this Swagger object based on the given api _ name , swagger _ file'''
deployments = __salt__ [ 'boto_apigateway.describe_api_deployments' ] ( restApiId = self . restApiId , ** self . _common_aws_args ) . get ( 'deployments' ) if deployments : for deployment in deployments : if deployment . get ( 'description' ) == self . deployment_label_json : return deployment ....
def bulk_update_resourcedata ( scenario_ids , resource_scenarios , ** kwargs ) : """Update the data associated with a list of scenarios ."""
user_id = kwargs . get ( 'user_id' ) res = None res = { } net_ids = db . DBSession . query ( Scenario . network_id ) . filter ( Scenario . id . in_ ( scenario_ids ) ) . all ( ) if len ( set ( net_ids ) ) != 1 : raise HydraError ( "Scenario IDS are not in the same network" ) for scenario_id in scenario_ids : _ch...
def do_local_server_auth_flow ( session_params = None , force_new_client = False ) : """Starts a local http server , opens a browser to have the user authenticate , and gets the code redirected to the server ( no copy and pasting required )"""
session_params = session_params or { } # start local server and create matching redirect _ uri with start_local_server ( listen = ( "127.0.0.1" , 0 ) ) as server : _ , port = server . socket . getsockname ( ) redirect_uri = "http://localhost:{}" . format ( port ) # get the ConfidentialApp client object and ...
def add_file ( self , src , dest = None ) : """Add the file at ` ` src ` ` to the archive . If ` ` dest ` ` is ` ` None ` ` then it is added under just the original filename . So ` ` add _ file ( ' foo / bar . txt ' ) ` ` ends up at ` ` bar . txt ` ` in the archive , while ` ` add _ file ( ' bar . txt ' , ' f...
dest = dest or os . path . basename ( src ) with open ( src , 'rb' ) as fp : contents = fp . read ( ) self . add_contents ( dest , contents )
def add_node ( self , payload ) : """Returns int Identifier for the inserted node ."""
self . nodes . append ( Node ( len ( self . nodes ) , payload ) ) return len ( self . nodes ) - 1
def get_dos ( self , partial_dos = False , npts_mu = 10000 , T = None ) : """Return a Dos object interpolating bands Args : partial _ dos : if True , projections will be interpolated as well and partial doses will be return . Projections must be available in the loader . npts _ mu : number of energy point...
spin = self . data . spin if isinstance ( self . data . spin , int ) else 1 energies , densities , vvdos , cdos = BL . BTPDOS ( self . eband , self . vvband , npts = npts_mu ) if T is not None : densities = BL . smoothen_DOS ( energies , densities , T ) tdos = Dos ( self . efermi / units . eV , energies / units . e...
def ToJson ( self ) : """Convert object members to a dictionary that can be parsed as JSON . Returns : dict :"""
items = [ ] for i in self . Items : items . append ( { 'index' : i . index , 'height' : i . height } ) return { 'version' : self . StateVersion , 'txHash' : self . TransactionHash . ToString ( ) , 'txHeight' : self . TransactionHeight , 'items' : items }
def get_header ( self ) : """Returns the header for screen logging of the minimization"""
result = " " if self . step_rms is not None : result += " Step RMS" if self . step_max is not None : result += " Step MAX" if self . grad_rms is not None : result += " Grad RMS" if self . grad_max is not None : result += " Grad MAX" if self . rel_grad_rms is not None : result += " Grad/...
def _pfp__parse ( self , stream , save_offset = False ) : """Parse the IO stream for this numeric field : stream : An IO stream that can be read from : returns : The number of bytes parsed"""
if save_offset : self . _pfp__offset = stream . tell ( ) if self . bitsize is None : raw_data = stream . read ( self . width ) data = utils . binary ( raw_data ) else : bits = self . bitfield_rw . read_bits ( stream , self . bitsize , self . bitfield_padded , self . bitfield_left_right , self . endian )...
def _parse_image ( self ) : """Returns an instance of the image . Image class for the RSS feed ."""
image = { 'title' : self . _channel . find ( './image/title' ) . text , 'width' : int ( self . _channel . find ( './image/width' ) . text ) , 'height' : int ( self . _channel . find ( './image/height' ) . text ) , 'link' : self . _channel . find ( './image/link' ) . text , 'url' : self . _channel . find ( './image/url'...
def get_required_status_checks ( self ) : """: calls : ` GET / repos / : owner / : repo / branches / : branch / protection / required _ status _ checks < https : / / developer . github . com / v3 / repos / branches > ` _ : rtype : : class : ` github . RequiredStatusChecks . RequiredStatusChecks `"""
headers , data = self . _requester . requestJsonAndCheck ( "GET" , self . protection_url + "/required_status_checks" ) return github . RequiredStatusChecks . RequiredStatusChecks ( self . _requester , headers , data , completed = True )
def spec_check ( self , auth_list , fun , args , form ) : '''Check special API permissions'''
if not auth_list : return False if form != 'cloud' : comps = fun . split ( '.' ) if len ( comps ) != 2 : # Hint at a syntax error when command is passed improperly , # rather than returning an authentication error of some kind . # See Issue # 21969 for more information . return { 'error' : {...
def brain ( self ) : """Catalog brain of the wrapped object"""
if self . _brain is None : logger . debug ( "SuperModel::brain: *Fetch catalog brain*" ) self . _brain = self . get_brain_by_uid ( self . uid ) return self . _brain
def play_env_problem_randomly ( env_problem , num_steps ) : """Plays the env problem by randomly sampling actions for ` num _ steps ` ."""
# Reset all environments . env_problem . reset ( ) # Play all environments , sampling random actions each time . for _ in range ( num_steps ) : # Sample batch _ size actions from the action space and stack them . actions = np . stack ( [ env_problem . action_space . sample ( ) for _ in range ( env_problem . batch_s...
def send_error ( self , status_code = 500 , ** kwargs ) : """Override implementation to report all exceptions to sentry , even after self . flush ( ) or self . finish ( ) is called , for pre - v3.1 Tornado ."""
if hasattr ( super ( SentryMixin , self ) , 'log_exception' ) : return super ( SentryMixin , self ) . send_error ( status_code , ** kwargs ) else : rv = super ( SentryMixin , self ) . send_error ( status_code , ** kwargs ) if 500 <= status_code <= 599 : self . captureException ( exc_info = kwargs . ...
def fix_timezone_separator ( cls , timestr ) : """Replace invalid timezone separator to prevent ` dateutil . parser . parse ` to raise . : return : the new string if invalid separators were found , ` None ` otherwise"""
tz_sep = cls . TIMEZONE_SEPARATOR . match ( timestr ) if tz_sep is not None : return tz_sep . group ( 1 ) + tz_sep . group ( 2 ) + ':' + tz_sep . group ( 3 ) return timestr
def execute ( self , eopatch ) : """Transforms [ n , w , h , d ] eopatch into a [ n , w , h , 1 ] eopatch , adding it the classification mask . : param eopatch : An input EOPatch : type eopatch : EOPatch : return : Outputs EOPatch with n classification masks appended to out _ feature _ type with out _ feature...
in_type , in_name = next ( self . input_feature ( eopatch ) ) out_type , out_name = next ( self . input_feature ( ) ) eopatch [ out_type ] [ out_name ] = self . classifier . image_predict ( eopatch [ in_type ] [ in_name ] ) return eopatch
async def create_cred ( self , cred_offer_json , cred_req_json : str , cred_attrs : dict , rr_size : int = None ) -> ( str , str , int ) : """Create credential as Issuer out of credential request and dict of key : value ( raw , unencoded ) entries for attributes . Return credential json , and if cred def suppor...
LOGGER . debug ( 'Issuer.create_cred >>> cred_offer_json: %s, cred_req_json: %s, cred_attrs: %s, rr_size: %s' , cred_offer_json , cred_req_json , cred_attrs , rr_size ) cd_id = json . loads ( cred_offer_json ) [ 'cred_def_id' ] cred_def = json . loads ( await self . get_cred_def ( cd_id ) ) # ensure cred def is in cach...
def get_attribute_classes ( ) -> Dict [ str , Attribute ] : """Lookup all builtin Attribute subclasses , load them , and return a dict"""
attribute_children = pkgutil . iter_modules ( importlib . import_module ( 'jawa.attributes' ) . __path__ , prefix = 'jawa.attributes.' ) result = { } for _ , name , _ in attribute_children : classes = inspect . getmembers ( importlib . import_module ( name ) , lambda c : ( inspect . isclass ( c ) and issubclass ( c...
def get_sentry_data_from_request ( self ) : """Extracts the data required for ' sentry . interfaces . Http ' from the current request being handled by the request handler : param return : A dictionary ."""
return { 'request' : { 'url' : self . request . full_url ( ) , 'method' : self . request . method , 'data' : self . request . body , 'query_string' : self . request . query , 'cookies' : self . request . headers . get ( 'Cookie' , None ) , 'headers' : dict ( self . request . headers ) , } }
async def serviceQueues ( self , limit = None ) -> int : """Service at most ` limit ` messages from the inBox . : param limit : the maximum number of messages to service : return : the number of messages successfully processed"""
return await self . _inbox_router . handleAll ( self . _inbox , limit )
def get_port_profile_status_input_port_profile_name ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_port_profile_status = ET . Element ( "get_port_profile_status" ) config = get_port_profile_status input = ET . SubElement ( get_port_profile_status , "input" ) port_profile_name = ET . SubElement ( input , "port-profile-name" ) port_profile_name . text = kwargs . pop ( 'port_profi...
def get_subnet_association ( subnets , region = None , key = None , keyid = None , profile = None ) : '''Given a subnet ( aka : a vpc zone identifier ) or list of subnets , returns vpc association . Returns a VPC ID if the given subnets are associated with the same VPC ID . Returns False on an error or if the...
try : conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) # subnet _ ids = subnets can accept either a string or a list subnets = conn . get_all_subnets ( subnet_ids = subnets ) except BotoServerError as e : return { 'error' : __utils__ [ 'boto.get_error' ] ( e ) } # usi...
def __get_types ( for_type = None , for_types = None ) : """Parse the arguments and return a tuple of types to implement for . Raises : ValueError or TypeError as appropriate ."""
if for_type : if for_types : raise ValueError ( "Cannot pass both for_type and for_types." ) for_types = ( for_type , ) elif for_types : if not isinstance ( for_types , tuple ) : raise TypeError ( "for_types must be passed as a tuple of " "types (classes)." ) else : raise ValueError ( "M...
def add ( self , email ) : """Add a collaborator . Args : str : Collaborator email address ."""
if email not in self . _collaborators : self . _collaborators [ email ] = ShareRequestValue . Add self . _dirty = True
def parse ( self , name , description ) : """Parse option name . : param name : option ' s name : param description : option ' s description Parsing acceptable names : * - f : shortname * - - force : longname * - f , - - force : shortname and longname * - o < output > : shortname and a required value ...
name = name . strip ( ) if '<' in name : self . required = True self . boolean = False name = name [ : name . index ( '<' ) ] . strip ( ) elif '[' in name : self . required = False self . boolean = False name = name [ : name . index ( '[' ) ] . strip ( ) else : self . required = False se...
def _histogram_fixed_binsize ( a , start , width , n ) : """histogram _ even ( a , start , width , n ) - > histogram Return an histogram where the first bin counts the number of lower outliers and the last bin the number of upper outliers . Works only with fixed width bins . : Stochastics : a : array Ar...
return flib . fixed_binsize ( a , start , width , n )
def _safe_copy ( dat ) : '''mongodb doesn ' t allow ' . ' in keys , but does allow unicode equivs . Apparently the docs suggest using escaped unicode full - width encodings . * sigh * \\ - - > \\ \ $ --> \\ \\ u0024 . - - > \\ \\ u002e Personally , I prefer URL encodings , \\ - - > % 5c $ - - > % 24 ...
if isinstance ( dat , dict ) : ret = { } for k in dat : r = k . replace ( '%' , '%25' ) . replace ( '\\' , '%5c' ) . replace ( '$' , '%24' ) . replace ( '.' , '%2e' ) if r != k : log . debug ( 'converting dict key from %s to %s for mongodb' , k , r ) ret [ r ] = _safe_copy ( ...
def generic_adjust ( colors , light ) : """Generic color adjustment for themers ."""
if light : for color in colors : color = util . saturate_color ( color , 0.60 ) color = util . darken_color ( color , 0.5 ) colors [ 0 ] = util . lighten_color ( colors [ 0 ] , 0.95 ) colors [ 7 ] = util . darken_color ( colors [ 0 ] , 0.75 ) colors [ 8 ] = util . darken_color ( colors [...
def addRectAnnot ( self , rect ) : """Add a ' Rectangle ' annotation ."""
CheckParent ( self ) val = _fitz . Page_addRectAnnot ( self , rect ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
def loadString ( self , profilestr , merge = False , loadProfile = True ) : """Loads the information for this toolbar from the inputed string . : param profilestr | < str >"""
try : xtoolbar = ElementTree . fromstring ( nativestring ( profilestr ) ) except ExpatError , e : return if not merge : self . clear ( ) self . blockSignals ( True ) for xprofile in xtoolbar : prof = XViewProfile . fromXml ( xprofile ) if merge : self . removeProfile ( prof . name ( ) , sile...
def is_uniform ( elements : list ) -> bool : """Python function to verify if all elements in a list are identical . Parameters : elements ( list ) : a list that could hold any data types Returns : bool : True if all elements are the same , False otherwise . Examples : > > > is _ uniform ( [ ' same ' , '...
return len ( set ( elements ) ) == 1
def calculate_field_widths ( self , width = None , min_label_width = 10 , min_progress_width = 10 ) : """Calculate how wide each field should be so we can align them . We always find room for the summaries since these are short and packed with information . If possible , we will also find room for labels , bu...
if width is None : # pragma : no cover width = shutil . get_terminal_size ( ) [ 0 ] summary_width = self . summary_width ( ) label_width = self . label_width ( ) remaining = width - summary_width - label_width - 2 if remaining >= min_progress_width : progress_width = remaining else : progress_width = min_pr...
def _get_bin_width ( stdev , count ) : """Return the histogram ' s optimal bin width based on Sturges http : / / www . jstor . org / pss / 2965501"""
w = int ( round ( ( 3.5 * stdev ) / ( count ** ( 1.0 / 3 ) ) ) ) if w : return w else : return 1
def set_params ( self , arg_params , aux_params , allow_missing = False , force_init = True , allow_extra = False ) : """Assigns parameter and aux state values . Parameters arg _ params : dict Dictionary of name to ` NDArray ` . aux _ params : dict Dictionary of name to ` NDArray ` . allow _ missing : b...
if not allow_missing : self . init_params ( initializer = None , arg_params = arg_params , aux_params = aux_params , allow_missing = allow_missing , force_init = force_init , allow_extra = allow_extra ) return if self . params_initialized and not force_init : warnings . warn ( "Parameters already initialize...
def seqs_from_file ( filename , exit_on_err = False , return_qual = False ) : """Extract sequences from a file Name : seqs _ from _ file Author ( s ) : Martin C F Thomsen Date : 18 Jul 2013 Description : Iterator which extract sequence data from the input file Args : filename : string which cont...
# VALIDATE INPUT if not isinstance ( filename , str ) : msg = 'Filename has to be a string.' if exit_on_err : sys . stderr . write ( 'Error: %s\n' % msg ) sys . exit ( 1 ) else : raise IOError ( msg ) if not os . path . exists ( filename ) : msg = 'File "%s" does not exist.' % fi...
def get_productivity_stats ( self , api_token , ** kwargs ) : """Return a user ' s productivity stats . : param api _ token : The user ' s login api _ token . : type api _ token : str : return : The HTTP response to the request . : rtype : : class : ` requests . Response `"""
params = { 'token' : api_token } return self . _get ( 'get_productivity_stats' , params , ** kwargs )
def SA_ellipsoidal_head ( D , a ) : r'''Calculates the surface area of an ellipsoidal head according to [ 1 ] _ . Formula below is for the full shape , the result of which is halved . The formula also does not support ` D ` being larger than ` a ` ; this is ensured by simply swapping the variables if necessar...
if D == a * 2 : return pi * D ** 2 / 2 # necessary to avoid a division by zero when D = = a D = D / 2. D , a = min ( ( D , a ) ) , max ( ( D , a ) ) e1 = ( 1 - D ** 2 / a ** 2 ) ** 0.5 return ( 2 * pi * a ** 2 + pi * D ** 2 / e1 * log ( ( 1 + e1 ) / ( 1 - e1 ) ) ) / 2.
def get_valid_app_auth ( self , app_uri ) : """获得账号下可用的应用的密钥 列出指定应用的可用密钥 Args : - app _ uri : 应用的完整标识 Returns : 返回一个tuple对象 , 其格式为 ( < result > , < ResponseInfo > ) - result 成功返回可用秘钥列表 , 失败返回None - ResponseInfo 请求的Response信息"""
ret , retInfo = self . get_app_keys ( app_uri ) if ret is None : return None for k in ret : if ( k . get ( 'state' ) == 'enabled' ) : return QiniuMacAuth ( k . get ( 'ak' ) , k . get ( 'sk' ) ) return None
def check_mac ( original_mac ) : '''Checks the format of a MAC address and returns it without double - colons and in capital letters , if it is correct . Otherwise it returns None . * it accepts the format of the double colons and a single hex string'''
mac = ( original_mac . upper ( ) ) . strip ( ) parts = mac . split ( ':' ) if len ( parts ) == 6 : # let ' s think that it is a : separated mac for p in parts : if len ( p ) != 2 : return None mac = '' . join ( parts ) elif len ( parts ) > 1 : return None for c in mac : if c not in '...
def main ( ) : """Run the CLI ."""
parser = argparse . ArgumentParser ( description = 'Search artists, lyrics, and songs!' ) parser . add_argument ( 'artist' , help = 'Specify an artist name (Default: Taylor Swift)' , default = 'Taylor Swift' , nargs = '?' , ) parser . add_argument ( '-s' , '--song' , help = 'Given artist name, specify a song name' , re...
def find_any_field ( browser , field_types , field_name ) : """Find a field of any of the specified types ."""
return reduce ( operator . add , ( find_field ( browser , field_type , field_name ) for field_type in field_types ) )
def is_state_machine_stopped_to_proceed ( selected_sm_id = None , root_window = None ) : """Check if state machine is stopped and in case request user by dialog how to proceed The function checks if a specific state machine or by default all state machines have stopped or finished execution . If a state machine...
# check if the / a state machine is still running if not state_machine_execution_engine . finished_or_stopped ( ) : if selected_sm_id is None or selected_sm_id == state_machine_manager . active_state_machine_id : message_string = "A state machine is still running. This state machine can only be refreshed" "...
def sink_get ( self , project , sink_name ) : """API call : retrieve a sink resource . : type project : str : param project : ID of the project containing the sink . : type sink _ name : str : param sink _ name : the name of the sink : rtype : dict : returns : The sink object returned from the API ( con...
path = "projects/%s/sinks/%s" % ( project , sink_name ) sink_pb = self . _gapic_api . get_sink ( path ) # NOTE : LogSink message type does not have an ` ` Any ` ` field # so ` MessageToDict ` ` can safely be used . return MessageToDict ( sink_pb )
def company_category ( self , symbol = '' ) : '''查询公司信息目录 : param market : 市场代码 : param symbol : 股票代码 : return : pd . dataFrame or None'''
market = get_stock_market ( symbol ) with self . client . connect ( * self . bestip ) : data = self . client . get_company_info_category ( int ( market ) , symbol ) return self . client . to_df ( data )
def parallel_iterate ( source_iterators : Sequence [ Iterator [ Optional [ Any ] ] ] , target_iterator : Iterator [ Optional [ Any ] ] , skip_blanks : bool = True ) : """Yields parallel source ( s ) , target sequences from iterables . Checks for token parallelism in source sequences . Skips pairs where element ...
num_skipped = 0 while True : try : sources = [ next ( source_iter ) for source_iter in source_iterators ] target = next ( target_iterator ) except StopIteration : break if skip_blanks and ( any ( ( s is None for s in sources ) ) or target is None ) : num_skipped += 1 ...
def plot_cumulative_density ( self , ** kwargs ) : """Plots a pretty figure of { 0 } . { 1} Matplotlib plot arguments can be passed in inside the kwargs , plus Parameters show _ censors : bool place markers at censorship events . Default : False censor _ styles : bool If show _ censors , this dictionary...
return _plot_estimate ( self , estimate = self . cumulative_density_ , confidence_intervals = self . confidence_interval_cumulative_density_ , ** kwargs )
def create_object ( self , data , view_kwargs ) : """Create an object through sqlalchemy : param dict data : the data validated by marshmallow : param dict view _ kwargs : kwargs from the resource view : return DeclarativeMeta : an object from sqlalchemy"""
self . before_create_object ( data , view_kwargs ) relationship_fields = get_relationships ( self . resource . schema , model_field = True ) nested_fields = get_nested_fields ( self . resource . schema , model_field = True ) join_fields = relationship_fields + nested_fields obj = self . model ( ** { key : value for ( k...
def options ( self , context , module_options ) : '''USER Search for the specified username in available tokens ( default : None ) USERFILE File containing usernames to search for in available tokens ( defult : None )'''
self . user = None self . userfile = None if 'USER' in module_options and 'USERFILE' in module_options : context . log . error ( 'USER and USERFILE options are mutually exclusive!' ) sys . exit ( 1 ) if 'USER' in module_options : self . user = module_options [ 'USER' ] elif 'USERFILE' in module_options : ...
def get_mesh_name ( mesh_id , offline = False ) : """Get the MESH label for the given MESH ID . Uses the mappings table in ` indra / resources ` ; if the MESH ID is not listed there , falls back on the NLM REST API . Parameters mesh _ id : str MESH Identifier , e . g . ' D003094 ' . offline : bool Whe...
indra_mesh_mapping = mesh_id_to_name . get ( mesh_id ) if offline or indra_mesh_mapping is not None : return indra_mesh_mapping # Look up the MESH mapping from NLM if we don ' t have it locally return get_mesh_name_from_web ( mesh_id )
def SetActiveBreakpoints ( self , breakpoints_data ) : """Adds new breakpoints and removes missing ones . Args : breakpoints _ data : updated list of active breakpoints ."""
with self . _lock : ids = set ( [ x [ 'id' ] for x in breakpoints_data ] ) # Clear breakpoints that no longer show up in active breakpoints list . for breakpoint_id in six . viewkeys ( self . _active ) - ids : self . _active . pop ( breakpoint_id ) . Clear ( ) # Create new breakpoints . self...
def sink_delete ( self , project , sink_name ) : """API call : delete a sink resource . See https : / / cloud . google . com / logging / docs / reference / v2 / rest / v2 / projects . sinks / delete : type project : str : param project : ID of the project containing the sink . : type sink _ name : str :...
target = "/projects/%s/sinks/%s" % ( project , sink_name ) self . api_request ( method = "DELETE" , path = target )
def can_create_family_with_record_types ( self , family_record_types ) : """Tests if this user can create a single ` ` Family ` ` using the desired record types . While ` ` RelationshipManager . getFamilyRecordTypes ( ) ` ` can be used to examine which records are supported , this method tests which record ( ...
# Implemented from template for # osid . resource . BinAdminSession . can _ create _ bin _ with _ record _ types # NOTE : It is expected that real authentication hints will be # handled in a service adapter above the pay grade of this impl . if self . _catalog_session is not None : return self . _catalog_session . ...
def parse ( name , content , releases , get_head_fn ) : """Parses the given content for a valid changelog : param name : str , package name : param content : str , content : param releases : list , releases : param get _ head _ fn : function : return : dict , changelog"""
try : return { e [ "version" ] : e [ "changelog" ] for e in content [ "entries" ] if e [ "changelog" ] } except KeyError : return { }
def client ( self ) : """Get an elasticsearch client"""
if not hasattr ( self , "_client" ) : self . _client = connections . get_connection ( "default" ) return self . _client
def task_table ( self , task_id = None ) : """Fetch and parse the task table information for one or more task IDs . Args : task _ id : A hex string of the task ID to fetch information about . If this is None , then the task object table is fetched . Returns : Information from the task table ."""
self . _check_connected ( ) if task_id is not None : task_id = ray . TaskID ( hex_to_binary ( task_id ) ) return self . _task_table ( task_id ) else : task_table_keys = self . _keys ( ray . gcs_utils . TablePrefix_RAYLET_TASK_string + "*" ) task_ids_binary = [ key [ len ( ray . gcs_utils . TablePrefix_R...
def connect ( self ) : '''Connect to the serial port'''
if self . _port : self . _driver = MagDeckDriver ( ) self . _driver . connect ( self . _port ) self . _device_info = self . _driver . get_device_info ( ) else : # Sanity check : Should never happen , because connect should # never be called without a port on Module raise MissingDevicePortError ( "MagDec...
def file_modify ( filename , settings ) : """Modifies file access Args : filename ( str ) : Filename . settings ( dict ) : Can be " mode " or " owners " """
for k , v in settings . items ( ) : if k == "mode" : os . chmod ( filename , v ) if k == "owners" : os . chown ( filename , v )
def async_or_eager ( self , ** options ) : """Attempt to call self . apply _ async , or if that fails because of a problem with the broker , run the task eagerly and return an EagerResult ."""
args = options . pop ( "args" , None ) kwargs = options . pop ( "kwargs" , None ) possible_broker_errors = self . _get_possible_broker_errors_tuple ( ) try : return self . apply_async ( args , kwargs , ** options ) except possible_broker_errors : return self . apply ( args , kwargs , ** options )
def keyserverprefs ( self ) : """A ` ` list ` ` of : py : obj : ` ~ constants . KeyServerPreferences ` in this signature , if any . Otherwise , an empty ` ` list ` ` ."""
if 'KeyServerPreferences' in self . _signature . subpackets : return next ( iter ( self . _signature . subpackets [ 'h_KeyServerPreferences' ] ) ) . flags return [ ]
def masked_array ( data , data_units = None , ** kwargs ) : """Create a : class : ` numpy . ma . MaskedArray ` with units attached . This is a thin wrapper around : func : ` numpy . ma . masked _ array ` that ensures that units are properly attached to the result ( otherwise units are silently lost ) . Units ...
if data_units is None : data_units = data . units return units . Quantity ( np . ma . masked_array ( data , ** kwargs ) , data_units )
def _init_metadata ( self ) : """stub"""
DecimalValuesFormRecord . _init_metadata ( self ) IntegerValuesFormRecord . _init_metadata ( self ) TextAnswerFormRecord . _init_metadata ( self ) super ( MultiLanguageCalculationInteractionFeedbackAndFilesAnswerFormRecord , self ) . _init_metadata ( ) self . _tolerance_mode_metadata = { 'element_id' : Id ( self . my_o...
def set_baseline ( self , version ) : """Set the baseline into the creation information table version : str The version of the current database to set in the information table . The baseline must be in the format x . x . x where x are numbers ."""
pattern = re . compile ( r"^\d+\.\d+\.\d+$" ) if not re . match ( pattern , version ) : raise ValueError ( 'Wrong version format' ) query = """ INSERT INTO {} ( version, description, type, script, che...
def translate ( self , address ) : """Translates the given address to another address specific to network or service . : param address : ( : class : ` ~ hazelcast . core . Address ` ) , private address to be translated : return : ( : class : ` ~ hazelcast . core . Address ` ) , new address if given address is k...
if address is None : return None public_address = self . _private_to_public . get ( address ) if public_address : return public_address self . refresh ( ) return self . _private_to_public . get ( address )
def init_ui ( state ) : """Post initialization for UI application ."""
app = state . app init_common ( app ) # Register blueprint for templates app . register_blueprint ( blueprint , url_prefix = app . config [ 'USERPROFILES_PROFILE_URL' ] )
def parse_line ( text ) : """: param text : : type text : str : return :"""
indent , text = calculate_indent ( text ) results = line_parser . parseString ( text , parseAll = True ) . asList ( ) return indent , results [ 0 ]
def getWidget ( self , ** kwargs ) : """Wrapper function that returns a new widget attached to this simulation . Widgets provide real - time 3D visualizations from within an Jupyter notebook . See the Widget class for more details on the possible arguments . Arguments All arguments passed to this wrapper fu...
from . widget import Widget # ondemand from ipywidgets import DOMWidget from IPython . display import display , HTML if not hasattr ( self , '_widgets' ) : self . _widgets = [ ] def display_heartbeat ( simp ) : for w in self . _widgets : w . refresh ( simp , isauto = 1 ) self . visualiza...
def calc_pc_v1 ( self ) : """Apply the precipitation correction factors and adjust precipitation to the altitude of the individual zones . Required control parameters : | NmbZones | | PCorr | | PCAlt | | ZoneZ | | ZRelP | Required input sequence : Required flux sequences : | RfC | | SfC | Ca...
con = self . parameters . control . fastaccess inp = self . sequences . inputs . fastaccess flu = self . sequences . fluxes . fastaccess for k in range ( con . nmbzones ) : flu . pc [ k ] = inp . p * ( 1. + con . pcalt [ k ] * ( con . zonez [ k ] - con . zrelp ) ) if flu . pc [ k ] <= 0. : flu . pc [ k ...
def _delay ( self ) -> int : """Extract departure delay ."""
try : return int ( self . journey . MainStop . BasicStop . Dep . Delay . text ) except AttributeError : return 0
def sign_request ( self , signature_method , consumer , token ) : """Set the signature parameter to the result of sign ."""
if not self . is_form_encoded : # according to # http : / / oauth . googlecode . com / svn / spec / ext / body _ hash / 1.0 / oauth - bodyhash . html # section 4.1.1 " OAuth Consumers MUST NOT include an # oauth _ body _ hash parameter on requests with form - encoded # request bodies . " if not self . body : ...
def selenium_retry ( target = None , retry = True ) : """Decorator to turn on automatic retries of flaky selenium failures . Decorate a robotframework library class to turn on retries for all selenium calls from that library : @ selenium _ retry class MyLibrary ( object ) : # Decorate a method to turn it ...
if isinstance ( target , bool ) : # Decorator was called with a single boolean argument retry = target target = None def decorate ( target ) : if isinstance ( target , type ) : cls = target # Metaclass time . # We ' re going to generate a new subclass that : # a ) mixes in Re...
def websocket_handler ( request ) : """Handle a new socket connection ."""
logger . debug ( 'New websocket connection.' ) websocket = web . WebSocketResponse ( ) yield from websocket . prepare ( request ) uuid = uuid4 ( ) request . app [ 'dispatcher' ] . subscribe ( uuid , websocket ) while True : # Consume input buffer try : msg = yield from websocket . receive ( ) except Run...
def get_data_source_bulk_request ( self , rids , limit = 5 ) : """This grabs each datasource and its multiple datapoints for a particular device ."""
headers = { 'User-Agent' : self . user_agent ( ) , 'Content-Type' : self . content_type ( ) } headers . update ( self . headers ( ) ) r = requests . get ( self . portals_url ( ) + '/data-sources/[' + "," . join ( rids ) + ']/data?limit=' + str ( limit ) , headers = headers , auth = self . auth ( ) ) if HTTP_STATUS . OK...
def tj_email ( self ) : """Get ( or guess ) a user ' s TJ email . If a fcps . edu or tjhsst . edu email is specified in their email list , use that . Otherwise , append the user ' s username to the proper email suffix , depending on whether they are a student or teacher ."""
for email in self . emails . all ( ) : if email . address . endswith ( ( "@fcps.edu" , "@tjhsst.edu" ) ) : return email if self . is_teacher : domain = "fcps.edu" else : domain = "tjhsst.edu" return "{}@{}" . format ( self . username , domain )
def get_block ( self , x , y , z ) : """Get a block from relative x , y , z ."""
sy , by = divmod ( y , 16 ) section = self . get_section ( sy ) if section == None : return None return section . get_block ( x , by , z )
def xinfo_consumers ( self , stream , group_name ) : """Retrieve consumers of a consumer group"""
fut = self . execute ( b'XINFO' , b'CONSUMERS' , stream , group_name ) return wait_convert ( fut , parse_lists_to_dicts )
def update_agent_requirements ( req_file , check , newline ) : """Replace the requirements line for the given check"""
package_name = get_package_name ( check ) lines = read_file_lines ( req_file ) for i , line in enumerate ( lines ) : current_package_name = line . split ( '==' ) [ 0 ] if current_package_name == package_name : lines [ i ] = '{}\n' . format ( newline ) break write_file_lines ( req_file , sorted (...
def copyto ( self , other ) : """Copies the value of this array to another array . If ` ` other ` ` is a ` ` NDArray ` ` object , then ` ` other . shape ` ` and ` ` self . shape ` ` should be the same . This function copies the value from ` ` self ` ` to ` ` other ` ` . If ` ` other ` ` is a context , a new...
if isinstance ( other , NDArray ) : if other . handle is self . handle : warnings . warn ( 'You are attempting to copy an array to itself' , RuntimeWarning ) return False return _internal . _copyto ( self , out = other ) elif isinstance ( other , Context ) : hret = NDArray ( _new_alloc_handl...
def checksum_status ( self , area_uuid , filename ) : """Retrieve checksum status and values for a file : param str area _ uuid : A RFC4122 - compliant ID for the upload area : param str filename : The name of the file within the Upload Area : return : a dict with checksum information : rtype : dict : rai...
url_safe_filename = urlparse . quote ( filename ) path = "/area/{uuid}/{filename}/checksum" . format ( uuid = area_uuid , filename = url_safe_filename ) response = self . _make_request ( 'get' , path ) return response . json ( )
def json_friendly ( obj ) : """Convert an object into something that ' s more becoming of JSON"""
converted = True typename = get_full_typename ( obj ) if is_tf_tensor_typename ( typename ) : obj = obj . eval ( ) elif is_pytorch_tensor_typename ( typename ) : try : if obj . requires_grad : obj = obj . detach ( ) except AttributeError : pass # before 0.4 is only present on...
def morphemes ( args ) : """Segment words according to their morphemes ."""
morfessor = load_morfessor_model ( lang = args . lang ) for l in args . input : words = l . strip ( ) . split ( ) morphemes = [ ( w , u"_" . join ( morfessor . viterbi_segment ( w ) [ 0 ] ) ) for w in words ] line_annotations = [ u"{:<16}{:<5}" . format ( w , p ) for w , p in morphemes ] _print ( u"\n" ...
def write ( self , output , mode = "w" , keep_rc = False ) : """Executes the pipeline and writes the results to the supplied output . If output is a filename and the file didn ' t already exist before trying to write , the file will be removed if an exception is raised . Args : output ( str or file like obj...
if isinstance ( output , six . string_types ) : already_exists = os . path . exists ( output ) try : with open ( output , mode ) as f : p = self . _build_pipes ( f ) rc = p . wait ( ) if keep_rc : return rc if rc : raise Cal...
def split_top_down ( lower , upper , __fval = None , ** fval ) : """This call un - links an association that was made using bind _ top _ down . Have a look at help ( bind _ top _ down )"""
if __fval is not None : fval . update ( __fval ) if lower in upper . _overload_fields : ofval = upper . _overload_fields [ lower ] if any ( k not in ofval or ofval [ k ] != v for k , v in six . iteritems ( fval ) ) : # noqa : E501 return upper . _overload_fields = upper . _overload_fields . copy...
def transform ( self , sequences ) : """Apply the dimensionality reduction on X . Parameters sequences : list of array - like , each of shape ( n _ samples _ i , n _ features ) Training data , where n _ samples _ i in the number of samples in sequence i and n _ features is the number of features . Returns...
check_iter_of_sequences ( sequences , max_iter = 3 ) # we might be lazy - loading sequences_new = [ ] for X in sequences : X = array2d ( X ) if self . means_ is not None : X = X - self . means_ X_transformed = np . dot ( X , self . components_ . T ) if self . kinetic_mapping : X_transfor...
def get_dev_at_mountpoint ( mntpoint ) : """Retrieves the device mounted at mntpoint , or raises MountError if none ."""
results = util . subp ( [ 'findmnt' , '-o' , 'SOURCE' , mntpoint ] ) if results . return_code != 0 : raise MountError ( 'No device mounted at %s' % mntpoint ) stdout = results . stdout . decode ( sys . getdefaultencoding ( ) ) return stdout . replace ( 'SOURCE\n' , '' ) . strip ( ) . split ( '\n' ) [ - 1 ]
def add_force_flaky_options ( add_option ) : """Add options to the test runner that force all tests to be flaky . : param add _ option : A function that can add an option to the test runner . Its argspec should equal that of argparse . add _ option . : type add _ option : ` callable `"""
add_option ( '--force-flaky' , action = "store_true" , dest = "force_flaky" , default = False , help = "If this option is specified, we will treat all tests as " "flaky." ) add_option ( '--max-runs' , action = "store" , dest = "max_runs" , type = int , default = 2 , help = "If --force-flaky is specified, we will run ea...
def clear_end_timestamp ( self ) : """stub"""
if ( self . get_end_timestamp_metadata ( ) . is_read_only ( ) or self . get_end_timestamp_metadata ( ) . is_required ( ) ) : raise NoAccess ( ) self . my_osid_object_form . _my_map [ 'endTimestamp' ] = self . get_end_timestamp_metadata ( ) . get_default_integer_values ( )
def formfield ( self , form_class = None , choices_form_class = None , ** kwargs ) : """Returns a django . forms . Field instance for this database Field ."""
defaults = { 'required' : not self . blank , 'label' : capfirst ( self . verbose_name ) , 'help_text' : self . help_text , } if self . has_default ( ) : if callable ( self . default ) : defaults [ 'initial' ] = self . default defaults [ 'show_hidden_initial' ] = True else : defaults [ 'i...
def deploy_config_from_estimator ( estimator , task_id , task_type , initial_instance_count , instance_type , model_name = None , endpoint_name = None , tags = None , ** kwargs ) : """Export Airflow deploy config from a SageMaker estimator Args : estimator ( sagemaker . model . EstimatorBase ) : The SageMaker e...
update_estimator_from_task ( estimator , task_id , task_type ) model = estimator . create_model ( ** kwargs ) model . name = model_name config = deploy_config ( model , initial_instance_count , instance_type , endpoint_name , tags ) return config
def link_blob_into_repository ( self , session , digest , source_repo , target_repo ) : """Links ( " mounts " in Docker Registry terminology ) a blob from one repository in a registry into another repository in the same registry ."""
self . log . debug ( "%s: Linking blob %s from %s to %s" , session . registry , digest , source_repo , target_repo ) # Check that it exists in the source repository url = "/v2/{}/blobs/{}" . format ( source_repo , digest ) result = session . head ( url ) if result . status_code == requests . codes . NOT_FOUND : sel...
def get_conf ( self , test = False ) : """Send a HTTP request to the satellite ( GET / managed _ configurations ) and update the cfg _ managed attribute with the new information Set to { } on failure the managed configurations are a dictionary which keys are the scheduler link instance id and the values are...
logger . debug ( "Get managed configuration for %s, %s %s" , self . name , self . alive , self . reachable ) if test : self . cfg_managed = { } self . have_conf = True logger . debug ( "Get managed configuration test ..." ) if getattr ( self , 'unit_test_pushed_configuration' , None ) is not None : # No...
def memoizemethod ( method ) : """Decorator to cause a method to cache it ' s results in self for each combination of inputs and return the cached result on subsequent calls . Does not support named arguments or arg values that are not hashable . > > > class Foo ( object ) : . . . @ memoizemethod . . . de...
@ wraps ( method ) def _wrapper ( self , * args , ** kwargs ) : # NOTE : a _ _ dict _ _ check is performed here rather than using the # built - in hasattr function because hasattr will look up to an object ' s # class if the attr is not directly found in the object ' s dict . That ' s # bad for this if the class itself...
def clean ( self ) : """Global cleanup ."""
super ( LineFormSet , self ) . clean ( ) if any ( self . errors ) : # Already seen errors , let ' s skip . return self . clean_unique_fields ( )
def paginate_results ( self , results , options ) : "Return a django . core . paginator . Page of results ."
limit = options . get ( 'limit' , settings . SELECTABLE_MAX_LIMIT ) paginator = Paginator ( results , limit ) page = options . get ( 'page' , 1 ) try : results = paginator . page ( page ) except ( EmptyPage , InvalidPage ) : results = paginator . page ( paginator . num_pages ) return results