signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _delete ( self , url ) : """Wrapper around request . delete ( ) to use the API prefix . Returns a JSON response ."""
req = self . _session . delete ( self . _api_prefix + url ) return self . _action ( req )
def get_additional_params ( self , ** params ) : """Filter to get the additional params needed for polling"""
# TODO : Move these params to their own vertical if needed . polling_params = [ 'locationschema' , 'carrierschema' , 'sorttype' , 'sortorder' , 'originairports' , 'destinationairports' , 'stops' , 'outbounddeparttime' , 'outbounddepartstarttime' , 'outbounddepartendtime' , 'inbounddeparttime' , 'inbounddepartstarttime'...
def scrape ( language , method , word , * args , ** kwargs ) : '''Uses custom scrapers and calls provided method .'''
scraper = Scrape ( language , word ) if hasattr ( scraper , method ) : function = getattr ( scraper , method ) if callable ( function ) : return function ( * args , ** kwargs ) else : raise NotImplementedError ( 'The method ' + method + '() is not implemented so far.' )
def create_work_item ( self , document , project , type , validate_only = None , bypass_rules = None , suppress_notifications = None , expand = None ) : """CreateWorkItem . [ Preview API ] Creates a single work item . : param : class : ` < [ JsonPatchOperation ] > < azure . devops . v5_1 . work _ item _ trackin...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if type is not None : route_values [ 'type' ] = self . _serialize . url ( 'type' , type , 'str' ) query_parameters = { } if validate_only is not None : query_parameters [ 'validat...
def price_change ( self ) : """This method returns any price change . : return :"""
try : if self . _data_from_search : return self . _data_from_search . find ( 'div' , { 'class' : 'price-changes-sr' } ) . text else : return self . _ad_page_content . find ( 'div' , { 'class' : 'price-changes-sr' } ) . text except Exception as e : if self . _debug : logging . error (...
def _init_dut ( self ) : """Initialize the DUT . DUT will be restarted . and openthread will started ."""
if self . auto_dut : self . dut = None return dut_port = settings . DUT_DEVICE [ 0 ] dut = OpenThreadController ( dut_port ) self . dut = dut
def _determine_current_dimension_size ( self , dim_name , max_size ) : """Helper method to determine the current size of a dimension ."""
# Limited dimension . if self . dimensions [ dim_name ] is not None : return max_size def _find_dim ( h5group , dim ) : if dim not in h5group : return _find_dim ( h5group . parent , dim ) return h5group [ dim ] dim_variable = _find_dim ( self . _h5group , dim_name ) if "REFERENCE_LIST" not in dim_va...
def walk ( self , dispatcher , node ) : """Walk through the node with a custom dispatcher for extraction of details that are required ."""
deferrable_handlers = { Declare : self . declare , Resolve : self . register_reference , } layout_handlers = { PushScope : self . push_scope , PopScope : self . pop_scope , PushCatch : self . push_catch , # should really be different , but given that the # mechanism is within the same tree , the only difference # would...
def resume_from ( self ) : """Get a timestamp representing the position just after the last written gauge"""
position = self . driver . get_writer_position ( self . config . writer_name ) return position + self . config . resolution if position else 0
def handle_delete_user ( self , req ) : """Handles the DELETE v2 / < account > / < user > call for deleting a user from an account . Can only be called by an account . admin . : param req : The swob . Request to process . : returns : swob . Response , 2xx on success ."""
# Validate path info account = req . path_info_pop ( ) user = req . path_info_pop ( ) if req . path_info or not account or account [ 0 ] == '.' or not user or user [ 0 ] == '.' : return HTTPBadRequest ( request = req ) # if user to be deleted is reseller _ admin , then requesting # user must be the super _ admin is...
def get_search_form ( self ) : """Return list of form based on model"""
magic_dico_form = self . get_dict_for_forms ( ) forms = [ ] initial = list ( self . request . GET . lists ( ) ) for key , value in magic_dico_form . items ( ) : form = Form ( ) model = value [ "model" ] if not value [ "fields" ] : continue for field in value [ "fields" ] : formfield = ge...
def astimezone ( self , tz ) : """Return a : py : class : ` khayyam . JalaliDatetime ` object with new : py : meth : ` khayyam . JalaliDatetime . tzinfo ` attribute tz , adjusting the date and time data so the result is the same UTC time as self , but in * tz * ‘ s local time . * tz * must be an instance of a :...
if self . tzinfo is tz : return self if self . tzinfo : utc = self - self . utcoffset ( ) else : utc = self return tz . fromutc ( utc . replace ( tzinfo = tz ) )
def sequence_mutation_summary ( self , alignment_ids = None , alignment_type = None ) : """Summarize all mutations found in the sequence _ alignments attribute . Returns 2 dictionaries , single _ counter and fingerprint _ counter . single _ counter : Dictionary of ` ` { point mutation : list of genes / strain...
if alignment_ids : ssbio . utils . force_list ( alignment_ids ) if len ( self . sequence_alignments ) == 0 : log . error ( '{}: no sequence alignments' . format ( self . id ) ) return { } , { } fingerprint_counter = defaultdict ( list ) single_counter = defaultdict ( list ) for alignment in self . sequence_...
def edit ( self , entry , name , mark = False ) : """Edit an entry ( file or directory ) : param entry : : class : ` . BaseFile ` object : param str name : new name for the entry : param bool mark : whether to bookmark the entry"""
fcid = None if isinstance ( entry , File ) : fcid = entry . fid elif isinstance ( entry , Directory ) : fcid = entry . cid else : raise APIError ( 'Invalid BaseFile instance for an entry.' ) is_mark = 0 if mark is True : is_mark = 1 if self . _req_files_edit ( fcid , name , is_mark ) : entry . reloa...
def temp_file_context ( raw_dump_path , logger = None ) : """this contextmanager implements conditionally deleting a pathname at the end of a context if the pathname indicates that it is a temp file by having the word ' TEMPORARY ' embedded in it ."""
try : yield raw_dump_path finally : if 'TEMPORARY' in raw_dump_path : try : os . unlink ( raw_dump_path ) except OSError : if logger is None : logger = FakeLogger ( ) logger . warning ( 'unable to delete %s. manual deletion is required.' , raw_...
def commit ( * args ) : """Commit changes to the fragments repository , limited to FILENAME ( s ) if specified ."""
parser = argparse . ArgumentParser ( prog = "%s %s" % ( __package__ , commit . __name__ ) , description = commit . __doc__ ) parser . add_argument ( 'FILENAME' , help = "file(s) to commit" , nargs = "*" , default = [ '.' ] ) args = parser . parse_args ( args ) config = FragmentsConfig ( ) for s , curr_path in _iterate_...
def _read_pcm_information ( self ) : """Parses information from PCM solvent calculations ."""
temp_dict = read_pattern ( self . text , { "g_electrostatic" : r"\s*G_electrostatic\s+=\s+([\d\-\.]+)\s+hartree\s+=\s+([\d\-\.]+)\s+kcal/mol\s*" , "g_cavitation" : r"\s*G_cavitation\s+=\s+([\d\-\.]+)\s+hartree\s+=\s+([\d\-\.]+)\s+kcal/mol\s*" , "g_dispersion" : r"\s*G_dispersion\s+=\s+([\d\-\.]+)\s+hartree\s+=\s+([\d\-...
def index_list ( self ) : '''Lists indices'''
request = self . session url = 'http://%s:%s/_cluster/state/' % ( self . host , self . port ) response = request . get ( url ) if request . status_code == 200 : return response . get ( 'metadata' , { } ) . get ( 'indices' , { } ) . keys ( ) else : return response
def list_build_configurations_for_product ( id = None , name = None , page_size = 200 , page_index = 0 , sort = "" , q = "" ) : """List all BuildConfigurations associated with the given Product ."""
data = list_build_configurations_for_product_raw ( id , name , page_size , page_index , sort , q ) if data : return utils . format_json_list ( data )
def parseprint ( code , filename = "<string>" , mode = "exec" , ** kwargs ) : """Parse some code from a string and pretty - print it ."""
node = parse ( code , mode = mode ) # An ode to the code print ( dump ( node , ** kwargs ) )
def parse_csv ( self , infile , delimiter = "," , decimal_sep = "." ) : "Parse template format csv file and create elements dict"
keys = ( 'name' , 'type' , 'x1' , 'y1' , 'x2' , 'y2' , 'font' , 'size' , 'bold' , 'italic' , 'underline' , 'foreground' , 'background' , 'align' , 'text' , 'priority' , 'multiline' ) self . elements = [ ] self . pg_no = 0 if not PY3K : f = open ( infile , 'rb' ) else : f = open ( infile ) for row in csv . reade...
def elife_references_rewrite_json ( ) : """Here is the DOI and references json replacements data for elife"""
references_rewrite_json = { } references_rewrite_json [ "10.7554/eLife.00051" ] = { "bib25" : { "date" : "2012" } } references_rewrite_json [ "10.7554/eLife.00278" ] = { "bib11" : { "date" : "2013" } } references_rewrite_json [ "10.7554/eLife.00444" ] = { "bib2" : { "date" : "2013" } } references_rewrite_json [ "10.755...
def split_message ( message , max_length ) : """Split long messages"""
if len ( message ) > max_length : for message in textwrap . wrap ( message , max_length ) : yield message else : yield message . rstrip ( STRIPPED_CHARS )
def hot_unplug_cpu ( self , cpu ) : """Removes a CPU from the machine . in cpu of type int The CPU id to remove ."""
if not isinstance ( cpu , baseinteger ) : raise TypeError ( "cpu can only be an instance of type baseinteger" ) self . _call ( "hotUnplugCPU" , in_p = [ cpu ] )
def decr ( self , conn , key , decrement = 1 ) : """Command is used to change data for some item in - place , decrementing it . The data for the item is treated as decimal representation of a 64 - bit unsigned integer . : param key : ` ` bytes ` ` , is the key of the item the client wishes to change : par...
assert self . _validate_key ( key ) resp = yield from self . _incr_decr ( conn , b'decr' , key , decrement ) return resp
def _imp_semsim ( self , c1 , c2 ) : """The paper ' s implicit semantic similarity metric involves iteratively computing string overlaps ; this is a modification where we instead use inverse Sift4 distance ( a fast approximation of Levenshtein distance ) . Frankly ~ I don ' t know if this is an appropriate ...
desc1 = self . _description ( c1 ) desc2 = self . _description ( c2 ) raw_sim = 1 / ( sift4 ( desc1 , desc2 ) + 1 ) return math . log ( raw_sim + 1 )
def predict_compound_pairs ( reaction , compound_formula , pair_weights = { } , weight_func = element_weight ) : """Predict compound pairs for a single reaction . Performs greedy matching on reaction compounds using a scoring function that uses generalized Jaccard similarity corrected by the weights in the gi...
def score_func ( inst1 , inst2 ) : score = _jaccard_similarity ( inst1 . formula , inst2 . formula , weight_func ) if score is None : return None pair = inst1 . compound . name , inst2 . compound . name pair_weight = pair_weights . get ( pair , 1.0 ) return pair_weight * score return _match_...
def email_confirm ( request , confirmation_key , template_name = 'accounts/email_confirm_fail.html' , success_url = None , extra_context = None ) : """Confirms an email address with a confirmation key . Confirms a new email address by running : func : ` User . objects . confirm _ email ` method . If the method ...
user = AccountsSignup . objects . confirm_email ( confirmation_key ) if user : if accounts_settings . ACCOUNTS_USE_MESSAGES : messages . success ( request , _ ( 'Your email address has been changed.' ) , fail_silently = True ) if success_url : redirect_to = success_url else : redirec...
def save_summaries ( frames , keys , selected_summaries , batch_dir , batch_name ) : """Writes the summaries to csv - files Args : frames : list of ` ` cellpy ` ` summary DataFrames keys : list of indexes ( typically run - names ) for the different runs selected _ summaries : list defining which summary dat...
if not frames : logger . info ( "Could save summaries - no summaries to save!" ) logger . info ( "You have no frames - aborting" ) return None if not keys : logger . info ( "Could save summaries - no summaries to save!" ) logger . info ( "You have no keys - aborting" ) return None selected_summa...
def usage ( self , subcommand ) : """Returns * how to use command * text ."""
usage = ' ' . join ( [ '%prog' , subcommand , '[options]' ] ) if self . args : usage = '%s %s' % ( usage , str ( self . args ) ) return usage
def read ( self , file , * , fs ) : """Write a row on the next line of given file . Prefix is used for newlines ."""
for line in file : yield line . rstrip ( self . eol )
def fit ( self , x , y , deg , w = None , y_vs_x = True , times_sigma_reject = None , title = None , debugplot = 0 ) : """Update the arc line from least squares fit to data . Parameters x : 1d numpy array , float X coordinates of the data being fitted . y : 1d numpy array , float Y coordinates of the data...
# protections if type ( x ) is not np . ndarray : raise ValueError ( "x=" + str ( x ) + " must be a numpy.ndarray" ) if type ( y ) is not np . ndarray : raise ValueError ( "y=" + str ( y ) + " must be a numpy.ndarray" ) if x . size != y . size : raise ValueError ( "x.size != y.size" ) if w is not None : ...
def rename_edges ( self , old_node_name , new_node_name ) : """Change references to a node in existing edges . Args : old _ node _ name ( str ) : The old name for the node . new _ node _ name ( str ) : The new name for the node ."""
graph = self . graph for node , edges in graph . items ( ) : if node == old_node_name : graph [ new_node_name ] = copy ( edges ) del graph [ old_node_name ] else : if old_node_name in edges : edges . remove ( old_node_name ) edges . add ( new_node_name )
def _get_mine ( fun ) : '''Return the mine function from all the targeted minions . Just a small helper to avoid redundant pieces of code .'''
if fun in _CACHE and _CACHE [ fun ] : return _CACHE [ fun ] net_runner_opts = _get_net_runner_opts ( ) _CACHE [ fun ] = __salt__ [ 'mine.get' ] ( net_runner_opts . get ( 'target' ) , fun , tgt_type = net_runner_opts . get ( 'expr_form' ) ) return _CACHE [ fun ]
def translations ( context : Context , pull = False , push = False ) : """Synchronises translations with transifex . com"""
if not ( pull or push ) : raise TaskError ( 'Specify whether to push or pull translations' ) if pull : context . shell ( 'tx' , 'pull' ) make_messages ( context , javascript = False ) make_messages ( context , javascript = True ) if push : context . shell ( 'tx' , 'push' , '--source' , '--no-interac...
def is_expired ( self , max_idle_seconds ) : """Determines whether this record is expired or not . : param max _ idle _ seconds : ( long ) , the maximum idle time of record , maximum time after the last access time . : return : ( bool ) , ` ` true ` ` is this record is not expired ."""
now = current_time ( ) return ( self . expiration_time is not None and self . expiration_time < now ) or ( max_idle_seconds is not None and self . last_access_time + max_idle_seconds < now )
def interp2d2d ( x , y , Z , xout , yout , split_factor = 1 , ** kwargs ) : """INTERP2D2D : Interpolate a 2D matrix into another 2D matrix @ param x : 1st dimension vector of size NX @ param y : 2nd dimension vector of size NY @ param Z : Array to interpolate ( NXxNY ) @ param xout : 1st dimension vector of...
# Queued thread class ThreadClass ( threading . Thread ) : # We override the _ _ init _ _ method def __init__ ( self , input_q , indices_q , result_q ) : threading . Thread . __init__ ( self ) self . input = input_q self . indices = indices_q self . result = result_q def task ( s...
def to_representation ( self , obj ) : """Represent data for the field ."""
many = isinstance ( obj , collections . Iterable ) or isinstance ( obj , models . Manager ) and not isinstance ( obj , dict ) assert self . serializer is not None and issubclass ( self . serializer , serializers . ModelSerializer ) , ( "Bad serializer defined %s" % self . serializer ) extra_params = { } if issubclass (...
def specific_notes ( hazard , exposure ) : """Return notes which are specific for a given hazard and exposure . : param hazard : The hazard definition . : type hazard : safe . definition . hazard : param exposure : The exposure definition . : type hazard : safe . definition . exposure : return : List of n...
for item in ITEMS : if item [ 'hazard' ] == hazard and item [ 'exposure' ] == exposure : return item . get ( 'notes' , [ ] ) return [ ]
def setup ( config ) : """Setup persistence to be used in cinderlib . By default memory persistance will be used , but there are other mechanisms available and other ways to use custom mechanisms : - Persistence plugins : Plugin mechanism uses Python entrypoints under namespace cinderlib . persistence . sto...
if config is None : config = { } else : config = config . copy ( ) # Prevent driver dynamic loading clearing configuration options volume_cmd . CONF . _ConfigOpts__cache = MyDict ( ) # Default configuration is using memory storage storage = config . pop ( 'storage' , None ) or DEFAULT_STORAGE if isinstance ( st...
def on_created ( self , event ) : '''Fired when something ' s been created'''
if self . trigger != "create" : return action_input = ActionInput ( event , "" , self . name ) flows . Global . MESSAGE_DISPATCHER . send_message ( action_input )
def getStrikes ( self , contract_identifier , smin = None , smax = None ) : """return strikes of contract / " multi " contract ' s contracts"""
strikes = [ ] contracts = self . contractDetails ( contract_identifier ) [ "contracts" ] if contracts [ 0 ] . m_secType not in ( "FOP" , "OPT" ) : return [ ] # collect expirations for contract in contracts : strikes . append ( contract . m_strike ) # convert to floats strikes = list ( map ( float , strikes ) ) ...
def on_event ( self , evt , is_final ) : """this is invoked from in response to COM PumpWaitingMessages - different thread"""
for msg in XmlHelper . message_iter ( evt ) : # Single security element in historical request node = msg . GetElement ( 'securityData' ) if node . HasElement ( 'securityError' ) : secid = XmlHelper . get_child_value ( node , 'security' ) self . security_errors . append ( XmlHelper . as_security_...
def _try_convert_value ( conversion_finder , attr_name : str , attr_value : S , desired_attr_type : Type [ T ] , logger : Logger , options : Dict [ str , Dict [ str , Any ] ] ) -> T : """Utility method to try to use provided conversion _ finder to convert attr _ value into desired _ attr _ type . If no conversion...
# check if we need additional conversion # ( a ) a collection with details about the internal item type if is_typed_collection ( desired_attr_type ) : return ConversionFinder . convert_collection_values_according_to_pep ( coll_to_convert = attr_value , desired_type = desired_attr_type , conversion_finder = conversi...
async def store_cred ( self , cred_json : str , cred_req_metadata_json : str ) -> str : """Store cred in wallet as HolderProver , return its credential identifier as created in wallet . Raise AbsentTails if tails file not available for revocation registry for input credential . Raise WalletState if wallet is cl...
LOGGER . debug ( 'HolderProver.store_cred >>> cred_json: %s, cred_req_metadata_json: %s' , cred_json , cred_req_metadata_json ) if not self . wallet . handle : LOGGER . debug ( 'HolderProver.store_cred <!< Wallet %s is closed' , self . name ) raise WalletState ( 'Wallet {} is closed' . format ( self . name ) ) ...
def _request ( self , domain , type_name , search_command , db_method , body = None ) : """Make the API request for a Data Store CRUD operation Args : domain ( string ) : One of ' local ' , ' organization ' , or ' system ' . type _ name ( string ) : This is a free form index type name . The ThreatConnect API ...
headers = { 'Content-Type' : 'application/json' , 'DB-Method' : db_method } search_command = self . _clean_datastore_path ( search_command ) url = '/v2/exchange/db/{}/{}/{}' . format ( domain , type_name , search_command ) r = self . tcex . session . post ( url , data = body , headers = headers , params = self . _param...
def remove_external_references_from_srl_layer ( self ) : """Removes all external references present in the term layer"""
if self . srl_layer is not None : for pred in self . srl_layer . get_predicates ( ) : pred . remove_external_references ( ) pred . remove_external_references_from_roles ( )
def xmoe2_v1_l4k_global_only ( ) : """With sequence length 4096."""
hparams = xmoe2_v1_l4k ( ) hparams . decoder_layers = [ "att" if l == "local_att" else l for l in hparams . decoder_layers ] return hparams
def update_check_point ( self , project , logstore , consumer_group , shard , check_point , consumer = '' , force_success = True ) : """Update check point : type project : string : param project : project name : type logstore : string : param logstore : logstore name : type consumer _ group : string : p...
request = ConsumerGroupUpdateCheckPointRequest ( project , logstore , consumer_group , consumer , shard , check_point , force_success ) params = request . get_request_params ( ) body_str = request . get_request_body ( ) headers = { "Content-Type" : "application/json" } resource = "/logstores/" + logstore + "/consumergr...
def get_value ( self , group , key = None ) : """get value"""
if key is None : key = group obj = self . get_queryset_by_group_and_key ( group = group , key = key ) . first ( ) if obj is None : return None return obj . value
def blip_rId ( self ) : """Value of ` p : blipFill / a : blip / @ r : embed ` . Returns | None | if not present ."""
blip = self . blipFill . blip if blip is not None and blip . rEmbed is not None : return blip . rEmbed return None
def add_format ( self , format_id , number , entry_type , description ) : """Add a format line to the header . Arguments : format _ id ( str ) : The id of the format line number ( str ) : Integer or any of [ A , R , G , . ] entry _ type ( str ) : Any of [ Integer , Float , Flag , Character , String ] desc...
format_line = '##FORMAT=<ID={0},Number={1},Type={2},Description="{3}">' . format ( format_id , number , entry_type , description ) logger . info ( "Adding format line to vcf: {0}" . format ( format_line ) ) self . parse_meta_data ( format_line ) return
def add_keyword ( self , keyword , schema = None , source = None ) : """Add a keyword . Args : keyword ( str ) : keyword to add . schema ( str ) : schema to which the keyword belongs . source ( str ) : source for the keyword ."""
keyword_dict = self . _sourced_dict ( source , value = keyword ) if schema is not None : keyword_dict [ 'schema' ] = schema self . _append_to ( 'keywords' , keyword_dict )
def is_thenable ( cls , obj ) : # type : ( Any ) - > bool """A utility function to determine if the specified object is a promise using " duck typing " ."""
_type = obj . __class__ if obj is None or _type in BASE_TYPES : return False return ( issubclass ( _type , Promise ) or iscoroutine ( obj ) # type : ignore or is_future_like ( _type ) )
def add_input ( self , in_name , type_or_parse = None ) : """Declare a possible input"""
if type_or_parse is None : type_or_parse = GenericType ( ) elif not isinstance ( type_or_parse , GenericType ) and callable ( type_or_parse ) : type_or_parse = GenericType ( parse = type_or_parse ) elif not isinstance ( type_or_parse , GenericType ) : raise ValueError ( "the given 'type_or_parse' is invalid...
def is_bridge ( self ) : """bool : Is this zone a bridge ?"""
# Since this does not change over time ( ? ) check whether we already # know the answer . If so , there is no need to go further if self . _is_bridge is not None : return self . _is_bridge # if not , we have to get it from the zone topology . This will set # self . _ is _ bridge for us for next time , so we won ' t...
def resource ( self , uri , methods = frozenset ( { 'GET' } ) , ** kwargs ) : """Decorates a function to be registered as a resource route . : param uri : path of the URL : param methods : list or tuple of methods allowed : param host : : param strict _ slashes : : param stream : : param version : : p...
def decorator ( f ) : if kwargs . get ( 'stream' ) : f . is_stream = kwargs [ 'stream' ] self . add_resource ( f , uri = uri , methods = methods , ** kwargs ) return decorator
def revoke_auth ( self , load ) : '''Allow a minion to request revocation of its own key'''
if 'id' not in load : return False keyapi = salt . key . Key ( self . opts ) keyapi . delete_key ( load [ 'id' ] , preserve_minions = load . get ( 'preserve_minion_cache' , False ) ) return True
def _muaprocessnew ( self ) : """Moves all ' new ' files into cur , correctly flagging"""
foldername = self . _foldername ( "new" ) files = self . filesystem . listdir ( foldername ) for filename in files : if filename == "" : continue curfilename = self . _foldername ( joinpath ( "new" , filename ) ) newfilename = joinpath ( self . _cur , "%s:2,%s" % ( filename , "" ) ) self . files...
def get_level_id ( self ) : """Gets the ` ` Id ` ` of a ` ` Grade ` ` corresponding to the assessment difficulty . return : ( osid . id . Id ) - a grade ` ` Id ` ` * compliance : mandatory - - This method must be implemented . *"""
# Implemented from template for osid . resource . Resource . get _ avatar _ id _ template if not bool ( self . _my_map [ 'levelId' ] ) : raise errors . IllegalState ( 'this Assessment has no level' ) else : return Id ( self . _my_map [ 'levelId' ] )
def tcp ( q , where , timeout = None , port = 53 , af = None , source = None , source_port = 0 , one_rr_per_rrset = False ) : """Return the response obtained after sending a query via TCP . @ param q : the query @ type q : dns . message . Message object @ param where : where to send the message @ type where...
wire = q . to_wire ( ) if af is None : try : af = dns . inet . af_for_address ( where ) except Exception : af = dns . inet . AF_INET if af == dns . inet . AF_INET : destination = ( where , port ) if source is not None : source = ( source , source_port ) elif af == dns . inet . AF...
def _parse_udf_vol_descs ( self , extent , length , descs ) : # type : ( int , int , PyCdlib . _ UDFDescriptors ) - > None '''An internal method to parse a set of UDF Volume Descriptors . Parameters : extent - The extent at which to start parsing . length - The number of bytes to read from the incoming ISO . ...
# Read in the Volume Descriptor Sequence self . _seek_to_extent ( extent ) vd_data = self . _cdfp . read ( length ) # And parse it . Since the sequence doesn ' t have to be in any set order , # and since some of the entries may be missing , we parse the Descriptor # Tag ( the first 16 bytes ) to find out what kind of d...
def get_connection_by_id ( self , id ) : '''Search for a connection on this port by its ID .'''
with self . _mutex : for conn in self . connections : if conn . id == id : return conn return None
def _request ( self , op ) : """Implementations of : meth : ` request ` call this method to send the request and process the reply . In synchronous mode , blocks until the reply is received and returns : class : ` RPCReply ` . Depending on the : attr : ` raise _ mode ` a ` rpc - error ` element in the reply may l...
self . logger . info ( 'Requesting %r' , self . __class__ . __name__ ) req = self . _wrap ( op ) self . _session . send ( req ) if self . _async : self . logger . debug ( 'Async request, returning %r' , self ) return self else : self . logger . debug ( 'Sync request, will wait for timeout=%r' , self . _time...
def _convert_nonstring_categoricals ( self , param_dict ) : """Apply the self . categorical _ mappings _ mappings where necessary ."""
return { name : ( self . categorical_mappings_ [ name ] [ val ] if name in self . categorical_mappings_ else val ) for ( name , val ) in param_dict . items ( ) }
def probability_lt ( self , x ) : """Returns the probability of a random variable being less than the given value ."""
if self . mean is None : return return normdist ( x = x , mu = self . mean , sigma = self . standard_deviation )
def maybeStartBuildsOn ( self , new_builders ) : """Try to start any builds that can be started right now . This function returns immediately , and promises to trigger those builders eventually . @ param new _ builders : names of new builders that should be given the opportunity to check for new requests ."...
if not self . running : return d = self . _maybeStartBuildsOn ( new_builders ) self . _pendingMSBOCalls . append ( d ) try : yield d except Exception as e : # pragma : no cover log . err ( e , "while starting builds on {0}" . format ( new_builders ) ) finally : self . _pendingMSBOCalls . remove ( d )
def zero_or_more ( e , delimiter = None ) : """Create a PEG function to match zero or more expressions . Args : e : the expression to match delimiter : an optional expression to match between the primary * e * matches ."""
if delimiter is None : delimiter = lambda s , grm , pos : ( s , Ignore , ( pos , pos ) ) def match_zero_or_more ( s , grm = None , pos = 0 ) : start = pos try : s , obj , span = e ( s , grm , pos ) pos = span [ 1 ] data = [ ] if obj is Ignore else [ obj ] except PegreError : ...
def process ( self , metric ) : """process a single metric @ type metric : diamond . metric . Metric @ param metric : metric to process @ rtype None"""
for rule in self . rules : rule . process ( metric , self )
def cdna_codon_sequence_after_deletion_or_substitution_frameshift ( sequence_from_start_codon , cds_offset , trimmed_cdna_ref , trimmed_cdna_alt ) : """Logic for any frameshift which isn ' t an insertion . We have insertions as a special case since our base - inclusive indexing means something different for ins...
mutated_codon_index = cds_offset // 3 # get the sequence starting from the first modified codon until the end # of the transcript . sequence_after_mutated_codon = sequence_from_start_codon [ mutated_codon_index * 3 : ] # the variant ' s ref nucleotides should start either 0 , 1 , or 2 nucleotides # into ` sequence _ af...
def get_stops_in_polygon ( feed : "Feed" , polygon : Polygon , geo_stops = None ) -> DataFrame : """Return the slice of ` ` feed . stops ` ` that contains all stops that lie within the given Shapely Polygon object that is specified in WGS84 coordinates . Parameters feed : Feed polygon : Shapely Polygon ...
if geo_stops is not None : f = geo_stops . copy ( ) else : f = geometrize_stops ( feed . stops ) cols = f . columns f [ "hit" ] = f [ "geometry" ] . within ( polygon ) f = f [ f [ "hit" ] ] [ cols ] return ungeometrize_stops ( f )
def set ( self , dic , val = None , force = False ) : """set can assign versatile options from ` CMAOptions . versatile _ options ( ) ` with a new value , use ` init ( ) ` for the others . Arguments ` dic ` either a dictionary or a key . In the latter case , ` val ` must be provided ` val ` value fo...
if val is not None : # dic is a key in this case dic = { dic : val } # compose a dictionary for key_original , val in list ( dict ( dic ) . items ( ) ) : key = self . corrected_key ( key_original ) if not self . _lock_setting or key in CMAOptions . versatile_options ( ) : self [ key ] = val ...
def truncate_html ( html , * args , ** kwargs ) : """Truncates HTML string . : param html : The HTML string or parsed element tree ( with : func : ` html5lib . parse ` ) . : param kwargs : Similar with : class : ` . filters . TruncationFilter ` . : return : The truncated HTML string ."""
if hasattr ( html , 'getchildren' ) : etree = html else : etree = html5lib . parse ( html ) walker = html5lib . getTreeWalker ( 'etree' ) stream = walker ( etree ) stream = TruncationFilter ( stream , * args , ** kwargs ) serializer = html5lib . serializer . HTMLSerializer ( ) serialized = serializer . serializ...
def plot_kde ( values , values2 = None , cumulative = False , rug = False , label = None , bw = 4.5 , quantiles = None , rotated = False , contour = True , fill_last = True , textsize = None , plot_kwargs = None , fill_kwargs = None , rug_kwargs = None , contour_kwargs = None , contourf_kwargs = None , pcolormesh_kwarg...
if ax is None : ax = plt . gca ( ) figsize = ax . get_figure ( ) . get_size_inches ( ) figsize , * _ , xt_labelsize , linewidth , markersize = _scale_fig_size ( figsize , textsize , 1 , 1 ) if isinstance ( values , xr . Dataset ) : raise ValueError ( "Xarray dataset object detected.Use plot_posterior, plot_dens...
def parse_args ( * args ) : """Parse the arguments for the command"""
parser = argparse . ArgumentParser ( description = "Send push notifications for a feed" ) parser . add_argument ( '--version' , action = 'version' , version = "%(prog)s " + __version__ . __version__ ) parser . add_argument ( 'feeds' , type = str , nargs = '*' , metavar = 'feed_url' , help = 'A URL for a feed to process...
def num_time_steps ( self ) : """Returns the number of time - steps in completed and incomplete trajectories ."""
num_time_steps = sum ( t . num_time_steps for t in self . trajectories ) return num_time_steps + self . num_completed_time_steps
def _initialize_tableaux ( payoff_matrices , tableaux , bases ) : """Given a tuple of payoff matrices , initialize the tableau and basis arrays in place . For each player ` i ` , if ` payoff _ matrices [ i ] . min ( ) ` is non - positive , then stored in the tableau are payoff values incremented by ` abs ( ...
nums_actions = payoff_matrices [ 0 ] . shape consts = np . zeros ( 2 ) # To be added to payoffs if min < = 0 for pl in range ( 2 ) : min_ = payoff_matrices [ pl ] . min ( ) if min_ <= 0 : consts [ pl ] = min_ * ( - 1 ) + 1 for pl , ( py_start , sl_start ) in enumerate ( zip ( ( 0 , nums_actions [ 0 ] ) ...
def range_piles ( ranges ) : """Return piles of intervals that overlap . The piles are only interrupted by regions of zero coverage . > > > ranges = [ Range ( " 2 " , 0 , 1 , 3 , 0 ) , Range ( " 2 " , 1 , 4 , 3 , 1 ) , Range ( " 3 " , 5 , 7 , 3 , 2 ) ] > > > list ( range _ piles ( ranges ) ) [ [ 0 , 1 ] , [...
endpoints = _make_endpoints ( ranges ) for seqid , ends in groupby ( endpoints , lambda x : x [ 0 ] ) : active = [ ] depth = 0 for seqid , pos , leftright , i , score in ends : if leftright == LEFT : active . append ( i ) depth += 1 else : depth -= 1 ...
def do_alarm_list ( mc , args ) : '''List alarms for this tenant .'''
fields = { } if args . alarm_definition_id : fields [ 'alarm_definition_id' ] = args . alarm_definition_id if args . metric_name : fields [ 'metric_name' ] = args . metric_name if args . metric_dimensions : fields [ 'metric_dimensions' ] = utils . format_dimensions_query ( args . metric_dimensions ) if args...
def _to_DOM ( self ) : """Dumps object data to a fully traversable DOM representation of the object . : returns : a ` ` xml . etree . Element ` ` object"""
root_node = ET . Element ( "no2index" ) reference_time_node = ET . SubElement ( root_node , "reference_time" ) reference_time_node . text = str ( self . _reference_time ) reception_time_node = ET . SubElement ( root_node , "reception_time" ) reception_time_node . text = str ( self . _reception_time ) interval_node = ET...
async def stop ( wallet_name : str ) -> None : """Gracefully stop an external revocation registry builder , waiting for its current . The indy - sdk toolkit uses a temporary directory for tails file mustration , and shutting down the toolkit removes the directory , crashing the external tails file write . Thi...
LOGGER . debug ( 'RevRegBuilder.stop >>>' ) dir_sentinel = join ( RevRegBuilder . dir_tails_sentinel ( wallet_name ) ) if isdir ( dir_sentinel ) : open ( join ( dir_sentinel , '.stop' ) , 'w' ) . close ( ) # touch while any ( isfile ( join ( dir_sentinel , d , '.in-progress' ) ) for d in listdir ( dir_senti...
def unique ( enumeration ) : """Class decorator that ensures only unique members exist in an enumeration ."""
duplicates = [ ] for name , member in enumeration . __members__ . items ( ) : if name != member . name : duplicates . append ( ( name , member . name ) ) if duplicates : duplicate_names = ', ' . join ( [ "%s -> %s" % ( alias , name ) for ( alias , name ) in duplicates ] ) raise ValueError ( 'duplica...
def find_table_file ( root_project_dir ) : """Find the EUPS table file for a project . Parameters root _ project _ dir : ` str ` Path to the root directory of the main documentation project . This is the directory containing the ` ` conf . py ` ` file and a ` ` ups ` ` directory . Returns table _ path...
ups_dir_path = os . path . join ( root_project_dir , 'ups' ) table_path = None for name in os . listdir ( ups_dir_path ) : if name . endswith ( '.table' ) : table_path = os . path . join ( ups_dir_path , name ) break if not os . path . exists ( table_path ) : raise RuntimeError ( 'Could not find...
def can_finalise ( self , step , exhausted , status ) : """The step is running and the inputs are exhausted : param step : : param exhausted : : return :"""
return step in status and step in exhausted and status [ step ] == 'running' and all ( in_ in exhausted [ step ] for in_ in step . ins )
def calc_blr ( xsqlda ) : "Calculate BLR from XSQLVAR array ."
ln = len ( xsqlda ) * 2 blr = [ 5 , 2 , 4 , 0 , ln & 255 , ln >> 8 ] for x in xsqlda : sqltype = x . sqltype if sqltype == SQL_TYPE_VARYING : blr += [ 37 , x . sqllen & 255 , x . sqllen >> 8 ] elif sqltype == SQL_TYPE_TEXT : blr += [ 14 , x . sqllen & 255 , x . sqllen >> 8 ] elif sqltype...
def prepare_method ( self , method ) : """Prepares the given HTTP method ."""
self . method = method if self . method is not None : self . method = self . method . upper ( )
def get_linked_sections ( section , include_instructor_not_on_time_schedule = True ) : """Returns a list of uw _ sws . models . Section objects , representing linked sections for the passed section ."""
linked_sections = [ ] for url in section . linked_section_urls : section = get_section_by_url ( url , include_instructor_not_on_time_schedule ) linked_sections . append ( section ) return linked_sections
def request_sid ( self ) : """Request a BOSH session according to http : / / xmpp . org / extensions / xep - 0124 . html # session - request Returns the new SID ( str ) ."""
if self . _sid : return self . _sid self . log . debug ( 'Prepare to request BOSH session' ) data = self . send_request ( self . get_body ( sid_request = True ) ) if not data : return None # This is XML . response _ body contains the < body / > element of the # response . response_body = ET . fromstring ( data ...
def galcencyl_to_XYZ ( R , phi , Z , Xsun = 1. , Zsun = 0. , _extra_rot = True ) : """NAME : galcencyl _ to _ XYZ PURPOSE : transform cylindrical Galactocentric coordinates to XYZ coordinates ( wrt Sun ) INPUT : R , phi , Z - Galactocentric cylindrical coordinates Xsun - cylindrical distance to the GC (...
Xr , Yr , Zr = cyl_to_rect ( R , phi , Z ) return galcenrect_to_XYZ ( Xr , Yr , Zr , Xsun = Xsun , Zsun = Zsun , _extra_rot = _extra_rot )
def start ( self ) : """Start the pinging coroutine using the client and event loop which was passed to the constructor . : meth : ` start ` always behaves as if : meth : ` stop ` was called right before it ."""
self . stop ( ) self . _task = asyncio . ensure_future ( self . _pinger ( ) , loop = self . _loop )
def pretty_print_gremlin ( gremlin ) : """Return a human - readable representation of a gremlin command string ."""
gremlin = remove_custom_formatting ( gremlin ) too_many_parts = re . split ( r'([)}]|scatter)[ ]?\.' , gremlin ) # Put the ) and } back on . parts = [ too_many_parts [ i ] + too_many_parts [ i + 1 ] for i in six . moves . xrange ( 0 , len ( too_many_parts ) - 1 , 2 ) ] parts . append ( too_many_parts [ - 1 ] ) # Put th...
def setSignalHeader ( self , edfsignal , channel_info ) : """Sets the parameter for signal edfsignal . channel _ info should be a dict with these values : ' label ' : channel label ( string , < = 16 characters , must be unique ) ' dimension ' : physical dimension ( e . g . , mV ) ( string , < = 8 characters...
if edfsignal < 0 or edfsignal > self . n_channels : raise ChannelDoesNotExist ( edfsignal ) self . channels [ edfsignal ] = channel_info self . update_header ( )
def file_writelines_flush_sync ( path , lines ) : """Fill file at @ path with @ lines then flush all buffers ( Python and system buffers )"""
fp = open ( path , 'w' ) try : fp . writelines ( lines ) flush_sync_file_object ( fp ) finally : fp . close ( )
def login_required ( func ) : '''decorator describing User methods that need to be logged in'''
def ret ( obj , * args , ** kw ) : if not hasattr ( obj , 'sessionToken' ) : message = '%s requires a logged-in session' % func . __name__ raise ResourceRequestLoginRequired ( message ) return func ( obj , * args , ** kw ) return ret
def _do_select ( self , start_bindex , end_bindex ) : """select the given range by buffer indices selects items like this : . . . . . xxxxx xxxxx xxxxx xxxxx . . . . . * not * like this : . . . . . xxxxx . . . . . . . . . . xxxxx . . . . . . . . . . xxxxx . . . . . . . . . . xxxxx . . . . ."""
self . select ( QItemSelection ( ) , QItemSelectionModel . Clear ) if start_bindex > end_bindex : start_bindex , end_bindex = end_bindex , start_bindex selection = QItemSelection ( ) if row_number ( end_bindex ) - row_number ( start_bindex ) == 0 : # all on one line self . _bselect ( selection , start_bindex , ...
def set_or_create ( self , path , * args , ** kwargs ) : """Sets the data of a node at the given path , or creates it ."""
d = self . set ( path , * args , ** kwargs ) @ d . addErrback def _error ( result ) : return self . create ( path , * args , ** kwargs ) return d
def _convert_epoch_anchor ( cls , reading ) : """Convert a reading containing an epoch timestamp to datetime ."""
delta = datetime . timedelta ( seconds = reading . value ) return cls . _EpochReference + delta
def search_group ( self , search_query ) : """Searches for public groups using a query Results will be returned using the on _ group _ search _ response ( ) callback : param search _ query : The query that contains some of the desired groups ' name ."""
log . info ( "[+] Initiating a search for groups using the query '{}'" . format ( search_query ) ) return self . _send_xmpp_element ( roster . GroupSearchRequest ( search_query ) )
def compile_update ( self , query , values ) : """Compile an update statement into SQL : param query : A QueryBuilder instance : type query : QueryBuilder : param values : The update values : type values : dict : return : The compiled update : rtype : str"""
table = self . wrap_table ( query . from__ ) columns = self . _compile_update_columns ( values ) from_ = self . _compile_update_from ( query ) where = self . _compile_update_wheres ( query ) return ( "UPDATE %s SET %s%s %s" % ( table , columns , from_ , where ) ) . strip ( )
def to_text_diagram_drawer ( self , * , use_unicode_characters : bool = True , qubit_namer : Optional [ Callable [ [ ops . Qid ] , str ] ] = None , transpose : bool = False , precision : Optional [ int ] = 3 , qubit_order : ops . QubitOrderOrList = ops . QubitOrder . DEFAULT , get_circuit_diagram_info : Optional [ Call...
qubits = ops . QubitOrder . as_qubit_order ( qubit_order ) . order_for ( self . all_qubits ( ) ) qubit_map = { qubits [ i ] : i for i in range ( len ( qubits ) ) } if qubit_namer is None : qubit_namer = lambda q : str ( q ) + ( '' if transpose else ': ' ) diagram = TextDiagramDrawer ( ) for q , i in qubit_map . ite...