signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_bank ( self ) : """Gets the ` ` Bank ` ` at this node . return : ( osid . assessment . Bank ) - the bank represented by this node * compliance : mandatory - - This method must be implemented . *"""
if self . _lookup_session is None : mgr = get_provider_manager ( 'ASSESSMENT' , runtime = self . _runtime , proxy = self . _proxy ) self . _lookup_session = mgr . get_bank_lookup_session ( proxy = getattr ( self , "_proxy" , None ) ) return self . _lookup_session . get_bank ( Id ( self . _my_map [ 'id' ] ) )
def get_entries ( self ) : """Return a list of the entries ( messages ) that would be part of the current " view " ; that is , all of the ones from this . po file matching the current query or msg _ filter ."""
if self . query : # Scenario # 1 : terms matching a search query rx = re . compile ( re . escape ( self . query ) , re . IGNORECASE ) def concat_entry ( e ) : return ( six . text_type ( e . msgstr ) + six . text_type ( e . msgid ) + six . text_type ( e . msgctxt ) + six . text_type ( e . comment ) + u''...
def canOrder ( self , commit : Commit ) -> Tuple [ bool , Optional [ str ] ] : """Return whether the specified commitRequest can be returned to the node . Decision criteria : - If have got just n - f Commit requests then return request to node - If less than n - f of commit requests then probably don ' t have...
quorum = self . quorums . commit . value if not self . commits . hasQuorum ( commit , quorum ) : return False , "no quorum ({}): {} commits where f is {}" . format ( quorum , commit , self . f ) key = ( commit . viewNo , commit . ppSeqNo ) if self . has_already_ordered ( * key ) : return False , "already ordere...
def _port_action_vxlan ( self , port , segment , func ) : """Verify configuration and then process event ."""
# If the segment is None , just log a warning message and return . if segment is None : self . _log_missing_segment ( ) return device_id = port . get ( 'device_id' ) mcast_group = segment . get ( api . PHYSICAL_NETWORK ) host_id = port . get ( bc . portbindings . HOST_ID ) vni = segment . get ( api . SEGMENTATI...
def get_children_to_delete ( self ) : """Return all children that are not referenced : returns : list or : class : ` Reftrack ` : rtype : list : raises : None"""
refobjinter = self . get_refobjinter ( ) children = self . get_all_children ( ) todelete = [ ] for c in children : if c . status ( ) is None : # if child is not in scene we do not have to delete it continue rby = refobjinter . referenced_by ( c . get_refobj ( ) ) if rby is None : # child is not part...
def undefine ( self ) : """Undefine the Template . Python equivalent of the CLIPS undeftemplate command . The object becomes unusable after this method has been called ."""
if lib . EnvUndeftemplate ( self . _env , self . _tpl ) != 1 : raise CLIPSError ( self . _env )
def owner_type ( self , value ) : """Set ` ` owner _ type ` ` to the given value . In addition : * Update the internal type of the ` ` owner ` ` field . * Update the value of the ` ` owner ` ` field if a value is already set ."""
self . _owner_type = value if value == 'User' : self . _fields [ 'owner' ] = entity_fields . OneToOneField ( User ) if hasattr ( self , 'owner' ) : # pylint : disable = no - member self . owner = User ( self . _server_config , id = self . owner . id if isinstance ( self . owner , Entity ) else self . ow...
def create ( self , build_sid ) : """Create a new DeploymentInstance : param unicode build _ sid : The build _ sid : returns : Newly created DeploymentInstance : rtype : twilio . rest . serverless . v1 . service . environment . deployment . DeploymentInstance"""
data = values . of ( { 'BuildSid' : build_sid , } ) payload = self . _version . create ( 'POST' , self . _uri , data = data , ) return DeploymentInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , environment_sid = self . _solution [ 'environment_sid' ] , )
def set_vads_payment_config ( self ) : """vads _ payment _ config can be set only after object saving . A custom payment config can be set once PaymentRequest saved ( adding elements to the m2m relationship ) . As a consequence we set vads _ payment _ config just before sending data elements to payzen ."""
self . vads_payment_config = tools . get_vads_payment_config ( self . payment_config , self . custom_payment_config . all ( ) )
def restore ( name = None , ** kwargs ) : '''Make sure that the system contains the packages and repos from a frozen state . Read the list of packages and repositories from the freeze file , and compare it with the current list of packages and repos . If there is any difference , all the missing packages ar...
if not status ( name ) : raise CommandExecutionError ( 'Frozen state not found.' ) frozen_pkgs = { } frozen_repos = { } for name , content in zip ( _paths ( name ) , ( frozen_pkgs , frozen_repos ) ) : with fopen ( name ) as fp : content . update ( json . load ( fp ) ) # The ordering of removing or addin...
def open_only ( f ) : "decorator"
@ functools . wraps ( f ) def f2 ( self , * args , ** kwargs ) : if self . closed : raise NotSupportedError ( 'connection is closed' ) return f ( self , * args , ** kwargs ) return f2
def implied_vol ( self , value , precision = 1.0e-5 , iters = 100 ) : """Get implied vol at the specified price using an iterative approach . There is no closed - form inverse of BSM - value as a function of sigma , so start at an anchoring volatility level from Brenner & Subrahmanyam (1988 ) and work iterati...
vol = np . sqrt ( 2.0 * np . pi / self . T ) * ( value / self . S0 ) for _ in itertools . repeat ( None , iters ) : # Faster than range opt = BSM ( S0 = self . S0 , K = self . K , T = self . T , r = self . r , sigma = vol , kind = self . kind , ) diff = value - opt . value ( ) if abs ( diff ) < precision : ...
def copy ( self ) : """Returns a copy of Filter ."""
other = ConcurrentMeanStdFilter ( self . shape ) other . sync ( self ) return other
def _set_redistribute_isis ( self , v , load = False ) : """Setter method for redistribute _ isis , mapped from YANG variable / routing _ system / router / router _ bgp / address _ family / ipv6 / ipv6 _ unicast / default _ vrf / af _ ipv6 _ uc _ and _ vrf _ cmds _ call _ point _ holder / redistribute / redistribut...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = redistribute_isis . redistribute_isis , is_container = 'container' , presence = True , yang_name = "redistribute-isis" , rest_name = "isis" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods...
def kegg_mapping_and_metadata_parallelize ( self , sc , kegg_organism_code , custom_gene_mapping = None , outdir = None , set_as_representative = False , force_rerun = False ) : """Map all genes in the model to KEGG IDs using the KEGG service . Steps : 1 . Download all metadata and sequence files in the sequenc...
# First map all of the organism ' s KEGG genes to UniProt kegg_to_uniprot = ssbio . databases . kegg . map_kegg_all_genes ( organism_code = kegg_organism_code , target_db = 'uniprot' ) # Parallelize the genes list genes_rdd = sc . parallelize ( self . genes ) # Write a sub - function to carry out the bulk of the origin...
def get ( self , repi , mag ) : """: param repi : an array of epicentral distances in the range self . repi : param mag : a magnitude in the range self . mags : returns : an array of equivalent distances"""
mag_idx = numpy . abs ( mag - self . mags ) . argmin ( ) dists = [ ] for dist in repi : repi_idx = numpy . abs ( dist - self . repi ) . argmin ( ) dists . append ( self . reqv [ repi_idx , mag_idx ] ) return numpy . array ( dists )
def connected_components ( G ) : """Compute the connected components of a graph . The connected components of a graph G , which is represented by a symmetric sparse matrix , are labeled with the integers 0,1 , . . ( K - 1 ) where K is the number of components . Parameters G : symmetric matrix , preferably...
G = asgraph ( G ) N = G . shape [ 0 ] components = np . empty ( N , G . indptr . dtype ) fn = amg_core . connected_components fn ( N , G . indptr , G . indices , components ) return components
def subscribe ( self , client , channel_name ) : """Register a new client to receive messages on a channel ."""
if channel_name not in self . channels : self . channels [ channel_name ] = channel = Channel ( channel_name ) channel . start ( ) self . channels [ channel_name ] . subscribe ( client )
def send ( self , ws , seq ) : """Sends heartbeat message to Discord Attributes : ws : Websocket connection to discord seq : Sequence number of heartbeat"""
payload = { 'op' : 1 , 'd' : seq } payload = json . dumps ( payload ) logger . debug ( "Sending heartbeat with payload {}" . format ( payload ) ) ws . send ( payload ) return
def find ( query ) : """Search by Name , SMILES , InChI , InChIKey , etc . Returns first 100 Compounds"""
assert type ( query ) == str or type ( query ) == str , 'query not a string object' searchurl = 'http://www.chemspider.com/Search.asmx/SimpleSearch?query=%s&token=%s' % ( urlquote ( query ) , TOKEN ) response = urlopen ( searchurl ) tree = ET . parse ( response ) elem = tree . getroot ( ) csid_tags = elem . getiterator...
def shape ( self ) : """Raster shape ."""
if self . _shape is None : self . _populate_from_rasterio_object ( read_image = False ) return self . _shape
def listeners_iter ( self ) : """Return an iterator over the mapping of event = > listeners bound . The listener list ( s ) returned should * * not * * be mutated . NOTE ( harlowja ) : Each listener in the yielded ( event , listeners ) tuple is an instance of the : py : class : ` ~ . Listener ` type , which ...
topics = set ( six . iterkeys ( self . _topics ) ) while topics : event_type = topics . pop ( ) try : yield event_type , self . _topics [ event_type ] except KeyError : pass
def transformToNative ( obj ) : """Turn obj . value into a datetime . timedelta ."""
if obj . isNative : return obj obj . isNative = True obj . value = obj . value if obj . value == '' : return obj else : deltalist = stringToDurations ( obj . value ) # When can DURATION have multiple durations ? For now : if len ( deltalist ) == 1 : obj . value = deltalist [ 0 ] retu...
def add ( self , cmd ) : '''Add a new command ( waypoint ) at the end of the command list . . . note : : Commands are sent to the vehicle only after you call : : py : func : ` upload ( ) < Vehicle . commands . upload > ` . : param Command cmd : The command to be added .'''
self . wait_ready ( ) self . _vehicle . _handler . fix_targets ( cmd ) self . _vehicle . _wploader . add ( cmd , comment = 'Added by DroneKit' ) self . _vehicle . _wpts_dirty = True
def get_observer_look ( self , utc_time , lon , lat , alt ) : """Calculate observers look angle to a satellite . http : / / celestrak . com / columns / v02n02/ utc _ time : Observation time ( datetime object ) lon : Longitude of observer position on ground in degrees east lat : Latitude of observer position...
utc_time = dt2np ( utc_time ) ( pos_x , pos_y , pos_z ) , ( vel_x , vel_y , vel_z ) = self . get_position ( utc_time , normalize = False ) ( opos_x , opos_y , opos_z ) , ( ovel_x , ovel_y , ovel_z ) = astronomy . observer_position ( utc_time , lon , lat , alt ) lon = np . deg2rad ( lon ) lat = np . deg2rad ( lat ) thet...
def add_paths_to_os ( self , key = None , update = None ) : '''Add the paths in tree environ into the os environ This code goes through the tree environ and checks for existence in the os environ , then adds them Parameters : key ( str ) : The section name to check against / add update ( bool ) : If T...
if key is not None : allpaths = key if isinstance ( key , list ) else [ key ] else : allpaths = [ k for k in self . environ . keys ( ) if 'default' not in k ] for key in allpaths : paths = self . get_paths ( key ) self . check_paths ( paths , update = update )
def _get_decimal128 ( data , position , dummy0 , dummy1 , dummy2 ) : """Decode a BSON decimal128 to bson . decimal128 . Decimal128."""
end = position + 16 return Decimal128 . from_bid ( data [ position : end ] ) , end
def fast_cov ( x , y = None , destination = None ) : """calculate the covariance matrix for the columns of x ( MxN ) , or optionally , the covariance matrix between the columns of x and and the columns of y ( MxP ) . ( In the language of statistics , the columns are variables , the rows are observations ) . A...
validate_inputs ( x , y , destination ) if y is None : y = x if destination is None : destination = numpy . zeros ( ( x . shape [ 1 ] , y . shape [ 1 ] ) ) mean_x = numpy . mean ( x , axis = 0 ) mean_y = numpy . mean ( y , axis = 0 ) mean_centered_x = ( x - mean_x ) . astype ( destination . dtype ) mean_centere...
def neighbor ( pos , tune_params ) : """return a random neighbor of pos"""
size = len ( pos ) pos_out = [ ] # random mutation # expected value is set that values all dimensions attempt to get mutated for i in range ( size ) : key = list ( tune_params . keys ( ) ) [ i ] values = tune_params [ key ] if random . random ( ) < 0.2 : # replace with random value new_value = rando...
def _read_file ( path ) : '''Reads and returns the contents of a text file'''
try : with salt . utils . files . flopen ( path , 'rb' ) as contents : return [ salt . utils . stringutils . to_str ( line ) for line in contents . readlines ( ) ] except ( OSError , IOError ) : return ''
def _set_l2_spf6_timer ( self , v , load = False ) : """Setter method for l2 _ spf6 _ timer , mapped from YANG variable / isis _ state / router _ isis _ config / l2 _ spf6 _ timer ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ l2 _ spf6 _ timer is conside...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = l2_spf6_timer . l2_spf6_timer , is_container = 'container' , presence = False , yang_name = "l2-spf6-timer" , rest_name = "l2-spf6-timer" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods ,...
def addcommenttocommit ( self , project_id , author , sha , path , line , note ) : """Adds an inline comment to a specific commit : param project _ id : project id : param author : The author info as returned by create mergerequest : param sha : The name of a repository branch or tag or if not given the defau...
data = { 'author' : author , 'note' : note , 'path' : path , 'line' : line , 'line_type' : 'new' } request = requests . post ( '{0}/{1}/repository/commits/{2}/comments' . format ( self . projects_url , project_id , sha ) , headers = self . headers , data = data , verify = self . verify_ssl ) if request . status_code ==...
def merge ( self , * args ) : """Merge multiple dictionary objects into one . : param variadic args : Multiple dictionary items : return dict"""
values = [ ] for entry in args : values = values + list ( entry . items ( ) ) return dict ( values )
def get_hash ( name , password = None ) : '''Returns the hash of a certificate in the keychain . name The name of the certificate ( which you can get from keychain . get _ friendly _ name ) or the location of a p12 file . password The password that is used in the certificate . Only required if your passin...
if '.p12' in name [ - 4 : ] : cmd = 'openssl pkcs12 -in {0} -passin pass:{1} -passout pass:{1}' . format ( name , password ) else : cmd = 'security find-certificate -c "{0}" -m -p' . format ( name ) out = __salt__ [ 'cmd.run' ] ( cmd ) matches = re . search ( '-----BEGIN CERTIFICATE-----(.*)-----END CERTIFICATE...
def delete_persistent_volume ( self , name , ** kwargs ) : # noqa : E501 """delete _ persistent _ volume # noqa : E501 delete a PersistentVolume # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . delete_persistent_volume_with_http_info ( name , ** kwargs ) # noqa : E501 else : ( data ) = self . delete_persistent_volume_with_http_info ( name , ** kwargs ) # noqa : E501 return data
def get_object ( self , binding_name , cls ) : """Get a reference to a remote object using CORBA"""
return self . _state . get_object ( self , binding_name , cls )
def remove_redistribution ( self , protocol ) : """Removes a protocol redistribution to OSPF Args : protocol ( str ) : protocol to redistribute route _ map _ name ( str ) : route - map to be used to filter the protocols Returns : bool : True if the command completes successfully Exception : ValueErr...
protocols = [ 'bgp' , 'rip' , 'static' , 'connected' ] if protocol not in protocols : raise ValueError ( 'redistributed protocol must be' 'bgp, connected, rip or static' ) cmd = 'no redistribute {}' . format ( protocol ) return self . configure_ospf ( cmd )
def _fix ( self , fmt = 'i' ) : """Read pre - or suffix of line at current position with given format ` fmt ` ( default ' i ' ) ."""
fmt = self . endian + fmt fix = self . read ( struct . calcsize ( fmt ) ) if fix : return struct . unpack ( fmt , fix ) [ 0 ] else : raise EOFError
async def _load ( self , data , check = True ) : """Looking for proxies in the passed data . Transform the passed data from [ raw string | file - like object | list ] to set { ( host , port ) , . . . } : { ( ' 192.168.0.1 ' , ' 80 ' ) , }"""
log . debug ( 'Load proxies from the raw data' ) if isinstance ( data , io . TextIOWrapper ) : data = data . read ( ) if isinstance ( data , str ) : data = IPPortPatternLine . findall ( data ) proxies = set ( data ) for proxy in proxies : await self . _handle ( proxy , check = check ) await self . _on_check...
def nguHanh ( tenHanh ) : """Args : tenHanh ( string ) : Tên Hành trong ngũ hành , Kim hoặc K , Moc hoặc M , Thuy hoặc T , Hoa hoặc H , Tho hoặc O Returns : Dictionary : ID của Hành , tên đầy đủ của Hành , số Cục của Hành Raises : Exception : Description"""
if tenHanh in [ "Kim" , "K" ] : return { "id" : 1 , "tenHanh" : "Kim" , "cuc" : 4 , "tenCuc" : "Kim tứ Cục" , "css" : "hanhKim" } elif tenHanh == "Moc" or tenHanh == "M" : return { "id" : 2 , "tenHanh" : "Mộc" , "cuc" : 3 , "tenCuc" : "Mộc tam Cục" , "css" : "hanhMoc" } elif tenHanh == "Thuy" or tenHanh == "T" ...
def inner_products ( self , vec ) : """Get the inner product of a vector with every embedding . : param ( np . array ) vector : the query vector : return ( list [ tuple [ str , float ] ] ) : a map of embeddings to inner products"""
products = self . array . dot ( vec ) return self . _word_to_score ( np . arange ( len ( products ) ) , products )
def constructor ( self , random , args ) : """Return a candidate solution for an ant colony optimization ."""
self . _use_ants = True candidate = [ ] while len ( candidate ) < len ( self . components ) : # Find feasible components feasible_components = [ ] if len ( candidate ) == 0 : feasible_components = self . components else : remaining_capacity = self . capacity - sum ( [ c . element for c in ca...
def _transform_data ( self , X ) : """Binarize the data for each column separately ."""
if self . _binarizers == [ ] : raise NotFittedError ( ) if self . binarize is not None : X = binarize ( X , threshold = self . binarize ) if len ( self . _binarizers ) != X . shape [ 1 ] : raise ValueError ( "Expected input with %d features, got %d instead" % ( len ( self . _binarizers ) , X . shape [ 1 ] )...
def pack ( self ) : "Pack and save file"
pack_name = self . args . prefix + op . basename ( self . path ) pack_path = op . join ( self . args . output or self . basedir , pack_name ) self . out ( "Packing: %s" % self . path ) self . out ( "Output: %s" % pack_path ) if self . args . format : ext = self . get_ext ( self . path ) self . parsers [ ext ] =...
def InitPrivateKey ( self ) : """Makes sure this client has a private key set . It first tries to load an RSA key from the certificate . If no certificate is found , or it is invalid , we make a new random RSA key , and store it as our certificate . Returns : An RSA key - either from the certificate or a ...
if self . private_key : try : self . common_name = rdf_client . ClientURN . FromPrivateKey ( self . private_key ) logging . info ( "Starting client %s" , self . common_name ) return self . private_key except type_info . TypeValueError : pass # We either have an invalid key or no ...
def relabel ( self , i ) : '''API : relabel ( self , i ) Description : Used by max _ flow _ preflowpush ( ) method for relabelling node i . Input : i : Node that is being relabelled . Post : ' distance ' attribute of node i is updated .'''
min_distance = 2 * len ( self . get_node_list ( ) ) + 1 for j in self . get_neighbors ( i ) : if ( self . get_node_attr ( j , 'distance' ) < min_distance and ( self . get_edge_attr ( i , j , 'flow' ) < self . get_edge_attr ( i , j , 'capacity' ) ) ) : min_distance = self . get_node_attr ( j , 'distance' ) f...
def infer_transportation_mode ( self , clf , min_time ) : """In - place transportation mode inferring of segments Returns : This track"""
for segment in self . segments : segment . infer_transportation_mode ( clf , min_time ) return self
def files ( self ) : """Files in torrent . List of namedtuples ( filepath , size ) . : rtype : list [ TorrentFile ]"""
files = [ ] info = self . _struct . get ( 'info' ) if not info : return files if 'files' in info : base = info [ 'name' ] for f in info [ 'files' ] : files . append ( TorrentFile ( join ( base , * f [ 'path' ] ) , f [ 'length' ] ) ) else : files . append ( TorrentFile ( info [ 'name' ] , info [ ...
def get_service_account_token ( request , service_account = 'default' ) : """Get the OAuth 2.0 access token for a service account . Args : request ( google . auth . transport . Request ) : A callable used to make HTTP requests . service _ account ( str ) : The string ' default ' or a service account email ...
token_json = get ( request , 'instance/service-accounts/{0}/token' . format ( service_account ) ) token_expiry = _helpers . utcnow ( ) + datetime . timedelta ( seconds = token_json [ 'expires_in' ] ) return token_json [ 'access_token' ] , token_expiry
def get_scratch_path ( self , local_file ) : """Construct and return a path in the scratch area from a local file ."""
( local_dirname , local_basename ) = self . split_local_path ( local_file ) return self . construct_scratch_path ( local_dirname , local_basename )
def _process_slice ( self , arg ) : """process the input slice for use calling the C code"""
start = arg . start stop = arg . stop step = arg . step nrows = self . _info [ 'nrows' ] if step is None : step = 1 if start is None : start = 0 if stop is None : stop = nrows if start < 0 : start = nrows + start if start < 0 : raise IndexError ( "Index out of bounds" ) if stop < 0 : sto...
def mappability ( args ) : """% prog mappability reference . fasta Generate 50mer mappability for reference genome . Commands are based on gem mapper . See instructions : < https : / / github . com / xuefzhao / Reference . Mappability >"""
p = OptionParser ( mappability . __doc__ ) p . add_option ( "--mer" , default = 50 , type = "int" , help = "User mer size" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) ref , = args K = opts . mer pf = ref . rsplit ( "." , 1 ) [ 0 ] mm = MakeMa...
def parse_pseudo_lang ( self , sel , m , has_selector ) : """Parse pseudo language ."""
values = m . group ( 'values' ) patterns = [ ] for token in RE_VALUES . finditer ( values ) : if token . group ( 'split' ) : continue value = token . group ( 'value' ) if value . startswith ( ( '"' , "'" ) ) : parts = css_unescape ( value [ 1 : - 1 ] , True ) . split ( '-' ) else : ...
def get_fws ( value ) : """FWS = 1 * WSP This isn ' t the RFC definition . We ' re using fws to represent tokens where folding can be done , but when we are parsing the * un * folding has already been done so we don ' t need to watch out for CRLF ."""
newvalue = value . lstrip ( ) fws = WhiteSpaceTerminal ( value [ : len ( value ) - len ( newvalue ) ] , 'fws' ) return fws , newvalue
def partition_ordered ( sequence , key = None ) : """Partition ordered sequence by key . Sequence is expected to already be ordered . Parameters sequence : iterable data . key : partition key function Yields iterable tuple ( s ) of partition key , data list pairs . Examples 1 . By object attributes ...
yield from ( ( k , list ( g ) ) for k , g in groupby ( sequence , key = key ) )
def auto_delete_cohort ( instance , ** kwargs ) : "Deletes and auto - created cohort named after the instance ."
cohorts = Cohort . objects . filter ( autocreated = True ) if isinstance ( instance , Project ) : cohorts = cohorts . filter ( project = instance ) elif isinstance ( instance , Batch ) : cohorts = cohorts . filter ( batch = instance ) else : return count = cohorts . count ( ) cohorts . delete ( ) log . info...
def main ( args_list = None ) : """Script which loads variants and annotates them with overlapping genes and predicted coding effects . Example usage : varcode - - vcf mutect . vcf - - vcf strelka . vcf - - maf tcga _ brca . maf - - variant chr1 498584 C G - - json - variants more _ variants . json"""
print_version_info ( ) if args_list is None : args_list = sys . argv [ 1 : ] args = arg_parser . parse_args ( args_list ) variants = variant_collection_from_args ( args ) effects = variants . effects ( ) if args . only_coding : effects = effects . drop_silent_and_noncoding ( ) if args . one_per_variant : va...
def angleOfView ( XY , shape = None , a = None , f = None , D = None , center = None ) : '''Another vignetting equation from : M . Koentges , M . Siebert , and D . Hinken , " Quantitative analysis of PV - modules by electroluminescence images for quality control " 2009 f - - > Focal length D - - > Diameter ...
if a is None : assert f is not None and D is not None # https : / / en . wikipedia . org / wiki / Angular _ aperture a = 2 * np . arctan2 ( D / 2 , f ) x , y = XY try : c0 , c1 = center except : s0 , s1 = shape c0 , c1 = s0 / 2 , s1 / 2 rx = ( x - c0 ) ** 2 ry = ( y - c1 ) ** 2 return 1 / ( 1 + ...
def filter ( self , * args , ** kwargs ) : """See : py : meth : ` nornir . core . inventory . Inventory . filter ` Returns : : obj : ` Nornir ` : A new object with same configuration as ` ` self ` ` but filtered inventory ."""
b = Nornir ( ** self . __dict__ ) b . inventory = self . inventory . filter ( * args , ** kwargs ) return b
def var_explained ( y_true , y_pred ) : """Fraction of variance explained ."""
var_resid = K . var ( y_true - y_pred ) var_y_true = K . var ( y_true ) return 1 - var_resid / var_y_true
def results_class_wise_metrics ( self ) : """Class - wise metrics Returns dict results in a dictionary format"""
results = { } for scene_id , scene_label in enumerate ( self . scene_label_list ) : if scene_label not in results : results [ scene_label ] = { } results [ scene_label ] [ 'count' ] = { } results [ scene_label ] [ 'count' ] [ 'Ncorr' ] = self . scene_wise [ scene_label ] [ 'Ncorr' ] results [ sc...
def Increment ( self , delta , fields = None ) : """Increments counter value by a given delta ."""
if delta < 0 : raise ValueError ( "Counter increment should not be < 0 (received: %d)" % delta ) self . _metric_values [ _FieldsToKey ( fields ) ] = self . Get ( fields = fields ) + delta
def ph2full ( ptrans , htrans ) : """Convert a p - state transition matrix and h - state matrices to the full transation matrix The full transmat hase N = n _ pstates * n _ hstates states"""
n_pstates = len ( ptrans ) n_hstates = len ( htrans [ 0 , 0 ] ) N = n_pstates * n_hstates trans = np . zeros ( ( N , N ) ) for pidx in range ( n_pstates ) : for hidx in range ( n_hstates ) : trans [ pidx * n_hstates + hidx ] = ( ptrans [ pidx , : , np . newaxis ] * htrans [ pidx , : , hidx ] ) . flatten ( )...
def _install_toolplus ( args ) : """Install additional tools we cannot distribute , updating local manifest ."""
manifest_dir = os . path . join ( _get_data_dir ( ) , "manifest" ) toolplus_manifest = os . path . join ( manifest_dir , "toolplus-packages.yaml" ) system_config = os . path . join ( _get_data_dir ( ) , "galaxy" , "bcbio_system.yaml" ) # Handle toolplus installs inside Docker container if not os . path . exists ( syste...
def wasModified ( self ) : """Check to see if this module has been modified on disk since the last time it was cached . @ return : True if it has been modified , False if not ."""
self . filePath . restat ( ) mtime = self . filePath . getmtime ( ) if mtime >= self . lastModified : return True else : return False
def from_string ( string ) : """Reads a string representation to a Cssr object . Args : string ( str ) : A string representation of a CSSR . Returns : Cssr object ."""
lines = string . split ( "\n" ) toks = lines [ 0 ] . split ( ) lengths = [ float ( i ) for i in toks ] toks = lines [ 1 ] . split ( ) angles = [ float ( i ) for i in toks [ 0 : 3 ] ] latt = Lattice . from_lengths_and_angles ( lengths , angles ) sp = [ ] coords = [ ] for l in lines [ 4 : ] : m = re . match ( r"\d+\s...
def debug ( self ) : """Return debug setting"""
debug = False if os . path . isfile ( os . path . join ( self . tcex . args . tc_temp_path , 'DEBUG' ) ) : debug = True return debug
def get_owner_asset_ids ( self , address ) : """Get the list of assets owned by an address owner . : param address : ethereum account address , hex str : return :"""
block_filter = self . _get_event_filter ( owner = address ) log_items = block_filter . get_all_entries ( max_tries = 5 ) did_list = [ ] for log_i in log_items : did_list . append ( id_to_did ( log_i . args [ '_did' ] ) ) return did_list
def set_server ( self , pos , key , value ) : """Set the key to the value for the pos ( position in the list ) ."""
self . _ports_list [ pos ] [ key ] = value
def execute ( self , context , goals ) : """Executes the supplied goals and their dependencies against the given context . : param context : The pants run context . : param list goals : A list of ` ` Goal ` ` objects representing the command line goals explicitly requested . : returns int : An exit code of ...
try : self . attempt ( context , goals ) return 0 except TaskError as e : message = str ( e ) if message : print ( '\nFAILURE: {0}\n' . format ( message ) ) else : print ( '\nFAILURE\n' ) return e . exit_code
def push ( self , value ) : """SNEAK value TO FRONT OF THE QUEUE"""
if self . closed and not self . allow_add_after_close : Log . error ( "Do not push to closed queue" ) with self . lock : self . _wait_for_queue_space ( ) if not self . closed : self . queue . appendleft ( value ) return self
def update_package_versions ( self , batch_request , feed_id ) : """UpdatePackageVersions . [ Preview API ] Update several packages from a single feed in a single request . The updates to the packages do not happen atomically . : param : class : ` < NuGetPackagesBatchRequest > < azure . devops . v5_0 . nuget . ...
route_values = { } if feed_id is not None : route_values [ 'feedId' ] = self . _serialize . url ( 'feed_id' , feed_id , 'str' ) content = self . _serialize . body ( batch_request , 'NuGetPackagesBatchRequest' ) self . _send ( http_method = 'POST' , location_id = '00c58ea7-d55f-49de-b59f-983533ae11dc' , version = '5...
def view_500 ( request , url = None ) : """it returns a 500 http response"""
res = render_to_response ( "500.html" , context_instance = RequestContext ( request ) ) res . status_code = 500 return res
def select ( self , Class , set = None , recursive = True , ignore = True , node = None ) : """See : meth : ` AbstractElement . select `"""
if self . include : return self . subdoc . data [ 0 ] . select ( Class , set , recursive , ignore , node ) # pass it on to the text node of the subdoc else : return iter ( [ ] )
def network_profile_name_list ( self , obj ) : """Get AP profile names ."""
profile_list = pointer ( WLAN_PROFILE_INFO_LIST ( ) ) self . _wlan_get_profile_list ( self . _handle , byref ( obj [ 'guid' ] ) , byref ( profile_list ) ) profiles = cast ( profile_list . contents . ProfileInfo , POINTER ( WLAN_PROFILE_INFO ) ) profile_name_list = [ ] for i in range ( profile_list . contents . dwNumber...
def yosys_area_delay ( library , abc_cmd = None , block = None ) : """Synthesize with Yosys and return estimate of area and delay . : param library : stdcell library file to target in liberty format : param abc _ cmd : string of commands for yosys to pass to abc for synthesis : param block : pyrtl block to an...
if abc_cmd is None : abc_cmd = 'strash;scorr;ifraig;retime;dch,-f;map;print_stats;' else : # first , replace whitespace with commas as per yosys requirements re . sub ( r"\s+" , ',' , abc_cmd ) # then append with " print _ stats " to generate the area and delay info abc_cmd = '%s;print_stats;' % abc_cmd...
def installed ( name , features = None , recurse = False , restart = False , source = None , exclude = None ) : '''Install the windows feature . To install a single feature , use the ` ` name ` ` parameter . To install multiple features , use the ` ` features ` ` parameter . . . note : : Some features require...
ret = { 'name' : name , 'result' : True , 'changes' : { } , 'comment' : '' } # Check if features is not passed , use name . Split commas if features is None : features = name . split ( ',' ) # Make sure features is a list , split commas if not isinstance ( features , list ) : features = features . split ( ',' )...
def binary2pb ( b , proto_id , proto_fmt_type ) : """Transfer binary to pb message : param b : binary content to be transformed to pb message : return : pb message"""
rsp = pb_map [ proto_id ] if rsp is None : return None if proto_fmt_type == ProtoFMT . Json : return json2pb ( type ( rsp ) , b . decode ( 'utf-8' ) ) elif proto_fmt_type == ProtoFMT . Protobuf : rsp = type ( rsp ) ( ) # logger . debug ( ( proto _ id ) ) if IS_PY2 : rsp . ParseFromString ( s...
def add_metrics ( last_metrics : Collection [ Rank0Tensor ] , mets : Union [ Rank0Tensor , Collection [ Rank0Tensor ] ] ) : "Return a dictionary for updating ` last _ metrics ` with ` mets ` ."
last_metrics , mets = listify ( last_metrics ) , listify ( mets ) return { 'last_metrics' : last_metrics + mets }
def multipart_upload_lister ( bucket , key_marker = '' , upload_id_marker = '' , headers = None ) : """A generator function for listing multipart uploads in a bucket ."""
more_results = True k = None while more_results : rs = bucket . get_all_multipart_uploads ( key_marker = key_marker , upload_id_marker = upload_id_marker , headers = headers ) for k in rs : yield k key_marker = rs . next_key_marker upload_id_marker = rs . next_upload_id_marker more_results =...
def analyze ( self , using = None , ** kwargs ) : """Perform the analysis process on a text and return the tokens breakdown of the text . Any additional keyword arguments will be passed to ` ` Elasticsearch . indices . analyze ` ` unchanged ."""
return self . _get_connection ( using ) . indices . analyze ( index = self . _name , ** kwargs )
def _import_object ( self , path , look_for_cls_method ) : """Imports the module that contains the referenced method . Args : path : python path of class / function look _ for _ cls _ method ( bool ) : If True , treat the last part of path as class method . Returns : Tuple . ( class object , class name , ...
last_nth = 2 if look_for_cls_method else 1 path = path . split ( '.' ) module_path = '.' . join ( path [ : - last_nth ] ) class_name = path [ - last_nth ] module = importlib . import_module ( module_path ) if look_for_cls_method and path [ - last_nth : ] [ 0 ] == path [ - last_nth ] : class_method = path [ - last_n...
def _expand_variable_match ( positional_vars , named_vars , match ) : """Expand a matched variable with its value . Args : positional _ vars ( list ) : A list of positonal variables . This list will be modified . named _ vars ( dict ) : A dictionary of named variables . match ( re . Match ) : A regular ex...
positional = match . group ( "positional" ) name = match . group ( "name" ) if name is not None : try : return six . text_type ( named_vars [ name ] ) except KeyError : raise ValueError ( "Named variable '{}' not specified and needed by template " "`{}` at position {}" . format ( name , match . ...
def _init_idxs_float ( self , usr_hdrs ) : """List of indexes whose values will be floats ."""
self . idxs_float = [ Idx for Hdr , Idx in self . hdr2idx . items ( ) if Hdr in usr_hdrs and Hdr in self . float_hdrs ]
async def prepare_decrypter ( client , cdn_client , cdn_redirect ) : """Prepares a new CDN decrypter . : param client : a TelegramClient connected to the main servers . : param cdn _ client : a new client connected to the CDN . : param cdn _ redirect : the redirect file object that caused this call . : retu...
cdn_aes = AESModeCTR ( key = cdn_redirect . encryption_key , # 12 first bytes of the IV . . 4 bytes of the offset ( 0 , big endian ) iv = cdn_redirect . encryption_iv [ : 12 ] + bytes ( 4 ) ) # We assume that cdn _ redirect . cdn _ file _ hashes are ordered by offset , # and that there will be enough of these to retrie...
def delete ( self , key ) : """: param key : a string with length of [ 0 , 32]"""
if not is_string ( key ) : raise Exception ( "Key must be string" ) if len ( key ) > 32 : raise Exception ( "Max key length is 32" ) self . root_node = self . _delete_and_delete_storage ( self . root_node , bin_to_nibbles ( to_string ( key ) ) ) self . _update_root_hash ( )
def list_to_1d_numpy ( data , dtype = np . float32 , name = 'list' ) : """Convert data to 1 - D numpy array ."""
if is_numpy_1d_array ( data ) : if data . dtype == dtype : return data else : return data . astype ( dtype = dtype , copy = False ) elif is_1d_list ( data ) : return np . array ( data , dtype = dtype , copy = False ) elif isinstance ( data , Series ) : return data . values . astype ( dty...
def _get_node_name ( self , node ) : """Get the name of the node - check for node . name and node . type . declname . Not sure why the second one occurs exactly - it happens with declaring a new struct field with parameters"""
res = getattr ( node , "name" , None ) if res is None : return res if isinstance ( res , AST . TypeDecl ) : return res . declname return res
def plot_predict ( self , h = 5 , past_values = 20 , intervals = True , ** kwargs ) : """Plots forecasts with the estimated model Parameters h : int ( default : 5) How many steps ahead would you like to forecast ? past _ values : int ( default : 20) How many past observations to show on the forecast graph...
figsize = kwargs . get ( 'figsize' , ( 10 , 7 ) ) if self . latent_variables . estimated is False : raise Exception ( "No latent variables estimated!" ) else : import matplotlib . pyplot as plt import seaborn as sns # Retrieve data , dates and ( transformed ) latent variables mu , Y = self . _model ...
def system_monitor_sfp_alert_action ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) system_monitor = ET . SubElement ( config , "system-monitor" , xmlns = "urn:brocade.com:mgmt:brocade-system-monitor" ) sfp = ET . SubElement ( system_monitor , "sfp" ) alert = ET . SubElement ( sfp , "alert" ) action = ET . SubElement ( alert , "action" ) action . text = kwargs . pop ...
def parse_config_file ( self , path : str , final : bool = True ) -> None : """Parses and loads the config file at the given path . The config file contains Python code that will be executed ( so it is * * not safe * * to use untrusted config files ) . Anything in the global namespace that matches a defined o...
config = { "__file__" : os . path . abspath ( path ) } with open ( path , "rb" ) as f : exec_in ( native_str ( f . read ( ) ) , config , config ) for name in config : normalized = self . _normalize_name ( name ) if normalized in self . _options : option = self . _options [ normalized ] if op...
def harden ( overrides = None ) : """Hardening decorator . This is the main entry point for running the hardening stack . In order to run modules of the stack you must add this decorator to charm hook ( s ) and ensure that your charm config . yaml contains the ' harden ' option set to one or more of the sup...
if overrides is None : overrides = [ ] def _harden_inner1 ( f ) : # As this has to be py2.7 compat , we can ' t use nonlocal . Use a trick # to capture the dictionary that can then be updated . _logged = { 'done' : False } def _harden_inner2 ( * args , ** kwargs ) : # knock out hardening via a config var ; ...
def cmdHISTORY ( self , params ) : """Display the command history"""
cnt = 0 self . writeline ( 'Command history\n' ) for line in self . history : cnt = cnt + 1 self . writeline ( "%-5d : %s" % ( cnt , '' . join ( line ) ) )
def markov_network_bqm ( MN ) : """Construct a binary quadratic model for a markov network . Parameters G : NetworkX graph A Markov Network as returned by : func : ` . markov _ network ` Returns bqm : : obj : ` dimod . BinaryQuadraticModel ` A binary quadratic model ."""
bqm = dimod . BinaryQuadraticModel . empty ( dimod . BINARY ) # the variable potentials for v , ddict in MN . nodes ( data = True , default = None ) : potential = ddict . get ( 'potential' , None ) if potential is None : continue # for single nodes we don ' t need to worry about order phi0 = pot...
def _get_description ( self , element ) : """Returns the description of element . : param element : The element . : type element : hatemile . util . html . htmldomelement . HTMLDOMElement : return : The description of element . : rtype : str"""
description = None if element . has_attribute ( 'title' ) : description = element . get_attribute ( 'title' ) elif element . has_attribute ( 'aria-label' ) : description = element . get_attribute ( 'aria-label' ) elif element . has_attribute ( 'alt' ) : description = element . get_attribute ( 'alt' ) elif e...
def list_role_binding_for_all_namespaces ( self , ** kwargs ) : """list or watch objects of kind RoleBinding This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . list _ role _ binding _ for _ all _ namespaces ( asy...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . list_role_binding_for_all_namespaces_with_http_info ( ** kwargs ) else : ( data ) = self . list_role_binding_for_all_namespaces_with_http_info ( ** kwargs ) return data
def make_duplicate_request ( request ) : """Since werkzeug request objects are immutable , this is needed to create an identical reuet object with immutable values so it can be retried after a POST failure ."""
class FakeRequest ( object ) : method = 'GET' path = request . path headers = request . headers GET = request . GET POST = request . POST user = getattr ( request , 'user' , None ) cookies = request . cookies is_xhr = request . is_xhr return FakeRequest ( )
def topil ( self ) : """Returns a PIL . Image version of this Pix"""
from PIL import Image # Leptonica manages data in words , so it implicitly does an endian # swap . Tell Pillow about this when it reads the data . pix = self if sys . byteorder == 'little' : if self . mode == 'RGB' : raw_mode = 'XBGR' elif self . mode == 'RGBA' : raw_mode = 'ABGR' elif self ...
def _report_command ( self , cmd , procs = None ) : """Writes a command to both stdout and to the commands log file ( self . pipeline _ commands _ file ) . : param str cmd : command to report : param str | list [ str ] procs : process numbers for processes in the command"""
if isinstance ( procs , list ) : procs = "," . join ( map ( str , procs ) ) if procs : line = "\n> `{cmd}` ({procs})\n" . format ( cmd = str ( cmd ) , procs = procs ) else : line = "\n> `{cmd}`\n" . format ( cmd = str ( cmd ) ) print ( line ) with open ( self . pipeline_commands_file , "a" ) as myfile : ...
def step ( self , y , u , t , h ) : """This is called by solve , but can be called by the user who wants to run through an integration with a control force . y - state at t u - control inputs at t t - time h - step size"""
k1 = h * self . func ( t , y , u ) k2 = h * self . func ( t + .5 * h , y + .5 * h * k1 , u ) k3 = h * self . func ( t + .5 * h , y + .5 * h * k2 , u ) k4 = h * self . func ( t + h , y + h * k3 , u ) return y + ( k1 + 2 * k2 + 2 * k3 + k4 ) / 6.0