signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _loadData ( self , data ) : """Load attribute values from Plex XML response ."""
self . _setValue = None self . id = data . attrib . get ( 'id' ) self . label = data . attrib . get ( 'label' ) self . summary = data . attrib . get ( 'summary' ) self . type = data . attrib . get ( 'type' ) self . default = self . _cast ( data . attrib . get ( 'default' ) ) self . value = self . _cast ( data . attrib ...
def tsplit ( string , delimiters ) : """Behaves str . split but supports tuples of delimiters ."""
delimiters = tuple ( delimiters ) if len ( delimiters ) < 1 : return [ string , ] final_delimiter = delimiters [ 0 ] for i in delimiters [ 1 : ] : string = string . replace ( i , final_delimiter ) return string . split ( final_delimiter )
def get_topics ( self ) : """: calls : ` GET / repos / : owner / : repo / topics < https : / / developer . github . com / v3 / repos / # list - all - topics - for - a - repository > ` _ : rtype : list of strings"""
headers , data = self . _requester . requestJsonAndCheck ( "GET" , self . url + "/topics" , headers = { 'Accept' : Consts . mediaTypeTopicsPreview } ) return data [ 'names' ]
def _import_plugins ( self ) : """Internal function , ensure all plugin packages are imported ."""
if self . detected : return # In some cases , plugin scanning may start during a request . # Make sure there is only one thread scanning for plugins . self . scanLock . acquire ( ) if self . detected : return # previous threaded released + completed try : import_apps_submodule ( "content_plugins" ) self...
def duplicates_removed ( it , already_seen = ( ) ) : """Returns a list with duplicates removed from the iterable ` it ` . Order is preserved ."""
lst = [ ] seen = set ( ) for i in it : if i in seen or i in already_seen : continue lst . append ( i ) seen . add ( i ) return lst
def do_verify ( marfile , keyfiles = None ) : """Verify the MAR file ."""
try : with open ( marfile , 'rb' ) as f : with MarReader ( f ) as m : # Check various parts of the mar file # e . g . signature algorithms and additional block sections errors = m . get_errors ( ) if errors : print ( "File is not well formed: {}" . format ( er...
def todict ( self ) : """Returns a dictionary fully representing the state of this object"""
return { 'index' : self . index , 'seed' : hb_encode ( self . seed ) , 'n' : self . n , 'root' : hb_encode ( self . root ) , 'hmac' : hb_encode ( self . hmac ) , 'timestamp' : self . timestamp }
def get_private_rooms ( self , ** kwargs ) : """Get a listing of all private rooms with their names and IDs"""
return GetPrivateRooms ( settings = self . settings , ** kwargs ) . call ( ** kwargs )
def _delete_stale ( self ) : """Delete files left in self . _ stale _ files . Also delete their directories if empty ."""
for name , hash_ in self . _stale_files . items ( ) : path = self . download_root . joinpath ( name ) if not path . exists ( ) : continue current_hash = self . _path_hash ( path ) if current_hash == hash_ : progress_logger . info ( 'deleting: %s which is stale...' , name ) path ....
def write_metadata ( self , symbol , metadata , prune_previous_version = True , ** kwargs ) : """Write ' metadata ' under the specified ' symbol ' name to this library . The data will remain unchanged . A new version will be created . If the symbol is missing , it causes a write with empty data ( None , pickled...
# Make a normal write with empty data and supplied metadata if symbol does not exist try : previous_version = self . _read_metadata ( symbol ) except NoDataFoundException : return self . write ( symbol , data = None , metadata = metadata , prune_previous_version = prune_previous_version , ** kwargs ) # Reaching...
def backoff ( max_tries = constants . BACKOFF_DEFAULT_MAXTRIES , delay = constants . BACKOFF_DEFAULT_DELAY , factor = constants . BACKOFF_DEFAULT_FACTOR , exceptions = None ) : """Implements an exponential backoff decorator which will retry decorated function upon given exceptions . This implementation is based o...
if max_tries <= 0 : raise ValueError ( 'Max tries must be greater than 0; got {!r}' . format ( max_tries ) ) if delay <= 0 : raise ValueError ( 'Delay must be greater than 0; got {!r}' . format ( delay ) ) if factor <= 1 : raise ValueError ( 'Backoff factor must be greater than 1; got {!r}' . format ( facto...
def do_page_truncate ( self , args : List [ str ] ) : """Read in a text file and display its output in a pager , truncating long lines if they don ' t fit . Truncated lines can still be accessed by scrolling to the right using the arrow keys . Usage : page _ chop < file _ path >"""
if not args : self . perror ( 'page_truncate requires a path to a file as an argument' , traceback_war = False ) return self . page_file ( args [ 0 ] , chop = True )
def corr_flat_und ( a1 , a2 ) : '''Returns the correlation coefficient between two flattened adjacency matrices . Only the upper triangular part is used to avoid double counting undirected matrices . Similarity metric for weighted matrices . Parameters A1 : NxN np . ndarray undirected matrix 1 A2 : NxN ...
n = len ( a1 ) if len ( a2 ) != n : raise BCTParamError ( "Cannot calculate flattened correlation on " "matrices of different size" ) triu_ix = np . where ( np . triu ( np . ones ( ( n , n ) ) , 1 ) ) return np . corrcoef ( a1 [ triu_ix ] . flat , a2 [ triu_ix ] . flat ) [ 0 ] [ 1 ]
def norm ( self , order = 2 ) : """Find the vector norm , with the given order , of the values"""
return ( sum ( val ** order for val in abs ( self ) . values ( ) ) ) ** ( 1 / order )
def load_label ( self , idx ) : """Load label image as 1 x height x width integer array of label indices . The leading singleton dimension is required by the loss . The full 400 labels are translated to the 59 class task labels ."""
label_400 = scipy . io . loadmat ( '{}/trainval/{}.mat' . format ( self . context_dir , idx ) ) [ 'LabelMap' ] label = np . zeros_like ( label_400 , dtype = np . uint8 ) for idx , l in enumerate ( self . labels_59 ) : idx_400 = self . labels_400 . index ( l ) + 1 label [ label_400 == idx_400 ] = idx + 1 label =...
def tweak ( environment , opts ) : """Commands operating on environment data Usage : datacats tweak - - install - postgis [ ENVIRONMENT ] datacats tweak - - add - redis [ ENVIRONMENT ] datacats tweak - - admin - password [ ENVIRONMENT ] Options : - - install - postgis Install postgis in ckan database ...
environment . require_data ( ) if opts [ '--install-postgis' ] : print "Installing postgis" environment . install_postgis_sql ( ) if opts [ '--add-redis' ] : # Let the user know if they are trying to add it and it is already there print ( 'Adding redis extra container... Please note that you will have ' 'to...
def mrca_matrix ( self ) : '''Return a dictionary storing all pairwise MRCAs . ` ` M [ u ] [ v ] ` ` = MRCA of nodes ` ` u ` ` and ` ` v ` ` . Excludes ` ` M [ u ] [ u ] ` ` because MRCA of node and itself is itself Returns : ` ` dict ` ` : ` ` M [ u ] [ v ] ` ` = MRCA of nodes ` ` u ` ` and ` ` v ` `'''
M = dict ( ) leaves_below = dict ( ) for node in self . traverse_postorder ( ) : leaves_below [ node ] = list ( ) if node . is_leaf ( ) : leaves_below [ node ] . append ( node ) ; M [ node ] = dict ( ) else : for i in range ( len ( node . children ) - 1 ) : for l1 in leav...
def get_class ( classname , all = False ) : """Retrieve a class from the registry . : raises : marshmallow . exceptions . RegistryError if the class cannot be found or if there are multiple entries for the given class name ."""
try : classes = _registry [ classname ] except KeyError : raise RegistryError ( 'Class with name {!r} was not found. You may need ' 'to import the class.' . format ( classname ) ) if len ( classes ) > 1 : if all : return _registry [ classname ] raise RegistryError ( 'Multiple classes with name {...
def fetch_bookshelf ( start_url , output_dir ) : """Fetch all the books off of a gutenberg project bookshelf page example bookshelf page , http : / / www . gutenberg . org / wiki / Children % 27s _ Fiction _ ( Bookshelf )"""
# make output directory try : os . mkdir ( OUTPUT_DIR + output_dir ) except OSError as e : raise ( e ) # fetch page r = requests . get ( start_url ) # extract links soup = bs ( r . text , 'html.parser' ) book_links = soup . find_all ( class_ = re . compile ( "extiw" ) ) new_links = [ ] for el in book_links : ...
def env_to_statement ( env ) : '''Return the abstraction description of an environment variable definition into a statement for shell script . > > > env _ to _ statement ( dict ( name = ' X ' , value = ' Y ' ) ) ' X = " Y " ; export X ' > > > env _ to _ statement ( dict ( name = ' X ' , value = ' Y ' , raw ...
source_file = env . get ( 'file' , None ) if source_file : return '. %s' % __escape ( source_file , env ) execute = env . get ( 'execute' , None ) if execute : return execute name = env [ 'name' ] value = __escape ( env [ 'value' ] , env ) return '%s=%s; export %s' % ( name , value , name )
def remove_markup ( s ) : """Remove all < * > html markup tags from s ."""
mo = _markup_re . search ( s ) while mo : s = s [ 0 : mo . start ( ) ] + s [ mo . end ( ) : ] mo = _markup_re . search ( s ) return s
def padding ( s , bs = AES . block_size ) : """Fills a bytes - like object with arbitrary symbols to make its length divisible by ` bs ` ."""
s = to_bytes ( s ) if len ( s ) % bs == 0 : res = s + b'' . join ( map ( to_bytes , [ random . SystemRandom ( ) . choice ( string . ascii_lowercase + string . digits ) for _ in range ( bs - 1 ) ] ) ) + to_bytes ( chr ( 96 - bs ) ) elif len ( s ) % bs > 0 and len ( s ) > bs : res = s + b'' . join ( map ( to_byte...
def _resume_with_session_id ( self , server_info : ServerConnectivityInfo , ssl_version_to_use : OpenSslVersionEnum ) -> bool : """Perform one session resumption using Session IDs ."""
session1 = self . _resume_ssl_session ( server_info , ssl_version_to_use ) try : # Recover the session ID session1_id = self . _extract_session_id ( session1 ) except IndexError : # Session ID not assigned return False if session1_id == '' : # Session ID empty return False # Try to resume that SSL session s...
def followers ( self ) : """获取关注此问题的用户 : return : 关注此问题的用户 : rtype : Author . Iterable : 问题 : 要注意若执行过程中另外有人关注 , 可能造成重复获取到某些用户"""
self . _make_soup ( ) followers_url = self . url + 'followers' for x in common_follower ( followers_url , self . xsrf , self . _session ) : yield x
def _patch_multiple ( target , spec = None , create = False , spec_set = None , autospec = None , new_callable = None , ** kwargs ) : """Perform multiple patches in a single call . It takes the object to be patched ( either as an object or a string to fetch the object by importing ) and keyword arguments for th...
if type ( target ) in ( unicode , str ) : getter = lambda : _importer ( target ) else : getter = lambda : target if not kwargs : raise ValueError ( 'Must supply at least one keyword argument with patch.multiple' ) # need to wrap in a list for python 3 , where items is a view items = list ( kwargs . items ( ...
def set_server_handler ( self , handler_func , name = None , header_filter = None , alias = None , interval = 0.5 ) : """Sets an automatic handler for the type of message template currently loaded . This feature allows users to set a python handler function which is called automatically by the Rammbock message ...
msg_template = self . _get_message_template ( ) server , server_name = self . _servers . get_with_name ( name ) server . set_handler ( msg_template , handler_func , header_filter = header_filter , alias = alias , interval = interval )
def parse_text ( file_name ) : """Parse data from Ohio State University text mocap files ( http : / / accad . osu . edu / research / mocap / mocap _ data . htm ) ."""
# Read the header fid = open ( file_name , 'r' ) point_names = np . array ( fid . readline ( ) . split ( ) ) [ 2 : - 1 : 3 ] fid . close ( ) for i in range ( len ( point_names ) ) : point_names [ i ] = point_names [ i ] [ 0 : - 2 ] # Read the matrix data S = np . loadtxt ( file_name , skiprows = 1 ) field = np . ui...
def toProtocolElement ( self ) : """Returns the representation of this CallSet as the corresponding ProtocolElement ."""
variantSet = self . getParentContainer ( ) gaCallSet = protocol . CallSet ( biosample_id = self . getBiosampleId ( ) ) if variantSet . getCreationTime ( ) : gaCallSet . created = variantSet . getCreationTime ( ) if variantSet . getUpdatedTime ( ) : gaCallSet . updated = variantSet . getUpdatedTime ( ) gaCallSet...
def rescale_variables ( df , variables_include = [ ] , variables_exclude = [ ] ) : """Rescale variables in a DataFrame , excluding variables with NaNs and strings , excluding specified variables , and including specified variables ."""
variables_not_rescale = variables_exclude variables_not_rescale . extend ( df . columns [ df . isna ( ) . any ( ) ] . tolist ( ) ) # variables with NaNs variables_not_rescale . extend ( df . select_dtypes ( include = [ "object" , "datetime" , "timedelta" ] ) . columns ) # variables with strings variables_rescale = list...
def call_filter ( self , name , value , args = None , kwargs = None , context = None , eval_ctx = None ) : """Invokes a filter on a value the same way the compiler does it . Note that on Python 3 this might return a coroutine in case the filter is running from an environment in async mode and the filter suppo...
func = self . filters . get ( name ) if func is None : fail_for_missing_callable ( 'no filter named %r' , name ) args = [ value ] + list ( args or ( ) ) if getattr ( func , 'contextfilter' , False ) : if context is None : raise TemplateRuntimeError ( 'Attempted to invoke context ' 'filter without contex...
def process_post ( self , post , render = True ) : """A high level view to create post processing . : param post : Dictionary representing the post : type post : dict : param render : Choice if the markdown text has to be converted or not : type render : bool : return :"""
post_processor = self . post_processor post_processor . process ( post , render ) try : author = self . user_callback ( post [ "user_id" ] ) except Exception : raise Exception ( "No user_loader has been installed for this " "BloggingEngine. Add one with the " "'BloggingEngine.user_loader' decorator." ) if autho...
def fbresnet152 ( num_classes = 1000 , pretrained = 'imagenet' ) : """Constructs a ResNet - 152 model . Args : pretrained ( bool ) : If True , returns a model pre - trained on ImageNet"""
model = FBResNet ( Bottleneck , [ 3 , 8 , 36 , 3 ] , num_classes = num_classes ) if pretrained is not None : settings = pretrained_settings [ 'fbresnet152' ] [ pretrained ] assert num_classes == settings [ 'num_classes' ] , "num_classes should be {}, but is {}" . format ( settings [ 'num_classes' ] , num_classe...
def set_nweight ( self , node_from , node_to , weight_there , weight_back ) : r"""Set a single n - weight / edge - weight . Parameters node _ from : int Node - id from the first node of the edge . node _ to : int Node - id from the second node of the edge . weight _ there : float Weight from first to ...
if node_from >= self . __nodes or node_from < 0 : raise ValueError ( 'Invalid node id (node_from) of {}. Valid values are 0 to {}.' . format ( node_from , self . __nodes - 1 ) ) elif node_to >= self . __nodes or node_to < 0 : raise ValueError ( 'Invalid node id (node_to) of {}. Valid values are 0 to {}.' . form...
def help ( self , * args ) : """Can be overridden ( and for example _ Menu does ) ."""
if args : self . messages . error ( self . messages . command_does_not_accept_arguments ) else : print ( self . helpfull )
def _validate_header ( self , hed ) : """Validate the list that represents the table header . : param hed : The list that represents the table header . : type hed : list ( list ( hatemile . util . html . htmldomelement . HTMLDOMElement ) ) : return : True if the table header is valid or False if the table hea...
# pylint : disable = no - self - use if not bool ( hed ) : return False length = - 1 for row in hed : if not bool ( row ) : return False elif length == - 1 : length = len ( row ) elif len ( row ) != length : return False return True
def _GetShowID ( self , stringSearch , origStringSearch = None ) : """Search for given string as an existing entry in the database file name table or , if no match is found , as a show name from the TV guide . If an exact match is not found in the database the user can accept or decline the best match from th...
showInfo = tvfile . ShowInfo ( ) if origStringSearch is None : goodlogging . Log . Info ( "RENAMER" , "Looking up show ID for: {0}" . format ( stringSearch ) ) origStringSearch = stringSearch goodlogging . Log . IncreaseIndent ( ) showInfo . showID = self . _db . SearchFileNameTable ( stringSearch ) if showInfo...
def get_sampleV ( self , res , DV = None , resMode = 'abs' , ind = None , Out = '(X,Y,Z)' ) : """Sample , with resolution res , the volume defined by DV or ind"""
args = [ self . Poly , self . dgeom [ 'P1Min' ] [ 0 ] , self . dgeom [ 'P1Max' ] [ 0 ] , self . dgeom [ 'P2Min' ] [ 1 ] , self . dgeom [ 'P2Max' ] [ 1 ] , res ] kwdargs = dict ( DV = DV , dVMode = resMode , ind = ind , VType = self . Id . Type , VLim = self . Lim , Out = Out , margin = 1.e-9 ) pts , dV , ind , reseff =...
def truncate_to ( self , cert ) : """Remove all certificates in the path after the cert specified : param cert : An asn1crypto . x509 . Certificate object to find : raises : LookupError - when the certificate could not be found : return : The current ValidationPath object , for chaining"""
cert_index = None for index , entry in enumerate ( self ) : if entry . issuer_serial == cert . issuer_serial : cert_index = index break if cert_index is None : raise LookupError ( 'Unable to find the certificate specified' ) while len ( self ) > cert_index + 1 : self . pop ( ) return self
def check_user ( self , user_id ) : """Check whether this user can read this dataset"""
if self . hidden == 'N' : return True for owner in self . owners : if int ( owner . user_id ) == int ( user_id ) : if owner . view == 'Y' : return True return False
def export ( self , class_name , method_name , export_data = False , export_dir = '.' , export_filename = 'data.json' , export_append_checksum = False , ** kwargs ) : """Port a trained estimator to the syntax of a chosen programming language . Parameters : param class _ name : string The name of the class in ...
# Arguments : self . class_name = class_name self . method_name = method_name # Estimator : est = self . estimator self . output_activation = est . out_activation_ self . hidden_activation = est . activation self . n_layers = est . n_layers_ self . n_hidden_layers = est . n_layers_ - 2 self . n_inputs = len ( est . coe...
def _authenticate ( ) : '''Retrieve CSRF and API tickets for the Proxmox API'''
global url , port , ticket , csrf , verify_ssl url = config . get_cloud_config_value ( 'url' , get_configured_provider ( ) , __opts__ , search_global = False ) port = config . get_cloud_config_value ( 'port' , get_configured_provider ( ) , __opts__ , default = 8006 , search_global = False ) username = config . get_clou...
def move_images ( self , image_directory ) : """Moves png - files one directory up from path / image / * . png - > path / * . png"""
image_paths = glob ( image_directory + "/**/*.png" , recursive = True ) for image_path in image_paths : destination = image_path . replace ( "\\image\\" , "\\" ) shutil . move ( image_path , destination ) image_folders = glob ( image_directory + "/**/image" , recursive = True ) for image_folder in image_folders...
def GetMultipleTags ( tag_list , start_time , end_time , sampling_rate = None , fill_limit = 99999 , verify_time = False , desc_as_label = False , utc = False ) : """Retrieves raw data from eDNA history for multiple tags , merging them into a single DataFrame , and resampling the data according to the specified ...
# Since we are pulling data from multiple tags , let ' s iterate over each # one . For this case , we only want to pull data using the " raw " method , # which will obtain all data as it is actually stored in the historian . dfs = [ ] columns_names = [ ] for tag in tag_list : df = GetHist ( tag , start_time , end_t...
def GET_getitemtypes ( self ) -> None : """Get the types of all current exchange items supposed to return the values of | Parameter | or | Sequence | objects or the time series of | IOSequence | objects ."""
for item in state . getitems : type_ = self . _get_itemtype ( item ) for name , _ in item . yield_name2value ( ) : self . _outputs [ name ] = type_
def phrase_strings ( self , phrase_type ) : """Returns strings corresponding all phrases matching a given phrase type : param phrase _ type : POS such as " NP " , " VP " , " det " , etc . : type phrase _ type : str : return : a list of strings representing those phrases"""
return [ u" " . join ( subtree . leaves ( ) ) for subtree in self . subtrees_for_phrase ( phrase_type ) ]
def _handle_create ( self , response , ignore_tombstone , auto_refresh ) : '''Handles response from self . create ( ) Args : response ( requests . models . Response ) : response object from self . create ( ) ignore _ tombstone ( bool ) : If True , will attempt creation , if tombstone exists ( 409 ) , will del...
# 201 , success , refresh if response . status_code == 201 : # if not specifying uri , capture from response and append to object self . uri = self . repo . parse_uri ( response . text ) # creation successful if auto_refresh : self . refresh ( ) elif auto_refresh == None : if self . repo...
def max_word_width ( myDict ) : '''currd = { 0 : ' AutoPauseSpeed ' , 125 : ' HRLimitLow ' , 6 : ' Activity ' } max _ wordwidth ( currd )'''
maxValueWidth = 0 for each in myDict : eachValueWidth = myDict [ each ] . __len__ ( ) if ( eachValueWidth > maxValueWidth ) : maxValueWidth = eachValueWidth return ( maxValueWidth )
def find_outer_region ( im , r = 0 ) : r"""Finds regions of the image that are outside of the solid matrix . This function uses the rolling ball method to define where the outer region ends and the void space begins . This function is particularly useful for samples that do not fill the entire rectangular i...
if r == 0 : dt = spim . distance_transform_edt ( input = im ) r = int ( sp . amax ( dt ) ) * 2 im_padded = sp . pad ( array = im , pad_width = r , mode = 'constant' , constant_values = True ) dt = spim . distance_transform_edt ( input = im_padded ) seeds = ( dt >= r ) + get_border ( shape = im_padded . shape ) ...
def wait_for_task ( task_data , task_uri = '/tasks' ) : """Run task and check the result . Args : task _ data ( str ) : the task json to execute Returns : str : Task status ."""
taskid = post_task ( task_data , task_uri ) if isinstance ( task_data , str ) : json_data = json . loads ( task_data ) else : json_data = task_data # inspect the task to see if a timeout is configured job = json_data [ 'job' ] [ 0 ] env = job . get ( 'credentials' ) task_type = job . get ( 'type' ) timeout = TA...
def tt_comp ( self , sampled_topics ) : """Compute term - topic matrix from sampled _ topics ."""
samples = sampled_topics . shape [ 0 ] tt = np . zeros ( ( self . V , self . K , samples ) ) for s in range ( samples ) : tt [ : , : , s ] = samplers_lda . tt_comp ( self . tokens , sampled_topics [ s , : ] , self . N , self . V , self . K , self . beta ) return tt
def unique_everseen ( iterable , key = None ) : """Yield unique elements , preserving order . > > > list ( unique _ everseen ( ' AAAABBBCCDAABBB ' ) ) [ ' A ' , ' B ' , ' C ' , ' D ' ] > > > list ( unique _ everseen ( ' ABBCcAD ' , str . lower ) ) [ ' A ' , ' B ' , ' C ' , ' D ' ] Sequences with a mix of ...
seenset = set ( ) seenset_add = seenset . add seenlist = [ ] seenlist_add = seenlist . append if key is None : for element in iterable : try : if element not in seenset : seenset_add ( element ) yield element except TypeError : if element not i...
def get ( self , name , handler , request = None ) : """Begin Fetch of current value of a PV : param name : A single name string or list of name strings : param request : A : py : class : ` p4p . Value ` or string to qualify this request , or None to use a default . : param callable handler : Completion notif...
chan = self . _channel ( name ) return _p4p . ClientOperation ( chan , handler = unwrapHandler ( handler , self . _nt ) , pvRequest = wrapRequest ( request ) , get = True , put = False )
def register_i18n_js ( self , * paths ) : """Register templates path translations files , like ` select2 / select2 _ locale _ { lang } . js ` . Only existing files are registered ."""
languages = self . config [ "BABEL_ACCEPT_LANGUAGES" ] assets = self . extensions [ "webassets" ] for path in paths : for lang in languages : filename = path . format ( lang = lang ) try : assets . resolver . search_for_source ( assets , filename ) except IOError : pa...
def resample_ann ( resampled_t , ann_sample ) : """Compute the new annotation indices Parameters resampled _ t : numpy array Array of signal locations as returned by scipy . signal . resample ann _ sample : numpy array Array of annotation locations Returns resampled _ ann _ sample : numpy array Arra...
tmp = np . zeros ( len ( resampled_t ) , dtype = 'int16' ) j = 0 tprec = resampled_t [ j ] for i , v in enumerate ( ann_sample ) : while True : d = False if v < tprec : j -= 1 tprec = resampled_t [ j ] if j + 1 == len ( resampled_t ) : tmp [ j ] += 1 ...
def new_result ( self , data_mode = 'value' , time_mode = 'framewise' ) : '''Create a new result Attributes data _ object : MetadataObject id _ metadata : MetadataObject audio _ metadata : MetadataObject frame _ metadata : MetadataObject label _ metadata : MetadataObject parameters : dict'''
from datetime import datetime result = AnalyzerResult ( data_mode = data_mode , time_mode = time_mode ) # Automatically write known metadata result . id_metadata . date = datetime . now ( ) . replace ( microsecond = 0 ) . isoformat ( ' ' ) result . id_metadata . version = timeside . core . __version__ result . id_metad...
def macronize_text ( self , text ) : """Return macronized form of text . E . g . " Gallia est omnis divisa in partes tres , " - > " galliā est omnis dīvīsa in partēs trēs , " : param text : raw text : return : macronized text : rtype : str"""
macronized_words = [ entry [ 2 ] for entry in self . macronize_tags ( text ) ] return " " . join ( macronized_words )
def partition_chem_env ( self , n_sphere = 4 , use_lookup = None ) : """This function partitions the molecule into subsets of the same chemical environment . A chemical environment is specified by the number of surrounding atoms of a certain kind around an atom with a certain atomic number represented by a ...
if use_lookup is None : use_lookup = settings [ 'defaults' ] [ 'use_lookup' ] def get_chem_env ( self , i , n_sphere ) : env_index = self . get_coordination_sphere ( i , n_sphere = n_sphere , only_surface = False , give_only_index = True , use_lookup = use_lookup ) env_index . remove ( i ) atoms = self ...
def present ( name , type , url , access = None , user = None , password = None , database = None , basic_auth = None , basic_auth_user = None , basic_auth_password = None , tls_auth = None , json_data = None , is_default = None , with_credentials = None , type_logo_url = None , orgname = None , profile = 'grafana' ) :...
if isinstance ( profile , string_types ) : profile = __salt__ [ 'config.option' ] ( profile ) ret = { 'name' : name , 'result' : None , 'comment' : None , 'changes' : { } } datasource = __salt__ [ 'grafana4.get_datasource' ] ( name , orgname , profile ) data = _get_json_data ( name = name , type = type , url = url ...
def multi_interpolation_basis ( n_objectives = 6 , n_interp_steps = 5 , width = 128 , channels = 3 ) : """A paramaterization for interpolating between each pair of N objectives . Sometimes you want to interpolate between optimizing a bunch of objectives , in a paramaterization that encourages images to align . ...
N , M , W , Ch = n_objectives , n_interp_steps , width , channels const_term = sum ( [ lowres_tensor ( [ W , W , Ch ] , [ W // k , W // k , Ch ] ) for k in [ 1 , 2 , 4 , 8 ] ] ) const_term = tf . reshape ( const_term , [ 1 , 1 , 1 , W , W , Ch ] ) example_interps = [ sum ( [ lowres_tensor ( [ M , W , W , Ch ] , [ 2 , W...
def validate ( self , fixerrors = True ) : """Validates that the geometry is correctly formatted according to the geometry type . Parameters : - * * fixerrors * * ( optional ) : Attempts to fix minor errors without raising exceptions ( defaults to True ) Returns : - True if the geometry is valid . Raises ...
# validate nullgeometry or has type and coordinates keys if not self . _data : # null geometry , no further checking needed return True elif "type" not in self . _data or "coordinates" not in self . _data : raise Exception ( "A geometry dictionary or instance must have the type and coordinates entries" ) # firs...
def registrar_for_scope ( cls , goal ) : """Returns a subclass of this registrar suitable for registering on the specified goal . Allows reuse of the same registrar for multiple goals , and also allows us to decouple task code from knowing which goal ( s ) the task is to be registered in ."""
type_name = '{}_{}' . format ( cls . __name__ , goal ) if PY2 : type_name = type_name . encode ( 'utf-8' ) return type ( type_name , ( cls , ) , { 'options_scope' : goal } )
def list ( self , ** params ) : """Retrieve all contacts Returns all contacts available to the user according to the parameters provided : calls : ` ` get / contacts ` ` : param dict params : ( optional ) Search options . : return : List of dictionaries that support attriubte - style access , which represen...
_ , _ , contacts = self . http_client . get ( "/contacts" , params = params ) return contacts
def get_idxs ( data , eid2idx ) : """Convert from event IDs to event indices . : param data : an array with a field eid : param eid2idx : a dictionary eid - > idx : returns : the array of event indices"""
uniq , inv = numpy . unique ( data [ 'eid' ] , return_inverse = True ) idxs = numpy . array ( [ eid2idx [ eid ] for eid in uniq ] ) [ inv ] return idxs
def match_url ( self , request ) : """Match the request against a file in the adapter directory : param request : The request : type request : : class : ` requests . Request ` : return : Path to the file : rtype : ` ` str ` `"""
parsed_url = urlparse ( request . path_url ) path_url = parsed_url . path query_params = parsed_url . query match = None for path in self . paths : for item in self . index : target_path = os . path . join ( BASE_PATH , path , path_url [ 1 : ] ) query_path = target_path . lower ( ) + quote ( '?' + q...
def _get_aria_autocomplete ( self , field ) : """Returns the appropriate value for attribute aria - autocomplete of field . : param field : The field . : type field : hatemile . util . html . htmldomelement . HTMLDOMElement : return : The ARIA value of field . : rtype : str"""
tag_name = field . get_tag_name ( ) input_type = None if field . has_attribute ( 'type' ) : input_type = field . get_attribute ( 'type' ) . lower ( ) if ( ( tag_name == 'TEXTAREA' ) or ( ( tag_name == 'INPUT' ) and ( not ( ( input_type == 'button' ) or ( input_type == 'submit' ) or ( input_type == 'reset' ) or ( in...
def _aggregate_on_chunks ( x , f_agg , chunk_len ) : """Takes the time series x and constructs a lower sampled version of it by applying the aggregation function f _ agg on consecutive chunks of length chunk _ len : param x : the time series to calculate the aggregation of : type x : numpy . ndarray : param...
return [ getattr ( x [ i * chunk_len : ( i + 1 ) * chunk_len ] , f_agg ) ( ) for i in range ( int ( np . ceil ( len ( x ) / chunk_len ) ) ) ]
def badgify_badges ( ** kwargs ) : """Returns all badges or only awarded badges for the given user ."""
User = get_user_model ( ) user = kwargs . get ( 'user' , None ) username = kwargs . get ( 'username' , None ) if username : try : user = User . objects . get ( username = username ) except User . DoesNotExist : pass if user : awards = Award . objects . filter ( user = user ) . select_related...
def room ( self , name , participantIdentity = None , ** kwargs ) : """Create a < Room > element : param name : Room name : param participantIdentity : Participant identity when connecting to the Room : param kwargs : additional attributes : returns : < Room > element"""
return self . nest ( Room ( name , participantIdentity = participantIdentity , ** kwargs ) )
def msg ( message ) : """Log a regular message : param message : the message to be logged"""
to_stdout ( " --- {message}" . format ( message = message ) ) if _logger : _logger . info ( message )
def remove ( self , rev , permanent = False ) : """Removes a revision from this changelist : param rev : Revision to remove : type rev : : class : ` . Revision ` : param permanent : Whether or not we need to set the changelist to default : type permanent : bool"""
if not isinstance ( rev , Revision ) : raise TypeError ( 'argument needs to be an instance of Revision' ) if rev not in self : raise ValueError ( '{} not in changelist' . format ( rev ) ) self . _files . remove ( rev ) if not permanent : rev . changelist = self . _connection . default
def get_full_recirc_content ( self , published = True ) : """performs es search and gets all content objects"""
q = self . get_query ( ) search = custom_search_model ( Content , q , published = published , field_map = { "feature_type" : "feature_type.slug" , "tag" : "tags.slug" , "content-type" : "_type" } ) return search
def wrap_io_os_err ( e ) : '''Formats IO and OS error messages for wrapping in FSQExceptions'''
msg = '' if e . strerror : msg = e . strerror if e . message : msg = ' ' . join ( [ e . message , msg ] ) if e . filename : msg = ': ' . join ( [ msg , e . filename ] ) return msg
def extract_css_links ( bs4 ) : """Extracting css links from BeautifulSoup object : param bs4 : ` BeautifulSoup ` : return : ` list ` List of links"""
links = extract_links ( bs4 ) real_css = [ anchor for anchor in links if anchor . endswith ( ( '.css' , '.CSS' ) ) ] css_link_tags = [ anchor [ 'href' ] for anchor in bs4 . select ( 'link[type="text/css"]' ) if anchor . has_attr ( 'href' ) ] return list ( set ( real_css + css_link_tags ) )
async def list_statuses ( self , request ) : """Fetches the committed status of batches by either a POST or GET . Request : body : A JSON array of one or more id strings ( if POST ) query : - id : A comma separated list of up to 15 ids ( if GET ) - wait : Request should not return until all batches commit...
error_traps = [ error_handlers . StatusResponseMissing ] # Parse batch ids from POST body , or query paramaters if request . method == 'POST' : if request . headers [ 'Content-Type' ] != 'application/json' : LOGGER . debug ( 'Request headers had wrong Content-Type: %s' , request . headers [ 'Content-Type' ]...
def fft_coefficient ( self , x , param = None ) : """As in tsfresh ` fft _ coefficient < https : / / github . com / blue - yonder / tsfresh / blob / master / tsfresh / feature _ extraction / feature _ calculators . py # L852 > ` _ Calculates the fourier coefficients of the one - dimensional discrete Fourier Transfo...
if param is None : param = [ { 'attr' : 'abs' , 'coeff' : 44 } , { 'attr' : 'abs' , 'coeff' : 63 } , { 'attr' : 'abs' , 'coeff' : 0 } , { 'attr' : 'real' , 'coeff' : 0 } , { 'attr' : 'real' , 'coeff' : 23 } ] _fft_coef = feature_calculators . fft_coefficient ( x , param ) logging . debug ( "fft coefficient by tsfre...
def get_country_long ( self , ip ) : '''Get country _ long'''
rec = self . get_all ( ip ) return rec and rec . country_long
def is_jid ( jid ) : '''Returns True if the passed in value is a job id'''
if not isinstance ( jid , six . string_types ) : return False if len ( jid ) != 20 and ( len ( jid ) <= 21 or jid [ 20 ] != '_' ) : return False try : int ( jid [ : 20 ] ) return True except ValueError : return False
def event ( self , event ) : """Allow GUI to be closed upon holding Shift"""
if event . type ( ) == QtCore . QEvent . Close : modifiers = self . app . queryKeyboardModifiers ( ) shift_pressed = QtCore . Qt . ShiftModifier & modifiers states = self . app . controller . states if shift_pressed : print ( "Force quitted.." ) self . app . controller . host . emit ( "p...
def update ( self ) : '''Update our object ' s data'''
self . _json = self . _request ( method = 'GET' , url = self . API ) . _json
def validate ( self , input_parameters , context ) : """Runs all set type transformers / validators against the provided input parameters and returns any errors"""
errors = { } for key , type_handler in self . input_transformations . items ( ) : if self . raise_on_invalid : if key in input_parameters : input_parameters [ key ] = self . initialize_handler ( type_handler , input_parameters [ key ] , context = context ) else : try : if...
def group_by_key_func ( iterable , key_func ) : """Create a dictionary from an iterable such that the keys are the result of evaluating a key function on elements of the iterable and the values are lists of elements all of which correspond to the key . > > > def si ( d ) : return sorted ( d . items ( ) ) > > ...
result = defaultdict ( list ) for item in iterable : result [ key_func ( item ) ] . append ( item ) return result
def read_config ( * args ) : '''Read Traffic Server configuration variable definitions . . . versionadded : : 2016.11.0 . . code - block : : bash salt ' * ' trafficserver . read _ config proxy . config . http . keep _ alive _ post _ out'''
ret = { } if _TRAFFICCTL : cmd = _traffic_ctl ( 'config' , 'get' ) else : cmd = _traffic_line ( '-r' ) try : for arg in args : log . debug ( 'Querying: %s' , arg ) ret [ arg ] = _subprocess ( cmd + [ arg ] ) except KeyError : pass return ret
def end_at ( self , document_fields ) : """End query results at a particular document value . The result set will * * include * * the document specified by ` ` document _ fields ` ` . If the current query already has specified an end cursor - - either via this method or : meth : ` ~ . firestore _ v1beta1 ...
return self . _cursor_helper ( document_fields , before = False , start = False )
def _build ( self , parent_cache ) : """Build the initial cache from the parent . Only include the | MICE | which are unaffected by the subsystem cut . A | MICE | is affected if either the cut splits the mechanism or splits the connections between the purview and mechanism"""
for key , mice in parent_cache . cache . items ( ) : if not mice . damaged_by_cut ( self . subsystem ) : self . cache [ key ] = mice
def login_user ( server , login , password ) : """Get the login session . : param server : The Geonode server URL . : type server : basestring : param login : The login to use on Geonode . : type login : basestring : param password : The password to use on Geonode . : type password : basestring"""
login_url = urljoin ( server , login_url_prefix ) # Start the web session session = requests . session ( ) result = session . get ( login_url ) # Check if the request ok if not result . ok : message = ( tr ( 'Request failed to {geonode_url}, got status code {status_code} ' 'and reason {request_reason}' ) . format (...
def match_arr_lengths ( l ) : """Check that all the array lengths match so that a DataFrame can be created successfully . : param list l : Nested arrays : return bool : Valid or invalid"""
try : # length of first list . use as basis to check other list lengths against . inner_len = len ( l [ 0 ] ) # check each nested list for i in l : # if the length doesn ' t match the first list , then don ' t proceed . if len ( i ) != inner_len : return False except IndexError : # could...
def _is_en_passant_valid ( self , opponent_pawn_location , position ) : """Finds if their opponent ' s pawn is next to this pawn : rtype : bool"""
try : pawn = position . piece_at_square ( opponent_pawn_location ) return pawn is not None and isinstance ( pawn , Pawn ) and pawn . color != self . color and position . piece_at_square ( opponent_pawn_location ) . just_moved_two_steps except IndexError : return False
def namedb_namespace_insert ( cur , input_namespace_rec ) : """Add a namespace to the database , if it doesn ' t exist already . It must be a * revealed * namespace , not a ready namespace ( to mark a namespace as ready , you should use the namedb _ apply _ operation ( ) method ) ."""
namespace_rec = copy . deepcopy ( input_namespace_rec ) namedb_namespace_fields_check ( namespace_rec ) try : query , values = namedb_insert_prepare ( cur , namespace_rec , "namespaces" ) except Exception , e : log . exception ( e ) log . error ( "FATAL: Failed to insert revealed namespace '%s'" % namespace...
def build ( ctx , max_revisions , targets , operators , archiver ) : """Build the wily cache ."""
config = ctx . obj [ "CONFIG" ] from wily . commands . build import build if max_revisions : logger . debug ( f"Fixing revisions to {max_revisions}" ) config . max_revisions = max_revisions if operators : logger . debug ( f"Fixing operators to {operators}" ) config . operators = operators . strip ( ) . ...
def list_items ( queue ) : '''List contents of a queue'''
itemstuple = _list_items ( queue ) items = [ item [ 0 ] for item in itemstuple ] return items
def parse_fastp_log ( self , f ) : """Parse the JSON output from fastp and save the summary statistics"""
try : parsed_json = json . load ( f [ 'f' ] ) except : log . warn ( "Could not parse fastp JSON: '{}'" . format ( f [ 'fn' ] ) ) return None # Fetch a sample name from the command s_name = f [ 's_name' ] cmd = parsed_json [ 'command' ] . split ( ) for i , v in enumerate ( cmd ) : if v == '-i' : ...
def transpose ( self , * axes ) : """Permute the dimensions of a Timeseries ."""
if self . ndim <= 1 : return self ar = np . asarray ( self ) . transpose ( * axes ) if axes [ 0 ] != 0 : # then axis 0 is unaffected by the transposition newlabels = [ self . labels [ ax ] for ax in axes ] return Timeseries ( ar , self . tspan , newlabels ) else : return ar
def init_app ( self , app , ** kwargs ) : """Initialize application object . : param app : An instance of : class : ` ~ flask . Flask ` ."""
self . init_config ( app ) # Initialize extensions self . menu_ext . init_app ( app ) self . menu = app . extensions [ 'menu' ] self . breadcrumbs . init_app ( app ) # Register blueprint in order to register template and static folder . app . register_blueprint ( Blueprint ( 'invenio_theme' , __name__ , template_folder...
def write_ndef ( self , ndef , slot = 1 ) : """Write an NDEF tag configuration to the YubiKey NEO ."""
if not self . capabilities . have_nfc_ndef ( slot ) : raise yubikey_base . YubiKeyVersionError ( "NDEF slot %i unsupported in %s" % ( slot , self ) ) return self . _device . _write_config ( ndef , _NDEF_SLOTS [ slot ] )
def pdb_downloader_and_metadata ( self , outdir = None , pdb_file_type = None , force_rerun = False ) : """Download ALL mapped experimental structures to the protein structures directory . Args : outdir ( str ) : Path to output directory , if protein structures directory not set or other output directory is d...
if not outdir : outdir = self . structure_dir if not outdir : raise ValueError ( 'Output directory must be specified' ) if not pdb_file_type : pdb_file_type = self . pdb_file_type # Check if we have any PDBs if self . num_structures_experimental == 0 : log . debug ( '{}: no structures available ...
def _escape ( self , bits ) : """value : ' foobar { ' - > ' foobar { { ' value : ' x } ' - > ' x } } '"""
# for value , field _ name , format _ spec , conversion in bits : while True : try : value , field_name , format_spec , conversion = next ( bits ) if value : end = value [ - 1 ] if end in ( u'{' , u'}' ) : value += end yield value , field_name , format...
def setup_logging ( app , disable_existing_loggers = True ) : """Setup the logging using logging . yaml . : param app : The app which setups the logging . Used for the log ' s filename and for the log ' s name . : type app : str : param disable _ existing _ loggers : If False , loggers which exist when this c...
conf = yaml . load ( open ( os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , 'logging.yaml' ) , 'r' ) ) conf [ 'disable_existing_loggers' ] = disable_existing_loggers conf [ 'loggers' ] [ app ] = conf [ 'loggers' ] . pop ( '__name__' ) logging . config . dictConfig ( conf )
def removeRnaQuantificationSet ( self ) : """Removes an rnaQuantificationSet from this repo"""
self . _openRepo ( ) dataset = self . _repo . getDatasetByName ( self . _args . datasetName ) rnaQuantSet = dataset . getRnaQuantificationSetByName ( self . _args . rnaQuantificationSetName ) def func ( ) : self . _updateRepo ( self . _repo . removeRnaQuantificationSet , rnaQuantSet ) self . _confirmDelete ( "RnaQu...
def procrustes ( a , b , reflection = True , translation = True , scale = True , return_cost = True ) : """Perform Procrustes ' analysis subject to constraints . Finds the transformation T mapping a to b which minimizes the square sum distances between Ta and b , also called the cost . Parameters a : ( n , ...
a = np . asanyarray ( a , dtype = np . float64 ) b = np . asanyarray ( b , dtype = np . float64 ) if not util . is_shape ( a , ( - 1 , 3 ) ) or not util . is_shape ( b , ( - 1 , 3 ) ) : raise ValueError ( 'points must be (n,3)!' ) if len ( a ) != len ( b ) : raise ValueError ( 'a and b must contain same number ...
def fetch_starting_at_coord ( self , coord ) : # b2 = BAMFile ( self . path , blockStart = coord [ 0 ] , innerStart = coord [ 1 ] , index _ obj = self . index , reference = self . _ reference ) """starting at a certain coordinate was supposed to make output . . warning : : creates a new instance of a BAMFile obje...
b2 = BAMFile ( self . path , BAMFile . Options ( blockStart = coord [ 0 ] , innerStart = coord [ 1 ] , reference = self . reference ) ) return b2