signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def add_bgcolor ( self , colname , cmap = 'copper' , mode = 'absmax' , threshold = 2 ) : """Change column content into HTML paragraph with background color : param colname : : param cmap : a colormap ( matplotlib ) or created using colormap package ( from pypi ) . : param mode : type of normalisation in ' a...
try : # if a cmap is provided , it may be just a known cmap name cmap = cmap_builder ( cmap ) except : pass data = self . df [ colname ] . values if len ( data ) == 0 : return if mode == 'clip' : data = [ min ( x , threshold ) / float ( threshold ) for x in data ] elif mode == 'absmax' : m = abs ( d...
def submitter ( self ) : """| Comment : The user who submitted the ticket . The submitter always becomes the author of the first comment on the ticket"""
if self . api and self . submitter_id : return self . api . _get_user ( self . submitter_id )
def getFileDescription ( self , fileInfo ) : """Function to get the description of a file ."""
data = 'Description' result = fileInfo [ fileInfo . find ( data + "</td>" ) + len ( data + "</td>" ) : ] result . lstrip ( ) result = result [ : result . find ( "</td>" ) ] result = result [ result . rfind ( "<" ) : ] if "<td" in result : result = result [ result . find ( ">" ) + 1 : ] return result
def map_plus ( target : Callable , mi , ma , a , mk , k ) : """The builtin ` map ( ) ` , but with superpowers ."""
if a is None : a = [ ] if k is None : k = { } if mi is None and ma is None and mk is None : return [ ] elif mi is None and ma is None : return [ target ( * a , ** mki , ** k ) for mki in mk ] elif ma is None and mk is None : return [ target ( mii , * a , ** k ) for mii in mi ] elif mk is None and mi...
def imagej_description ( shape , rgb = None , colormaped = False , version = None , hyperstack = None , mode = None , loop = None , ** kwargs ) : """Return ImageJ image description from data shape . ImageJ can handle up to 6 dimensions in order TZCYXS . > > > imagej _ description ( ( 51 , 5 , 2 , 196 , 171 ) ) ...
if colormaped : raise NotImplementedError ( 'ImageJ colormapping not supported' ) if version is None : version = '1.11a' shape = imagej_shape ( shape , rgb = rgb ) rgb = shape [ - 1 ] in ( 3 , 4 ) result = [ 'ImageJ=%s' % version ] append = [ ] result . append ( 'images=%i' % product ( shape [ : - 3 ] ) ) if hy...
def get_neutralized_variable ( variable ) : """Return a new neutralized variable ( to be used by reforms ) . A neutralized variable always returns its default value , and does not cache anything ."""
result = variable . clone ( ) result . is_neutralized = True result . label = '[Neutralized]' if variable . label is None else '[Neutralized] {}' . format ( variable . label ) , return result
def _retrieve_tag ( self , text ) : """Tag text with chosen tagger and clean tags . Tag format : [ ( ' word ' , ' tag ' ) ] : param text : string : return : list of tuples , with each tuple containing the word and its pos tag : rtype : list"""
if self . tagger == 'tag_ngram_123_backoff' : # Data format : Perseus Style ( see https : / / github . com / cltk / latin _ treebank _ perseus ) tags = POSTag ( 'latin' ) . tag_ngram_123_backoff ( text . lower ( ) ) return [ ( tag [ 0 ] , tag [ 1 ] ) for tag in tags ] elif self . tagger == 'tag_tnt' : tags ...
def associations ( self , association_resource ) : """Retrieve Association for this resource of the type in association _ resource . This method will return all * resources * ( group , indicators , task , victims , etc ) for this resource that are associated with the provided association resource _ type . * *...
resource = self . copy ( ) resource . _request_entity = association_resource . api_entity resource . _request_uri = '{}/{}' . format ( resource . _request_uri , association_resource . request_uri ) return resource
def second_parameter ( self , singular_value ) : """get the solution space contribution to parameter error variance at a singular value ( G * obscov * G ^ T ) Parameters singular _ value : int singular value to calc second term at Returns second _ parameter : pyemu . Cov second term contribution to pa...
self . log ( "calc second term parameter @" + str ( singular_value ) ) result = self . G ( singular_value ) * self . obscov * self . G ( singular_value ) . T self . log ( "calc second term parameter @" + str ( singular_value ) ) return result
def execute_service_endpoint_request ( self , service_endpoint_request , project , endpoint_id ) : """ExecuteServiceEndpointRequest . [ Preview API ] Proxy for a GET request defined by a service endpoint . : param : class : ` < ServiceEndpointRequest > < azure . devops . v5_0 . service _ endpoint . models . Ser...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) query_parameters = { } if endpoint_id is not None : query_parameters [ 'endpointId' ] = self . _serialize . query ( 'endpoint_id' , endpoint_id , 'str' ) content = self . _serialize ....
def null_advance_strain ( self , blocksize ) : """Advance and insert zeros Parameters blocksize : int The number of seconds to attempt to read from the channel"""
sample_step = int ( blocksize * self . sample_rate ) csize = sample_step + self . corruption * 2 self . strain . roll ( - sample_step ) # We should roll this off at some point too . . . self . strain [ len ( self . strain ) - csize + self . corruption : ] = 0 self . strain . start_time += blocksize # The next time we n...
def _init_level_set ( init_level_set , image_shape ) : """Auxiliary function for initializing level sets with a string . If ` init _ level _ set ` is not a string , it is returned as is ."""
if isinstance ( init_level_set , str ) : if init_level_set == 'checkerboard' : res = checkerboard_level_set ( image_shape ) elif init_level_set == 'circle' : res = circle_level_set ( image_shape ) else : raise ValueError ( "`init_level_set` not in " "['checkerboard', 'circle']" ) els...
def delete_resource_subscription ( self , device_id , _resource_path , ** kwargs ) : # noqa : E501 """Remove a subscription # noqa : E501 To remove an existing subscription from a resource path . * * Example usage : * * curl - X DELETE \\ https : / / api . us - east - 1 . mbedcloud . com / v2 / subscriptions / { ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . delete_resource_subscription_with_http_info ( device_id , _resource_path , ** kwargs ) # noqa : E501 else : ( data ) = self . delete_resource_subscription_with_http_info ( device_id , _resource_path , ** kwargs ) ...
def map_ids ( queries , frm = 'ACC' , to = 'ENSEMBL_PRO_ID' , organism_taxid = 9606 , test = False ) : """https : / / www . uniprot . org / help / api _ idmapping"""
url = 'https://www.uniprot.org/uploadlists/' params = { 'from' : frm , 'to' : to , 'format' : 'tab' , 'organism' : organism_taxid , 'query' : ' ' . join ( queries ) , } response = requests . get ( url , params = params ) if test : print ( response . url ) if response . ok : df = pd . read_table ( response . url...
def decode ( self , packet ) : """Check a parsed packet and figure out if it is an Eddystone Beacon . If it is , return the relevant data as a dictionary . Return None , it is not an Eddystone Beacon advertising packet"""
ssu = packet . retrieve ( "Complete uuids" ) found = False for x in ssu : if EDDY_UUID in x : found = True break if not found : return None found = False adv = packet . retrieve ( "Advertised Data" ) for x in adv : luuid = x . retrieve ( "Service Data uuid" ) for uuid in luuid : ...
def highpass ( timeseries , frequency , filter_order = 8 , attenuation = 0.1 ) : """Return a new timeseries that is highpassed . Return a new time series that is highpassed above the ` frequency ` . Parameters Time Series : TimeSeries The time series to be high - passed . frequency : float The frequency...
if not isinstance ( timeseries , TimeSeries ) : raise TypeError ( "Can only resample time series" ) if timeseries . kind is not 'real' : raise TypeError ( "Time series must be real" ) lal_data = timeseries . lal ( ) _highpass_func [ timeseries . dtype ] ( lal_data , frequency , 1 - attenuation , filter_order ) ...
async def destroy ( self , token ) : """Destroys a given token . Parameters : token ( ObjectID ) : Token ID Returns : bool : ` ` True ` ` on success"""
token_id = extract_attr ( token , keys = [ "ID" ] ) response = await self . _api . put ( "/v1/acl/destroy" , token_id ) return response . body
def hybrid_meco_frequency ( m1 , m2 , chi1 , chi2 , qm1 = None , qm2 = None ) : """Return the frequency of the hybrid MECO Parameters m1 : float Mass of the primary object in solar masses . m2 : float Mass of the secondary object in solar masses . chi1 : float Dimensionless spin of the primary object ...
if qm1 is None : qm1 = 1 if qm2 is None : qm2 = 1 return velocity_to_frequency ( hybrid_meco_velocity ( m1 , m2 , chi1 , chi2 , qm1 , qm2 ) , m1 + m2 )
def set_provider_links ( self , resource_ids = None ) : """Sets a provider chain in order from the most recent source to the originating source . : param resource _ ids : the new source : type resource _ ids : ` ` osid . id . Id [ ] ` ` : raise : ` ` InvalidArgument ` ` - - ` ` resource _ ids ` ` is invalid...
if resource_ids is None : raise NullArgument ( ) metadata = Metadata ( ** settings . METADATA [ 'provider_link_ids' ] ) if metadata . is_read_only ( ) : raise NoAccess ( ) if self . _is_valid_input ( resource_ids , metadata , array = True ) : self . _my_map [ 'providerLinkIds' ] = [ ] for i in resource_...
def from_frame ( klass , frame , connection ) : """Create a new TaskStateChange event from a Stompest Frame ."""
event = frame . headers [ 'new' ] data = json . loads ( frame . body ) info = data [ 'info' ] task = Task . fromDict ( info ) task . connection = connection return klass ( task , event )
def read ( self , x ) : """Read from the memory . An external component can use the results via a simple MLP , e . g . , fn ( x W _ x + retrieved _ mem W _ m ) . Args : x : a tensor in the shape of [ batch _ size , length , depth ] . Returns : access _ logits : the logits for accessing the memory in sha...
access_logits = self . _address_content ( x ) weights = tf . nn . softmax ( access_logits ) retrieved_mem = tf . reduce_sum ( tf . multiply ( tf . expand_dims ( weights , 3 ) , tf . expand_dims ( self . mem_vals , axis = 1 ) ) , axis = 2 ) return access_logits , retrieved_mem
def universal_transformer_with_lstm_as_transition_function ( layer_inputs , step , hparams , ffn_unit , attention_unit , pad_remover = None ) : """Universal Transformer which uses a lstm as transition function . It ' s kind of like having a lstm , filliped vertically next to the Universal Transformer that contr...
state , unused_inputs , memory = tf . unstack ( layer_inputs , num = None , axis = 0 , name = "unstack" ) # NOTE : # state ( ut _ state ) : output of the lstm in the previous step # inputs ( ut _ input ) : original input - - > we don ' t use it here # memory : lstm memory # Multi _ head _ attention : assert not hparams...
def intersect_regions ( flist ) : """Construct a region which is the intersection of all regions described in the given list of file names . Parameters flist : list A list of region filenames . Returns region : : class : ` AegeanTools . regions . Region ` The intersection of all regions , possibly emp...
if len ( flist ) < 2 : raise Exception ( "Require at least two regions to perform intersection" ) a = Region . load ( flist [ 0 ] ) for b in [ Region . load ( f ) for f in flist [ 1 : ] ] : a . intersect ( b ) return a
def reset ( self ) : """Reseting wrapped function"""
super ( SinonSpy , self ) . unwrap ( ) super ( SinonSpy , self ) . wrap2spy ( )
def run ( self , script_file , args = None , verbose = False ) : """The run command will execute a command script from the file pointed to by the file argument , which should contain Cytoscape commands , one per line . Arguments to the script are provided by the args argument . : param script _ file : file to...
PARAMS = set_param ( [ "file" , "args" ] , [ script_file , args ] ) response = api ( url = self . __url + "/run" , PARAMS = PARAMS , verbose = verbose ) return response
def get_measurements_from_kal_scan ( kal_out ) : """Return a list of all measurements from kalibrate channel scan ."""
result = [ ] for line in kal_out . splitlines ( ) : if "offset " in line : p_line = line . split ( ' ' ) result . append ( p_line [ - 1 ] ) return result
def unique_authors ( self , limit ) : """Unique list of authors , but preserving order ."""
seen = set ( ) if limit == 0 : limit = None seen_add = seen . add # Assign to variable , so not resolved each time return [ x . author for x in self . sorted_commits [ : limit ] if not ( x . author in seen or seen_add ( x . author ) ) ]
def daterange_end ( value ) : '''Parse a date range end boundary'''
if not value : return None elif isinstance ( value , datetime ) : return value . date ( ) elif isinstance ( value , date ) : return value result = parse_dt ( value ) . date ( ) dashes = value . count ( '-' ) if dashes >= 2 : # Full date return result elif dashes == 1 : # Year / Month return result +...
def get_compositions_by_repositories ( self , repository_ids ) : """Gets the list of ` ` Compositions ` ` corresponding to a list of ` ` Repository ` ` objects . arg : repository _ ids ( osid . id . IdList ) : list of repository ` ` Ids ` ` return : ( osid . repository . CompositionList ) - list of Compositio...
# Implemented from template for # osid . resource . ResourceBinSession . get _ resources _ by _ bins composition_list = [ ] for repository_id in repository_ids : composition_list += list ( self . get_compositions_by_repository ( repository_id ) ) return objects . CompositionList ( composition_list )
def formfield_for_dbfield ( self , db_field , ** kwargs ) : """Hook for specifying the form Field instance for a given database Field instance . If kwargs are given , they ' re passed to the form Field ' s constructor . Default implementation uses the overrides returned by ` get _ formfield _ overrides ` . ...
overides = self . get_formfield_overrides ( ) # If we ' ve got overrides for the formfield defined , use ' em . * * kwargs # passed to formfield _ for _ dbfield override the defaults . for klass in db_field . __class__ . mro ( ) : if klass in overides : kwargs = dict ( overides [ klass ] , ** kwargs ) ...
def disable_oozie_ha ( self , active_name ) : """Disable high availability for Oozie @ param active _ name : Name of the Oozie Server that will be active after High Availability is disabled . @ return : Reference to the submitted command . @ since : API v6"""
args = dict ( activeName = active_name ) return self . _cmd ( 'oozieDisableHa' , data = args , api_version = 6 )
def sample ( self , count , ** kwargs ) : """Use rejection sampling to generate random points inside a polygon . Parameters count : int Number of points to return If there are multiple bodies , there will be up to count * bodies points returned factor : float How many points to test per loop IE , ...
poly = self . polygons_full if len ( poly ) == 0 : samples = np . array ( [ ] ) elif len ( poly ) == 1 : samples = polygons . sample ( poly [ 0 ] , count = count , ** kwargs ) else : samples = util . vstack_empty ( [ polygons . sample ( i , count = count , ** kwargs ) for i in poly ] ) return samples
def reconstitute ( html ) : """Given a file - like object as ` ` html ` ` , reconstruct it into models ."""
try : htree = etree . parse ( html ) except etree . XMLSyntaxError : html . seek ( 0 ) htree = etree . HTML ( html . read ( ) ) xhtml = etree . tostring ( htree , encoding = 'utf-8' ) return adapt_single_html ( xhtml )
def builtin ( self , ref , context = None ) : """Get whether the specified reference is an ( xs ) builtin . @ param ref : A str or qref . @ type ref : ( str | qref ) @ return : True if builtin , else False . @ rtype : bool"""
w3 = 'http://www.w3.org' try : if isqref ( ref ) : ns = ref [ 1 ] return ref [ 0 ] in Factory . tags and ns . startswith ( w3 ) if context is None : context = self . root prefix = splitPrefix ( ref ) [ 0 ] prefixes = context . findPrefixes ( w3 , 'startswith' ) return prefix ...
def _list_queues ( self , prefix = None , marker = None , max_results = None , include = None , timeout = None , _context = None ) : '''Returns a list of queues under the specified account . Makes a single list request to the service . Used internally by the list _ queues method . : param str prefix : Filters...
request = HTTPRequest ( ) request . method = 'GET' request . host_locations = self . _get_host_locations ( secondary = True ) request . path = _get_path ( ) request . query = { 'comp' : 'list' , 'prefix' : _to_str ( prefix ) , 'marker' : _to_str ( marker ) , 'maxresults' : _int_to_str ( max_results ) , 'include' : _to_...
def reset_topology_change_flag ( self ) : """Set topology _ change attribute to False in all hosts and services : return : None"""
for i in self . hosts : i . topology_change = False for i in self . services : i . topology_change = False
def get_rank ( self , member , reverse = False , pipe = None ) : """Return the rank of * member * in the collection . By default , the member with the lowest score has rank 0. If * reverse * is ` ` True ` ` , the member with the highest score has rank 0."""
pipe = self . redis if pipe is None else pipe method = getattr ( pipe , 'zrevrank' if reverse else 'zrank' ) rank = method ( self . key , self . _pickle ( member ) ) return rank
def set_address ( self , address ) : """Set the radio address to be used"""
if len ( address ) != 5 : raise Exception ( 'Crazyradio: the radio address shall be 5' ' bytes long' ) if address != self . current_address : _send_vendor_setup ( self . handle , SET_RADIO_ADDRESS , 0 , 0 , address ) self . current_address = address
def increase_i ( self ) : """i means the ith round . Increase i by 1"""
self . i += 1 if self . i > self . bracket_id : self . no_more_trial = True
async def settings ( dev : Device ) : """Print out all possible settings ."""
settings_tree = await dev . get_settings ( ) for module in settings_tree : await traverse_settings ( dev , module . usage , module . settings )
def _check_stack_for_module_return ( stack ) : """Verify that the stack is in the expected state before the dummy RETURN _ VALUE instruction of a module or class ."""
fail = ( len ( stack ) != 1 or not isinstance ( stack [ 0 ] , instrs . LOAD_CONST ) or stack [ 0 ] . arg is not None ) if fail : raise DecompilationError ( "Reached end of non-function code " "block with unexpected stack: %s." % stack )
def _groups_of ( length , total_length ) : """Return an iterator of tuples for slicing , in ' length ' chunks . Parameters length : int Length of each chunk . total _ length : int Length of the object we are slicing Returns iterable of tuples Values defining a slice range resulting in length ' lengt...
indices = tuple ( range ( 0 , total_length , length ) ) + ( None , ) return _pairwise ( indices )
def get_whitelist_page ( self , page_number = None , page_size = None ) : """Gets a paginated list of indicators that the user ' s company has whitelisted . : param int page _ number : the page number to get . : param int page _ size : the size of the page to be returned . : return : A | Page | of | Indicator...
params = { 'pageNumber' : page_number , 'pageSize' : page_size } resp = self . _client . get ( "whitelist" , params = params ) return Page . from_dict ( resp . json ( ) , content_type = Indicator )
def initialize ( ) : """All named pins in OUTPUT _ PINS and INPUT _ PINS are exported , and set the HALT pin high ( normal running state ) , since the default value after export is low ."""
for pin in sorted ( OUTPUT_PINS . values ( ) ) : _enable_pin ( pin , OUT ) for pin in sorted ( INPUT_PINS . values ( ) ) : _enable_pin ( pin , IN )
def notify ( name , states , callback ) : '''executes the callback function with no parameters when the container reaches the specified state or states states can be or - ed or and - ed notify ( ' test ' , ' STOPPED ' , letmeknow ) notify ( ' test ' , ' STOPPED | RUNNING ' , letmeknow )'''
if not exists ( name ) : raise ContainerNotExists ( "The container (%s) does not exist!" % name ) cmd = [ 'lxc-wait' , '-n' , name , '-s' , states ] def th ( ) : subprocess . check_call ( cmd ) callback ( ) _logger . info ( "Waiting on states %s for container %s" , states , name ) threading . Thread ( targe...
def click ( self , x , y ) : '''click at arbitrary coordinates .'''
return self . server . jsonrpc . click ( x , y )
def plot_profile_histogram ( x , y , n_bins = 100 , title = None , x_label = None , y_label = None , log_y = False , filename = None ) : '''Takes 2D point data ( x , y ) and creates a profile histogram similar to the TProfile in ROOT . It calculates the y mean for every bin at the bin center and gives the y mean ...
if len ( x ) != len ( y ) : raise ValueError ( 'x and y dimensions have to be the same' ) n , bin_edges = np . histogram ( x , bins = n_bins ) # needed to calculate the number of points per bin sy = np . histogram ( x , bins = n_bins , weights = y ) [ 0 ] # the sum of the bin values sy2 = np . histogram ( x , bins ...
def update ( gandi , resource , memory , cores , console , password , background , reboot ) : """Update a virtual machine . Resource can be a Hostname or an ID"""
pwd = None if password : pwd = click . prompt ( 'password' , hide_input = True , confirmation_prompt = True ) max_memory = None if memory : max_memory = gandi . iaas . required_max_memory ( resource , memory ) if max_memory and not reboot : gandi . echo ( 'memory update must be done offline.' ) if not c...
def raises_not_implemented ( self ) : """Check if this node raises a : class : ` NotImplementedError ` . : returns : True if this node raises a : class : ` NotImplementedError ` , False otherwise . : rtype : bool"""
if not self . exc : return False for name in self . exc . _get_name_nodes ( ) : if name . name == "NotImplementedError" : return True return False
def create_result ( self , ip , host_port , container_port , meta , val , dividers ) : """The format is the same as the default docker cli client : : ip : hostPort : containerPort | ip : : containerPort | hostPort : containerPort | containerPort"""
if host_port in ( '' , NotSpecified ) and container_port in ( '' , NotSpecified ) : container_port = ip ip = NotSpecified host_port = NotSpecified elif container_port in ( '' , NotSpecified ) : container_port = host_port host_port = ip ip = NotSpecified elif host_port in ( '' , NotSpecified ) : ...
def render ( self ) : '''Renders widget to template'''
data = self . prepare_data ( ) if self . field . readable : return self . env . template . render ( self . template , ** data ) return ''
def unlock_account ( account ) : """Unlock the account . : param account : Account : return :"""
return Web3Provider . get_web3 ( ) . personal . unlockAccount ( account . address , account . password )
def _evaluate ( self , R , z , phi = 0. , t = 0. ) : """NAME : _ evaluate PURPOSE : evaluate the potential at R , z INPUT : R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT : Phi ( R , z ) HISTORY : 2015-02-07 - Written - Bovy ( IAS )"""
return self . _mn3 [ 0 ] ( R , z , phi = phi , t = t ) + self . _mn3 [ 1 ] ( R , z , phi = phi , t = t ) + self . _mn3 [ 2 ] ( R , z , phi = phi , t = t )
def get_token ( self ) : """Gets the authorization token"""
payload = { 'grant_type' : 'client_credentials' , 'client_id' : self . client_id , 'client_secret' : self . client_secret } r = requests . post ( OAUTH_ENDPOINT , data = json . dumps ( payload ) , headers = { 'content-type' : 'application/json' } ) response = r . json ( ) if r . status_code != 200 and not ERROR_KEY in ...
def contents ( self ) : """Returns the item in the container , if there is one . This will be a standard item object ."""
rawitem = self . _item . get ( "contained_item" ) if rawitem : return self . __class__ ( rawitem , self . _schema )
def _find_models ( self , constructor , table_name , constraints = None , * , columns = None , order_by = None , limiting = None ) : """Calls DataAccess . find _ all and passes the results to the given constructor ."""
for record in self . find_all ( table_name , constraints , columns = columns , order_by = order_by , limiting = limiting ) : yield constructor ( record )
def unzip_manifest ( self , raw_manifest ) : """Decompress gzip encoded manifest : type raw _ manifest : str : param raw _ manifest : compressed gzip manifest file content"""
buf = BytesIO ( raw_manifest ) f = gzip . GzipFile ( fileobj = buf ) manifest = f . read ( ) return manifest
def check ( self , records ) : """Check current value ."""
for value , target in records : LOGGER . info ( "%s [%s]: %s" , self . name , target , value ) if value is None : self . notify ( self . no_data , value , target ) continue for rule in self . rules : if self . evaluate_rule ( rule , value , target ) : self . notify ( rule...
def input_has_value ( step , field_name , value ) : """Check that the form input element has given value ."""
with AssertContextManager ( step ) : text_field = find_any_field ( world . browser , DATE_FIELDS + TEXT_FIELDS , field_name ) assert_false ( step , text_field is False , 'Can not find a field named "%s"' % field_name ) assert_equals ( text_field . get_attribute ( 'value' ) , value )
def append_note ( self , player , text ) : """Append text to an already existing note ."""
note = self . _find_note ( player ) note . text += text
def _preconditions_snapshots_postconditions ( checker : Callable ) -> _PrePostSnaps : """Collect the preconditions , snapshots and postconditions from a contract checker of a function ."""
preconditions = getattr ( checker , "__preconditions__" , [ ] ) # type : List [ List [ icontract . _ Contract ] ] assert all ( isinstance ( precondition_group , list ) for precondition_group in preconditions ) assert ( all ( isinstance ( precondition , icontract . _Contract ) for precondition_group in preconditions for...
def user ( self , username ) : """Returns the : class : ` ~ plexapi . myplex . MyPlexUser ` that matches the email or username specified . Parameters : username ( str ) : Username , email or id of the user to return ."""
for user in self . users ( ) : # Home users don ' t have email , username etc . if username . lower ( ) == user . title . lower ( ) : return user elif ( user . username and user . email and user . id and username . lower ( ) in ( user . username . lower ( ) , user . email . lower ( ) , str ( user . id )...
def _get_tough_method ( self , method ) : """Return a " tough " version of a connection class method . The tough version checks whether the connection is bad ( lost ) and automatically and transparently tries to reset the connection if this is the case ( for instance , the database has been restarted ) ."""
def tough_method ( * args , ** kwargs ) : transaction = self . _transaction if not transaction : try : # check whether connection status is bad if not self . _con . db . status : raise AttributeError if self . _maxusage : # or connection used too often ...
def relevantindices ( self ) -> List [ int ] : """A | list | of all currently relevant indices , calculated as an intercection of the ( constant ) class attribute ` RELEVANT _ VALUES ` and the ( variable ) property | IndexMask . refindices | ."""
return [ idx for idx in numpy . unique ( self . refindices . values ) if idx in self . RELEVANT_VALUES ]
def by_filenumber ( self ) : """Iterates over categories and returns a filtered datamat . If a categories object is attached , the images object for the given category is returned as well ( else None is returned ) . Returns : ( datamat , categories ) : A tuple that contains first the filtered datamat ( ha...
for value in np . unique ( self . filenumber ) : file_fm = self . filter ( self . filenumber == value ) if self . _categories : yield ( file_fm , self . _categories [ self . category [ 0 ] ] [ value ] ) else : yield ( file_fm , None )
def filter ( select , iterable , namespaces = None , flags = 0 , ** kwargs ) : # noqa : A001 """Filter list of nodes ."""
return compile ( select , namespaces , flags , ** kwargs ) . filter ( iterable )
def mod_run_check ( onlyif , unless , creates ) : '''Execute the onlyif / unless / creates logic . Returns a result dict if any of the checks fail , otherwise returns True'''
cmd_kwargs = { 'use_vt' : False , 'bg' : False } if onlyif is not None : if isinstance ( onlyif , six . string_types ) : onlyif = [ onlyif ] if not isinstance ( onlyif , list ) or not all ( isinstance ( x , six . string_types ) for x in onlyif ) : return { 'comment' : 'onlyif is not a string or ...
def align_two_alignments ( aln1 , aln2 , moltype , params = None ) : """Returns an Alignment object from two existing Alignments . aln1 , aln2 : cogent . core . alignment . Alignment objects , or data that can be used to build them . - Mafft profile alignment only works with aligned sequences . Alignment ob...
# create SequenceCollection object from seqs aln1 = Alignment ( aln1 , MolType = moltype ) # Create mapping between abbreviated IDs and full IDs aln1_int_map , aln1_int_keys = aln1 . getIntMap ( ) # Create SequenceCollection from int _ map . aln1_int_map = Alignment ( aln1_int_map , MolType = moltype ) # create Alignme...
def diff_asymmetric ( self , catalogue , prime_label , tokenizer , output_fh ) : """Returns ` output _ fh ` populated with CSV results giving the difference in n - grams between the witnesses of labelled sets of works in ` catalogue ` , limited to those works labelled with ` prime _ label ` . : param catalo...
labels = list ( self . _set_labels ( catalogue ) ) if len ( labels ) < 2 : raise MalformedQueryError ( constants . INSUFFICIENT_LABELS_QUERY_ERROR ) try : labels . remove ( prime_label ) except ValueError : raise MalformedQueryError ( constants . LABEL_NOT_IN_CATALOGUE_ERROR ) label_placeholders = self . _g...
def set_cells ( self , cells_location ) : """Set self . cells to function : cells in file pathname . py : param cells _ location : cells location , format ' pathname . py : cells ' : return :"""
if ':' in cells_location : pathname , func_name = cells_location . split ( ':' ) else : pathname = cells_location func_name = 'cells' check_isfile ( pathname ) try : self . cells = get_func ( func_name , pathname ) except SyntaxError as e : fatal ( traceback . format_exc ( limit = 1 ) ) return pathn...
def ifft ( self ) : """Compute the one - dimensional discrete inverse Fourier transform of this ` FrequencySeries ` . Returns out : : class : ` ~ gwpy . timeseries . TimeSeries ` the normalised , real - valued ` TimeSeries ` . See Also : mod : ` scipy . fftpack ` for the definition of the DFT and conven...
from . . timeseries import TimeSeries nout = ( self . size - 1 ) * 2 # Undo normalization from TimeSeries . fft # The DC component does not have the factor of two applied # so we account for it here dift = npfft . irfft ( self . value * nout ) / 2 new = TimeSeries ( dift , epoch = self . epoch , channel = self . channe...
def paths_wanted ( self ) : """The set of paths where we expect to find missing nodes ."""
return set ( address . new ( b , target = 'all' ) for b in self . missing_nodes )
def transfer ( self , name , local , remote , ** kwargs ) : """Transfers the file with the given name from the local to the remote storage backend . : param name : The name of the file to transfer : param local : The local storage backend instance : param remote : The remote storage backend instance : ret...
try : remote . save ( name , local . open ( name ) ) return True except Exception as e : logger . error ( "Unable to save '%s' to remote storage. " "About to retry." % name ) logger . exception ( e ) return False
def remove_collisions ( self , min_dist = 0.5 ) : """Remove predicted sites that are too close to existing atoms in the structure . Args : min _ dist ( float ) : The minimum distance ( in Angstrom ) that a predicted site needs to be from existing atoms . A min _ dist with value < = 0 returns all sites wit...
s_f_coords = self . structure . frac_coords f_coords = self . extrema_coords if len ( f_coords ) == 0 : if self . extrema_type is None : logger . warning ( "Please run ChargeDensityAnalyzer.get_local_extrema first!" ) return new_f_coords = [ ] self . _update_extrema ( new_f_coords , self . e...
def show_guiref ( self ) : """Show qtconsole help"""
from qtconsole . usage import gui_reference self . main . help . show_rich_text ( gui_reference , collapse = True )
def compressBWT ( inputFN , outputFN , numProcs , logger ) : '''Current encoding scheme uses 3 LSB for the letter and 5 MSB for a count , note that consecutive ones of the same character combine to create one large count . So to represent 34A , you would have 00010 | 001 followed by 00001 | 001 which can be thoug...
# create bit spacings letterBits = 3 numberBits = 8 - letterBits numPower = 2 ** numberBits mask = 255 >> letterBits # load the thing to compress logger . info ( 'Loading src file...' ) bwt = np . load ( inputFN , 'r' ) logger . info ( 'Original size:' + str ( bwt . shape [ 0 ] ) + 'B' ) numProcs = min ( numProcs , bwt...
def optimise_levenberg_marquardt ( x , a , c , damping = 0.001 , tolerance = 0.001 ) : """Optimise value of x using levenberg - marquardt"""
x_new = x x_old = x - 1 # dummy value f_old = f ( x_new , a , c ) while np . abs ( x_new - x_old ) . sum ( ) > tolerance : x_old = x_new x_tmp = levenberg_marquardt_update ( x_old , a , c , damping ) f_new = f ( x_tmp , a , c ) if f_new < f_old : damping = np . max ( damping / 10. , 1e-20 ) ...
def oscltx ( state , et , mu ) : """Determine the set of osculating conic orbital elements that corresponds to the state ( position , velocity ) of a body at some epoch . In additional to the classical elements , return the true anomaly , semi - major axis , and period , if applicable . https : / / naif . j...
state = stypes . toDoubleVector ( state ) et = ctypes . c_double ( et ) mu = ctypes . c_double ( mu ) elts = stypes . emptyDoubleVector ( 20 ) libspice . oscltx_c ( state , et , mu , elts ) return stypes . cVectorToPython ( elts ) [ 0 : 11 ]
def on_shutdown ( self ) : """Respond to shutdown by sending close ( ) to every target , allowing their receive loop to exit and clean up gracefully ."""
LOG . debug ( '%r.on_shutdown()' , self ) for stream , state in self . _state_by_stream . items ( ) : state . lock . acquire ( ) try : for sender , fp in reversed ( state . jobs ) : sender . close ( ) fp . close ( ) state . jobs . pop ( ) finally : state ....
def get_nonconflicting_path_old ( base_fmtstr , dpath , offset = 0 ) : r"""base _ fmtstr must have a % d in it"""
import utool as ut from os . path import basename pattern = '*' dname_list = ut . glob ( dpath , pattern , recursive = False , with_files = True , with_dirs = True ) conflict_set = set ( [ basename ( dname ) for dname in dname_list ] ) newname = ut . get_nonconflicting_string ( base_fmtstr , conflict_set , offset = off...
def value_from_datadict ( self , data , files , name ) : """Returns uploaded file from serialized value ."""
upload = super ( StickyUploadWidget , self ) . value_from_datadict ( data , files , name ) if upload is not None : # File was posted or cleared as normal return upload else : # Try the hidden input hidden_name = self . get_hidden_name ( name ) value = data . get ( hidden_name , None ) if value is not No...
def get_context ( self , ** kwargs ) : """Use this method to built context data for the template Mix django wizard context data with django - xadmin context"""
context = self . get_context_data ( form = self . form_obj , ** kwargs ) context . update ( super ( FormAdminView , self ) . get_context ( ) ) return context
def create_resource_quota ( self , name , quota_json ) : """Prevent builds being scheduled and wait for running builds to finish . : return :"""
url = self . _build_k8s_url ( "resourcequotas/" ) response = self . _post ( url , data = json . dumps ( quota_json ) , headers = { "Content-Type" : "application/json" } ) if response . status_code == http_client . CONFLICT : url = self . _build_k8s_url ( "resourcequotas/%s" % name ) response = self . _put ( url...
def wait_until_exit ( self ) : """Wait until all the threads are finished ."""
[ t . join ( ) for t in self . threads ] self . threads = list ( )
def create_checkbox ( self , name , margin = 10 ) : """Function creates a checkbox with his name"""
chk_btn = Gtk . CheckButton ( name ) chk_btn . set_margin_right ( margin ) return chk_btn
def load_zip_data ( zipname , f_sino_real , f_sino_imag , f_angles = None , f_phantom = None , f_info = None ) : """Load example sinogram data from a . zip file"""
ret = [ ] with zipfile . ZipFile ( str ( zipname ) ) as arc : sino_real = np . loadtxt ( arc . open ( f_sino_real ) ) sino_imag = np . loadtxt ( arc . open ( f_sino_imag ) ) sino = sino_real + 1j * sino_imag ret . append ( sino ) if f_angles : angles = np . loadtxt ( arc . open ( f_angles ) ...
def n_segments ( neurites , neurite_type = NeuriteType . all ) : '''Number of segments in a collection of neurites'''
return sum ( len ( s . points ) - 1 for s in iter_sections ( neurites , neurite_filter = is_type ( neurite_type ) ) )
def name_conversion ( caffe_layer_name ) : """Convert a caffe parameter name to a tensorflow parameter name as defined in the above model"""
# beginning & end mapping NAME_MAP = { 'bn_conv1/beta' : 'conv0/bn/beta' , 'bn_conv1/gamma' : 'conv0/bn/gamma' , 'bn_conv1/mean/EMA' : 'conv0/bn/mean/EMA' , 'bn_conv1/variance/EMA' : 'conv0/bn/variance/EMA' , 'conv1/W' : 'conv0/W' , 'conv1/b' : 'conv0/b' , 'fc1000/W' : 'linear/W' , 'fc1000/b' : 'linear/b' } if caffe_la...
def is_dxlink ( x ) : ''': param x : A potential DNAnexus link Returns whether * x * appears to be a DNAnexus link ( is a dict with key ` ` " $ dnanexus _ link " ` ` ) with a referenced data object .'''
if not isinstance ( x , dict ) : return False if '$dnanexus_link' not in x : return False link = x [ '$dnanexus_link' ] if isinstance ( link , basestring ) : return True elif isinstance ( link , dict ) : return any ( key in link for key in ( 'id' , 'job' ) ) return False
def delete_repository ( self , namespace , repository ) : """DELETE / v1 / repositories / ( namespace ) / ( repository ) /"""
return self . _http_call ( self . REPO , delete , namespace = namespace , repository = repository )
async def read_message ( self ) -> Optional [ Data ] : """Read a single message from the connection . Re - assemble data frames if the message is fragmented . Return ` ` None ` ` when the closing handshake is started ."""
frame = await self . read_data_frame ( max_size = self . max_size ) # A close frame was received . if frame is None : return None if frame . opcode == OP_TEXT : text = True elif frame . opcode == OP_BINARY : text = False else : # frame . opcode = = OP _ CONT raise WebSocketProtocolError ( "Unexpected op...
def publish_api ( self , ret , stage_variables ) : '''this method tie the given stage _ name to a deployment matching the given swagger _ file'''
stage_desc = dict ( ) stage_desc [ 'current_deployment_label' ] = self . deployment_label stage_desc_json = _dict_to_json_pretty ( stage_desc ) if self . _deploymentId : # just do a reassociate of stage _ name to an already existing deployment res = self . _set_current_deployment ( stage_desc_json , stage_variables...
def process_request_thread ( self , request , client_address ) : """Process the request ."""
try : self . finish_request ( request , client_address ) self . shutdown_request ( request ) except Exception as e : self . logger . error ( e ) self . handle_error ( request , client_address ) self . shutdown_request ( request )
def set_position ( self , pos ) : """Seek in the current playing media ."""
time_in_ms = int ( pos ) * 1000 return self . apple_tv . set_property ( 'dacp.playingtime' , time_in_ms )
def list_users ( self , instance , limit = None , marker = None ) : """Returns all users for the specified instance ."""
return instance . list_users ( limit = limit , marker = marker )
def _set_attributes ( self , response , attribute_dict ) : """Set user attributes based on response code : param response : HTTP response from Cognito : attribute dict : Dictionary of attribute name and values"""
status_code = response . get ( 'HTTPStatusCode' , response [ 'ResponseMetadata' ] [ 'HTTPStatusCode' ] ) if status_code == 200 : for k , v in attribute_dict . items ( ) : setattr ( self , k , v )
def _get_task_host ( ) : """Get the Host header value for all mr tasks . Task Host header determines which instance this task would be routed to . Current version id format is : v7.368834058928280579 Current module id is just the module ' s name . It could be " default " Default version hostname is app _ id...
version = os . environ [ "CURRENT_VERSION_ID" ] . split ( "." ) [ 0 ] default_host = os . environ [ "DEFAULT_VERSION_HOSTNAME" ] module = os . environ [ "CURRENT_MODULE_ID" ] if os . environ [ "CURRENT_MODULE_ID" ] == "default" : return "%s.%s" % ( version , default_host ) return "%s.%s.%s" % ( version , module , d...
def getrepaymentsurl ( idcred , * args , ** kwargs ) : """Request loan Repayments URL . If idcred is set , you ' ll get a response adequate for a MambuRepayments object . There ' s a MambuRepayment object too , but you ' ll get a list first and each element of it will be automatically converted to a MambuRe...
url = getmambuurl ( * args , ** kwargs ) + "loans/" + idcred + "/repayments" return url
def scan ( self , file_or_stream ) : """: param file _ or _ stream : : class : ` Blob ` instance , filename or file object : returns : True if file is ' clean ' , False if a virus is detected , None if file could not be scanned . If ` file _ or _ stream ` is a Blob , scan result is stored in Blob . meta [ '...
if not clamd : return None res = self . _scan ( file_or_stream ) if isinstance ( file_or_stream , Blob ) : file_or_stream . meta [ "antivirus" ] = res return res
def getCurrentItem ( self ) : # TODO : rename ? getCurrentItemAndIndex ? getCurrentTuple ? getCurrent ? """Find the current tree item ( and the current index while we ' re at it ) Returns a tuple with the current item , and its index . The item may be None . See also the notes at the top of this module on curre...
currentIndex = self . getRowCurrentIndex ( ) currentItem = self . model ( ) . getItem ( currentIndex ) return currentItem , currentIndex