signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def calc_qib2_v1 ( self ) : """Calculate the first inflow component released from the soil . Required control parameters : | NHRU | | Lnk | | NFk | | DMin | | DMax | Required derived parameter : | WZ | Required state sequence : | BoWa | Calculated flux sequence : | QIB2 | Basic equation : ...
con = self . parameters . control . fastaccess der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess sta = self . sequences . states . fastaccess for k in range ( con . nhru ) : if ( ( con . lnk [ k ] in ( VERS , WASSER , FLUSS , SEE ) ) or ( sta . bowa [ k ] <= der . wz [ k ] ...
def create_stack ( self , args ) : """创建服务组 创建新一个指定名称的服务组 , 并创建其下的服务 。 Args : - args : 服务组描述 , 参考 http : / / kirk - docs . qiniu . com / apidocs / Returns : 返回一个tuple对象 , 其格式为 ( < result > , < ResponseInfo > ) - result 成功返回空dict { } , 失败返回 { " error " : " < errMsg string > " } - ResponseInfo 请求的Respon...
url = '{0}/v3/stacks' . format ( self . host ) return self . __post ( url , args )
def _eq ( field , value , document ) : """Returns True if the value of a document field is equal to a given value"""
try : return document . get ( field , None ) == value except TypeError : # pragma : no cover Python < 3.0 return False
def team_accessLogs ( self , ** kwargs ) -> SlackResponse : """Gets the access logs for the current team ."""
self . _validate_xoxp_token ( ) return self . api_call ( "team.accessLogs" , http_verb = "GET" , params = kwargs )
def model_to_json ( self , object , cleanup = True ) : """Take a model instance and return it as a json struct"""
model_name = type ( object ) . __name__ if model_name not in self . swagger_dict [ 'definitions' ] : raise ValidationError ( "Swagger spec has no definition for model %s" % model_name ) model_def = self . swagger_dict [ 'definitions' ] [ model_name ] log . debug ( "Marshalling %s into json" % model_name ) m = marsh...
def _set_route_profiletype ( self , v , load = False ) : """Setter method for route _ profiletype , mapped from YANG variable / hardware / profile / route / predefined / route _ profiletype ( route - profile - subtype ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ ro...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'default' : { 'value' : 0 } , u'route-enhance' : { 'value' : 1 } } , ) , is_leaf = True , yang_name = "route_profiletype" , rest...
def reverse_list ( head ) : """: type head : ListNode : rtype : ListNode"""
if not head or not head . next : return head prev = None while head : current = head head = head . next current . next = prev prev = current return prev
def intra_mean ( self , values ) : """Calculate the mean of a quantity within strata Parameters values : array - like , shape = ( n _ items , n _ class ) array containing the values of the quantity for each item in the pool Returns numpy . ndarray , shape = ( n _ strata , n _ class ) array containing ...
# TODO Check that quantity is valid if values . ndim > 1 : return np . array ( [ np . mean ( values [ x , : ] , axis = 0 ) for x in self . allocations_ ] ) else : return np . array ( [ np . mean ( values [ x ] ) for x in self . allocations_ ] )
def add_row ( self , * cells , color = None , escape = None , mapper = None , strict = True ) : """Add a row of cells to the table . Args cells : iterable , such as a ` list ` or ` tuple ` There ' s two ways to use this method . The first method is to pass the content of each cell as a separate argument . T...
if len ( cells ) == 1 and _is_iterable ( cells ) : cells = cells [ 0 ] if escape is None : escape = self . escape # Propagate packages used in cells for c in cells : if isinstance ( c , LatexObject ) : for p in c . packages : self . packages . add ( p ) # Count cell contents cell_count =...
def finalize ( self , ** kwargs ) : """Finalize executes any subclass - specific axes finalization steps . The user calls poof and poof calls finalize ."""
indices = np . arange ( len ( self . classes_ ) ) # Set the title self . set_title ( "Class Prediction Error for {}" . format ( self . name ) ) # Set the x ticks with the class names self . ax . set_xticks ( indices ) self . ax . set_xticklabels ( self . classes_ ) # Set the axes labels self . ax . set_xlabel ( "actual...
def wait_for_stateful_block_init ( context , mri , timeout = DEFAULT_TIMEOUT ) : """Wait until a Block backed by a StatefulController has initialized Args : context ( Context ) : The context to use to make the child block mri ( str ) : The mri of the child block timeout ( float ) : The maximum time to wait"...
context . when_matches ( [ mri , "state" , "value" ] , StatefulStates . READY , bad_values = [ StatefulStates . FAULT , StatefulStates . DISABLED ] , timeout = timeout )
def seqnum ( self , value ) : """Set SeqNum for Annotation : param value : SeqNum value : type value : int"""
if not re . match ( r'\d+' , str ( value ) ) or value < 0 : raise AttributeError ( "Invalid SeqNum value supplied" ) self . _seqnum = value
def parse_authorization_header ( value ) : """Parse the Authenticate header . Returns nothing on failure , opts hash on success with type = ' basic ' or ' digest ' and other params . < http : / / nullege . com / codes / search / werkzeug . http . parse _ authorization _ header > < http : / / stackoverflow ....
try : ( auth_type , auth_info ) = value . split ( ' ' , 1 ) auth_type = auth_type . lower ( ) except ValueError : return if ( auth_type == 'basic' ) : try : decoded = base64 . b64decode ( auth_info ) . decode ( 'utf-8' ) # b64decode gives bytes in python3 ( username , password ) ...
def get_parent ( self , log_info ) : """Get the parent container for the log sink"""
if self . data . get ( 'scope' , 'log' ) == 'log' : if log_info . scope_type != 'projects' : raise ValueError ( "Invalid log subscriber scope" ) parent = "%s/%s" % ( log_info . scope_type , log_info . scope_id ) elif self . data [ 'scope' ] == 'project' : parent = 'projects/{}' . format ( self . dat...
def hasmethod ( obj , meth ) : """Checks if an object , obj , has a callable method , meth return True or False"""
if hasattr ( obj , meth ) : return callable ( getattr ( obj , meth ) ) return False
def _ondim ( self , dimension , valuestring ) : """Converts valuestring to int and assigns result to self . dim If there is an error ( such as an empty valuestring ) or if the value is < 1 , the value 1 is assigned to self . dim Parameters dimension : int \t Dimension that is to be updated . Must be in [ ...
try : self . dimensions [ dimension ] = int ( valuestring ) except ValueError : self . dimensions [ dimension ] = 1 self . textctrls [ dimension ] . SetValue ( str ( 1 ) ) if self . dimensions [ dimension ] < 1 : self . dimensions [ dimension ] = 1 self . textctrls [ dimension ] . SetValue ( str ( 1...
def createMSBWTFromSeqs ( seqArray , mergedDir , numProcs , areUniform , logger ) : '''This function takes a series of sequences and creates the BWT using the technique from Cox and Bauer @ param seqArray - a list of ' $ ' - terminated sequences to be in the MSBWT @ param mergedFN - the final destination filena...
# wipe the auxiliary data stored here MSBWTGen . clearAuxiliaryData ( mergedDir ) # TODO : do we want a special case for N = 1 ? there was one in early code , but we could just assume users aren ' t dumb seqFN = mergedDir + '/seqs.npy' offsetFN = mergedDir + '/offsets.npy' # sort the sequences seqCopy = sorted ( seqArr...
def is_valid ( self , qstr = None ) : """Return True if string is valid"""
if qstr is None : qstr = self . currentText ( ) return osp . isdir ( to_text_string ( qstr ) )
def _make_canonical_headers ( headers , headers_to_sign ) : """Return canonicalized headers . @ param headers : The request headers . @ type headers : L { dict } @ param headers _ to _ sign : A sequence of header names that should be signed . @ type headers _ to _ sign : A sequence of L { bytes } @ retu...
pairs = [ ] for name in headers_to_sign : if name not in headers : continue values = headers [ name ] if not isinstance ( values , ( list , tuple ) ) : values = [ values ] comma_values = b',' . join ( ' ' . join ( line . strip ( ) . split ( ) ) for value in values for line in value . spl...
def get_permalink_ids_iter ( self ) : '''Method to get permalink ids from content . To be bound to the class last thing .'''
permalink_id_key = self . settings [ 'PERMALINK_ID_METADATA_KEY' ] permalink_ids = self . metadata . get ( permalink_id_key , '' ) for permalink_id in permalink_ids . split ( ',' ) : if permalink_id : yield permalink_id . strip ( )
def hash_array ( vals , encoding = 'utf8' , hash_key = None , categorize = True ) : """Given a 1d array , return an array of deterministic integers . . . versionadded : : 0.19.2 Parameters vals : ndarray , Categorical encoding : string , default ' utf8' encoding for data & key when strings hash _ key : ...
if not hasattr ( vals , 'dtype' ) : raise TypeError ( "must pass a ndarray-like" ) dtype = vals . dtype if hash_key is None : hash_key = _default_hash_key # For categoricals , we hash the categories , then remap the codes to the # hash values . ( This check is above the complex check so that we don ' t ask # nu...
def newChannelOpened_channel_ ( self , notif , newChannel ) : """Handle when a client connects to the server channel . ( This method is called for both RFCOMM and L2CAP channels . )"""
if newChannel is not None and newChannel . isIncoming ( ) : # not sure if delegate really needs to be set newChannel . setDelegate_ ( self ) if hasattr ( self . __cb_obj , '_handle_channelopened' ) : self . __cb_obj . _handle_channelopened ( newChannel )
def get_operator ( self , operator ) : """Get a comparison suffix to be used in Django ORM & inversion flag for it : param operator : string , DjangoQL comparison operator : return : ( suffix , invert ) - a tuple with 2 values : suffix - suffix to be used in ORM query , for example ' _ _ gt ' for ' > ' inve...
op = { '=' : '' , '>' : '__gt' , '>=' : '__gte' , '<' : '__lt' , '<=' : '__lte' , '~' : '__icontains' , 'in' : '__in' , } . get ( operator ) if op is not None : return op , False op = { '!=' : '' , '!~' : '__icontains' , 'not in' : '__in' , } [ operator ] return op , True
def jacobian ( sess , x , grads , target , X , nb_features , nb_classes , feed = None ) : """TensorFlow implementation of the foward derivative / Jacobian : param x : the input placeholder : param grads : the list of TF gradients returned by jacobian _ graph ( ) : param target : the target misclassification c...
warnings . warn ( "This function is dead code and will be removed on or after 2019-07-18" ) # Prepare feeding dictionary for all gradient computations feed_dict = { x : X } if feed is not None : feed_dict . update ( feed ) # Initialize a numpy array to hold the Jacobian component values jacobian_val = np . zeros ( ...
def set_difficulty_value ( self , difficulty ) : """stub"""
if not isinstance ( difficulty , float ) : raise InvalidArgument ( 'difficulty value must be a decimal' ) self . add_decimal_value ( difficulty , 'difficulty' )
def touch ( self , connection = None ) : """Mark this update as complete . IMPORTANT , If the marker table doesn ' t exist , the connection transaction will be aborted and the connection reset . Then the marker table will be created ."""
self . create_marker_table ( ) if connection is None : connection = self . connect ( ) connection . autocommit = True # if connection created here , we commit it here connection . cursor ( ) . execute ( """INSERT INTO {marker_table} (update_id, target_table) VALUES (%s, %s) ON DUPL...
def is_carrier_specific_for_region ( numobj , region_dialing_from ) : """Given a valid short number , determines whether it is carrier - specific when dialed from the given region ( however , nothing is implied about its validity ) . Carrier - specific numbers may connect to a different end - point , or not c...
if not _region_dialing_from_matches_number ( numobj , region_dialing_from ) : return False national_number = national_significant_number ( numobj ) metadata = PhoneMetadata . short_metadata_for_region ( region_dialing_from ) return ( metadata is not None and _matches_possible_number_and_national_number ( national_n...
def alter_add_column ( self , table , column_name , field , ** kwargs ) : """Fix fieldname for ForeignKeys ."""
name = field . name op = super ( SchemaMigrator , self ) . alter_add_column ( table , column_name , field , ** kwargs ) if isinstance ( field , pw . ForeignKeyField ) : field . name = name return op
def replace ( self , child , * nodes ) : r"""Replace provided node with node ( s ) . : param TexNode child : Child node to replace : param TexNode nodes : List of nodes to subtitute in > > > from TexSoup import TexSoup > > > soup = TexSoup ( r ' ' ' . . . \ begin { itemize } . . . \ item Hello . . . \...
self . expr . insert ( self . expr . remove ( child . expr ) , * nodes )
def _get_target_from_package_name ( self , target , package_name , file_path ) : """Get a dependent target given the package name and relative file path . This will only traverse direct dependencies of the passed target . It is not necessary to traverse further than that because transitive dependencies will be ...
address_path = self . parse_file_path ( file_path ) if not address_path : return None dep_spec_path = os . path . normpath ( os . path . join ( target . address . spec_path , address_path ) ) for dep in target . dependencies : if dep . package_name == package_name and dep . address . spec_path == dep_spec_path ...
def merge_segmentations ( segs1 , segs2 , strokes = None ) : """Parameters segs1 : a list of tuples Each tuple is a segmentation with its score segs2 : a list of tuples Each tuple is a segmentation with its score strokes : list of stroke names for segs2 Returns list of tuples : Segmentations with th...
def translate ( segmentation , strokes ) : t = [ ] for symbol in segmentation : symbol_new = [ ] for stroke in symbol : symbol_new . append ( strokes [ stroke ] ) t . append ( symbol_new ) return t if strokes is None : strokes = [ i for i in range ( len ( segs2 [ 0 ] ...
def create_ipv4 ( self , id_network_ipv4 ) : """Create VLAN in layer 2 using script ' navlan ' . : param id _ network _ ipv4 : NetworkIPv4 ID . : return : Following dictionary : { ‘ sucesso ’ : { ‘ codigo ’ : < codigo > , ‘ descricao ’ : { ' stdout ' : < stdout > , ' stderr ' : < stderr > } } } : raise Ne...
url = 'vlan/v4/create/' vlan_map = dict ( ) vlan_map [ 'id_network_ip' ] = id_network_ipv4 code , xml = self . submit ( { 'vlan' : vlan_map } , 'POST' , url ) return self . response ( code , xml )
async def postback_me ( msg : BaseMessage , platform : Platform ) -> Response : """Provides the front - end with details about the user . This output can be completed using the ` api _ postback _ me ` middleware hook ."""
async def get_basic_info ( _msg : BaseMessage , _platform : Platform ) : user = _msg . get_user ( ) return { 'friendly_name' : await user . get_friendly_name ( ) , 'locale' : await user . get_locale ( ) , 'platform' : _platform . NAME , } func = MiddlewareManager . instance ( ) . get ( 'api_postback_me' , get_b...
def check_managed_changes ( name , source , source_hash , source_hash_name , user , group , mode , attrs , template , context , defaults , saltenv , contents = None , skip_verify = False , keep_mode = False , seuser = None , serole = None , setype = None , serange = None , ** kwargs ) : '''Return a dictionary of wh...
# If the source is a list then find which file exists source , source_hash = source_list ( source , # pylint : disable = W0633 source_hash , saltenv ) sfn = '' source_sum = None if contents is None : # Gather the source file from the server sfn , source_sum , comments = get_managed ( name , template , source , sour...
def system_find_projects ( input_params = { } , always_retry = True , ** kwargs ) : """Invokes the / system / findProjects API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Search # API - method % 3A - % 2Fsystem % 2FfindProjects"""
return DXHTTPRequest ( '/system/findProjects' , input_params , always_retry = always_retry , ** kwargs )
def _get_cpu_info_internal ( ) : '''Returns the CPU info by using the best sources of information for your OS . Returns { } if nothing is found .'''
# Get the CPU arch and bits arch , bits = _parse_arch ( DataSource . arch_string_raw ) friendly_maxsize = { 2 ** 31 - 1 : '32 bit' , 2 ** 63 - 1 : '64 bit' } . get ( sys . maxsize ) or 'unknown bits' friendly_version = "{0}.{1}.{2}.{3}.{4}" . format ( * sys . version_info ) PYTHON_VERSION = "{0} ({1})" . format ( frien...
def OnWidgetToolbarToggle ( self , event ) : """Widget toolbar toggle event handler"""
self . main_window . widget_toolbar . SetGripperVisible ( True ) widget_toolbar_info = self . main_window . _mgr . GetPane ( "widget_toolbar" ) self . _toggle_pane ( widget_toolbar_info ) event . Skip ( )
def has_all_nonzero_neurite_radii ( neuron , threshold = 0.0 ) : '''Check presence of neurite points with radius not above threshold Arguments : neuron ( Neuron ) : The neuron object to test threshold : value above which a radius is considered to be non - zero Returns : CheckResult with result including l...
bad_ids = [ ] seen_ids = set ( ) for s in _nf . iter_sections ( neuron ) : for i , p in enumerate ( s . points ) : info = ( s . id , i ) if p [ COLS . R ] <= threshold and info not in seen_ids : seen_ids . add ( info ) bad_ids . append ( info ) return CheckResult ( len ( bad_...
def get_incomplete_assessment_sections ( self , assessment_taken_id ) : """Gets the incomplete assessment sections of this assessment . arg : assessment _ taken _ id ( osid . id . Id ) : ` ` Id ` ` of the ` ` AssessmentTaken ` ` return : ( osid . assessment . AssessmentSectionList ) - the list of incomplete...
section_list = [ ] for section in self . get_assessment_sections ( assessment_taken_id ) : if not section . is_complete ( ) : section_list . append ( section ) return objects . AssessmentSectionList ( section_list , runtime = self . _runtime , proxy = self . _proxy )
def connect_output ( self , node ) : """Connect another node to our output . This downstream node will automatically be triggered when we update our output . Args : node ( SGNode ) : The node that should receive our output"""
if len ( self . outputs ) == self . max_outputs : raise TooManyOutputsError ( "Attempted to connect too many nodes to the output of a node" , max_outputs = self . max_outputs , stream = self . stream ) self . outputs . append ( node )
def _on_mode_change ( self , mode ) : """Mode change broadcast from Abode SocketIO server ."""
if isinstance ( mode , ( tuple , list ) ) : mode = mode [ 0 ] if mode is None : _LOGGER . warning ( "Mode change event with no mode." ) return if not mode or mode . lower ( ) not in CONST . ALL_MODES : _LOGGER . warning ( "Mode change event with unknown mode: %s" , mode ) return _LOGGER . debug ( "A...
def _grab_version ( self ) : """Set the version to a non - development version ."""
original_version = self . vcs . version logger . debug ( "Extracted version: %s" , original_version ) if original_version is None : logger . critical ( 'No version found.' ) sys . exit ( 1 ) suggestion = utils . cleanup_version ( original_version ) new_version = utils . ask_version ( "Enter version" , default =...
def _validate_assets ( self , assets ) : """Validate that asset identifiers are contained in the daily bars . Parameters assets : array - like [ int ] The asset identifiers to validate . Raises NoDataForSid If one or more of the provided asset identifiers are not contained in the daily bars ."""
missing_sids = np . setdiff1d ( assets , self . sids ) if len ( missing_sids ) : raise NoDataForSid ( 'Assets not contained in daily pricing file: {}' . format ( missing_sids ) )
def project_sequence ( s , permutation = None ) : """Projects a point or sequence of points using ` project _ point ` to lists xs , ys for plotting with Matplotlib . Parameters s , Sequence - like The sequence of points ( 3 - tuples ) to be projected . Returns xs , ys : The sequence of projected points ...
xs , ys = unzip ( [ project_point ( p , permutation = permutation ) for p in s ] ) return xs , ys
def isLearned ( self , mode = None ) : """Return true if this parameter is learned Hidden parameters are not learned ; automatic parameters inherit behavior from package / cl ; other parameters are learned . If mode is set , it determines how automatic parameters behave . If not set , cl . mode parameter de...
if "l" in self . mode : return 1 if "h" in self . mode : return 0 if "a" in self . mode : if mode is None : mode = 'ql' # that is , iraf . cl . mode if "h" in mode and "l" not in mode : return 0 return 1
def set_node_config ( self , jid , config , node = None ) : """Update the configuration of a node . : param jid : Address of the PubSub service . : type jid : : class : ` aioxmpp . JID ` : param config : Configuration form : type config : : class : ` aioxmpp . forms . Data ` : param node : Name of the Pub...
iq = aioxmpp . stanza . IQ ( to = jid , type_ = aioxmpp . structs . IQType . SET ) iq . payload = pubsub_xso . OwnerRequest ( pubsub_xso . OwnerConfigure ( node = node ) ) iq . payload . payload . data = config yield from self . client . send ( iq )
def process_text ( text , save_xml_name = 'trips_output.xml' , save_xml_pretty = True , offline = False , service_endpoint = 'drum' ) : """Return a TripsProcessor by processing text . Parameters text : str The text to be processed . save _ xml _ name : Optional [ str ] The name of the file to save the ret...
if not offline : html = client . send_query ( text , service_endpoint ) xml = client . get_xml ( html ) else : if offline_reading : try : dr = DrumReader ( ) if dr is None : raise Exception ( 'DrumReader could not be instantiated.' ) except BaseExcepti...
def get_all_functional_groups ( self , elements = None , func_groups = None , catch_basic = True ) : """Identify all functional groups ( or all within a certain subset ) in the molecule , combining the methods described above . : param elements : List of elements that will qualify a carbon as special ( if onl...
heteroatoms = self . get_heteroatoms ( elements = elements ) special_cs = self . get_special_carbon ( elements = elements ) groups = self . link_marked_atoms ( heteroatoms . union ( special_cs ) ) if catch_basic : groups += self . get_basic_functional_groups ( func_groups = func_groups ) return groups
def generate ( self ) : '''Generate noise samples . Returns : ` np . ndarray ` of samples .'''
observed_arr = None for row in range ( self . __batch_size ) : arr = None for d in range ( self . __dim ) : _arr = self . __generate_sin ( amp = self . __amp , sampling_freq = self . __sampling_freq , freq = self . __freq , sec = self . __sec , seq_len = self . __seq_len ) _arr = np . expand_dim...
def process_alias_import_namespace ( namespace ) : """Validate input arguments when the user invokes ' az alias import ' . Args : namespace : argparse namespace object ."""
if is_url ( namespace . alias_source ) : alias_source = retrieve_file_from_url ( namespace . alias_source ) _validate_alias_file_content ( alias_source , url = namespace . alias_source ) else : namespace . alias_source = os . path . abspath ( namespace . alias_source ) _validate_alias_file_path ( namesp...
def get_header ( fn , file_format , header_bytes = 20000 , verbose = False , * args , ** kwargs ) : """Apply rules for detecting the boundary of the header : param str fn : file name : param str file _ format : either ` ` AmiraMesh ` ` or ` ` HyperSurface ` ` : param int header _ bytes : number of bytes in wh...
assert header_bytes > 0 assert file_format in [ 'AmiraMesh' , 'HyperSurface' ] with open ( fn , 'rb' ) as f : rough_header = f . read ( header_bytes ) if file_format == "AmiraMesh" : if verbose : print >> sys . stderr , "Using pattern: (?P<data>.*)\\n@1" m = re . search ( r'(?P<data>...
def extract_keywords_from_sentences ( self , sentences ) : """Method to extract keywords from the list of sentences provided . : param sentences : Text to extraxt keywords from , provided as a list of strings , where each string is a sentence ."""
phrase_list = self . _generate_phrases ( sentences ) self . _build_frequency_dist ( phrase_list ) self . _build_word_co_occurance_graph ( phrase_list ) self . _build_ranklist ( phrase_list )
def is_all_field_none ( self ) : """: rtype : bool"""
if self . _BunqMeTab is not None : return False if self . _BunqMeTabResultResponse is not None : return False if self . _BunqMeFundraiserResult is not None : return False if self . _Card is not None : return False if self . _CardDebit is not None : return False if self . _DraftPayment is not None : ...
def string_to_bytes ( string ) : """Returns the amount of bytes in a human readable form up to Yottabytes ( YB ) . : param string : integer with suffix ( b , k , m , g , t , p , e , z , y ) : return : amount of bytes in string representation > > > string _ to _ bytes ( ' 1024 ' ) 1024 > > > string _ to _ ...
if string == '0' : return 0 import re match = re . match ( '(\d+\.?\d?)\s?([bBkKmMgGtTpPeEzZyY])?(\D?)' , string ) if not match : raise RuntimeError ( '"{}" does not match "[integer] [suffix]"' . format ( string ) ) if match . group ( 3 ) : raise RuntimeError ( 'unknown suffix: "{}"' . format ( match . grou...
def delete_publisher ( self , publisher_name ) : """DeletePublisher . [ Preview API ] : param str publisher _ name :"""
route_values = { } if publisher_name is not None : route_values [ 'publisherName' ] = self . _serialize . url ( 'publisher_name' , publisher_name , 'str' ) self . _send ( http_method = 'DELETE' , location_id = '4ddec66a-e4f6-4f5d-999e-9e77710d7ff4' , version = '5.1-preview.1' , route_values = route_values )
def _setup_grid ( self , cutoff , unit_cell , grid ) : """Choose a proper grid for the binning process"""
if grid is None : # automatically choose a decent grid if unit_cell is None : grid = cutoff / 2.9 else : # The following would be faster , but it is not reliable # enough yet . # grid = unit _ cell . get _ optimal _ subcell ( cutoff / 2.0) divisions = np . ceil ( unit_cell . spacings / c...
def get_position ( self , topic_partition = None ) : """Return offset of the next record that will be fetched . - ` ` topic _ partition ` ` ( TopicPartition ) : Partition to check"""
if isinstance ( topic_partition , TopicPartition ) : return self . consumer . position ( topic_partition ) else : raise TypeError ( "topic_partition must be of type TopicPartition, create it with Create TopicPartition keyword." )
def get_bucket_inventory ( client , bucket , inventory_id ) : """Check a bucket for a named inventory , and return the destination ."""
inventories = client . list_bucket_inventory_configurations ( Bucket = bucket ) . get ( 'InventoryConfigurationList' , [ ] ) inventories = { i [ 'Id' ] : i for i in inventories } found = fnmatch . filter ( inventories , inventory_id ) if not found : return None i = inventories [ found . pop ( ) ] s3_info = i [ 'Des...
def compute_v ( self , memory_antecedent ) : """Compute value Tensor v . Args : memory _ antecedent : a Tensor with dimensions { memory _ input _ dim } + other _ dims Returns : a Tensor with dimensions memory _ heads _ dims + { value _ dim } + other _ dims"""
if self . shared_kv : raise ValueError ( "compute_v cannot be called with shared_kv" ) ret = mtf . einsum ( [ memory_antecedent , self . wv ] , reduced_dims = [ self . memory_input_dim ] ) if self . combine_dims : ret = mtf . replace_dimensions ( ret , ret . shape . dims [ - 1 ] , self . v_dims ) return ret
def _assemble_regulate_amount ( self , stmt ) : """Example : p ( HGNC : ELK1 ) = > p ( HGNC : FOS )"""
activates = isinstance ( stmt , IncreaseAmount ) relation = get_causal_edge ( stmt , activates ) self . _add_nodes_edges ( stmt . subj , stmt . obj , relation , stmt . evidence )
def find_mod_objs ( modname , onlylocals = False ) : """Returns all the public attributes of a module referenced by name . . . note : : The returned list * not * include subpackages or modules of ` modname ` , nor does it include private attributes ( those that beginwith ' _ ' or are not in ` _ _ all _ _ ` ...
__import__ ( modname ) mod = sys . modules [ modname ] if hasattr ( mod , '__all__' ) : pkgitems = [ ( k , mod . __dict__ [ k ] ) for k in mod . __all__ ] else : pkgitems = [ ( k , mod . __dict__ [ k ] ) for k in dir ( mod ) if k [ 0 ] != '_' ] # filter out modules and pull the names and objs out ismodule = ins...
def time_restarts ( data_path ) : """When called will create a file and measure its mtime on restarts"""
path = os . path . join ( data_path , 'last_restarted' ) if not os . path . isfile ( path ) : with open ( path , 'a' ) : os . utime ( path , None ) last_modified = os . stat ( path ) . st_mtime with open ( path , 'a' ) : os . utime ( path , None ) now = os . stat ( path ) . st_mtime dif = round ( now - ...
def out_of_bounds ( self , index ) : """Check index for out of bounds : param index : index as integer , tuple or slice : return : local index as tuple"""
if type ( index ) is int : return self . int_out_of_bounds ( index ) elif type ( index ) is slice : return self . slice_out_of_bounds ( index ) elif type ( index ) is tuple : local_index = [ ] for k , item in enumerate ( index ) : if type ( item ) is slice : temp_index = self . slice...
def _get_timezone ( self , root ) : """Find timezone informatation on bottom of the page ."""
tz_str = root . xpath ( '//div[@class="smallfont" and @align="center"]' ) [ 0 ] . text hours = int ( self . _tz_re . search ( tz_str ) . group ( 1 ) ) return tzoffset ( tz_str , hours * 60 )
def find_by_id ( self , organization_export , params = { } , ** options ) : """Returns details of a previously - requested Organization export . Parameters organization _ export : { Id } Globally unique identifier for the Organization export . [ params ] : { Object } Parameters for the request"""
path = "/organization_exports/%s" % ( organization_export ) return self . client . get ( path , params , ** options )
def __save_shadow_copy ( self ) : """Saves a copy of the stored routine source with pure SQL ( if shadow directory is set ) ."""
if not self . shadow_directory : return destination_filename = os . path . join ( self . shadow_directory , self . _routine_name ) + '.sql' if os . path . realpath ( destination_filename ) == os . path . realpath ( self . _source_filename ) : raise LoaderException ( "Shadow copy will override routine source '{}...
def disagg_prec ( dailyData , method = 'equal' , cascade_options = None , hourly_data_obs = None , zerodiv = "uniform" , shift = 0 ) : """The disaggregation function for precipitation . Parameters dailyData : pd . Series daily data method : str method to disaggregate cascade _ options : cascade object ...
if method not in ( 'equal' , 'cascade' , 'masterstation' ) : raise ValueError ( 'Invalid option' ) if method == 'equal' : precip_disagg = melodist . distribute_equally ( dailyData . precip , divide = True ) elif method == 'masterstation' : precip_disagg = precip_master_station ( dailyData , hourly_data_obs ...
def _is_valid_language ( self ) : """Return True if the value of component in attribute " language " is valid , and otherwise False . : returns : True if value is valid , False otherwise : rtype : boolean"""
comp_str = self . _encoded_value . lower ( ) lang_rxc = re . compile ( CPEComponentSimple . _LANGTAG_PATTERN ) return lang_rxc . match ( comp_str ) is not None
def roc ( y_true , y_score , ax = None ) : """Plot ROC curve . Parameters y _ true : array - like , shape = [ n _ samples ] Correct target values ( ground truth ) . y _ score : array - like , shape = [ n _ samples ] or [ n _ samples , 2 ] for binary classification or [ n _ samples , n _ classes ] for mult...
if any ( ( val is None for val in ( y_true , y_score ) ) ) : raise ValueError ( "y_true and y_score are needed to plot ROC" ) if ax is None : ax = plt . gca ( ) # get the number of classes based on the shape of y _ score y_score_is_vector = is_column_vector ( y_score ) or is_row_vector ( y_score ) if y_score_is...
def up ( tag , sql , revision ) : """Upgrade to revision"""
alembic_command . upgrade ( config = get_config ( ) , revision = revision , sql = sql , tag = tag )
def if_unmodified_since ( self ) -> Optional [ datetime . datetime ] : """The value of If - Unmodified - Since HTTP header , or None . This header is represented as a ` datetime ` object ."""
return self . _http_date ( self . headers . get ( hdrs . IF_UNMODIFIED_SINCE ) )
def GET_AUTH ( self , courseid , scoreboardid ) : # pylint : disable = arguments - differ """GET request"""
course = self . course_factory . get_course ( courseid ) scoreboards = course . get_descriptor ( ) . get ( 'scoreboard' , [ ] ) try : scoreboardid = int ( scoreboardid ) scoreboard_name = scoreboards [ scoreboardid ] [ "name" ] scoreboard_content = scoreboards [ scoreboardid ] [ "content" ] scoreboard_r...
def GetHist ( tag_name , start_time , end_time , period = 5 , mode = "raw" , desc_as_label = False , label = None , high_speed = False , utc = False ) : """Retrieves data from eDNA history for a given tag . : param tag _ name : fully - qualified ( site . service . tag ) eDNA tag : param start _ time : must be i...
# Check if the point even exists if not DoesIDExist ( tag_name ) : warnings . warn ( "WARNING- " + tag_name + " does not exist or " + "connection was dropped. Try again if tag does exist." ) return pd . DataFrame ( ) # Define all required variables in the correct ctypes format szPoint = c_char_p ( tag_name . en...
def p_BIT ( p ) : """asm : bitop expr COMMA A | bitop pexpr COMMA A | bitop expr COMMA reg8 | bitop pexpr COMMA reg8 | bitop expr COMMA reg8 _ hl | bitop pexpr COMMA reg8 _ hl"""
bit = p [ 2 ] . eval ( ) if bit < 0 or bit > 7 : error ( p . lineno ( 3 ) , 'Invalid bit position %i. Must be in [0..7]' % bit ) p [ 0 ] = None return p [ 0 ] = Asm ( p . lineno ( 3 ) , '%s %i,%s' % ( p [ 1 ] , bit , p [ 4 ] ) )
def add_variable ( self , node ) : """Add a variable node to this node . : sig : ( VariableNode ) - > None : param node : Variable node to add ."""
if node . name not in self . variable_names : self . variables . append ( node ) self . variable_names . add ( node . name ) node . parent = self
def count ( self , signature = None ) : """Counts how many crash dumps have been stored in this database . Optionally filters the count by heuristic signature . @ type signature : object @ param signature : ( Optional ) Count only the crashes that match this signature . See L { Crash . signature } for more ...
query = self . _session . query ( CrashDTO . id ) if signature : sig_pickled = pickle . dumps ( signature , protocol = 0 ) query = query . filter_by ( signature = sig_pickled ) return query . count ( )
def open_config ( self , type = "shared" ) : """Opens the configuration of the currently connected device Args : : type : The type of configuration you want to open . Any string can be provided , however the standard supported options are : * * exclusive * * , * * private * * , and * * shared * * . The default ...
try : # attempt to open a configuration output = self . dev . rpc ( "<open-configuration><{0}/></open-configuration>" . format ( type ) ) except Exception as err : # output an error if the configuration is not availble print err
def clipping_params ( ts , capacity = 100 , rate_limit = float ( 'inf' ) , method = None , max_attempts = 100 ) : """Start , end , and threshold that clips the value of a time series the most , given a limitted " capacity " and " rate " Assumes that signal can be linearly interpolated between points ( trapezoidal...
VALID_METHODS = [ 'L-BFGS-B' , 'TNC' , 'SLSQP' , 'COBYLA' ] # print ( ' in clipping params for ts . index = { 0 } and method = { 1 } ' . format ( ts . index [ 0 ] , method ) ) ts . index = ts . index . astype ( np . int64 ) costs = [ ] def cost_fun ( x , * args ) : thresh = x [ 0 ] ts , capacity , bounds = args...
def _check_and_expand_exponential ( expr , variables , data ) : """Check if the current operation specifies exponential expansion . ^ ^ 6 specifies all powers up to the 6th , ^ 5-6 the 5th and 6th powers , ^ 6 the 6th only ."""
if re . search ( r'\^\^[0-9]+$' , expr ) : order = re . compile ( r'\^\^([0-9]+)$' ) . findall ( expr ) order = range ( 1 , int ( * order ) + 1 ) variables , data = exponential_terms ( order , variables , data ) elif re . search ( r'\^[0-9]+[\-]?[0-9]*$' , expr ) : order = re . compile ( r'\^([0-9]+[\-]...
def build_dirs ( files ) : '''Build necessary directories based on a list of file paths'''
for i in files : if type ( i ) is list : build_dirs ( i ) continue else : if len ( i [ 'path' ] ) > 1 : addpath = os . path . join ( os . getcwd ( ) , * i [ 'path' ] [ : - 1 ] ) subdirs = all_subdirs ( os . getcwd ( ) ) if addpath and addpath not in su...
def match_alphabet ( self , pattern ) : """Initialise the alphabet for the Bitap algorithm . Args : pattern : The text to encode . Returns : Hash of character locations ."""
s = { } for char in pattern : s [ char ] = 0 for i in range ( len ( pattern ) ) : s [ pattern [ i ] ] |= 1 << ( len ( pattern ) - i - 1 ) return s
def evaluate_script ( self ) : """Evaluates current * * Script _ Editor _ tabWidget * * Widget tab Model editor content into the interactive console . : return : Method success . : rtype : bool"""
editor = self . get_current_editor ( ) if not editor : return False LOGGER . debug ( "> Evaluating 'Script Editor' content." ) if self . evaluate_code ( foundations . strings . to_string ( editor . toPlainText ( ) . toUtf8 ( ) ) ) : self . ui_refresh . emit ( ) return True
def get_submissions ( self , fullnames , * args , ** kwargs ) : """Generate Submission objects for each item provided in ` fullnames ` . A submission fullname looks like ` t3 _ < base36 _ id > ` . Submissions are yielded in the same order they appear in ` fullnames ` . Up to 100 items are batched at a time - ...
fullnames = fullnames [ : ] while fullnames : cur = fullnames [ : 100 ] fullnames [ : 100 ] = [ ] url = self . config [ 'by_id' ] + ',' . join ( cur ) for item in self . get_content ( url , limit = len ( cur ) , * args , ** kwargs ) : yield item
def get_layout ( ) : """Specify a hierarchy of our templates ."""
tica_msm = TemplateDir ( 'tica' , [ 'tica/tica.py' , 'tica/tica-plot.py' , 'tica/tica-sample-coordinate.py' , 'tica/tica-sample-coordinate-plot.py' , ] , [ TemplateDir ( 'cluster' , [ 'cluster/cluster.py' , 'cluster/cluster-plot.py' , 'cluster/sample-clusters.py' , 'cluster/sample-clusters-plot.py' , ] , [ TemplateDir ...
def getTotalCpuTimeAndMemoryUsage ( ) : """Gives the total cpu time and memory usage of itself and its children ."""
me = resource . getrusage ( resource . RUSAGE_SELF ) childs = resource . getrusage ( resource . RUSAGE_CHILDREN ) totalCpuTime = me . ru_utime + me . ru_stime + childs . ru_utime + childs . ru_stime totalMemoryUsage = me . ru_maxrss + me . ru_maxrss return totalCpuTime , totalMemoryUsage
def router_fabric_virtual_gateway_address_family_ipv4_accept_unicast_arp_request ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) router = ET . SubElement ( config , "router" , xmlns = "urn:brocade.com:mgmt:brocade-common-def" ) fabric_virtual_gateway = ET . SubElement ( router , "fabric-virtual-gateway" , xmlns = "urn:brocade.com:mgmt:brocade-anycast-gateway" ) address_family = ET . SubElement ( fabric_virtual_...
def _find_x86_candidates ( self , start_address , end_address ) : """Finds possible ' RET - ended ' gadgets ."""
roots = [ ] # find gadgets tail for addr in xrange ( start_address , end_address + 1 ) : # TODO : Make this ' speed improvement ' architecture - agnostic op_codes = [ 0xc3 , # RET 0xc2 , # RET imm16 0xeb , # JMP rel8 0xe8 , # CALL rel { 16,32} 0xe9 , # JMP rel { 16,32} 0xff , # JMP / CALL r / m ...
def new_transaction ( vm : VM , from_ : Address , to : Address , amount : int = 0 , private_key : PrivateKey = None , gas_price : int = 10 , gas : int = 100000 , data : bytes = b'' ) -> BaseTransaction : """Create and return a transaction sending amount from < from _ > to < to > . The transaction will be signed w...
nonce = vm . state . get_nonce ( from_ ) tx = vm . create_unsigned_transaction ( nonce = nonce , gas_price = gas_price , gas = gas , to = to , value = amount , data = data , ) return tx . as_signed_transaction ( private_key )
def finalize ( self ) : """Get the base64 - encoded signature itself . Can only be called once ."""
signature = self . signer . finalize ( ) sig_r , sig_s = decode_dss_signature ( signature ) sig_b64 = encode_signature ( sig_r , sig_s ) return sig_b64
def template_from_filename ( filename ) : """Returns the appropriate template name based on the given file name ."""
ext = filename . split ( os . path . extsep ) [ - 1 ] if not ext in TEMPLATES_MAP : raise ValueError ( "No template for file extension {}" . format ( ext ) ) return TEMPLATES_MAP [ ext ]
def login ( config , api_key = "" ) : """Store your Bugzilla API Key"""
if not api_key : info_out ( "If you don't have an API Key, go to:\n" "https://bugzilla.mozilla.org/userprefs.cgi?tab=apikey\n" ) api_key = getpass . getpass ( "API Key: " ) # Before we store it , let ' s test it . url = urllib . parse . urljoin ( config . bugzilla_url , "/rest/whoami" ) assert url . startswith ...
def read_mac ( self ) : """Read MAC from EFUSE region"""
words = [ self . read_efuse ( 2 ) , self . read_efuse ( 1 ) ] bitstring = struct . pack ( ">II" , * words ) bitstring = bitstring [ 2 : 8 ] # trim the 2 byte CRC try : return tuple ( ord ( b ) for b in bitstring ) except TypeError : # Python 3 , bitstring elements are already bytes return tuple ( bitstring )
def _init ( self ) : """Finalize the initialization of the RlzsAssoc object by setting the ( reduced ) weights of the realizations ."""
if self . num_samples : assert len ( self . realizations ) == self . num_samples , ( len ( self . realizations ) , self . num_samples ) for rlz in self . realizations : for k in rlz . weight . dic : rlz . weight . dic [ k ] = 1. / self . num_samples else : tot_weight = sum ( rlz . weight...
def cli ( env , identifier , price = False , guests = False ) : """Get details for a virtual server ."""
dhost = SoftLayer . DedicatedHostManager ( env . client ) table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) table . align [ 'name' ] = 'r' table . align [ 'value' ] = 'l' result = dhost . get_host ( identifier ) result = utils . NestedDict ( result ) table . add_row ( [ 'id' , result [ 'id' ] ] ) table . add_...
def _init_lsr ( n_items , alpha , initial_params ) : """Initialize the LSR Markov chain and the weights ."""
if initial_params is None : weights = np . ones ( n_items ) else : weights = exp_transform ( initial_params ) chain = alpha * np . ones ( ( n_items , n_items ) , dtype = float ) return weights , chain
def _build_jss_object_list ( self , response , obj_class ) : """Build a JSSListData object from response ."""
response_objects = [ item for item in response if item is not None and item . tag != "size" ] objects = [ JSSListData ( obj_class , { i . tag : i . text for i in response_object } , self ) for response_object in response_objects ] return JSSObjectList ( self , obj_class , objects )
def download_cutout ( self , reading , focus = None , needs_apcor = False ) : """Downloads a cutout of the FITS image for a given source reading . Args : reading : ossos . astrom . SourceReading The reading which will be the focus of the downloaded image . focus : tuple ( int , int ) The x , y coordinates...
logger . debug ( "Doing download_cutout with inputs: reading:{} focus:{} needs_apcor:{}" . format ( reading , focus , needs_apcor ) ) assert isinstance ( reading , SourceReading ) min_radius = config . read ( 'CUTOUTS.SINGLETS.RADIUS' ) if not isinstance ( min_radius , Quantity ) : min_radius = min_radius * units ....
def _get_index_name_by_column ( table , column_name ) : """Find the index name for a given table and column ."""
protected_name = metadata . protect_name ( column_name ) possible_index_values = [ protected_name , "values(%s)" % protected_name ] for index_metadata in table . indexes . values ( ) : options = dict ( index_metadata . index_options ) if options . get ( 'target' ) in possible_index_values : return index...
def build_items ( self ) : """main loop"""
conn = self . connect ( address = self . server_address , port = self . server_port ) if conn : while not self . queue . empty ( ) : item = self . queue . get ( ) self . pool . append ( item ) if type ( item . data ) is ( tuple or list ) : self . body [ 'data' ] . extend ( item ....
def _uniquewords ( * args ) : """Dictionary of words to their indices . Helper function to ` encode . `"""
words = { } n = 0 for word in itertools . chain ( * args ) : if word not in words : words [ word ] = n n += 1 return words