signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def terminate ( self ) : """Called when an existing task is removed from the configuration . This sets a Do Not Resuscitate flag and then initiates a stop sequence . Once all processes have stopped , the task will delete itself ."""
log = self . _params . get ( 'log' , self . _discard ) self . _dnr = time . time ( ) self . stop ( ) log . info ( "Task '%s' marked for death" , self . _name )
def reachability_latency ( tnet = None , paths = None , rratio = 1 , calc = 'global' ) : """Reachability latency . This is the r - th longest temporal path . Parameters data : array or dict Can either be a network ( graphlet or contact ) , binary unidrected only . Alternative can be a paths dictionary ( outpu...
if tnet is not None and paths is not None : raise ValueError ( 'Only network or path input allowed.' ) if tnet is None and paths is None : raise ValueError ( 'No input.' ) # if shortest paths are not calculated , calculate them if tnet is not None : paths = shortest_temporal_path ( tnet ) pathmat = np . zer...
def read_rle ( file_obj , header , bit_width , debug_logging ) : """Read a run - length encoded run from the given fo with the given header and bit _ width . The count is determined from the header and the width is used to grab the value that ' s repeated . Yields the value repeated count times ."""
count = header >> 1 zero_data = b"\x00\x00\x00\x00" width = ( bit_width + 7 ) // 8 data = file_obj . read ( width ) data = data + zero_data [ len ( data ) : ] value = struct . unpack ( b"<i" , data ) [ 0 ] if debug_logging : logger . debug ( "Read RLE group with value %s of byte-width %s and count %s" , value , wid...
def _GetMessage ( self , message_file_key , lcid , message_identifier ) : """Retrieves a specific message from a specific message table . Args : message _ file _ key ( int ) : message file key . lcid ( int ) : language code identifier ( LCID ) . message _ identifier ( int ) : message identifier . Returns ...
table_name = 'message_table_{0:d}_0x{1:08x}' . format ( message_file_key , lcid ) has_table = self . _database_file . HasTable ( table_name ) if not has_table : return None column_names = [ 'message_string' ] condition = 'message_identifier == "0x{0:08x}"' . format ( message_identifier ) values = list ( self . _dat...
def _get_storage_manager ( resource ) : """Return a storage manager which can process this resource ."""
for manager in ( AmazonS3 , ArvadosKeep , SevenBridges , DNAnexus , AzureBlob , GoogleCloud , RegularServer ) : if manager . check_resource ( resource ) : return manager ( ) raise ValueError ( "Unexpected object store %(resource)s" % { "resource" : resource } )
def parse_expression ( val , acceptable_types , name = None , raise_type = ValueError ) : """Attempts to parse the given ` val ` as a python expression of the specified ` acceptable _ types ` . : param string val : A string containing a python expression . : param acceptable _ types : The acceptable types of th...
def format_type ( typ ) : return typ . __name__ if not isinstance ( val , string_types ) : raise raise_type ( 'The raw `val` is not a string. Given {} of type {}.' . format ( val , format_type ( type ( val ) ) ) ) def get_name ( ) : return repr ( name ) if name else 'value' def format_raw_value ( ) : l...
def remove_duplicates_from_list ( array ) : "Preserves the order of elements in the list"
output = [ ] unique = set ( ) for a in array : if a not in unique : unique . add ( a ) output . append ( a ) return output
def efficiency_capacity_demand_difference ( slots , events , X , ** kwargs ) : """A function that calculates the total difference between demand for an event and the slot capacity it is scheduled in ."""
overflow = 0 for row , event in enumerate ( events ) : for col , slot in enumerate ( slots ) : overflow += ( event . demand - slot . capacity ) * X [ row , col ] return overflow
def _find_references ( model_name , references = None ) : """Iterate over model references for ` model _ name ` and return a list of parent model specifications ( including those of ` model _ name ` , ordered from parent to child ) ."""
references = references or [ ] references . append ( model_name ) ref = MODELS [ model_name ] . get ( 'reference' ) if ref is not None : _find_references ( ref , references ) parent_models = [ m for m in references ] parent_models . reverse ( ) return parent_models
def obj_to_grid ( self , file_path = None , delim = None , tab = None , quote_numbers = True , quote_empty_str = False ) : """This will return a str of a grid table . : param file _ path : path to data file , defaults to self ' s contents if left alone : param delim : dict of deliminators , defaults to obj ...
div_delims = { "top" : [ 'top left corner' , 'top intersect' , 'top edge' , 'top right corner' ] , "divide" : [ 'left major intersect' , 'internal major intersect' , 'bottom edge' , 'right major intersect' ] , "middle" : [ 'left intersect' , 'internal intersect' , 'internal horizontal edge' , 'right intersect' ] , "bot...
def read_json ( path , default = None , fatal = True , logger = None ) : """: param str | None path : Path to file to deserialize : param dict | list | None default : Default if file is not present , or if it ' s not json : param bool | None fatal : Abort execution on failure if True : param callable | None l...
path = resolved_path ( path ) if not path or not os . path . exists ( path ) : if default is None : return abort ( "No file %s" , short ( path ) , fatal = ( fatal , default ) ) return default try : with io . open ( path , "rt" ) as fh : data = json . load ( fh ) if default is not Non...
def send_packet ( self , packet , protocol = 'json' , time_precision = None ) : """Send an UDP packet . : param packet : the packet to be sent : type packet : ( if protocol is ' json ' ) dict ( if protocol is ' line ' ) list of line protocol strings : param protocol : protocol of input data , either ' json ...
if protocol == 'json' : data = make_lines ( packet , time_precision ) . encode ( 'utf-8' ) elif protocol == 'line' : data = ( '\n' . join ( packet ) + '\n' ) . encode ( 'utf-8' ) self . udp_socket . sendto ( data , ( self . _host , self . _udp_port ) )
def offset_gen ( offset , iterable , skip_signal = None ) : '''A generator that applies an ` offset ` , skipping ` offset ` elements from ` iterable ` . If skip _ signal is a callable , it will be called with every skipped element .'''
offset = int ( offset ) assert offset >= 0 , 'negative offset' for item in iterable : if offset > 0 : offset -= 1 if callable ( skip_signal ) : skip_signal ( item ) else : yield item
def monte_carlo_vol ( self , ctrs , ndraws = 10000 , rstate = None , return_overlap = False , kdtree = None ) : """Using ` ndraws ` Monte Carlo draws , estimate the volume of the * union * of cubes . If ` return _ overlap = True ` , also returns the estimated fractional overlap with the unit cube . Uses a K - D...
if rstate is None : rstate = np . random # Estimate the volume using Monte Carlo integration . samples = [ self . sample ( ctrs , rstate = rstate , return_q = True , kdtree = kdtree ) for i in range ( ndraws ) ] qsum = sum ( [ q for ( x , q ) in samples ] ) vol = 1. * ndraws / qsum * len ( ctrs ) * self . vol_cube ...
def _percentile ( self , values , percent , key = lambda x : x ) : """Find the percentile of a list of values . Args : values : A list of values for which percentiles are desired percent : A float value from 0 to 100 representing the requested percentile . key : optional key function to compute value from e...
vals = sorted ( values ) k = ( len ( vals ) - 1 ) * ( percent / 100 ) f = math . floor ( k ) c = math . ceil ( k ) if f == c : return key ( vals [ int ( k ) ] ) d0 = key ( vals [ int ( f ) ] ) * ( c - k ) d1 = key ( vals [ int ( c ) ] ) * ( k - f ) return d0 + d1
def init_encoders ( self , config = DataConfig ( ) ) : """Initialize the integer encoder and the one - hot encoder , fitting them to the vocabulary of the corpus . NB : From here on out , - ' ie ' stands for ' integer encoded ' , and - ' ohe ' stands for ' one - hot encoded '"""
self . log ( 'info' , 'Initializing the encoders ...' ) # create the integer encoder and fit it to our corpus ' vocab self . ie = LabelEncoder ( ) self . ie_vocab = self . ie . fit_transform ( self . vocab_list ) self . pad_u_index = self . ie . transform ( [ self . pad_u ] ) [ 0 ] # create the OHE encoder and fit it t...
def xcompile ( source_code , args = 0 , optimize = True ) : """Parses Crianza source code and returns a native Python function . Args : args : The resulting function ' s number of input parameters . Returns : A callable Python function ."""
code = crianza . compile ( crianza . parse ( source_code ) , optimize = optimize ) return crianza . native . compile ( code , args = args )
def split_lines ( tokenlist ) : """Take a single list of ( Token , text ) tuples and yield one such list for each line . Just like str . split , this will yield at least one item . : param tokenlist : List of ( token , text ) or ( token , text , mouse _ handler ) tuples ."""
line = [ ] for item in tokenlist : # For ( token , text ) tuples . if len ( item ) == 2 : token , string = item parts = string . split ( '\n' ) for part in parts [ : - 1 ] : if part : line . append ( ( token , part ) ) yield line line = [ ]...
def _get_elements ( mol , label ) : """The the elements of the atoms in the specified order Args : mol : The molecule . OpenBabel OBMol object . label : The atom indices . List of integers . Returns : Elements . List of integers ."""
elements = [ int ( mol . GetAtom ( i ) . GetAtomicNum ( ) ) for i in label ] return elements
def run_job ( self , job , backend = 'simulator' , shots = 1 , max_credits = None , seed = None , hub = None , group = None , project = None , hpc = None , access_token = None , user_id = None ) : """Execute a job"""
if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) if not self . check_credentials ( ) : return { "error" : "Not credentials valid" } backend_type = self . _check_backend ( backend , 'job' ) if not backend_type : raise Ba...
def remove_reftrack ( self , reftrack ) : """Remove the reftrack from the root . This will not handle row deletion in the model ! It is automatically done when calling : meth : ` Reftrack . delete ` . : param reftrack : the reftrack object to remove : type reftrack : : class : ` Reftrack ` : returns : Non...
self . _reftracks . remove ( reftrack ) refobj = reftrack . get_refobj ( ) if refobj and refobj in self . _parentsearchdict : del self . _parentsearchdict [ refobj ]
def _update_limits_from_api ( self ) : """Query ELB ' s DescribeAccountLimits API action , and update limits with the quotas returned . Updates ` ` self . limits ` ` ."""
self . connect ( ) logger . debug ( "Querying ELB DescribeAccountLimits for limits" ) attribs = self . conn . describe_account_limits ( ) name_to_limits = { 'classic-load-balancers' : 'Active load balancers' , 'classic-listeners' : 'Listeners per load balancer' , 'classic-registered-instances' : 'Registered instances p...
def markowitz ( I , sigma , r , alpha ) : """markowitz - - simple markowitz model for portfolio optimization . Parameters : - I : set of items - sigma [ i ] : standard deviation of item i - r [ i ] : revenue of item i - alpha : acceptance threshold Returns a model , ready to be solved ."""
model = Model ( "markowitz" ) x = { } for i in I : x [ i ] = model . addVar ( vtype = "C" , name = "x(%s)" % i ) # quantity of i to buy model . addCons ( quicksum ( r [ i ] * x [ i ] for i in I ) >= alpha ) model . addCons ( quicksum ( x [ i ] for i in I ) == 1 ) # set nonlinear objective : SCIP only allow for line...
def service ( ctx ) : """Install systemd service configuration"""
install_service ( ctx . obj [ 'instance' ] , ctx . obj [ 'dbhost' ] , ctx . obj [ 'dbname' ] , ctx . obj [ 'port' ] )
def Rz_to_lambdanu ( R , z , ac = 5. , Delta = 1. ) : """NAME : Rz _ to _ lambdanu PURPOSE : calculate the prolate spheroidal coordinates ( lambda , nu ) from galactocentric cylindrical coordinates ( R , z ) by solving eq . ( 2.2 ) in Dejonghe & de Zeeuw ( 1988a ) for ( lambda , nu ) : R ^ 2 = ( l + a )...
g = Delta ** 2 / ( 1. - ac ** 2 ) a = g - Delta ** 2 term = R ** 2 + z ** 2 - a - g discr = ( R ** 2 + z ** 2 - Delta ** 2 ) ** 2 + ( 4. * Delta ** 2 * R ** 2 ) l = 0.5 * ( term + nu . sqrt ( discr ) ) n = 0.5 * ( term - nu . sqrt ( discr ) ) if isinstance ( z , float ) and z == 0. : l = R ** 2 - a n = - g elif...
def restore ( self , ** kwargs ) : """Restores this version as a new version , and returns this new version . If a current version already exists , it will be terminated before restoring this version . Relations ( foreign key , reverse foreign key , many - to - many ) are not restored with the old version ....
if not self . pk : raise ValueError ( 'Instance must be saved and terminated before it can be ' 'restored.' ) if self . is_current : raise ValueError ( 'This is the current version, no need to restore it.' ) if self . get_deferred_fields ( ) : # It would be necessary to fetch the record from the database # agai...
def process ( specs ) : """Executes the passed in list of specs"""
pout , pin = chain_specs ( specs ) LOG . info ( "Processing" ) sw = StopWatch ( ) . start ( ) r = pout . process ( pin ) if r : print ( r ) LOG . info ( "Finished in %s" , sw . read ( ) )
def ripple_withdrawal ( self , amount , address , currency ) : """Returns true if successful ."""
data = { 'amount' : amount , 'address' : address , 'currency' : currency } response = self . _post ( "ripple_withdrawal/" , data = data , return_json = True ) return self . _expect_true ( response )
def get_streams ( self , game = None , channels = None , limit = 25 , offset = 0 ) : """Return a list of streams queried by a number of parameters sorted by number of viewers descending : param game : the game or name of the game : type game : : class : ` str ` | : class : ` models . Game ` : param channels...
if isinstance ( game , models . Game ) : game = game . name channelnames = [ ] cparam = None if channels : for c in channels : if isinstance ( c , models . Channel ) : c = c . name channelnames . append ( c ) cparam = ',' . join ( channelnames ) params = { 'limit' : limit , 'offs...
def convert_spanstring ( span_string ) : """converts a span of tokens ( str , e . g . ' word _ 88 . . word _ 91 ' ) into a list of token IDs ( e . g . [ ' word _ 88 ' , ' word _ 89 ' , ' word _ 90 ' , ' word _ 91 ' ] Note : Please don ' t use this function directly , use spanstring2tokens ( ) instead , which ...
prefix_err = "All tokens must share the same prefix: {0} vs. {1}" tokens = [ ] if not span_string : return tokens spans = span_string . split ( ',' ) for span in spans : span_elements = span . split ( '..' ) if len ( span_elements ) == 1 : tokens . append ( span_elements [ 0 ] ) elif len ( span_...
def buildDiscover ( base_url , out_dir ) : """Convert all files in a directory to apache mod _ asis files in another directory ."""
test_data = discoverdata . readTests ( discoverdata . default_test_file ) def writeTestFile ( test_name ) : template = test_data [ test_name ] data = discoverdata . fillTemplate ( test_name , template , base_url , discoverdata . example_xrds ) out_file_name = os . path . join ( out_dir , test_name ) out...
def revert_file ( self , file = None ) : """Reverts either given file or current * * Script _ Editor _ tabWidget * * Widget tab Model editor file . : param file : File to revert . : type file : unicode : return : Method success . : rtype : bool"""
editor = file and self . get_editor ( file ) or self . get_current_editor ( ) if not editor : return False file = editor . file LOGGER . info ( "{0} | Reverting '{1}' file!" . format ( self . __class__ . __name__ , file ) ) if self . reload_file ( file , is_modified = False ) : return True
def _bind_device ( self ) : """This method implements ` ` _ bind _ device ` ` from : class : ` ~ lewis . core . devices . InterfaceBase ` . It binds Cmd and Var definitions to implementations in Interface and Device ."""
patterns = set ( ) self . bound_commands = [ ] for cmd in self . commands : bound = cmd . bind ( self ) or cmd . bind ( self . device ) or None if bound is None : raise RuntimeError ( 'Unable to produce callable object for non-existing member \'{}\' ' 'of device or interface.' . format ( cmd . func ) ) ...
def display_map ( fname ) : """view a text file ( map ) in high resolution"""
print ( "viewing " , fname ) app = view_tk ( None ) app . show_grid_from_file ( fname ) app . title ( 'Map View' ) # app . after ( 2000 , vais _ main _ loop ( app ) ) # bind mouse and keyboard for interactivity # frame = Frame ( app , width = 100 , height = 100) # frame . bind ( " < Button - 1 > " , callback ) app . ca...
def read_lines_from_file ( cls_name , filename ) : """Read lines from file , parsing out header and metadata ."""
with tf . io . gfile . GFile ( filename , "rb" ) as f : lines = [ tf . compat . as_text ( line ) [ : - 1 ] for line in f ] header_line = "%s%s" % ( _HEADER_PREFIX , cls_name ) if lines [ 0 ] != header_line : raise ValueError ( "File {fname} does not seem to have been created from " "{name}.save_to_file." . form...
def filter ( self , func ) : """Filter array along an axis . Applies a function which should evaluate to boolean , along a single axis or multiple axes . Array will be aligned so that the desired set of axes are in the keys , which may require a transpose / reshape . Parameters func : function Functio...
if self . mode == 'local' : reshaped = self . _align ( self . baseaxes ) filtered = asarray ( list ( filter ( func , reshaped ) ) ) if self . labels is not None : mask = asarray ( list ( map ( func , reshaped ) ) ) if self . mode == 'spark' : sort = False if self . labels is None else True f...
def init_app ( application ) : """Initialise an application Set up whitenoise to handle static files ."""
config = { k : v for k , v in application . config . items ( ) if k in SCHEMA } kwargs = { 'autorefresh' : application . debug } kwargs . update ( ( k [ 11 : ] . lower ( ) , v ) for k , v in config . items ( ) ) instance = whitenoise . WhiteNoise ( application . wsgi_app , ** kwargs ) instance . add_files ( application...
def key_for_property ( cls , kind , property ) : """Return the _ _ property _ _ key for property of kind . Args : kind : kind whose key is requested . property : property whose key is requested . Returns : The key for property of kind ."""
return model . Key ( Kind . KIND_NAME , kind , Property . KIND_NAME , property )
def format_list ( self , at_char , user , list_name ) : '''Return formatted HTML for a list .'''
return '<a href="https://twitter.com/%s/lists/%s">%s%s/%s</a>' % ( user , list_name , at_char , user , list_name )
def merge ( data , skip = 50 , fraction = 1.0 ) : """Merge one every ' skip ' clouds into a single emcee population , using the later ' fraction ' of the run ."""
w , s , d = data . chains . shape start = int ( ( 1.0 - fraction ) * s ) total = int ( ( s - start ) / skip ) return data . chains [ : , start : : skip , : ] . reshape ( ( w * total , d ) )
def find_user_emails ( self , user ) : """Find all the UserEmail object belonging to a user ."""
user_emails = self . db_adapter . find_objects ( self . UserEmailClass , user_id = user . id ) return user_emails
def remove_primary_analyses ( self ) : """Remove analyses relocated to partitions"""
for ar , analyses in self . analyses_to_remove . items ( ) : analyses_ids = list ( set ( map ( api . get_id , analyses ) ) ) ar . manage_delObjects ( analyses_ids ) self . analyses_to_remove = dict ( )
def _format_name_map ( self , lonc , latc ) : '''Return the name of the map in the good format'''
return '_' . join ( [ 'WAC' , 'GLOBAL' ] + [ 'E' + latc + lonc , "{0:0>3}" . format ( self . ppd ) + 'P' ] )
def _load_data ( data_file , data_type ) : """Load data from CSV , JSON , Excel , . . . , formats ."""
raw_data = data_file . read ( ) if data_type is None : data_type = data_file . name . split ( '.' ) [ - 1 ] # Data list to process data = [ ] # JSON type if data_type == 'json' : data = json . loads ( raw_data ) return data # CSV type elif data_type == 'csv' : csv_data = StringIO ( raw_data ) reader...
def parse_form ( self , req , name , field ) : """Pull a form value from the request . . . note : : The request stream will be read and left at EOF ."""
form = self . _cache . get ( "form" ) if form is None : self . _cache [ "form" ] = form = parse_form_body ( req ) return core . get_value ( form , name , field )
def get_moments ( metricParams , vary_fmax = False , vary_density = None ) : """This function will calculate the various integrals ( moments ) that are needed to compute the metric used in template bank placement and coincidence . Parameters metricParams : metricParameters instance Structure holding all t...
# NOTE : Unless the TaylorR2F4 metric is used the log ^ 3 and log ^ 4 terms are # not needed . As this calculation is not too slow compared to bank # placement we just do this anyway . psd_amp = metricParams . psd . data psd_f = numpy . arange ( len ( psd_amp ) , dtype = float ) * metricParams . deltaF new_f , new_amp ...
def _cleanup ( self ) -> None : """Cleanup unused transports ."""
if self . _cleanup_handle : self . _cleanup_handle . cancel ( ) now = self . _loop . time ( ) timeout = self . _keepalive_timeout if self . _conns : connections = { } deadline = now - timeout for key , conns in self . _conns . items ( ) : alive = [ ] for proto , use_time in conns : ...
def __processUsers ( self ) : """Process users of the queue ."""
while self . __usersToProccess . empty ( ) and not self . __end : pass while not self . __end or not self . __usersToProccess . empty ( ) : self . __lockGetUser . acquire ( ) try : new_user = self . __usersToProccess . get ( False ) except Empty : self . __lockGetUser . release ( ) ...
def global_injector_decorator ( inject_globals ) : '''Decorator used by the LazyLoader to inject globals into a function at execute time . globals Dictionary with global variables to inject'''
def inner_decorator ( f ) : @ functools . wraps ( f ) def wrapper ( * args , ** kwargs ) : with salt . utils . context . func_globals_inject ( f , ** inject_globals ) : return f ( * args , ** kwargs ) return wrapper return inner_decorator
def from_params ( cls , params : Params , instances : Iterable [ 'adi.Instance' ] = None ) : # type : ignore """There are two possible ways to build a vocabulary ; from a collection of instances , using : func : ` Vocabulary . from _ instances ` , or from a pre - saved vocabulary , using : func : ` Vocabulary ....
# pylint : disable = arguments - differ # Vocabulary is ` ` Registrable ` ` so that you can configure a custom subclass , # but ( unlike most of our registrables ) almost everyone will want to use the # base implementation . So instead of having an abstract ` ` VocabularyBase ` ` or # such , we just add the logic for i...
def avoid_parallel_execution ( func ) : """A decorator to avoid the parallel execution of a function . If the function is currently called , the second call is just skipped . : param func : The function to decorate : return :"""
def func_wrapper ( * args , ** kwargs ) : if not getattr ( func , "currently_executing" , False ) : func . currently_executing = True try : return func ( * args , ** kwargs ) finally : func . currently_executing = False else : logger . verbose ( "Avoid par...
def get_async ( cls , blob_key , ** ctx_options ) : """Async version of get ( ) ."""
if not isinstance ( blob_key , ( BlobKey , basestring ) ) : raise TypeError ( 'Expected blob key, got %r' % ( blob_key , ) ) if 'parent' in ctx_options : raise TypeError ( 'Parent is not supported' ) return cls . get_by_id_async ( str ( blob_key ) , ** ctx_options )
def html2man ( data , formatter ) : """Convert HTML text from cplusplus . com to man pages ."""
groff_text = formatter ( data ) man_text = groff2man ( groff_text ) return man_text
def from_protobuf ( cls , proto : SaveStateProto ) -> SaveState : """Constructor from protobuf . Can raise ValueErrors from called from _ protobuf ( ) parsers . : param proto : protobuf structure : type proto : ~ unidown . plugin . protobuf . save _ state _ pb2 . SaveStateProto : return : the SaveState : rt...
data_dict = { } for key , link_item in proto . data . items ( ) : data_dict [ key ] = LinkItem . from_protobuf ( link_item ) if proto . version == "" : raise ValueError ( "version of SaveState does not exist or is empty inside the protobuf." ) try : version = Version ( proto . version ) except InvalidVersio...
def get_country_info_from_m49 ( cls , m49 , use_live = True , exception = None ) : # type : ( int , bool , Optional [ ExceptionUpperBound ] ) - > Optional [ Dict [ str ] ] """Get country name from M49 code Args : m49 ( int ) : M49 numeric code for which to get country information use _ live ( bool ) : Try to ...
iso3 = cls . get_iso3_from_m49 ( m49 , use_live = use_live , exception = exception ) if iso3 is not None : return cls . get_country_info_from_iso3 ( iso3 , exception = exception ) return None
def _ErrorOfDifferences ( self , cov , warning_cutoff = 1.0e-10 ) : """inputs : cov is the covariance matrix of A returns the statistical error matrix of A _ i - A _ j"""
diag = np . matrix ( cov . diagonal ( ) ) d2 = diag + diag . transpose ( ) - 2 * cov # Cast warning _ cutoff to compare a negative number cutoff = - abs ( warning_cutoff ) # check for any numbers below zero . if np . any ( d2 < 0.0 ) : if np . any ( d2 < cutoff ) : print ( "A squared uncertainty is negative...
def list_ ( saltenv = 'base' , test = None ) : '''List currently configured reactors CLI Example : . . code - block : : bash salt - run reactor . list'''
sevent = salt . utils . event . get_event ( 'master' , __opts__ [ 'sock_dir' ] , __opts__ [ 'transport' ] , opts = __opts__ , listen = True ) master_key = salt . utils . master . get_master_key ( 'root' , __opts__ ) __jid_event__ . fire_event ( { 'key' : master_key } , 'salt/reactors/manage/list' ) results = sevent . g...
def select ( self , fields , ** exprs ) : """Create a new table containing a subset of attributes , with optionally newly - added fields computed from each rec in the original table . @ param fields : list of strings , or single space - delimited string , listing attribute name to be included in the output ...
fields = self . _parse_fields_string ( fields ) def _make_string_callable ( expr ) : if isinstance ( expr , basestring ) : return lambda r : expr % r else : return expr exprs = dict ( ( k , _make_string_callable ( v ) ) for k , v in exprs . items ( ) ) raw_tuples = [ ] for ob in self . obs : ...
def tuple_replace ( tup , * pairs ) : """Return a copy of a tuple with some elements replaced . : param tup : The tuple to be copied . : param pairs : Any number of ( index , value ) tuples where index is the index of the item to replace and value is the new value of the item ."""
tuple_list = list ( tup ) for index , value in pairs : tuple_list [ index ] = value return tuple ( tuple_list )
def score_hist ( df , columns = None , groupby = None , threshold = 0.7 , stacked = True , bins = 20 , percent = True , alpha = 0.33 , show = True , block = False , save = False ) : """Plot multiple histograms on one plot , typically of " score " values between 0 and 1 Typically the groupby or columns of the data...
df = df if columns is None else df [ ( [ ] if groupby is None else [ groupby ] ) + list ( columns ) ] . copy ( ) if groupby is not None or threshold is not None : df = groups_from_scores ( df , groupby = groupby , threshold = threshold ) percent = 100. if percent else 1. if isinstance ( df , pd . core . groupby . D...
def process_once ( self , timeout = 0.01 ) : """Handles an event and calls it ' s handler Optional arguments : * timeout = 0.01 - Wait for an event until the timeout is reached ."""
try : event = self . recv ( timeout ) if event : event_t = event [ 0 ] event_c = event [ 1 ] if event_t == 'JOIN' : self . on_join ( event_c [ 0 ] , event_c [ 1 ] ) elif event_t == 'PART' : self . on_part ( event_c [ 0 ] , event_c [ 1 ] , event_c [ 2 ] ) ...
def _exec ( cmd ) : """Execute command using subprocess . Popen : param cmd : : return : ( code , stdout , stderr )"""
process = subprocess . Popen ( cmd , stderr = subprocess . PIPE , stdout = subprocess . PIPE ) # pylint : disable = unexpected - keyword - arg ( stdout , stderr ) = process . communicate ( timeout = defaults . DEFAULT_VCS_TIMEOUT ) return process . returncode , stdout . decode ( ) , stderr . decode ( )
def alreadyHasEntry ( oldClassString , og ) : """Return true if there is already an owl : Class with the old id"""
namespace = oldClassString . split ( ':' ) [ 0 ] if namespace == 'http' : target = rdflib . URIRef ( oldClassString ) print ( 'OLD CLASS ID IS A URL' , oldClassString ) else : try : og . add_known_namespaces ( namespace ) target = og . expand ( oldClassString ) except KeyError : ...
def _set_verbose ( self , verbose ) : """Check and set our : data : ` verbose ` attribute . The debug - level must be a string or an integer . If it is one of the allowed strings , GnuPG will translate it internally to it ' s corresponding integer level : basic = 1-2 advanced = 3-5 expert = 6-8 guru =...
string_levels = ( 'basic' , 'advanced' , 'expert' , 'guru' ) if verbose is True : # The caller wants logging , but we need a valid - - debug - level # for gpg . Default to " basic " , and warn about the ambiguity . verbose = 'basic' if ( isinstance ( verbose , str ) and not ( verbose in string_levels ) ) : verb...
def cmd_init ( self , * args ) : '''Create a initial buildozer . spec in the current directory'''
if exists ( 'buildozer.spec' ) : print ( 'ERROR: You already have a buildozer.spec file.' ) exit ( 1 ) copyfile ( join ( dirname ( __file__ ) , 'default.spec' ) , 'buildozer.spec' ) print ( 'File buildozer.spec created, ready to customize!' )
def read_header ( filename ) : '''returns a dictionary of values in the header of the given file'''
header = { } in_header = False data = nl . universal_read ( filename ) lines = [ x . strip ( ) for x in data . split ( '\n' ) ] for line in lines : if line == "*** Header Start ***" : in_header = True continue if line == "*** Header End ***" : return header fields = line . split ( ":...
def import_model ( self , name , path = "floyd.db.models" ) : """imports a model of name from path , returning from local model cache if it has been previously loaded otherwise importing"""
if name in self . _model_cache : return self . _model_cache [ name ] try : model = getattr ( __import__ ( path , None , None , [ name ] ) , name ) self . _model_cache [ name ] = model except ImportError : return False return model
def init_live_reload ( run ) : """Start the live reload task : param run : run the task inside of this function or just create it"""
from asyncio import get_event_loop from . _live_reload import start_child loop = get_event_loop ( ) if run : loop . run_until_complete ( start_child ( ) ) else : get_event_loop ( ) . create_task ( start_child ( ) )
def label_geometry_measures ( label_image , intensity_image = None ) : """Wrapper for the ANTs funtion labelGeometryMeasures ANTsR function : ` labelGeometryMeasures ` Arguments label _ image : ANTsImage image on which to compute geometry intensity _ image : ANTsImage ( optional ) image with intensity v...
if intensity_image is None : intensity_image = label_image . clone ( ) outcsv = mktemp ( suffix = '.csv' ) veccer = [ label_image . dimension , label_image , intensity_image , outcsv ] veccer_processed = utils . _int_antsProcessArguments ( veccer ) libfn = utils . get_lib_fn ( 'LabelGeometryMeasures' ) pp = libfn (...
def is_port_default ( self ) : '''Return whether the URL is using the default port .'''
if self . scheme in RELATIVE_SCHEME_DEFAULT_PORTS : return RELATIVE_SCHEME_DEFAULT_PORTS [ self . scheme ] == self . port
def sync ( self , vault_client ) : """Synchronizes the local and remote Vault resources . Has the net effect of adding backend if needed"""
if self . present : if not self . existing : LOG . info ( "Mounting %s backend on %s" , self . backend , self . path ) self . actually_mount ( vault_client ) else : LOG . info ( "%s backend already mounted on %s" , self . backend , self . path ) else : if self . existing : LO...
def var_fmpt ( P ) : """Variances of first mean passage times for an ergodic transition probability matrix . Parameters P : array ( k , k ) , an ergodic Markov transition probability matrix . Returns : array ( k , k ) , elements are the variances for the number of intervals required for a chain star...
P = np . matrix ( P ) A = P ** 1000 n , k = A . shape I = np . identity ( k ) Z = la . inv ( I - P + A ) E = np . ones_like ( Z ) D = np . diag ( 1. / np . diag ( A ) ) Zdg = np . diag ( np . diag ( Z ) ) M = ( I - Z + E * Zdg ) * D ZM = Z * M ZMdg = np . diag ( np . diag ( ZM ) ) W = M * ( 2 * Zdg * D - I ) + 2 * ( ZM...
def get_json_data ( latitude = 52.091579 , longitude = 5.119734 ) : """Get buienradar json data and return results ."""
final_result = { SUCCESS : False , MESSAGE : None , CONTENT : None , RAINCONTENT : None } log . info ( "Getting buienradar json data for latitude=%s, longitude=%s" , latitude , longitude ) result = __get_ws_data ( ) if result [ SUCCESS ] : # store json data : final_result [ CONTENT ] = result [ CONTENT ] final_...
def _iter_branch ( self , node ) : """yield ( key , value ) stored in this and the descendant nodes : param node : node in form of list , or BLANK _ NODE . . note : : Here key is in full form , rather than key of the individual node"""
if node == BLANK_NODE : raise StopIteration node_type = self . _get_node_type ( node ) if is_key_value_type ( node_type ) : nibbles = key_nibbles_from_key_value_node ( node ) key = b'+' . join ( [ to_string ( x ) for x in nibbles ] ) if node_type == NODE_TYPE_EXTENSION : sub_tree = self . _iter_...
def has_permission ( cls , user ) : """We override this method to customize the way permissions are checked . Using our roles to check permissions ."""
# no login is needed , so its always fine if not cls . requires_login : return True # if user is somehow not logged in if not user . is_authenticated : return False # attribute permission _ required is mandatory , returns tuple perms = cls . get_permission_required ( ) # if perms are defined and empty , we skip...
def max_normal_germline_depth ( in_file , params , somatic_info ) : """Calculate threshold for excluding potential heterozygotes based on normal depth ."""
bcf_in = pysam . VariantFile ( in_file ) depths = [ ] for rec in bcf_in : stats = _is_possible_loh ( rec , bcf_in , params , somatic_info ) if tz . get_in ( [ "normal" , "depth" ] , stats ) : depths . append ( tz . get_in ( [ "normal" , "depth" ] , stats ) ) if depths : return np . median ( depths )...
def solar_azimuth ( self , dateandtime = None ) : """Calculates the solar azimuth angle for a specific date / time . : param dateandtime : The date and time for which to calculate the angle . : type dateandtime : : class : ` ~ datetime . datetime ` : returns : The azimuth angle in degrees clockwise from North...
if self . astral is None : self . astral = Astral ( ) if dateandtime is None : dateandtime = datetime . datetime . now ( self . tz ) elif not dateandtime . tzinfo : dateandtime = self . tz . localize ( dateandtime ) dateandtime = dateandtime . astimezone ( pytz . UTC ) return self . astral . solar_azimuth (...
def open ( self ) : """Open an existing database"""
if self . _table_exists ( ) : self . mode = "open" # get table info self . _get_table_info ( ) self . types = dict ( [ ( f [ 0 ] , self . conv_func [ f [ 1 ] . upper ( ) ] ) for f in self . fields if f [ 1 ] . upper ( ) in self . conv_func ] ) return self else : # table not found raise IOError ,...
def get_task ( self , patient_id , task_id ) : """invokes TouchWorksMagicConstants . ACTION _ GET _ ENCOUNTER _ LIST _ FOR _ PATIENT action : return : JSON response"""
magic = self . _magic_json ( action = TouchWorksMagicConstants . ACTION_GET_TASK , patient_id = patient_id , parameter1 = task_id ) response = self . _http_request ( TouchWorksEndPoints . MAGIC_JSON , data = magic ) result = self . _get_results_or_raise_if_magic_invalid ( magic , response , TouchWorksMagicConstants . R...
def span ( self ) : """Return a contiguous range that is a superset of this range . Returns : A VersionRange object representing the span of this range . For example , the span of " 2 + < 4 | 6 + < 8 " would be " 2 + < 8 " ."""
other = VersionRange ( None ) bound = _Bound ( self . bounds [ 0 ] . lower , self . bounds [ - 1 ] . upper ) other . bounds = [ bound ] return other
def parse_connection_setup ( self ) : """Internal function used to parse connection setup response ."""
# Only the ConnectionSetupRequest has been sent so far r = self . sent_requests [ 0 ] while 1 : # print ' data _ send : ' , repr ( self . data _ send ) # print ' data _ recv : ' , repr ( self . data _ recv ) if r . _data : alen = r . _data [ 'additional_length' ] * 4 # The full response haven ' t ar...
def ChromeContext ( * args , ** kwargs ) : '''Context manager for conveniently handling the lifetime of the underlying chromium instance . In general , this should be the preferred way to use an instance of ` ChromeRemoteDebugInterface ` . All parameters are forwarded through to the underlying ChromeRemoteDebug...
log = logging . getLogger ( "Main.ChromeController.ChromeContext" ) chrome_created = False try : chrome_instance = ChromeRemoteDebugInterface ( * args , ** kwargs ) chrome_created = True log . info ( "Entering chrome context" ) yield chrome_instance except Exception as e : log . error ( "Exception i...
def _plane2col ( plane ) : '''take a string like ' xy ' , and return the indices from COLS . *'''
planes = ( 'xy' , 'yx' , 'xz' , 'zx' , 'yz' , 'zy' ) assert plane in planes , 'No such plane found! Please select one of: ' + str ( planes ) return ( getattr ( COLS , plane [ 0 ] . capitalize ( ) ) , getattr ( COLS , plane [ 1 ] . capitalize ( ) ) , )
def get_related_models ( cls , model ) : """Get a dictionary with related structure models for given class or model : > > SupportedServices . get _ related _ models ( gitlab _ models . Project ) ' service ' : nodeconductor _ gitlab . models . GitLabService , ' service _ project _ link ' : nodeconductor _ gitl...
from waldur_core . structure . models import ServiceSettings if isinstance ( model , ServiceSettings ) : model_str = cls . _registry . get ( model . type , { } ) . get ( 'model_name' , '' ) else : model_str = cls . _get_model_str ( model ) for models in cls . get_service_models ( ) . values ( ) : if model_s...
def verify ( self , subject , signature = None ) : """Verify a subject with a signature using this key . : param subject : The subject to verify : type subject : ` ` str ` ` , ` ` unicode ` ` , ` ` None ` ` , : py : obj : ` PGPMessage ` , : py : obj : ` PGPKey ` , : py : obj : ` PGPUID ` : param signature : I...
sspairs = [ ] # some type checking if not isinstance ( subject , ( type ( None ) , PGPMessage , PGPKey , PGPUID , PGPSignature , six . string_types , bytes , bytearray ) ) : raise TypeError ( "Unexpected subject value: {:s}" . format ( str ( type ( subject ) ) ) ) if not isinstance ( signature , ( type ( None ) , P...
def _to_narrow ( self , terms , data , mask , dates , assets ) : """Convert raw computed pipeline results into a DataFrame for public APIs . Parameters terms : dict [ str - > Term ] Dict mapping column names to terms . data : dict [ str - > ndarray [ ndim = 2 ] ] Dict mapping column names to computed resu...
if not mask . any ( ) : # Manually handle the empty DataFrame case . This is a workaround # to pandas failing to tz _ localize an empty dataframe with a # MultiIndex . It also saves us the work of applying a known - empty # mask to each array . # Slicing ` dates ` here to preserve pandas metadata . empty_dates = da...
def sigres_path ( self ) : """Absolute path of the SIGRES file . Empty string if file is not present ."""
# Lazy property to avoid multiple calls to has _ abiext . try : return self . _sigres_path except AttributeError : path = self . outdir . has_abiext ( "SIGRES" ) if path : self . _sigres_path = path return path
def hexbin ( x , y , size , orientation = "pointytop" , aspect_scale = 1 ) : '''Perform an equal - weight binning of data points into hexagonal tiles . For more sophisticated use cases , e . g . weighted binning or scaling individual tiles proportional to some other quantity , consider using HoloViews . Arg...
pd = import_required ( 'pandas' , 'hexbin requires pandas to be installed' ) q , r = cartesian_to_axial ( x , y , size , orientation , aspect_scale = aspect_scale ) df = pd . DataFrame ( dict ( r = r , q = q ) ) return df . groupby ( [ 'q' , 'r' ] ) . size ( ) . reset_index ( name = 'counts' )
def add_coconut_to_path ( ) : """Adds coconut to sys . path if it isn ' t there already ."""
try : import coconut # NOQA except ImportError : sys . path . insert ( 0 , os . path . dirname ( os . path . dirname ( os . path . abspath ( __file__ ) ) ) )
def isRunActive ( g ) : """Polls the data server to see if a run is active"""
if g . cpars [ 'hcam_server_on' ] : url = g . cpars [ 'hipercam_server' ] + 'summary' response = urllib . request . urlopen ( url , timeout = 2 ) rs = ReadServer ( response . read ( ) , status_msg = True ) if not rs . ok : raise DriverError ( 'isRunActive error: ' + str ( rs . err ) ) if rs ...
def _add_function ( self , func , identify_observed ) : """Add a function as an observer . Args : func : The function to register as an observer . identify _ observed : See docstring for add _ observer . Returns : True if the function is added , otherwise False ."""
key = self . make_key ( func ) if key not in self . observers : self . observers [ key ] = ObserverFunction ( func , identify_observed , ( key , self . observers ) ) return True else : return False
def findB ( self , tag_name , params = None , fn = None , case_sensitive = False ) : """Same as : meth : ` findAllB ` , but without ` endtags ` . You can always get them from : attr : ` endtag ` property ."""
return [ x for x in self . findAllB ( tag_name , params , fn , case_sensitive ) if not x . isEndTag ( ) ]
def on_chanmsg ( self , from_ , channel , message ) : """Event handler for channel messages ."""
if message == 'hello' : self . privmsg ( channel , 'Hello, %s!' % from_ [ 0 ] ) print ( '%s said hello!' % from_ [ 0 ] ) elif message == '!quit' : self . quit ( 'Bye!' )
def filter ( self , source_file , encoding ) : # noqa A001 """Parse XML file ."""
sources = [ ] if encoding : with codecs . open ( source_file , 'r' , encoding = encoding ) as f : src = f . read ( ) sources . extend ( self . _filter ( src , source_file , encoding ) ) else : for content , filename , enc in self . get_content ( source_file ) : sources . extend ( self . _fil...
def get ( self , pk ) : """Returns the object for the key Override it for efficiency ."""
for item in self . store . get ( self . query_class ) : # coverts pk value to correct type pk = item . properties [ item . pk ] . col_type ( pk ) if getattr ( item , item . pk ) == pk : return item
def _generate_label_matrix ( self ) : """Generate an [ n , m ] label matrix with entries in { 0 , . . . , k }"""
self . L = np . zeros ( ( self . n , self . m ) ) self . Y = np . zeros ( self . n , dtype = np . int64 ) for i in range ( self . n ) : y = choice ( self . k , p = self . p ) + 1 # Note that y \ in { 1 , . . . , k } self . Y [ i ] = y for j in range ( self . m ) : p_j = self . parent . get ( j ,...
def extract_attributes ( cls , fields , resource ) : """Builds the ` attributes ` object of the JSON API resource object ."""
data = OrderedDict ( ) for field_name , field in six . iteritems ( fields ) : # ID is always provided in the root of JSON API so remove it from attributes if field_name == 'id' : continue # don ' t output a key for write only fields if fields [ field_name ] . write_only : continue # Skip...
def submission_delete ( self , submission_id ) : """Delete a submission ."""
response = self . _post ( self . apiurl + '/v2/submission/delete' , data = { 'apikey' : self . apikey , 'submission_id' : submission_id } ) return self . _raise_or_extract ( response )
def set_calibration_reps ( self , reps ) : """Sets the number of repetitions for calibration stimuli : param reps : Number of times a unique stimulus is presented in calibration operations : type reps : int"""
self . bs_calibrator . set_reps ( reps ) self . tone_calibrator . set_reps ( reps )
def cycle_dist ( x , y , perimeter ) : """Find Distance between x , y by means of a n - length cycle . : param x : : param y : : param perimeter : Example : > > > cycle _ dist ( 1 , 23 , 24 ) = 2 > > > cycle _ dist ( 5 , 13 , 24 ) = 8 > > > cycle _ dist ( 0.0 , 2.4 , 1.0 ) = 0.4 > > > cycle _ dist (...
dist = abs ( x - y ) % perimeter if dist > 0.5 * perimeter : dist = perimeter - dist return dist