signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def handle ( self , error , connection ) : """Handle any cleanup or similar activity related to an error occurring on a pooled connection ."""
error_class = error . __class__ if error_class in ( ConnectionExpired , ServiceUnavailable , DatabaseUnavailableError ) : self . deactivate ( connection . address ) elif error_class in ( NotALeaderError , ForbiddenOnReadOnlyDatabaseError ) : self . remove_writer ( connection . address )
def refresh_hrefs ( self , request ) : """Refresh all the cached menu item HREFs in the database ."""
for item in treenav . MenuItem . objects . all ( ) : item . save ( ) # refreshes the HREF self . message_user ( request , _ ( 'Menu item HREFs refreshed successfully.' ) ) info = self . model . _meta . app_label , self . model . _meta . model_name changelist_url = reverse ( 'admin:%s_%s_changelist' % info , cur...
def values ( self ) : """Returns a list of all values in the dictionary . Returns : list of str : [ value1 , value2 , . . . , valueN ]"""
all_values = [ v . decode ( 'utf-8' ) for k , v in self . rdb . hgetall ( self . session_hash ) . items ( ) ] return all_values
def clean ( self , value ) : """Clean Goes through each of the values in the list , cleans it , stores it , and returns a new list Arguments : value { list } - - The value to clean Returns : list"""
# If the value is None and it ' s optional , return as is if value is None and self . _optional : return None # If the value is not a list if not isinstance ( value , list ) : raise ValueError ( 'value' ) # Recurse and return it return [ self . _node . clean ( m ) for m in value ]
def cone ( cls , ** kwargs ) : """Returns a cone . Kwargs : start ( list ) : Start of cone , default [ 0 , - 1 , 0 ] . end ( list ) : End of cone , default [ 0 , 1 , 0 ] . radius ( float ) : Maximum radius of cone at start , default 1.0. slices ( int ) : Number of slices , default 16."""
s = kwargs . get ( 'start' , Vector ( 0.0 , - 1.0 , 0.0 ) ) e = kwargs . get ( 'end' , Vector ( 0.0 , 1.0 , 0.0 ) ) if isinstance ( s , list ) : s = Vector ( * s ) if isinstance ( e , list ) : e = Vector ( * e ) r = kwargs . get ( 'radius' , 1.0 ) slices = kwargs . get ( 'slices' , 16 ) ray = e . minus ( s ) ax...
def changed ( self , filename = '.md5' , glob = None ) : """Are any of the files matched by ` ` glob ` ` changed ?"""
if glob is not None : filename += '.glob-' + '' . join ( ch . lower ( ) for ch in glob if ch . isalpha ( ) ) return changed ( self , filename , glob = glob )
def later_than ( after , before ) : """True if then is later or equal to that"""
if isinstance ( after , str ) : after = str_to_time ( after ) elif isinstance ( after , int ) : after = time . gmtime ( after ) if isinstance ( before , str ) : before = str_to_time ( before ) elif isinstance ( before , int ) : before = time . gmtime ( before ) return after >= before
def _hash ( self , iv , value ) : """Generate and hmac signature for this encrypted data : param key : : param iv : : param value : : return string :"""
return hmac . new ( self . key , msg = iv + value , digestmod = hashlib . sha256 ) . hexdigest ( )
def get_protein_id_list ( df , level = 0 ) : """Return a complete list of shortform IDs from a DataFrame Extract all protein IDs from a dataframe from multiple rows containing protein IDs in MaxQuant output format : e . g . P07830 ; P63267 ; Q54A44 ; P63268 Long names ( containing species information ) are el...
protein_list = [ ] for s in df . index . get_level_values ( level ) : protein_list . extend ( get_protein_ids ( s ) ) return list ( set ( protein_list ) )
def _push_tag_buffer ( self , data ) : """Write a pending tag attribute from * data * to the stack ."""
if data . context & data . CX_QUOTED : self . _emit_first ( tokens . TagAttrQuote ( char = data . quoter ) ) self . _emit_all ( self . _pop ( ) ) buf = data . padding_buffer self . _emit_first ( tokens . TagAttrStart ( pad_first = buf [ "first" ] , pad_before_eq = buf [ "before_eq" ] , pad_after_eq = buf [ "aft...
def restore ( self ) : """Copy files from the backup folder to the sym - linked optimizer folder ."""
if os . path . exists ( self . backup_path ) : for file in glob . glob ( self . backup_path + "/*" ) : shutil . copy ( file , self . path )
def parameters ( self ) : """A property that returns all of the model ' s parameters ."""
parameters = [ ] for hl in self . hidden_layers : parameters . extend ( hl . parameters ) parameters . extend ( self . top_layer . parameters ) return parameters
def add_typeattr ( typeattr , ** kwargs ) : """Add an typeattr to an existing type ."""
tmpltype = get_templatetype ( typeattr . type_id , user_id = kwargs . get ( 'user_id' ) ) ta = _set_typeattr ( typeattr ) tmpltype . typeattrs . append ( ta ) db . DBSession . flush ( ) return ta
def plot_aqhist ( samples , file_type , ** plot_args ) : """Create line graph plot of histogram data for BBMap ' aqhist ' output . The ' samples ' parameter could be from the bbmap mod _ data dictionary : samples = bbmap . MultiqcModule . mod _ data [ file _ type ]"""
sumy = sum ( [ int ( samples [ sample ] [ 'data' ] [ x ] [ 0 ] ) for sample in samples for x in samples [ sample ] [ 'data' ] ] ) cutoff = sumy * 0.999 all_x = set ( ) for item in sorted ( chain ( * [ samples [ sample ] [ 'data' ] . items ( ) for sample in samples ] ) ) : all_x . add ( item [ 0 ] ) cutoff -= it...
def _get_response ( self , method , endpoint , data = None ) : """Helper method for wrapping API requests , mainly for catching errors in one place . : param method : valid HTTP method : type method : str : param endpoint : API endpoint : type endpoint : str : param data : extra parameters passed with t...
url = urljoin ( IVONA_REGION_ENDPOINTS [ self . region ] , endpoint ) response = getattr ( self . session , method ) ( url , json = data , ) if 'x-amzn-ErrorType' in response . headers : raise IvonaAPIException ( response . headers [ 'x-amzn-ErrorType' ] ) if response . status_code != requests . codes . ok : ra...
def match_window ( in_data , offset ) : '''Find the longest match for the string starting at offset in the preceeding data'''
window_start = max ( offset - WINDOW_MASK , 0 ) for n in range ( MAX_LEN , THRESHOLD - 1 , - 1 ) : window_end = min ( offset + n , len ( in_data ) ) # we ' ve not got enough data left for a meaningful result if window_end - offset < THRESHOLD : return None str_to_find = in_data [ offset : window...
def _read_config ( self ) : """Read the configuration from the various places it may be read from . : rtype : str : raises : ValueError"""
if not self . _file_path : return None elif self . _file_path . startswith ( 's3://' ) : return self . _read_s3_config ( ) elif self . _file_path . startswith ( 'http://' ) or self . _file_path . startswith ( 'https://' ) : return self . _read_remote_config ( ) elif not path . exists ( self . _file_path ) :...
async def addNodes ( self , nodes ) : '''Add a list of packed nodes to the cortex . Args : nodes ( list ) : [ ( ( form , valu ) , { ' props ' : { } , ' tags ' : { } } ) , . . . ] Yields : ( tuple ) : Packed node tuples ( ( form , valu ) , { ' props ' : { } , ' tags ' : { } } )'''
# First check that that user may add each form done = { } for node in nodes : formname = node [ 0 ] [ 0 ] if done . get ( formname ) : continue self . _reqUserAllowed ( 'node:add' , formname ) done [ formname ] = True async with await self . cell . snap ( user = self . user ) as snap : with ...
def _compute_dk_dtau ( self , tau , n ) : r"""Evaluate : math : ` dk / d \ tau ` at the specified locations with the specified derivatives . Parameters tau : : py : class : ` Matrix ` , ( ` M ` , ` D ` ) ` M ` inputs with dimension ` D ` . n : : py : class : ` Array ` , ( ` D ` , ) Degree of derivative wi...
# Construct the derivative pattern : # For each dimension , this will contain the index of the dimension # repeated a number of times equal to the order of derivative with # respect to that dimension . # Example : For d ^ 3 k ( x , y , z ) / dx ^ 2 dy , n would be [ 2 , 1 , 0 ] and # deriv _ pattern should be [ 0 , 0 ,...
def _postprocess_hover ( self , renderer , source ) : """Limit hover tool to annular wedges only ."""
if isinstance ( renderer . glyph , AnnularWedge ) : super ( RadialHeatMapPlot , self ) . _postprocess_hover ( renderer , source )
def __objecthasfields ( bunchdt , data , commdct , idfobject , places = 7 , ** kwargs ) : """test if the idf object has the field values in kwargs"""
for key , value in list ( kwargs . items ( ) ) : if not isfieldvalue ( bunchdt , data , commdct , idfobject , key , value , places = places ) : return False return True
def make_market ( self , crypto , fiat , seperator = "_" ) : """Convert a crypto and fiat to a " market " string . All exchanges use their own format for specifying markets . Subclasses can define their own implementation ."""
return ( "%s%s%s" % ( self . fix_symbol ( crypto ) , seperator , self . fix_symbol ( fiat ) ) ) . lower ( )
def get_default_config ( self ) : """Returns the default collector settings"""
config = super ( NetworkCollector , self ) . get_default_config ( ) config . update ( { 'path' : 'network' , 'interfaces' : [ 'eth' , 'bond' , 'em' , 'p1p' , 'eno' , 'enp' , 'ens' , 'enx' ] , 'byte_unit' : [ 'bit' , 'byte' ] , 'greedy' : 'true' , } ) return config
def rmi ( self , force = False , via_name = False ) : """remove this image : param force : bool , force removal of the image : param via _ name : bool , refer to the image via name , if false , refer via ID , not used now : return : None"""
return os . remove ( self . local_location )
def login ( ctx ) : """Add an API key ( saved in ~ / . onecodex )"""
base_url = os . environ . get ( "ONE_CODEX_API_BASE" , "https://app.onecodex.com" ) if not ctx . obj [ "API_KEY" ] : _login ( base_url ) else : email = _login ( base_url , api_key = ctx . obj [ "API_KEY" ] ) ocx = Api ( api_key = ctx . obj [ "API_KEY" ] , telemetry = ctx . obj [ "TELEMETRY" ] ) # TODO :...
def solar_noon_utc ( self , date , longitude ) : """Calculate solar noon time in the UTC timezone . : param date : Date to calculate for . : type date : : class : ` datetime . date ` : param longitude : Longitude - Eastern longitudes should be positive : type longitude : float : return : The UTC date and ...
jc = self . _jday_to_jcentury ( self . _julianday ( date ) ) eqtime = self . _eq_of_time ( jc ) timeUTC = ( 720.0 - ( 4 * longitude ) - eqtime ) / 60.0 hour = int ( timeUTC ) minute = int ( ( timeUTC - hour ) * 60 ) second = int ( ( ( ( timeUTC - hour ) * 60 ) - minute ) * 60 ) if second > 59 : second -= 60 min...
def _lookup ( self , p , directory , fsclass , create = 1 ) : """The generic entry point for Node lookup with user - supplied data . This translates arbitrary input into a canonical Node . FS object of the specified fsclass . The general approach for strings is to turn it into a fully normalized absolute path...
if isinstance ( p , Base ) : # It ' s already a Node . FS object . Make sure it ' s the right # class and return . p . must_be_same ( fsclass ) return p # str ( p ) in case it ' s something like a proxy object p = str ( p ) if not os_sep_is_slash : p = p . replace ( OS_SEP , '/' ) if p [ 0 : 1 ] == '#' : # ...
def load_clubs ( self ) : """Fetches the MAL character clubs page and sets the current character ' s clubs attributes . : rtype : : class : ` . Character ` : return : Current character object ."""
character = self . session . session . get ( u'http://myanimelist.net/character/' + str ( self . id ) + u'/' + utilities . urlencode ( self . name ) + u'/clubs' ) . text self . set ( self . parse_clubs ( utilities . get_clean_dom ( character ) ) ) return self
async def _send_sleep ( self , request : Request , stack : Stack ) : """Sleep for the amount of time specified in the Sleep layer"""
duration = stack . get_layer ( lyr . Sleep ) . duration await sleep ( duration )
def copy_path_to_clipboard ( self ) : """Copies the file path to the clipboard"""
path = self . get_current_path ( ) QtWidgets . QApplication . clipboard ( ) . setText ( path ) debug ( 'path copied: %s' % path )
def activate ( request , activation_key , template_name = 'userena/activate_fail.html' , retry_template_name = 'userena/activate_retry.html' , success_url = None , extra_context = None ) : """Activate a user with an activation key . The key is a SHA1 string . When the SHA1 is found with an : class : ` UserenaSi...
try : if ( not UserenaSignup . objects . check_expired_activation ( activation_key ) or not userena_settings . USERENA_ACTIVATION_RETRY ) : user = UserenaSignup . objects . activate_user ( activation_key ) if user : # Sign the user in . auth_user = authenticate ( identification = user . ...
def open ( self , filepath , mode = 'w+b' ) : """Opens a file - will actually return a temporary file but replace the original file when the context is closed ."""
# Check if the filepath can be accessed and is writable before creating # the tempfile if not _isFileAccessible ( filepath ) : raise IOError ( 'File %s is not writable' % ( filepath , ) ) if filepath in self . _files : with open ( self . _files [ filepath ] , mode = mode ) as tmpf : yield tmpf else : ...
def agedepth ( self , d ) : """Get calendar age for a depth Parameters d : float Sediment depth ( in cm ) . Returns Numeric giving true age at given depth ."""
# TODO ( brews ) : Function cannot handle hiatus # See lines 77 - 100 of hist2 . cpp x = self . mcmcfit . sediment_rate theta0 = self . mcmcfit . headage # Age abscissa ( in yrs ) . If array , dimension should be iterations or realizations of the sediment deltac = self . thick c0 = min ( self . depth ) # Uniform depth ...
def separation ( sources , fs = 22050 , labels = None , alpha = 0.75 , ax = None , ** kwargs ) : '''Source - separation visualization Parameters sources : np . ndarray , shape = ( nsrc , nsampl ) A list of waveform buffers corresponding to each source fs : number > 0 The sampling rate labels : list of s...
# Get the axes handle ax , new_axes = __get_axes ( ax = ax ) # Make sure we have at least two dimensions sources = np . atleast_2d ( sources ) if labels is None : labels = [ 'Source {:d}' . format ( _ ) for _ in range ( len ( sources ) ) ] kwargs . setdefault ( 'scaling' , 'spectrum' ) # The cumulative spectrogram ...
def make_workspace ( measurement , channel = None , name = None , silence = False ) : """Create a workspace containing the model for a measurement If ` channel ` is None then include all channels in the model If ` silence ` is True , then silence HistFactory ' s output on stdout and stderr ."""
context = silence_sout_serr if silence else do_nothing with context ( ) : hist2workspace = ROOT . RooStats . HistFactory . HistoToWorkspaceFactoryFast ( measurement ) if channel is not None : workspace = hist2workspace . MakeSingleChannelModel ( measurement , channel ) else : workspace = his...
def convex_hull ( self ) : """Find the Convex Hull of the internal set of x , y points . Returns bnodes : array of ints indices corresponding to points on the convex hull"""
bnodes , nb , na , nt = _tripack . bnodes ( self . lst , self . lptr , self . lend , self . npoints ) return self . _deshuffle_simplices ( bnodes [ : nb ] - 1 )
def initnew ( self , fname ) : """Use the current IDD and create a new empty IDF . If the IDD has not yet been initialised then this is done first . Parameters fname : str , optional Path to an IDF . This does not need to be set at this point ."""
iddfhandle = StringIO ( iddcurrent . iddtxt ) if self . getiddname ( ) == None : self . setiddname ( iddfhandle ) idfhandle = StringIO ( '' ) self . idfname = idfhandle self . read ( ) if fname : self . idfname = fname
def sign_jwt ( data , secret_key , expires_in , salt = None , ** kw ) : """To create a signed JWT : param data : : param secret _ key : : param expires _ in : : param salt : : param kw : : return : string"""
s = itsdangerous . TimedJSONWebSignatureSerializer ( secret_key = secret_key , expires_in = expires_in , salt = salt , ** kw ) return s . dumps ( data )
def integratedAutocorrelationTime ( A_n , B_n = None , fast = False , mintime = 3 ) : """Estimate the integrated autocorrelation time . See Also statisticalInefficiency"""
g = statisticalInefficiency ( A_n , B_n , fast , mintime ) tau = ( g - 1.0 ) / 2.0 return tau
def after_epoch ( self , epoch_id : int , epoch_data : EpochData ) : """Check termination conditions . : param epoch _ id : number of the processed epoch : param epoch _ data : epoch data to be checked : raise KeyError : if the stream of variable was not found in ` ` epoch _ data ` ` : raise TypeError : if ...
if self . _stream not in epoch_data : raise KeyError ( 'The hook could not determine whether the threshold was exceeded as the stream `{}`' 'was not found in the epoch data' . format ( self . _stream ) ) if self . _variable not in epoch_data [ self . _stream ] : raise KeyError ( 'The hook could not determine wh...
def random_words_string ( count = 1 , maxchars = None , sep = '' ) : """Gets a"""
nouns = sep . join ( [ random_word ( ) for x in xrange ( 0 , count ) ] ) if maxchars is not None and nouns > maxchars : nouns = nouns [ 0 : maxchars - 1 ] return nouns
def identify ( self , geometry , mapExtent , imageDisplay , tolerance , geometryType = "esriGeometryPoint" , sr = None , layerDefs = None , time = None , layerTimeOptions = None , layers = "top" , returnGeometry = True , maxAllowableOffset = None , geometryPrecision = None , dynamicLayers = None , returnZ = False , ret...
params = { 'f' : 'json' , 'geometry' : geometry , 'geometryType' : geometryType , 'tolerance' : tolerance , 'mapExtent' : mapExtent , 'imageDisplay' : imageDisplay } if layerDefs is not None : params [ 'layerDefs' ] = layerDefs if layers is not None : params [ 'layers' ] = layers if sr is not None : params ...
def _resolve_deps ( self , depmap ) : """Given a map of gen - key = > target specs , resolves the target specs into references ."""
deps = defaultdict ( lambda : OrderedSet ( ) ) for category , depspecs in depmap . items ( ) : dependencies = deps [ category ] for depspec in depspecs : dep_address = Address . parse ( depspec ) try : self . context . build_graph . maybe_inject_address_closure ( dep_address ) ...
def boolean ( name , value , persist = False ) : '''Set up an SELinux boolean name The name of the boolean to set value The value to set on the boolean persist Defaults to False , set persist to true to make the boolean apply on a reboot'''
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } bools = __salt__ [ 'selinux.list_sebool' ] ( ) if name not in bools : ret [ 'comment' ] = 'Boolean {0} is not available' . format ( name ) ret [ 'result' ] = False return ret rvalue = _refine_value ( value ) if rvalue is None : ...
def save ( self ) : """Save current state of config dictionary ."""
with open ( self . config_file , "w" ) as f : f . write ( dump ( self . config , default_flow_style = False ) )
def run_checked ( cmd , ret_ok = ( 0 , ) , ** kwargs ) : """Run command and raise PatoolError on error ."""
retcode = run ( cmd , ** kwargs ) if retcode not in ret_ok : msg = "Command `%s' returned non-zero exit status %d" % ( cmd , retcode ) raise PatoolError ( msg ) return retcode
def commit ( cls , client = None ) : """Commit everything from datapoints via the client . : param client : InfluxDBClient instance for writing points to InfluxDB . : attention : any provided client will supersede the class client . : return : result of client . write _ points ."""
if not client : client = cls . _client rtn = client . write_points ( cls . _json_body_ ( ) ) cls . _reset_ ( ) return rtn
def get_gateway_id ( self ) : """Return a unique id for the gateway ."""
host , _ = self . server_address try : ip_address = ipaddress . ip_address ( host ) except ValueError : # Only hosts using ip address supports unique id . return None if ip_address . version == 6 : mac = get_mac_address ( ip6 = host ) else : mac = get_mac_address ( ip = host ) return mac
def generate_report ( self , output_file ) : """See base class . output _ file must be a file handler that takes in bytes !"""
if self . TEMPLATE_NAME is not None : template = TEMPLATE_ENV . get_template ( self . TEMPLATE_NAME ) report = template . render ( self . _context ( ) ) if isinstance ( report , six . string_types ) : report = report . encode ( 'utf-8' ) output_file . write ( report )
def format ( sql , args = None ) : """Resolve variable references in a query within an environment . This computes and resolves the transitive dependencies in the query and raises an exception if that fails due to either undefined or circular references . Args : sql : query to format . args : a dictionary...
resolved_vars = { } code = [ ] SqlStatement . _find_recursive_dependencies ( sql , args , code = code , resolved_vars = resolved_vars ) # Rebuild the SQL string , substituting just ' $ ' for escaped $ occurrences , # variable references substituted with their values , or literal text copied # over as - is . parts = [ ]...
def clear ( self ) : """Clears all the container for this query widget ."""
for i in range ( self . count ( ) ) : widget = self . widget ( i ) if widget is not None : widget . close ( ) widget . setParent ( None ) widget . deleteLater ( )
def save_data ( self , filename = None ) : """Save data"""
if filename is None : filename = self . filename if filename is None : filename = getcwd_or_home ( ) filename , _selfilter = getsavefilename ( self , _ ( "Save data" ) , filename , iofunctions . save_filters ) if filename : self . filename = filename else : return False QAppl...
def export_to_pypsa ( self , session , method = 'onthefly' ) : """Exports MVGridDing0 grid to PyPSA database tables Peculiarities of MV grids are implemented here . Derive general export method from this and adapt to needs of LVGridDing0 Parameters session : : sqlalchemy : ` SQLAlchemy session object < orm ...
# definitions for temp _ resolution table temp_id = 1 timesteps = 2 start_time = datetime ( 1970 , 1 , 1 , 00 , 00 , 0 ) resolution = 'H' nodes = self . _graph . nodes ( ) edges = [ edge for edge in list ( self . graph_edges ( ) ) if ( edge [ 'adj_nodes' ] [ 0 ] in nodes and not isinstance ( edge [ 'adj_nodes' ] [ 0 ] ...
def set_max_attempts ( self , value ) : """stub"""
if value is None : raise InvalidArgument ( 'value must be an integer' ) if value is not None and not isinstance ( value , int ) : raise InvalidArgument ( 'value is not an integer' ) if not self . my_osid_object_form . _is_valid_integer ( value , self . get_max_attempts_metadata ( ) ) : raise InvalidArgument...
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'id' ) and self . id is not None : _dict [ 'id' ] = self . id return _dict
def _ordered_iterator ( self ) : """Interleave the values of each QuerySet in order to handle the requested ordering . Also adds the ' # ' property to each returned item ."""
# A list of tuples , each with : # * The iterable # * The QuerySet number # * The next value # ( Remember that each QuerySet is already sorted . ) iterables = [ ] for i , qs in zip ( self . _queryset_idxs , self . _querysets ) : it = iter ( qs ) try : value = next ( it ) except StopIteration : # If ...
def submit ( ctx_name , parent_id , name , url , func , * args , ** kwargs ) : """Submit through a context Parameters ctx _ name : str The name of the context to submit through parent _ id : str The ID of the group that the job is a part of . name : str The name of the job url : str The handler th...
if isinstance ( ctx_name , Context ) : ctx = ctx_name else : ctx = ctxs . get ( ctx_name , ctxs [ ctx_default ] ) return _submit ( ctx , parent_id , name , url , func , * args , ** kwargs )
def feed ( self , json_item ) : '''Feeds a json item into the Kafka topic @ param json _ item : The loaded json object'''
@ MethodTimer . timeout ( self . settings [ 'KAFKA_FEED_TIMEOUT' ] , False ) def _feed ( json_item ) : producer = self . _create_producer ( ) topic = self . settings [ 'KAFKA_INCOMING_TOPIC' ] if not self . logger . json : self . logger . info ( 'Feeding JSON into {0}\n{1}' . format ( topic , json ....
def get_level_value ( level ) : """Returns the logging value associated with a particular level name . The argument must be present in LEVELS _ DICT or be an integer constant . Otherwise None will be returned ."""
try : # integral constants also work : they are the level value return int ( level ) except ValueError : try : return LEVELS_DICT [ level . upper ( ) ] except KeyError : logging . warning ( "level '%s' cannot be translated to a level value (not present in LEVELS_DICT)" % level ) retu...
def validate ( self , r ) : '''Called automatically by self . result .'''
if self . show_invalid : r . valid = True elif r . valid : if not r . description : r . valid = False if r . size and ( r . size + r . offset ) > r . file . size : r . valid = False if r . jump and ( r . jump + r . offset ) > r . file . size : r . valid = False if hasattr ( r...
def greenkhorn ( a , b , M , reg , numItermax = 10000 , stopThr = 1e-9 , verbose = False , log = False ) : """Solve the entropic regularization optimal transport problem and return the OT matrix The algorithm used is based on the paper Near - linear time approximation algorithms for optimal transport via Sinkho...
a = np . asarray ( a , dtype = np . float64 ) b = np . asarray ( b , dtype = np . float64 ) M = np . asarray ( M , dtype = np . float64 ) if len ( a ) == 0 : a = np . ones ( ( M . shape [ 0 ] , ) , dtype = np . float64 ) / M . shape [ 0 ] if len ( b ) == 0 : b = np . ones ( ( M . shape [ 1 ] , ) , dtype = np . ...
def find_sparse_mode ( self , core , additional , scaling , weights = { } ) : """Find a sparse mode containing reactions of the core subset . Return an iterator of the support of a sparse mode that contains as many reactions from core as possible , and as few reactions from additional as possible ( approximat...
if len ( core ) == 0 : return self . lp7 ( core ) k = set ( ) for reaction_id in core : flux = self . get_flux ( reaction_id ) if self . is_flipped ( reaction_id ) : flux *= - 1 if flux >= self . _epsilon : k . add ( reaction_id ) if len ( k ) == 0 : return self . lp10 ( k , addition...
def construct_blastn_cmdline ( fname1 , fname2 , outdir , blastn_exe = pyani_config . BLASTN_DEFAULT ) : """Returns a single blastn command . - filename - input filename - blastn _ exe - path to BLASTN executable"""
fstem1 = os . path . splitext ( os . path . split ( fname1 ) [ - 1 ] ) [ 0 ] fstem2 = os . path . splitext ( os . path . split ( fname2 ) [ - 1 ] ) [ 0 ] fstem1 = fstem1 . replace ( "-fragments" , "" ) prefix = os . path . join ( outdir , "%s_vs_%s" % ( fstem1 , fstem2 ) ) cmd = ( "{0} -out {1}.blast_tab -query {2} -db...
def ID_SDR_all_available ( SDR ) : """Return an array of inner diameters with a given SDR . IDs available are those commonly used based on the ' Used ' column in the pipedb ."""
ID = [ ] ND = ND_all_available ( ) for i in range ( len ( ND ) ) : ID . append ( ID_SDR ( ND [ i ] , SDR ) . magnitude ) return ID * u . inch
def collect_gaps ( blast , use_subject = False ) : """Collect the gaps between adjacent HSPs in the BLAST file ."""
key = lambda x : x . sstart if use_subject else x . qstart blast . sort ( key = key ) for a , b in zip ( blast , blast [ 1 : ] ) : if use_subject : if a . sstop < b . sstart : yield b . sstart - a . sstop else : if a . qstop < b . qstart : yield b . qstart - a . qstop
def gpg_version ( ) : """Returns the GPG version"""
cmd = flatten ( [ gnupg_bin ( ) , "--version" ] ) output = stderr_output ( cmd ) output = output . split ( '\n' ) [ 0 ] . split ( " " ) [ 2 ] . split ( '.' ) return tuple ( [ int ( x ) for x in output ] )
def countok ( self ) : """Boolean array showing which stars pass all count constraints . A " count constraint " is a constraint that affects the number of stars ."""
ok = np . ones ( len ( self . stars ) ) . astype ( bool ) for name in self . constraints : c = self . constraints [ name ] if c . name not in self . selectfrac_skip : ok &= c . ok return ok
def has_access_api ( f ) : """Use this decorator to enable granular security permissions to your API methods . Permissions will be associated to a role , and roles are associated to users . By default the permission ' s name is the methods name . this will return a message and HTTP 401 is case of unauthorized...
if hasattr ( f , '_permission_name' ) : permission_str = f . _permission_name else : permission_str = f . __name__ def wraps ( self , * args , ** kwargs ) : permission_str = PERMISSION_PREFIX + f . _permission_name if self . appbuilder . sm . has_access ( permission_str , self . __class__ . __name__ ) :...
def _set_extent ( ax , projection , extent , extrema ) : """Sets the plot extent . Parameters ax : cartopy . GeoAxesSubplot instance The axis whose boundaries are being tweaked . projection : None or geoplot . crs instance The projection , if one is being used . extent : None or ( xmin , xmax , ymin , y...
if extent : xmin , xmax , ymin , ymax = extent xmin , xmax , ymin , ymax = max ( xmin , - 180 ) , min ( xmax , 180 ) , max ( ymin , - 90 ) , min ( ymax , 90 ) if projection : # Input ` ` extent ` ` into set _ extent ( ) . ax . set_extent ( ( xmin , xmax , ymin , ymax ) , crs = ccrs . PlateCarree ( )...
def load_shapefile ( self , feature_type , base_path ) : """Load downloaded shape file to QGIS Main Window . TODO : This is cut & paste from OSM - refactor to have one method : param feature _ type : What kind of features should be downloaded . Currently ' buildings ' , ' building - points ' or ' roads ' are ...
path = '%s.shp' % base_path if not os . path . exists ( path ) : message = self . tr ( '%s does not exist. The server does not have any data for ' 'this extent.' % path ) raise FileMissingError ( message ) self . iface . addVectorLayer ( path , feature_type , 'ogr' )
def convertforoutput ( self , outputfile ) : """Convert from one of the source formats into target format . Relevant if converters are used in OutputTemplates . Sourcefile is a CLAMOutputFile instance ."""
assert isinstance ( outputfile , CLAMOutputFile ) # metadata of the destination file ( file to be generated here ) if not outputfile . metadata . __class__ in self . acceptforoutput : raise Exception ( "Convertor " + self . __class__ . __name__ + " can not convert input files to " + outputfile . metadata . __class_...
def exists ( self ) : """Returns true if the job is still running or zero - os still knows about this job ID After a job is finished , a job remains on zero - os for max of 5min where you still can read the job result after the 5 min is gone , the job result is no more fetchable : return : bool"""
r = self . _client . _redis flag = '{}:flag' . format ( self . _queue ) return bool ( r . exists ( flag ) )
def write ( content , filename = 'cache' ) : """write data to cache file parameters : cache _ path - path to cache file content - a data structure to save into cache file"""
cache_path = get_cache_path ( filename ) with open ( cache_path , 'w' ) as file : if content is not None : json . dump ( content , file , indent = 3 , sort_keys = True )
def get_markov_blanket ( self , node ) : """Returns a markov blanket for a random variable . In the case of Bayesian Networks , the markov blanket is the set of node ' s parents , its children and its children ' s other parents . Returns list ( blanket _ nodes ) : List of nodes contained in Markov Blanket ...
children = self . get_children ( node ) parents = self . get_parents ( node ) blanket_nodes = children + parents for child_node in children : blanket_nodes . extend ( self . get_parents ( child_node ) ) blanket_nodes = set ( blanket_nodes ) blanket_nodes . remove ( node ) return list ( blanket_nodes )
def get_extended_attrtext ( value ) : """attrtext = 1 * ( any non - ATTRIBUTE _ ENDS character plus ' % ' ) This is a special parsing routine so that we get a value that includes % escapes as a single string ( which we decode as a single string later ) ."""
m = _non_extended_attribute_end_matcher ( value ) if not m : raise errors . HeaderParseError ( "expected extended attrtext but found {!r}" . format ( value ) ) attrtext = m . group ( ) value = value [ len ( attrtext ) : ] attrtext = ValueTerminal ( attrtext , 'extended-attrtext' ) _validate_xtext ( attrtext ) retur...
def get_user ( self , validated_token ) : """Returns a stateless user object which is backed by the given validated token ."""
if api_settings . USER_ID_CLAIM not in validated_token : # The TokenUser class assumes tokens will have a recognizable user # identifier claim . raise InvalidToken ( _ ( 'Token contained no recognizable user identification' ) ) return TokenUser ( validated_token )
def brf ( path , f , t ) : """batch _ rename _ file | 批量重命名文件"""
from . tools . file import batch_rename_file batch_rename_file ( path , f , t )
def _validate_number ( self , input_number , path_to_root , object_title = '' ) : '''a helper method for validating properties of a number : return : input _ number'''
rules_path_to_root = re . sub ( '\[\d+\]' , '[0]' , path_to_root ) input_criteria = self . keyMap [ rules_path_to_root ] error_dict = { 'object_title' : object_title , 'model_schema' : self . schema , 'input_criteria' : input_criteria , 'failed_test' : 'value_datatype' , 'input_path' : path_to_root , 'error_value' : in...
def set_sampling_interval ( self , interval ) : """This method sets the sampling interval for the Firmata loop method : param interval : time in milliseconds : returns : No return value"""
task = asyncio . ensure_future ( self . core . set_sampling_interval ( interval ) ) self . loop . run_until_complete ( task )
def handleMatch ( self , m ) : username = self . unescape ( m . group ( 2 ) ) """Makesure ` username ` is registered and actived ."""
if MARTOR_ENABLE_CONFIGS [ 'mention' ] == 'true' : if username in [ u . username for u in User . objects . exclude ( is_active = False ) ] : url = '{0}{1}/' . format ( MARTOR_MARKDOWN_BASE_MENTION_URL , username ) el = markdown . util . etree . Element ( 'a' ) el . set ( 'href' , url ) ...
def application_id ( self , app_id ) : """Validate request application id matches true application id . Verifying the Application ID matches : https : / / goo . gl / qAdqe4. Args : app _ id : str . Request application _ id . Returns : bool : True if valid , False otherwise ."""
if self . app_id != app_id : warnings . warn ( 'Application ID is invalid.' ) return False return True
def texkeys2marc ( self , key , value ) : """Populate the ` ` 035 ` ` MARC field ."""
result = [ ] values = force_list ( value ) if values : value = values [ 0 ] result . append ( { '9' : 'INSPIRETeX' , 'a' : value , } ) for value in values [ 1 : ] : result . append ( { '9' : 'INSPIRETeX' , 'z' : value , } ) return result
def getgroupurl ( idgroup , * args , ** kwargs ) : """Request Groups URL . If idgroup is set , you ' ll get a response adequate for a MambuGroup object . If not set , you ' ll get a response adequate for a MambuGroups object . See mambugroup module and pydoc for further information . Currently implemented f...
getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "creditOfficerUsername=%s" % kw...
def processEnded ( self , reason ) : """Connected process shut down"""
log_debug ( "{name} process exited" , name = self . name ) if self . deferred : if reason . type == ProcessDone : self . deferred . callback ( reason . value . exitCode ) elif reason . type == ProcessTerminated : self . deferred . errback ( reason ) return self . deferred
def parser_from_buffer ( cls , fp ) : """Construct YamlParser from a file pointer ."""
yaml = YAML ( typ = "safe" ) return cls ( yaml . load ( fp ) )
def render ( self , name , value , attrs = None ) : '''Render the widget as HTML inputs for display on a form . : param name : form field base name : param value : date value : param attrs : - unused : returns : HTML text with three inputs for year / month / day'''
# expects a value in format YYYY - MM - DD or YYYY - MM or YYYY ( or empty / None ) year , month , day = 'YYYY' , 'MM' , 'DD' if value : # use the regular expression to pull out year , month , and day values # if regular expression does not match , inputs will be empty match = W3C_DATE_RE . match ( value ) if m...
def interval_offset_on_transcript ( start , end , transcript ) : """Given an interval [ start : end ] and a particular transcript , return the start offset of the interval relative to the chromosomal positions of the transcript ."""
# ensure that start _ pos : end _ pos overlap with transcript positions if start > end : raise ValueError ( "start_pos %d shouldn't be greater than end_pos %d" % ( start , end ) ) if start > transcript . end : raise ValueError ( "Range %d:%d starts after transcript %s (%d:%d)" % ( start , end , transcript , tra...
def register_to_sys_with_admin_list ( class_inst , admin_list = None , is_normal_admin_needed = False ) : """: param class _ inst : model class : param admin _ list : admin class : param is _ normal _ admin _ needed : is normal admin registration needed : return :"""
if admin_list is None : admin_class = get_valid_admin_class_with_list ( [ ] , class_inst ) else : admin_class = get_valid_admin_class_with_list ( admin_list , class_inst ) if is_normal_admin_needed : register_all_type_of_admin ( admin_class , class_inst ) else : register_admin ( admin_class , class_inst...
def handle_quit ( self , params ) : """Handle the client breaking off the connection with a QUIT command ."""
response = ':%s QUIT :%s' % ( self . client_ident ( ) , params . lstrip ( ':' ) ) # Send quit message to all clients in all channels user is in , and # remove the user from the channels . for channel in self . channels . values ( ) : for client in channel . clients : client . send_queue . append ( response ...
def validate ( self , nonce ) : """Does the nonce exist and is it valid for the request ?"""
if self . debug : print ( "Checking nonce " + str ( nonce ) , file = sys . stderr ) try : opaque , ip , expiretime = self . get ( nonce ) # pylint : disable = unused - variable if expiretime < time . time ( ) : if self . debug : print ( "Nonce expired" , file = sys . stderr ) ...
def release ( self , key , owner ) : """Release lock with given name . ` key ` - lock name ` owner ` - name of application / component / whatever which held a lock Raises ` MongoLockException ` if no such a lock ."""
status = self . collection . find_and_modify ( { '_id' : key , 'owner' : owner } , { 'locked' : False , 'owner' : None , 'created' : None , 'expire' : None } )
def _init_date_range ( self , start_date = None , end_date = None ) : """Set date range defaults if no dates are passed"""
self . end_date = end_date self . start_date = start_date if self . end_date is None : today = now_utc ( ) . date ( ) end_date = self . event . end_dt . date ( ) self . end_date = end_date if end_date < today else today if self . start_date is None : self . start_date = self . end_date - timedelta ( day...
def _opt_to_args ( cls , opt , val ) : """Convert a named option and optional value to command line argument notation , correctly handling options that take no value or that have special representations ( e . g . verify and verbose ) ."""
no_value = ( "alloptions" , "all-logs" , "batch" , "build" , "debug" , "experimental" , "list-plugins" , "list-presets" , "list-profiles" , "noreport" , "quiet" , "verify" ) count = ( "verbose" , ) if opt in no_value : return [ "--%s" % opt ] if opt in count : return [ "--%s" % opt for d in range ( 0 , int ( va...
def fielddefsql_from_fieldspeclist ( self , fieldspeclist : FIELDSPECLIST_TYPE ) -> str : """Returns list of field - defining SQL fragments ."""
return "," . join ( [ self . fielddefsql_from_fieldspec ( x ) for x in fieldspeclist ] )
def find ( self , limit = None , reverse = False , sort = None , exclude = None , duplicates = True , pretty = False , ** filters ) : """Using filters and sorts , this finds all hyperlinks on a web page : param limit : Crop results down to limit specified : param reverse : Reverse the list of links , useful f...
if exclude is None : exclude = [ ] if 'href' not in filters : filters [ 'href' ] = True search = self . _soup . findAll ( 'a' , ** filters ) if reverse : search . reverse ( ) links = [ ] for anchor in search : build_link = anchor . attrs try : build_link [ u'seo' ] = seoify_hyperlink ( ancho...
def validate_port_range ( cls , port_range ) : """Validate port range for Nmap scan"""
ports = port_range . split ( "-" ) if all ( ports ) and int ( ports [ - 1 ] ) <= 65535 and not len ( ports ) != 2 : return True raise ScannerException ( "Invalid port range {}" . format ( port_range ) )
def revoke_token ( self , token , token_type = None ) : """Ask Reddit to revoke the provided token . : param token : The access or refresh token to revoke . : param token _ type : ( Optional ) When provided , hint to Reddit what the token type is for a possible efficiency gain . The value can be either ` ` ...
data = { "token" : token } if token_type is not None : data [ "token_type_hint" ] = token_type url = self . _requestor . reddit_url + const . REVOKE_TOKEN_PATH self . _post ( url , success_status = codes [ "no_content" ] , ** data )
def _create_key ( lang , instance ) : """Crea la clave única de la caché"""
model_name = instance . __class__ . __name__ return "{0}__{1}_{2}" . format ( lang , model_name , instance . id )
def _update_raster_info ( self , ** update_props ) : """Ensures complete removal of raster _ info given the two roots : < spdoinfo > and < spref >"""
xpath_map = self . _data_structures [ update_props [ 'prop' ] ] return [ update_complex ( xpath_root = self . _data_map . get ( '_raster_info_root' ) , xpath_map = xpath_map , ** update_props ) , update_complex ( xpath_root = self . _data_map . get ( '__raster_res_root' ) , xpath_map = xpath_map , ** update_props ) ]
def add_case ( self , case_obj ) : """Add a case obj with individuals to adapter Args : case _ obj ( puzzle . models . Case )"""
for ind_obj in case_obj . individuals : self . _add_individual ( ind_obj ) logger . debug ( "Adding case {0} to plugin" . format ( case_obj . case_id ) ) self . case_objs . append ( case_obj )