signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def set_expire ( name , expire , root = None ) : '''. . versionchanged : : 2014.7.0 Sets the value for the date the account expires as days since the epoch ( January 1 , 1970 ) . Using a value of - 1 will clear expiration . See man chage . name User to modify date Date the account expires root Dir...
return _set_attrib ( name , 'expire' , expire , '-E' , root = root , validate = False )
def attime ( self , ** kwargs ) : r"""Returns a dictionary of latest observations at a user specified location for a specified time . Users must specify at least one geographic search parameter ( ' stid ' , ' state ' , ' country ' , ' county ' , ' radius ' , ' bbox ' , ' cwa ' , ' nwsfirezone ' , ' gacc ' , or ...
self . _check_geo_param ( kwargs ) kwargs [ 'token' ] = self . token return self . _get_response ( 'stations/nearesttime' , kwargs )
def clean_field_dict ( field_dict , cleaner = str . strip , time_zone = None ) : r"""Normalize field values by stripping whitespace from strings , localizing datetimes to a timezone , etc > > > ( sorted ( clean _ field _ dict ( { ' _ state ' : object ( ) , ' x ' : 1 , ' y ' : " \ t Wash Me ! \ n " } ) . items ( )...
d = { } if time_zone is None : tz = DEFAULT_TZ for k , v in viewitems ( field_dict ) : if k == '_state' : continue if isinstance ( v , basestring ) : d [ k ] = cleaner ( str ( v ) ) elif isinstance ( v , ( datetime . datetime , datetime . date ) ) : d [ k ] = tz . localize ( v ) ...
def order_by_descending ( self , key ) : """Returns new Enumerable sorted in descending order by given key : param key : key to sort by as lambda expression : return : new Enumerable object"""
if key is None : raise NullArgumentError ( u"No key for sorting given" ) kf = [ OrderingDirection ( key , reverse = True ) ] return SortedEnumerable3 ( kf , self . _data )
def ints2str ( self , int_values ) : """Conversion list [ int ] = > decoded string ."""
if not self . _encoder : raise ValueError ( "Text.ints2str is not available because encoder hasn't been defined." ) return self . _encoder . decode ( int_values )
def load_febrl1 ( return_links = False ) : """Load the FEBRL 1 dataset . The Freely Extensible Biomedical Record Linkage ( Febrl ) package is distributed with a dataset generator and four datasets generated with the generator . This function returns the first Febrl dataset as a : class : ` pandas . DataFram...
df = _febrl_load_data ( 'dataset1.csv' ) if return_links : links = _febrl_links ( df ) return df , links else : return df
def vanity ( self ) : """Returns the user ' s vanity url if it exists , None otherwise"""
purl = self . profile_url . strip ( '/' ) if purl . find ( "/id/" ) != - 1 : return os . path . basename ( purl )
def model_from_string ( self , model_str , verbose = True ) : """Load Booster from a string . Parameters model _ str : string Model will be loaded from this string . verbose : bool , optional ( default = True ) Whether to print messages while loading model . Returns self : Booster Loaded Booster obj...
if self . handle is not None : _safe_call ( _LIB . LGBM_BoosterFree ( self . handle ) ) self . _free_buffer ( ) self . handle = ctypes . c_void_p ( ) out_num_iterations = ctypes . c_int ( 0 ) _safe_call ( _LIB . LGBM_BoosterLoadModelFromString ( c_str ( model_str ) , ctypes . byref ( out_num_iterations ) , ctypes ....
def random_model ( ctx , model_class_name ) : """Get a random model identifier by class name . For example : : # db / fixtures / Category . yml { % for i in range ( 0 , 10 ) % } category { { i } } : name : { { faker . name ( ) } } { % endfor % } # db / fixtures / Post . yml a _ blog _ post : categor...
model_identifiers = ctx [ 'model_identifiers' ] [ model_class_name ] if not model_identifiers : return 'None' idx = random . randrange ( 0 , len ( model_identifiers ) ) return '"%s(%s)"' % ( model_class_name , model_identifiers [ idx ] )
def _skip ( options ) : """Return true if the task should be entirely skipped , and thus have no product requirements ."""
values = [ options . missing_direct_deps , options . unnecessary_deps ] return all ( v == 'off' for v in values )
def on_hid_pnp ( self , hid_event = None ) : """This function will be called on per class event changes , so we need to test if our device has being connected or is just gone"""
old_device = self . hid_device if hid_event : self . pnpChanged . emit ( hid_event ) if hid_event == "connected" : # test if our device is available if self . hid_device : # see , at this point we could detect multiple devices ! # but . . . we only want just one pass else : self . test_f...
def shape_vecs ( * args ) : '''Reshape all ndarrays with ` ` shape = = ( n , ) ` ` to ` ` shape = = ( n , 1 ) ` ` . Recognizes ndarrays and ignores all others .'''
ret_args = [ ] flat_vecs = True for arg in args : if type ( arg ) is numpy . ndarray : if len ( arg . shape ) == 1 : arg = shape_vec ( arg ) else : flat_vecs = False ret_args . append ( arg ) return flat_vecs , ret_args
def _produce_jbig2_images ( jbig2_groups , root , log , options ) : """Produce JBIG2 images from their groups"""
def jbig2_group_futures ( executor , root , groups ) : for group , xref_exts in groups . items ( ) : prefix = f'group{group:08d}' future = executor . submit ( jbig2enc . convert_group , cwd = fspath ( root ) , infiles = ( img_name ( root , xref , ext ) for xref , ext in xref_exts ) , out_prefix = pr...
def parse_declaration ( self , tup_tree ) : """< ! ELEMENT DECLARATION ( DECLGROUP | DECLGROUP . WITHNAME | DECLGROUP . WITHPATH ) + > Note : We only support the DECLGROUP child , at this point ."""
self . check_node ( tup_tree , 'DECLARATION' ) child = self . one_child ( tup_tree , ( 'DECLGROUP' , ) ) return name ( tup_tree ) , attrs ( tup_tree ) , child
def get ( ) : """Get the config chosen by the flags ."""
configs = { c . name ( ) : c for c in lib . RunConfig . all_subclasses ( ) if c . priority ( ) } if not configs : raise sc_process . SC2LaunchError ( "No valid run_configs found." ) if FLAGS . sc2_run_config is None : # Find the highest priority as default . return max ( configs . values ( ) , key = lambda c : ...
def DoxyEmitter ( source , target , env ) : """Doxygen Doxyfile emitter"""
# possible output formats and their default values and output locations output_formats = { "HTML" : ( "YES" , "html" ) , "LATEX" : ( "YES" , "latex" ) , "RTF" : ( "NO" , "rtf" ) , "MAN" : ( "YES" , "man" ) , "XML" : ( "NO" , "xml" ) , } data = DoxyfileParse ( source [ 0 ] . get_contents ( ) ) targets = [ ] out_dir = da...
def pop ( self , key , default = None ) : """Removes the * * key * * from the Lib and returns the ` ` list ` ` of key members . If no key is found , * * default * * is returned . * * key * * is a : ref : ` type - string ` . This must return either * * default * * or a ` ` list ` ` of items as : ref : ` type -...
return super ( BaseLib , self ) . pop ( key , default )
def new ( self , node : Node ) : """Creates property for node"""
return Property ( self . name , self . _setter , node )
def user_package_watch_filter ( config , message , fasnick = None , * args , ** kw ) : """A particular user ' s packages ( watchcommits flag ) This rule includes messages that relate to packages where the specified user has the watchcommits flag set ."""
fasnick = kw . get ( 'fasnick' , fasnick ) if fasnick : msg_packages = fmn . rules . utils . msg2packages ( message , ** config ) if not msg_packages : # If the message has no packages associated with it , there ' s no # way that " one of them " is going to happen to belong to this user , # so let ' s n...
def reset ( self , value = None ) : """Resets the start time of the interval to now or the specified value ."""
if value is None : value = time . clock ( ) self . start = value if self . value_on_reset : self . value = self . value_on_reset
def distances ( x , y , px , py , plot = False ) : """Compute shortest distance of points ( px , py ) to the line described by the end points in ( x , y ) . Parameters x , y : x and y coordinates of line px : x coordinates of data points py : y coordiante of data points Returns distances : list of dis...
length_line = np . sqrt ( ( x [ 1 ] - x [ 0 ] ) ** 2 + ( y [ 1 ] - y [ 0 ] ) ** 2 ) horizontal = ( np . diff ( y ) == 0 ) vertical = ( np . diff ( x ) == 0 ) dist = [ ] dpl = [ ] counter = 0 for xp , yp in zip ( px , py ) : # compute distances to the end points dp = np . sqrt ( ( xp - x ) ** 2 + ( yp - y ) ** 2 ) ...
def upload_metric ( self , dataset_name , table_name , run_id ) : """Upload metric information to Bigquery . Args : dataset _ name : string , the name of bigquery dataset where the data will be uploaded . table _ name : string , the name of bigquery table under the dataset where the metric data will be up...
expected_file = os . path . join ( self . _logging_dir , logger . METRIC_LOG_FILE_NAME ) with tf . gfile . GFile ( expected_file ) as f : lines = f . readlines ( ) metrics = [ ] for line in filter ( lambda l : l . strip ( ) , lines ) : metric = json . loads ( line ) metric [ "run_id" ] = run...
def build_exception_map ( cls , tokens ) : """Generates a set of ranges where we accept trailing slashes , specifically within comments and strings ."""
exception_ranges = defaultdict ( list ) for token in tokens : token_type , _ , token_start , token_end = token [ 0 : 4 ] if token_type in ( tokenize . COMMENT , tokenize . STRING ) : if token_start [ 0 ] == token_end [ 0 ] : exception_ranges [ token_start [ 0 ] ] . append ( ( token_start [ 1...
def get_books_for_schedule ( self , schedule ) : """Returns a dictionary of data . SLNs are the keys , an array of Book objects are the values ."""
slns = self . _get_slns ( schedule ) books = { } for sln in slns : try : section_books = self . get_books_by_quarter_sln ( schedule . term . quarter , sln ) books [ sln ] = section_books except DataFailureException : # do nothing if bookstore doesn ' t have sln pass return books
def _get_struct_matrix ( self ) : """Get the values for the MATRIX record ."""
obj = _make_object ( "Matrix" ) bc = BitConsumer ( self . _src ) # scale obj . HasScale = bc . u_get ( 1 ) if obj . HasScale : obj . NScaleBits = n_scale_bits = bc . u_get ( 5 ) obj . ScaleX = bc . fb_get ( n_scale_bits ) obj . ScaleY = bc . fb_get ( n_scale_bits ) # rotate obj . HasRotate = bc . u_get ( 1 ...
def start ( self , argv ) : """Start BenchExec . @ param argv : command - line options for BenchExec"""
parser = self . create_argument_parser ( ) self . config = parser . parse_args ( argv [ 1 : ] ) for arg in self . config . files : if not os . path . exists ( arg ) or not os . path . isfile ( arg ) : parser . error ( "File {0} does not exist." . format ( repr ( arg ) ) ) if os . path . isdir ( self . confi...
def scan_channel ( self , channel , ** kwargs ) : """Run Kalibrate . Supported keyword arguments : gain - - Gain in dB device - - Index of device to be used error - - Initial frequency error in ppm"""
kal_run_line = fn . build_kal_scan_channel_string ( self . kal_bin , channel , kwargs ) raw_output = subprocess . check_output ( kal_run_line . split ( ' ' ) , stderr = subprocess . STDOUT ) kal_normalized = fn . parse_kal_channel ( raw_output ) return kal_normalized
def get_complete_version ( version = None ) : """Returns a tuple of the graphql version . If version argument is non - empty , then checks for correctness of the tuple provided ."""
if version is None : from graphql import VERSION as version else : assert len ( version ) == 5 assert version [ 3 ] in ( "alpha" , "beta" , "rc" , "final" ) return version
def register ( ) : """Register a new user . Validates that the username is not already taken . Hashes the password for security ."""
if request . method == "POST" : username = request . form [ "username" ] password = request . form [ "password" ] error = None if not username : error = "Username is required." elif not password : error = "Password is required." elif db . session . query ( User . query . filter_b...
def start_waiting ( self ) : """Show waiting progress bar until done _ waiting is called . Only has an effect if we are in waiting state ."""
if not self . waiting : self . waiting = True wait_msg = "Waiting for project to become ready for {}" . format ( self . msg_verb ) self . progress_bar . show_waiting ( wait_msg )
def epiweeks_in_year ( year : int ) -> int : """Return number of epiweeks in a year"""
if date_to_epiweek ( epiweek_to_date ( Epiweek ( year , 53 ) ) ) . year == year : return 53 else : return 52
def classify_host ( host ) : '''Host is an IPv4Address , IPv6Address or a string . If an IPv4Address or IPv6Address return it . Otherwise convert the string to an IPv4Address or IPv6Address object if possible and return it . Otherwise return the original string if it is a valid hostname . Raise ValueError i...
if isinstance ( host , ( IPv4Address , IPv6Address ) ) : return host if is_valid_hostname ( host ) : return host return ip_address ( host )
def map_keys_to_values ( l : List [ Any ] , d : Dict [ Any , Any ] , default : Any = None , raise_if_missing : bool = False , omit_if_missing : bool = False ) -> List [ Any ] : """The ` ` d ` ` dictionary contains a ` ` key - > value ` ` mapping . We start with a list of potential keys in ` ` l ` ` , and return a...
result = [ ] for k in l : if raise_if_missing and k not in d : raise ValueError ( "Missing key: " + repr ( k ) ) if omit_if_missing and k not in d : continue result . append ( d . get ( k , default ) ) return result
def set_function_name ( func , node_name , base_name , func_counter ) : """Set a sufficient name for the function"""
# NNabla requires each function to have a unique name # so we generate one here . func . name , count = generate_function_name ( func . type , base_name , node_name , func_counter ) update_function_counter ( func . type , func_counter , count )
def load_genotypes ( self ) : """Actually loads the first chunk of genotype data into memory due to the individual oriented format of MACH data . Due to the fragmented approach to data loading necessary to avoid running out of RAM , this function will initialize the data structures with the first chunk of loc...
lb = self . chunk * Parser . chunk_stride + 2 ub = ( self . chunk + 1 ) * Parser . chunk_stride + 2 buff = None self . current_file = self . archives [ self . file_index ] self . info_file = self . info_files [ self . file_index ] while buff is None : try : buff = self . parse_genotypes ( lb , ub ) exce...
def warnExtractFromRegexpGroups ( self , line , match ) : """Extract file name , line number , and warning text as groups ( 1,2,3) of warningPattern match ."""
file = match . group ( 1 ) lineNo = match . group ( 2 ) if lineNo is not None : lineNo = int ( lineNo ) text = match . group ( 3 ) return ( file , lineNo , text )
def permission_table ( user_permissions , all_permissions ) : """Creates a table of available permissions"""
table = formatting . Table ( [ 'Description' , 'KeyName' , 'Assigned' ] ) table . align [ 'KeyName' ] = 'l' table . align [ 'Description' ] = 'l' table . align [ 'Assigned' ] = 'l' for perm in all_permissions : assigned = user_permissions . get ( perm [ 'keyName' ] , False ) table . add_row ( [ perm [ 'name' ] ...
def add_sibling ( self , sibling ) : """Designate this a multi - feature representative and add a co - feature . Some features exist discontinuously on the sequence , and therefore cannot be declared with a single GFF3 entry ( which can encode only a single interval ) . The canonical encoding for these types ...
assert self . is_pseudo is False if self . siblings is None : self . siblings = list ( ) self . multi_rep = self sibling . multi_rep = self self . siblings . append ( sibling )
def histogram_month_counts ( df , variable ) : """Create a year - long histogram of counts of the variable for each month . It is assumed that the DataFrame index is datetime and that the variable ` month _ name ` exists ."""
if not df . index . dtype in [ "datetime64[ns]" , "<M8[ns]" , ">M8[ns]" ] : log . error ( "index is not datetime" ) return False counts = df . groupby ( df . index . strftime ( "%B" ) ) [ variable ] . count ( ) . reindex ( calendar . month_name [ 1 : ] ) counts . plot ( kind = "bar" , width = 1 , rot = 0 , alph...
def extent_size ( self , units = "MiB" ) : """Returns the volume group extent size in the given units . Default units are MiB . * Args : * * units ( str ) : Unit label ( ' MiB ' , ' GiB ' , etc . . . ) . Default is MiB ."""
self . open ( ) size = lvm_vg_get_extent_size ( self . handle ) self . close ( ) return size_convert ( size , units )
def _handle_cast ( self , node , scope , ctxt , stream ) : """Handle cast nodes : node : TODO : scope : TODO : ctxt : TODO : stream : TODO : returns : TODO"""
self . _dlog ( "handling cast" ) to_type = self . _handle_node ( node . to_type , scope , ctxt , stream ) val_to_cast = self . _handle_node ( node . expr , scope , ctxt , stream ) res = to_type ( ) res . _pfp__set_value ( val_to_cast ) return res
def split_transfer_kwargs ( kwargs , skip = None ) : """Takes keyword arguments * kwargs * , splits them into two separate dictionaries depending on their content , and returns them in a tuple . The first one will contain arguments related to potential file transfer operations ( e . g . ` ` " cache " ` ` or ` `...
skip = make_list ( skip ) if skip else [ ] transfer_kwargs = { name : kwargs . pop ( name ) for name in [ "cache" , "prefer_cache" , "retries" , "retry_delay" ] if name in kwargs and name not in skip } return transfer_kwargs , kwargs
def get_blocks_overview ( block_representation_list , coin_symbol = 'btc' , txn_limit = None , api_key = None ) : '''Batch request version of get _ blocks _ overview'''
for block_representation in block_representation_list : assert is_valid_block_representation ( block_representation = block_representation , coin_symbol = coin_symbol ) assert is_valid_coin_symbol ( coin_symbol ) blocks = ';' . join ( [ str ( x ) for x in block_representation_list ] ) url = make_url ( coin_symbol ,...
def get_mosaics ( self ) : '''Get information for all mosaics accessible by the current user . : returns : : py : Class : ` planet . api . models . Mosaics `'''
url = self . _url ( 'basemaps/v1/mosaics' ) return self . _get ( url , models . Mosaics ) . get_body ( )
def parse_map_Kd ( self ) : """Diffuse map"""
Kd = os . path . join ( self . dir , " " . join ( self . values [ 1 : ] ) ) self . this_material . set_texture ( Kd )
def random_id_generator ( self , size = 6 , chars = string . ascii_uppercase + string . digits ) : '''Generate random id numbers'''
return '' . join ( random . choice ( chars ) for x in range ( size ) )
def netconf_state_files_file_created ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) netconf_state = ET . SubElement ( config , "netconf-state" , xmlns = "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring" ) files = ET . SubElement ( netconf_state , "files" , xmlns = "http://tail-f.com/yang/netconf-monitoring" ) file = ET . SubElement ( files , "file" ) name_key = E...
async def send_request ( self , connection : Connection , payment_handle : int ) : """Approves the credential offer and submits a credential request . The result will be a credential stored in the prover ' s wallet . : param connection : connection to submit request from : param payment _ handle : currently unu...
if not hasattr ( Credential . send_request , "cb" ) : self . logger . debug ( "vcx_credential_send_request: Creating callback" ) Credential . send_request . cb = create_cb ( CFUNCTYPE ( None , c_uint32 , c_uint32 ) ) c_credential_handle = c_uint32 ( self . handle ) c_connection_handle = c_uint32 ( connection . ...
def as_region_filter ( shape_list , origin = 1 ) : """Often , the regions files implicitly assume the lower - left corner of the image as a coordinate ( 1,1 ) . However , the python convetion is that the array index starts from 0 . By default ( origin = 1 ) , coordinates of the returned mpl artists have coord...
filter_list = [ ] for shape in shape_list : if shape . name == "composite" : continue if shape . name == "polygon" : xy = np . array ( shape . coord_list ) - origin f = region_filter . Polygon ( xy [ : : 2 ] , xy [ 1 : : 2 ] ) elif shape . name == "rotbox" or shape . name == "box" : ...
def add_batch ( self , targets , sources ) : """Add pair of associated target and source to this Executor ' s list . This is necessary for " batch " Builders that can be called repeatedly to build up a list of matching target and source files that will be used in order to update multiple target files at once ...
self . batches . append ( Batch ( targets , sources ) )
def getVarianceComps ( self , univariance = False ) : """Return the estimated variance components Args : univariance : Boolean indicator , if True variance components are normalized to sum up to 1 for each trait Returns : variance components of all random effects on all phenotypes [ P , n _ randEffs matrix ...
RV = sp . zeros ( ( self . P , self . n_randEffs ) ) for term_i in range ( self . n_randEffs ) : RV [ : , term_i ] = self . getTraitCovar ( term_i ) . diagonal ( ) if univariance : RV /= RV . sum ( 1 ) [ : , sp . newaxis ] return RV
def randrange ( order , entropy = None ) : """Return a random integer k such that 1 < = k < order , uniformly distributed across that range . For simplicity , this only behaves well if ' order ' is fairly close ( but below ) a power of 256 . The try - try - again algorithm we use takes longer and longer time ...
# we could handle arbitrary orders ( even 256 * * k + 1 ) better if we created # candidates bit - wise instead of byte - wise , which would reduce the # worst - case behavior to avg = 2 loops , but that would be more complex . The # change would be to round the order up to a power of 256 , subtract one # ( to get 0xfff...
def get_indicators_metadata ( self , indicators ) : """Provide metadata associated with an list of indicators , including value , indicatorType , noteCount , sightings , lastSeen , enclaveIds , and tags . The metadata is determined based on the enclaves the user making the request has READ access to . : param...
data = [ { 'value' : i . value , 'indicatorType' : i . type } for i in indicators ] resp = self . _client . post ( "indicators/metadata" , data = json . dumps ( data ) ) return [ Indicator . from_dict ( x ) for x in resp . json ( ) ]
def _process_feature_affected_genes ( self , limit = None ) : """This table lists ( intrinsic ) genomic sequence alterations and their affected gene ( s ) . It provides the sequence alteration ID , SO type , abbreviation , and relationship to the affected gene , with the gene ' s ID , symbol , and SO type (...
# can use this to process and build the variant locus . # but will need to process through some kind of helper hash , # just like we do with the genotype file . # that ' s because each gene is on a separate line # for example , ZDB - ALT - 021021-2 is a deficiency that affects 4 genes # that case is when the relationsh...
def sadd ( self , key , * values ) : """Emulate sadd ."""
if len ( values ) == 0 : raise ResponseError ( "wrong number of arguments for 'sadd' command" ) redis_set = self . _get_set ( key , 'SADD' , create = True ) before_count = len ( redis_set ) redis_set . update ( map ( self . _encode , values ) ) after_count = len ( redis_set ) return after_count - before_count
def look_up_and_get ( cellpy_file_name , table_name ) : """Extracts table from cellpy hdf5 - file ."""
# infoname = ' / CellpyData / info ' # dataname = ' / CellpyData / dfdata ' # summaryname = ' / CellpyData / dfsummary ' # fidname = ' / CellpyData / fidtable ' # stepname = ' / CellpyData / step _ table ' root = '/CellpyData' table_path = '/' . join ( [ root , table_name ] ) logging . debug ( f"look_up_and_get({cellpy...
def _sanitize ( self , unsanitized ) : """Sanitize input string to optimize string comparison match : param unsanitized : str : return : str"""
sanitized = "" # strip punctuation and diacritics replace_punct = str . maketrans ( string . punctuation + "᾽᾿῾" , ' ' * ( len ( string . punctuation ) + 3 ) ) sanitized = unsanitized . translate ( replace_punct ) sanitized = "" . join ( c for c in unicodedata . normalize ( "NFD" , sanitized ) if unicodedata . category...
def vb_get_max_network_slots ( ) : '''Max number of slots any machine can have @ return : @ rtype : number'''
sysprops = vb_get_box ( ) . systemProperties totals = [ sysprops . getMaxNetworkAdapters ( adapter_type ) for adapter_type in [ 1 , # PIIX3 A PIIX3 ( PCI IDE ISA Xcelerator ) chipset . 2 # ICH9 A ICH9 ( I / O Controller Hub ) chipset ] ] return sum ( totals )
def ClientInit ( ) : """Run all startup routines for the client ."""
metric_metadata = client_metrics . GetMetadata ( ) metric_metadata . extend ( communicator . GetMetricMetadata ( ) ) stats_collector_instance . Set ( default_stats_collector . DefaultStatsCollector ( metric_metadata ) ) config_lib . SetPlatformArchContext ( ) config_lib . ParseConfigCommandLine ( ) client_logging . Log...
def get_affiliation_details ( self , value , affiliation_id , institute_literal ) : """This method is used to map the Affiliation between an author and Institution . Parameters value - The author name affiliation _ id - Primary key of the affiliation table institute _ literal Returns Affiliation details...
tokens = tuple ( [ t . upper ( ) . strip ( ) for t in value . split ( ',' ) ] ) if len ( tokens ) == 1 : tokens = value . split ( ) if len ( tokens ) > 0 : if len ( tokens ) > 1 : aulast , auinit = tokens [ 0 : 2 ] else : aulast = tokens [ 0 ] auinit = '' else : aulast , auinit =...
def get_relationship_mdata ( ) : """Return default mdata map for Relationship"""
return { 'source' : { 'element_label' : { 'text' : 'source' , 'languageTypeId' : str ( DEFAULT_LANGUAGE_TYPE ) , 'scriptTypeId' : str ( DEFAULT_SCRIPT_TYPE ) , 'formatTypeId' : str ( DEFAULT_FORMAT_TYPE ) , } , 'instructions' : { 'text' : 'accepts an osid.id.Id object' , 'languageTypeId' : str ( DEFAULT_LANGUAGE_TYPE )...
def common_timeline ( self , reference , hypothesis ) : """Return timeline common to both reference and hypothesis reference | - - - - - | | - - - - - | | - - - - - | | - - - - | hypothesis | - - - - - | | - - - - - | | - - - - - | timeline | - - | - - - - - | - - - - | - - - | - | - - - - - | | - | - - - - -...
timeline = reference . get_timeline ( copy = True ) timeline . update ( hypothesis . get_timeline ( copy = False ) ) return timeline . segmentation ( )
def compute ( self ) : """Run smoother ."""
self . smooth_result , self . cross_validated_residual = run_friedman_smooth ( self . x , self . y , self . _span )
def resample_returns ( returns , func , seed = 0 , num_trials = 100 ) : """Resample the returns and calculate any statistic on every new sample . https : / / en . wikipedia . org / wiki / Resampling _ ( statistics ) : param returns ( Series , DataFrame ) : Returns : param func : Given the resampled returns ca...
# stats = [ ] if type ( returns ) is pd . Series : stats = pd . Series ( index = range ( num_trials ) ) elif type ( returns ) is pd . DataFrame : stats = pd . DataFrame ( index = range ( num_trials ) , columns = returns . columns ) else : raise ( TypeError ( "returns needs to be a Series or DataFrame!" ) ) ...
def isword ( somestr ) : """Checks that some string is a word : param str somestr : It is some string that will be checked for word . The word is a string that contains only alphabetic characters , its length not less 2 characters and noone characters does not reeats more than 2 times in a row . The wor...
# check invalid data types OnlyStringsCanBeChecked ( somestr ) if somestr . isalpha ( ) and len ( somestr ) > 1 : # find characters that repeats more then 2 times in a row matches = re . search ( r'(.)(\1)(\1)' , somestr , flags = re . IGNORECASE ) if matches == None : # russian # check first character ...
def to_table_type ( val , cls , colname ) : """Cast a value to the correct type for inclusion in a LIGO _ LW table This method returns the input unmodified if a type mapping for ` ` colname ` ` isn ' t found . Parameters val : ` object ` The input object to convert , of any type cls : ` type ` , subclas...
from ligo . lw . types import ( ToNumPyType as numpytypes , ToPyType as pytypes , ) # if nothing to do . . . if val is None or colname not in cls . validcolumns : return val llwtype = cls . validcolumns [ colname ] # don ' t mess with formatted IlwdChar if llwtype == 'ilwd:char' : return _to_ilwd ( val , cls . ...
def _get_attach_id ( self , key , value , attributes ) : """Get the attach record ID and extra attributes ."""
if isinstance ( value , dict ) : key = list ( value . keys ( ) ) [ 0 ] attributes . update ( value [ key ] ) return [ key , attributes ] return value , attributes
def load ( fp , catalog = None , single_value = True , encoding = 'utf-8' , cls = None , object_hook = None , parse_float = None , parse_int = None , parse_constant = None , object_pairs_hook = None , use_decimal = None , ** kw ) : """Deserialize ` ` fp ` ` ( a file - like object ) , which contains a text or binary...
if isinstance ( fp , _TEXT_TYPES ) : raw_reader = text_reader ( is_unicode = True ) else : maybe_ivm = fp . read ( 4 ) fp . seek ( 0 ) if maybe_ivm == _IVM : raw_reader = binary_reader ( ) else : raw_reader = text_reader ( ) reader = blocking_reader ( managed_reader ( raw_reader , ca...
def file_download ( self , item_id : str , item_name : str , dir_name : str ) -> bool : """Download file from Google Drive : param item _ id : : param dir _ name : : return :"""
service = self . __get_service ( ) request = service . files ( ) . get_media ( fileId = item_id ) self . __create_download_dir ( dir_name ) fh = io . FileIO ( os . path . join ( dir_name , item_name ) , mode = 'wb' ) downloader = MediaIoBaseDownload ( fh , request ) done = False while done is False : status , done ...
def by_puuid ( self , region , encrypted_puuid ) : """Get a summoner by PUUID . : param string region : The region to execute this request on : param string encrypted _ puuid : PUUID : returns : SummonerDTO : represents a summoner"""
url , query = SummonerApiV4Urls . by_puuid ( region = region , encrypted_puuid = encrypted_puuid ) return self . _raw_request ( self . by_puuid . __name__ , region , url , query )
def load_from_file ( cfg_file ) : """Load the configuration from a file Parameters cfg _ file : str Path to configuration file Returns cfg : CaseInsensitiveDict Dictionary with configuration parameters"""
path = pathlib . Path ( cfg_file ) . resolve ( ) with path . open ( 'r' ) as f : code = f . readlines ( ) cfg = CaseInsensitiveDict ( ) for line in code : # We deal with comments and empty lines # We need to check line length first and then we look for # a hash . line = line . split ( "#" ) [ 0 ] . strip ( ) ...
def _hugoniot_pth ( self , v ) : """calculate thermal pressure along hugoniot : param v : unit - cell volume in A ^ 3 : return : thermal pressure along hugoniot in GPa"""
temp = self . _hugoniot_t ( v ) return self . cal_pth ( v , temp )
def build_statusbar ( self ) : """construct and return statusbar widget"""
info = { } cb = self . current_buffer btype = None if cb is not None : info = cb . get_info ( ) btype = cb . modename info [ 'buffer_no' ] = self . buffers . index ( cb ) info [ 'buffer_type' ] = btype info [ 'total_messages' ] = self . dbman . count_messages ( '*' ) info [ 'pending_writes' ] = len ( se...
def describe_features ( self , traj ) : """Return a list of dictionaries describing the contacts features . Parameters traj : mdtraj . Trajectory The trajectory to describe Returns feature _ descs : list of dict Dictionary describing each feature with the following information about the atoms particip...
feature_descs = [ ] # fill in the atom indices using just the first frame if self . soft_min : distances , residue_indices = md . compute_contacts ( traj [ 0 ] , self . contacts , self . scheme , self . ignore_nonprotein , soft_min = self . soft_min , soft_min_beta = self . soft_min_beta , periodic = self . periodi...
def activateRandomLocation ( self ) : """Set the location to a random point ."""
self . activePhases = np . array ( [ np . random . random ( 2 ) ] ) if self . anchoringMethod == "discrete" : # Need to place the phase in the middle of a cell self . activePhases = np . floor ( self . activePhases * self . cellDimensions ) / self . cellDimensions self . _computeActiveCells ( )
def get_atext ( value ) : """atext = < matches _ atext _ matcher > We allow any non - ATOM _ ENDS in atext , but add an InvalidATextDefect to the token ' s defects list if we find non - atext characters ."""
m = _non_atom_end_matcher ( value ) if not m : raise errors . HeaderParseError ( "expected atext but found '{}'" . format ( value ) ) atext = m . group ( ) value = value [ len ( atext ) : ] atext = ValueTerminal ( atext , 'atext' ) _validate_xtext ( atext ) return atext , value
def load_model_from_path ( model_path , meta = False , ** overrides ) : """Load a model from a data directory path . Creates Language class with pipeline from meta . json and then calls from _ disk ( ) with path ."""
if not meta : meta = get_model_meta ( model_path ) cls = get_lang_class ( meta [ "lang" ] ) nlp = cls ( meta = meta , ** overrides ) pipeline = meta . get ( "pipeline" , [ ] ) disable = overrides . get ( "disable" , [ ] ) if pipeline is True : pipeline = nlp . Defaults . pipe_names elif pipeline in ( False , No...
def _make_window ( window_dict ) : """Creates a new class for that window and registers it at this module ."""
cls_name = '%sWindow' % camel_case ( str ( window_dict [ 'name' ] ) ) bases = ( Window , ) attrs = { '__module__' : sys . modules [ __name__ ] , 'name' : str ( window_dict [ 'name' ] ) , 'inv_type' : str ( window_dict [ 'id' ] ) , 'inv_data' : window_dict , } # creates function - local index and size variables def make...
def program_files ( self , executable ) : """OPTIONAL , this method is only necessary for situations when the benchmark environment needs to know all files belonging to a tool ( to transport them to a cloud service , for example ) . Returns a list of files or directories that are necessary to run the tool .""...
directory = os . path . dirname ( executable ) return [ os . path . join ( '.' , directory , f ) for f in self . BINS ]
def load_tree ( self ) : """method iterates thru all objects older than synergy _ start _ timeperiod parameter in job collections and loads them into this timetable"""
timeperiod = settings . settings [ 'synergy_start_timeperiod' ] yearly_timeperiod = time_helper . cast_to_time_qualifier ( QUALIFIER_YEARLY , timeperiod ) monthly_timeperiod = time_helper . cast_to_time_qualifier ( QUALIFIER_MONTHLY , timeperiod ) daily_timeperiod = time_helper . cast_to_time_qualifier ( QUALIFIER_DAIL...
def emit_event ( project_slug , action_slug ) : """Publish message to action . Rio will trigger all registered webhooks related to this action and trace running process ."""
if request . headers . get ( 'Content-Type' ) == 'application/json' : payload = request . get_json ( ) elif request . method == 'POST' : payload = request . form . to_dict ( ) else : payload = request . args . to_dict ( ) if not request . authorization : return jsonify ( { 'message' : 'unauthorized' } )...
def encode_multipart_formdata ( fields , boundary = None ) : """Encode a dictionary of ` ` fields ` ` using the multipart / form - data MIME format . : param fields : Dictionary of fields or list of ( key , : class : ` ~ urllib3 . fields . RequestField ` ) . : param boundary : If not specified , then a rand...
body = BytesIO ( ) if boundary is None : boundary = choose_boundary ( ) for field in iter_field_objects ( fields ) : body . write ( b ( '--%s\r\n' % ( boundary ) ) ) writer ( body ) . write ( field . render_headers ( ) ) data = field . data if isinstance ( data , int ) : data = str ( data ) ...
def date_for_str ( date_str ) : '''tries to guess date from ambiguous date string'''
try : for date_format in itertools . permutations ( [ '%Y' , '%m' , '%d' ] ) : try : date = datetime . strptime ( date_str , '' . join ( date_format ) ) raise StopIteration except ValueError : pass return None except StopIteration : return date
def storages ( self ) : """Gathers relevant storage results . Returns : pandas : ` pandas . DataFrame < dataframe > ` Dataframe containing all storages installed in the MV grid and LV grids . Index of the dataframe are the storage representatives , columns are the following : nominal _ power : : obj : `...
grids = [ self . network . mv_grid ] + list ( self . network . mv_grid . lv_grids ) storage_results = { } storage_results [ 'storage_id' ] = [ ] storage_results [ 'nominal_power' ] = [ ] storage_results [ 'voltage_level' ] = [ ] storage_results [ 'grid_connection_point' ] = [ ] for grid in grids : for storage in gr...
def add_block_options ( self , top ) : """Return a list of URLs and titles for blocks which can be added to this column . All available blocks are grouped by block category ."""
from . blockadmin import blocks block_choices = [ ] # Group all block by category for category in sorted ( blocks . site . block_list ) : category_blocks = blocks . site . block_list [ category ] category_choices = [ ] for block in category_blocks : base_url = reverse ( 'block_admin:{}_{}_add' . for...
def do_index_command ( self , index , ** options ) : """Delete search index ."""
if options [ "interactive" ] : logger . warning ( "This will permanently delete the index '%s'." , index ) if not self . _confirm_action ( ) : logger . warning ( "Aborting deletion of index '%s' at user's request." , index ) return return delete_index ( index )
def make_interface_child ( device_name , interface_name , parent_name ) : '''. . versionadded : : 2019.2.0 Set an interface as part of a LAG . device _ name The name of the device , e . g . , ` ` edge _ router ` ` . interface _ name The name of the interface to be attached to LAG , e . g . , ` ` xe - 1/0/...
nb_device = get_ ( 'dcim' , 'devices' , name = device_name ) nb_parent = get_ ( 'dcim' , 'interfaces' , device_id = nb_device [ 'id' ] , name = parent_name ) if nb_device and nb_parent : return update_interface ( device_name , interface_name , lag = nb_parent [ 'id' ] ) else : return False
def tryCommit ( self , prepare : Prepare ) : """Try to commit if the Prepare message is ready to be passed into the commit phase ."""
rv , reason = self . canCommit ( prepare ) if rv : self . doCommit ( prepare ) else : self . logger . debug ( "{} cannot send COMMIT since {}" . format ( self , reason ) )
def add_client ( self , user_id = None ) : """Adds current instance to public or private channel . If user _ id is specified it will be added to the private channel , If user _ id is not specified it will be added to the public one instead ."""
if user_id is None : # generate a random uuid if it ' s an unauthenticated client self . channel = 'public' user_id = uuid . uuid1 ( ) . hex else : self . channel = 'private' self . id = user_id self . channels [ self . channel ] [ self . id ] = self print 'Client connected to the %s channel.' % self . chan...
def set_gcc ( ) : """Try to use GCC on OSX for OpenMP support ."""
# For macports and homebrew if 'darwin' in platform . platform ( ) . lower ( ) : gcc = extract_gcc_binaries ( ) if gcc is not None : os . environ [ "CC" ] = gcc os . environ [ "CXX" ] = gcc else : global use_openmp use_openmp = False logging . warning ( 'No GCC availa...
def close ( self ) : """Toggle state to closed switch disconnector"""
self . _state = 'closed' self . grid . graph . add_edge ( self . _nodes [ 0 ] , self . _nodes [ 1 ] , { 'line' : self . _line } )
async def read ( self ) : """Read from the box in a blocking manner . : returns : An item from the box ."""
result = await self . _queue . get ( ) self . _can_write . set ( ) if self . _queue . empty ( ) : self . _can_read . clear ( ) return result
def p_route_deprecation ( self , p ) : """route _ deprecation : DEPRECATED | DEPRECATED BY route _ name route _ version | empty"""
if len ( p ) == 5 : p [ 0 ] = ( True , p [ 3 ] , p [ 4 ] ) elif p [ 1 ] : p [ 0 ] = ( True , None , None )
def wrap_search ( cls , response ) : """Wrap the response from a stream search into instances and return them : param response : The response from searching a stream : type response : : class : ` requests . Response ` : returns : the new stream instances : rtype : : class : ` list ` of : class : ` stream ...
streams = [ ] json = response . json ( ) streamjsons = json [ 'streams' ] for j in streamjsons : s = cls . wrap_json ( j ) streams . append ( s ) return streams
def unique_rows ( arr , return_index = False , return_inverse = False ) : """Returns a copy of arr with duplicate rows removed . From Stackoverflow " Find unique rows in numpy . array . " Parameters arr : : py : class : ` Array ` , ( ` m ` , ` n ` ) The array to find the unique rows of . return _ index : ...
b = scipy . ascontiguousarray ( arr ) . view ( scipy . dtype ( ( scipy . void , arr . dtype . itemsize * arr . shape [ 1 ] ) ) ) try : out = scipy . unique ( b , return_index = True , return_inverse = return_inverse ) dum = out [ 0 ] idx = out [ 1 ] if return_inverse : inv = out [ 2 ] except Typ...
def add_columns ( self , layers : Union [ np . ndarray , Dict [ str , np . ndarray ] , loompy . LayerManager ] , col_attrs : Dict [ str , np . ndarray ] , * , row_attrs : Dict [ str , np . ndarray ] = None , fill_values : Dict [ str , np . ndarray ] = None ) -> None : """Add columns of data and attribute values to ...
if self . _file . mode != "r+" : raise IOError ( "Cannot add columns when connected in read-only mode" ) # If this is an empty loom file , just assign the provided row and column attributes , and set the shape is_new = self . shape == ( 0 , 0 ) if is_new : if row_attrs is None : raise ValueError ( "row_...
def rename_column ( self , model , old_name , new_name ) : """Rename field in model ."""
field = model . _meta . fields [ old_name ] if isinstance ( field , pw . ForeignKeyField ) : old_name = field . column_name self . __del_field__ ( model , field ) field . name = field . column_name = new_name model . _meta . add_field ( new_name , field ) if isinstance ( field , pw . ForeignKeyField ) : field ....
def build_attrs ( self , base_attrs , extra_attrs = None , ** kwargs ) : """Helper function for building an attribute dictionary . This is combination of the same method from Django < = 1.10 and Django1.11 +"""
attrs = dict ( base_attrs , ** kwargs ) if extra_attrs : attrs . update ( extra_attrs ) return attrs
def _proxy ( self ) : """Generate an instance context for the instance , the context is capable of performing various actions . All instance actions are proxied to the context : returns : DomainContext for this DomainInstance : rtype : twilio . rest . api . v2010 . account . sip . domain . DomainContext"""
if self . _context is None : self . _context = DomainContext ( self . _version , account_sid = self . _solution [ 'account_sid' ] , sid = self . _solution [ 'sid' ] , ) return self . _context
def showFileHeaderData ( peInstance ) : """Prints IMAGE _ FILE _ HEADER fields ."""
fileHeaderFields = peInstance . ntHeaders . fileHeader . getFields ( ) print "[+] IMAGE_FILE_HEADER values:\n" for field in fileHeaderFields : print "--> %s = 0x%08x" % ( field , fileHeaderFields [ field ] . value )