signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def implany ( self ) : """Set the type to < xsd : any / > when implicit . An element has an implicit < xsd : any / > type when it has no body and no explicitly defined type . @ return : self @ rtype : L { Element }"""
if self . type is None and self . ref is None and self . root . isempty ( ) : self . type = self . anytype ( )
def start_worker_message_handler ( self ) : """Start the worker message handler thread , that loops over messages from workers ( job progress updates , failures and successes etc . ) and then updates the job ' s status . Returns : None"""
t = InfiniteLoopThread ( func = lambda : self . handle_worker_messages ( timeout = 2 ) , thread_name = "WORKERMESSAGEHANDLER" , wait_between_runs = 0.5 ) t . start ( ) return t
def patch ( source , sink ) : """Create a direct link between a source and a sink . Implementation : : sink = sink ( ) for value in source ( ) : sink . send ( value ) . . | patch | replace : : : py : func : ` patch `"""
sink = sink ( ) for v in source ( ) : try : sink . send ( v ) except StopIteration : return
def getSrcDatasetParents ( self , url , dataset ) : """List block at src DBS"""
# resturl = " % s / datasetparents ? dataset = % s " % ( url , dataset ) params = { 'dataset' : dataset } return cjson . decode ( self . callDBSService ( url , 'datasetparents' , params , { } ) )
def save_tiles ( tiles , prefix = '' , directory = os . getcwd ( ) , format = 'png' ) : """Write image files to disk . Create specified folder ( s ) if they don ' t exist . Return list of : class : ` Tile ` instance . Args : tiles ( list ) : List , tuple or set of : class : ` Tile ` objects to save . prefix...
# Causes problems in CLI script . # if not os . path . exists ( directory ) : # os . makedirs ( directory ) for tile in tiles : tile . save ( filename = tile . generate_filename ( prefix = prefix , directory = directory , format = format ) , format = format ) return tuple ( tiles )
def search ( self , name ) : """Search node with given name based on regexp , basic method ( find ) uses equality"""
for node in self . climb ( ) : if re . search ( name , node . name ) : return node return None
def get_context ( self ) : """Return the context used to render the templates for the email subject and body . By default , this context includes : * All of the validated values in the form , as variables of the same names as their fields . * The current ` ` Site ` ` object , as the variable ` ` site ` ` ...
if not self . is_valid ( ) : raise ValueError ( "Cannot generate Context from invalid contact form" ) return dict ( self . cleaned_data , site = get_current_site ( self . request ) )
def request ( self , method , url , query_params = None , headers = None , body = None , post_params = None ) : """: param method : http request method : param url : http request url : param query _ params : query parameters in the url : param headers : http request headers : param body : request json body ...
method = method . upper ( ) assert method in [ 'GET' , 'HEAD' , 'DELETE' , 'POST' , 'PUT' , 'PATCH' , 'OPTIONS' ] if post_params and body : raise ValueError ( "body parameter cannot be used with post_params parameter." ) post_params = post_params or { } headers = headers or { } if 'Content-Type' not in headers : ...
def write_ds9region ( self , region , * args , ** kwargs ) : """Create a ds9 compatible region file from the ROI . It calls the ` to _ ds9 ` method and write the result to the region file . Only the file name is required . All other parameters will be forwarded to the ` to _ ds9 ` method , see the documentation...
lines = self . to_ds9 ( * args , ** kwargs ) with open ( region , 'w' ) as fo : fo . write ( "\n" . join ( lines ) )
def provides ( * specification ) : """Decorator marking wrapped : py : class : ` Module ` method as : term : ` provider ` for given : term : ` specification ` . For example : : class ApplicationModule ( Module ) : @ provides ( ' db _ connection ' ) def provide _ db _ connection ( self ) : return DBConne...
if len ( specification ) == 1 : specification = specification [ 0 ] else : specification = tuple ( specification ) def decorator ( function ) : function . __provides__ = specification return function return decorator
def lookup ( self , inc_raw = False , retry_count = 3 , asn_alts = None , extra_org_map = None , asn_methods = None , get_asn_description = True ) : """The wrapper function for retrieving and parsing ASN information for an IP address . Args : inc _ raw ( : obj : ` bool ` ) : Whether to include the raw results...
if asn_methods is None : if asn_alts is None : lookups = [ 'dns' , 'whois' , 'http' ] else : from warnings import warn warn ( 'IPASN.lookup() asn_alts argument has been deprecated ' 'and will be removed. You should now use the asn_methods ' 'argument.' ) lookups = [ 'dns' ] + asn...
def parse_args ( ) : """Parses the arguments and options ."""
parser = argparse . ArgumentParser ( prog = "geneparse-extractor" , description = "Genotype file extractor. This tool will extract markers " "according to names or to genomic locations." , epilog = "The parser arguments (PARSER_ARGS) are the same as the one in " "the API. For example, the arguments for the Plink parser...
def _map_values ( self , mapper , na_action = None ) : """An internal function that maps values using the input correspondence ( which can be a dict , Series , or function ) . Parameters mapper : function , dict , or Series The input correspondence object na _ action : { None , ' ignore ' } If ' ignore ...
# we can fastpath dict / Series to an efficient map # as we know that we are not going to have to yield # python types if isinstance ( mapper , dict ) : if hasattr ( mapper , '__missing__' ) : # If a dictionary subclass defines a default value method , # convert mapper to a lookup function ( GH # 15999 ) . ...
def respond ( self , output ) : """Generates server response ."""
response = { 'exit_code' : output . code , 'command_output' : output . log } self . send_response ( 200 ) self . send_header ( 'Content-type' , 'application/json' ) self . end_headers ( ) self . wfile . write ( bytes ( json . dumps ( response ) , "utf8" ) )
def task_done ( self ) -> None : """Indicate that a formerly enqueued task is complete . Used by queue consumers . For each ` . get ` used to fetch a task , a subsequent call to ` . task _ done ` tells the queue that the processing on the task is complete . If a ` . join ` is blocking , it resumes when all ...
if self . _unfinished_tasks <= 0 : raise ValueError ( "task_done() called too many times" ) self . _unfinished_tasks -= 1 if self . _unfinished_tasks == 0 : self . _finished . set ( )
def validate_rid ( model , rid ) : """Ensure the resource id is proper"""
rid_field = getattr ( model , model . rid_field ) if isinstance ( rid_field , IntType ) : try : int ( rid ) except ( TypeError , ValueError ) : abort ( exceptions . InvalidURL ( ** { 'detail' : 'The resource id {} in your request is not ' 'syntactically correct. Only numeric type ' 'resource id\...
def runjava ( self , classpath , main , jvm_options = None , args = None , workunit_name = None , workunit_labels = None , workunit_log_config = None , dist = None ) : """Runs the java main using the given classpath and args . If - - execution - strategy = subprocess is specified then the java main is run in a fr...
executor = self . create_java_executor ( dist = dist ) # Creating synthetic jar to work around system arg length limit is not necessary # when ` NailgunExecutor ` is used because args are passed through socket , therefore turning off # creating synthetic jar if nailgun is used . create_synthetic_jar = self . execution_...
def mark_address ( self , addr , size ) : """Marks address as being used in simulator"""
i = 0 while i < size : self . _register_map [ addr ] = True i += 1
def maybe_clean ( self ) : """Clean the cache if it ' s time to do so ."""
now = time . time ( ) if self . next_cleaning <= now : keys_to_delete = [ ] for ( k , v ) in self . data . iteritems ( ) : if v . expiration <= now : keys_to_delete . append ( k ) for k in keys_to_delete : del self . data [ k ] now = time . time ( ) self . next_cleaning =...
def inspiral_range_psd ( psd , snr = 8 , mass1 = 1.4 , mass2 = 1.4 , horizon = False ) : """Compute the inspiral sensitive distance PSD from a GW strain PSD Parameters psd : ` ~ gwpy . frequencyseries . FrequencySeries ` the instrumental power - spectral - density data snr : ` float ` , optional the signa...
# compute chirp mass and symmetric mass ratio mass1 = units . Quantity ( mass1 , 'solMass' ) . to ( 'kg' ) mass2 = units . Quantity ( mass2 , 'solMass' ) . to ( 'kg' ) mtotal = mass1 + mass2 mchirp = ( mass1 * mass2 ) ** ( 3 / 5. ) / mtotal ** ( 1 / 5. ) # compute ISCO fisco = ( constants . c ** 3 / ( constants . G * 6...
def process_pybel_neighborhood ( gene_names , network_file = None , network_type = 'belscript' , ** kwargs ) : """Return PybelProcessor around neighborhood of given genes in a network . This function processes the given network file and filters the returned Statements to ones that contain genes in the given lis...
if network_file is None : # Use large corpus as base network network_file = os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , os . path . pardir , os . path . pardir , os . path . pardir , 'data' , 'large_corpus.bel' ) if network_type == 'belscript' : bp = process_belscript ( network...
def iodp_srm_lore ( srm_file , dir_path = "." , input_dir_path = "" , noave = False , comp_depth_key = 'Depth CSF-B (m)' , meas_file = "srm_arch_measurements.txt" , spec_file = "srm_arch_specimens.txt" , samp_file = 'srm_arch_samples.txt' , site_file = 'srm_arch_sites.txt' , lat = "" , lon = "" ) : """Convert IODP ...
# initialize defaults version_num = pmag . get_version ( ) # format variables input_dir_path , output_dir_path = pmag . fix_directories ( input_dir_path , dir_path ) # convert cc to m ^ 3 meas_reqd_columns = [ 'specimen' , 'measurement' , 'experiment' , 'sequence' , 'quality' , 'method_codes' , 'instrument_codes' , 'ci...
def is_parsable ( url ) : """Check if the given URL is parsable ( make sure it ' s a valid URL ) . If it is parsable , also cache it . Args : url ( str ) : The URL to check . Returns : bool : True if parsable , False otherwise ."""
try : parsed = urlparse ( url ) URLHelper . __cache [ url ] = parsed return True except : return False
def big_dataframe_setup ( ) : # pragma : no cover """Sets pandas to display really big data frames ."""
pd . set_option ( 'display.max_colwidth' , sys . maxsize ) pd . set_option ( 'max_colwidth' , sys . maxsize ) # height has been deprecated . # pd . set _ option ( ' display . height ' , sys . maxsize ) pd . set_option ( 'display.max_rows' , sys . maxsize ) pd . set_option ( 'display.width' , sys . maxsize ) pd . set_op...
def inc_from_lat ( lat ) : """Calculate inclination predicted from latitude using the dipole equation Parameter lat : latitude in degrees Returns inc : inclination calculated using the dipole equation"""
rad = old_div ( np . pi , 180. ) inc = old_div ( np . arctan ( 2 * np . tan ( lat * rad ) ) , rad ) return inc
def file_copy ( self , source , destination , flags ) : """Copies a file from one guest location to another . Will overwrite the destination file unless : py : attr : ` FileCopyFlag . no _ replace ` is specified . in source of type str The path to the file to copy ( in the guest ) . Guest path style . in ...
if not isinstance ( source , basestring ) : raise TypeError ( "source can only be an instance of type basestring" ) if not isinstance ( destination , basestring ) : raise TypeError ( "destination can only be an instance of type basestring" ) if not isinstance ( flags , list ) : raise TypeError ( "flags can ...
def fullName ( self ) : """A full name , intended to uniquely identify a parameter"""
# join with ' _ ' if both are set ( cannot put ' . ' , because it is used as # * * kwargs ) if self . parentName and self . name : return self . parentName + '_' + self . name # otherwise just use the one that is set # ( this allows empty name for " anonymous nests " ) return self . name or self . parentName
def is_all ( self ) -> bool : """True if the sequence set starts at ` ` 1 ` ` and ends at the maximum value . This may be used to optimize cases of checking for a value in the set , avoiding the need to provide ` ` max _ value ` ` in : meth : ` . flatten ` or : meth : ` . iter ` ."""
first = self . sequences [ 0 ] return isinstance ( first , tuple ) and first [ 0 ] == 1 and isinstance ( first [ 1 ] , MaxValue )
def printex ( ex , msg = '[!?] Caught exception' , prefix = None , key_list = [ ] , locals_ = None , iswarning = False , tb = TB , pad_stdout = True , N = 0 , use_stdout = False , reraise = False , msg_ = None , keys = None , colored = None ) : """Prints ( and / or logs ) an exception with relevant info Args : ...
import utool as ut if isinstance ( ex , MemoryError ) : ut . print_resource_usage ( ) if keys is not None : # shorthand for key _ list key_list = keys # Get error prefix and local info if prefix is None : prefix = get_caller_prefix ( aserror = True , N = N ) if locals_ is None : locals_ = get_parent_fra...
def _Bound_Ps ( P , s ) : """Region definition for input P and s Parameters P : float Pressure , [ MPa ] s : float Specific entropy , [ kJ / kgK ] Returns region : float IAPWS - 97 region code References Wagner , W ; Kretzschmar , H - J : International Steam Tables : Properties of Water and St...
region = None if Pmin <= P <= Ps_623 : smin = _Region1 ( 273.15 , P ) [ "s" ] s14 = _Region1 ( _TSat_P ( P ) , P ) [ "s" ] s24 = _Region2 ( _TSat_P ( P ) , P ) [ "s" ] s25 = _Region2 ( 1073.15 , P ) [ "s" ] smax = _Region5 ( 2273.15 , P ) [ "s" ] if smin <= s <= s14 : region = 1 elif...
def compute_checksum ( self , payload_offset : Optional [ int ] = None ) : '''Compute and add the checksum data to the record fields . This function also sets the content length .'''
if not self . block_file : self . fields [ 'Content-Length' ] = '0' return block_hasher = hashlib . sha1 ( ) payload_hasher = hashlib . sha1 ( ) with wpull . util . reset_file_offset ( self . block_file ) : if payload_offset is not None : data = self . block_file . read ( payload_offset ) bl...
def can_allow_multiple_input_shapes ( spec ) : """Examines a model specification and determines if it can compute results for more than one output shape . : param spec : MLModel The protobuf specification of the model . : return : Bool Returns True if the model can allow multiple input shapes , False otherw...
# First , check that the model actually has a neural network in it try : layers = _get_nn_layers ( spec ) except : raise Exception ( 'Unable to verify that this model contains a neural network.' ) try : shaper = NeuralNetworkShaper ( spec , False ) except : raise Exception ( 'Unable to compute shapes fo...
def lnprior ( x ) : """Return the log prior given parameter vector ` x ` ."""
per , t0 , b = x if b < - 1 or b > 1 : return - np . inf elif per < 7 or per > 10 : return - np . inf elif t0 < 1978 or t0 > 1979 : return - np . inf else : return 0.
def canon_ref ( did : str , ref : str , delimiter : str = None ) : """Given a reference in a DID document , return it in its canonical form of a URI . : param did : DID acting as the identifier of the DID document : param ref : reference to canonicalize , either a DID or a fragment pointing to a location in the...
if not ok_did ( did ) : raise BadIdentifier ( 'Bad DID {} cannot act as DID document identifier' . format ( did ) ) if ok_did ( ref ) : # e . g . , LjgpST2rjsoxYegQDRm7EL return 'did:sov:{}' . format ( did ) if ok_did ( resource ( ref , delimiter ) ) : # e . g . , LjgpST2rjsoxYegQDRm7EL # keys - 1 return 'd...
def format_json ( item , ** kwargs ) : """formats a datatype object to a json value"""
try : json . dumps ( item . value ) return item . value except TypeError : if 'time' in item . class_type . lower ( ) or 'date' in item . class_type . lower ( ) : return item . value . isoformat ( ) raise
def filter ( self , record ) : """Adds user and remote _ addr to the record ."""
request = get_request ( ) if request : user = getattr ( request , 'user' , None ) if user and not user . is_anonymous ( ) : record . username = user . username else : record . username = '-' meta = getattr ( request , 'META' , { } ) record . remote_addr = meta . get ( 'REMOTE_ADDR' ,...
def insertPreviousCommand ( self ) : """Inserts the previous command from history into the line ."""
self . _currentHistoryIndex -= 1 if 0 <= self . _currentHistoryIndex < len ( self . _history ) : cmd = self . _history [ self . _currentHistoryIndex ] else : cmd = '>>> ' self . _currentHistoryIndex = len ( self . _history ) self . replaceCommand ( cmd )
def play_state ( self ) : """Play state , e . g . playing or paused ."""
state = parser . first ( self . playstatus , 'cmst' , 'caps' ) return convert . playstate ( state )
def make_private ( self , client = None ) : """Update blob ' s ACL , revoking read access for anonymous users . : type client : : class : ` ~ google . cloud . storage . client . Client ` or ` ` NoneType ` ` : param client : Optional . The client to use . If not passed , falls back to the ` ` client ` ` stor...
self . acl . all ( ) . revoke_read ( ) self . acl . save ( client = client )
def get_key_codes ( keys ) : """Calculates the list of key codes from a string with key combinations . Ex : ' CTRL + A ' will produce the output ( 17 , 65)"""
keys = keys . strip ( ) . upper ( ) . split ( '+' ) codes = list ( ) for key in keys : code = ks_settings . KEY_CODES . get ( key . strip ( ) ) if code : codes . append ( code ) return codes
def renameMenu ( self ) : """Prompts the user to supply a new name for the menu ."""
item = self . uiMenuTREE . currentItem ( ) name , accepted = QInputDialog . getText ( self , 'Rename Menu' , 'Name:' , QLineEdit . Normal , item . text ( 0 ) ) if ( accepted ) : item . setText ( 0 , name )
def tableexists ( tablename ) : """Test if a table exists ."""
result = True try : t = table ( tablename , ack = False ) except : result = False return result
def get_variable ( self , variable_name , client = None ) : """API call : get a variable via a ` ` GET ` ` request . This will return None if the variable doesn ' t exist : : > > > from google . cloud import runtimeconfig > > > client = runtimeconfig . Client ( ) > > > config = client . config ( ' my - conf...
client = self . _require_client ( client ) variable = Variable ( config = self , name = variable_name ) try : variable . reload ( client = client ) return variable except NotFound : return None
def sink ( self , * args , ** kwargs ) : """Define URL prefixes / handler matches where everything under the URL prefix should be handled"""
kwargs [ 'api' ] = self . api return sink ( * args , ** kwargs )
def result ( self , timeout = None , do_raise = True ) : """Retrieve the result of the future , waiting for it to complete or at max * timeout * seconds . : param timeout : The number of maximum seconds to wait for the result . : param do _ raise : Set to False to prevent any of the exceptions below to be r...
with self . _lock : self . wait ( timeout , do_raise = do_raise ) if self . _exc_info : if not do_raise : return None # Its more important to re - raise the exception from the worker . self . _exc_retrieved = True reraise ( * self . _exc_info ) if self . _cancelle...
def drawQuad ( self , quad ) : """Draw a Quad ."""
q = Quad ( quad ) return self . drawPolyline ( [ q . ul , q . ll , q . lr , q . ur , q . ul ] )
def ToJsonString ( self ) : """Converts FieldMask to string according to proto3 JSON spec ."""
camelcase_paths = [ ] for path in self . paths : camelcase_paths . append ( _SnakeCaseToCamelCase ( path ) ) return ',' . join ( camelcase_paths )
def print_featurelist ( feature_list ) : """Print the feature _ list in a human - readable form . Parameters feature _ list : list feature objects"""
input_features = sum ( map ( lambda n : n . get_dimension ( ) , feature_list ) ) print ( "## Features (%i)" % input_features ) print ( "```" ) for algorithm in feature_list : print ( "* %s" % str ( algorithm ) ) print ( "```" )
def namedb_read_version ( path ) : """Get the db version"""
con = sqlite3 . connect ( path , isolation_level = None , timeout = 2 ** 30 ) con . row_factory = namedb_row_factory sql = 'SELECT version FROM db_version;' args = ( ) try : rowdata = namedb_query_execute ( con , sql , args , abort = False ) row = rowdata . fetchone ( ) return row [ 'version' ] except : # n...
def query ( data , ** options ) : """Filter data with given JMESPath expression . See also : https : / / github . com / jmespath / jmespath . py and http : / / jmespath . org . : param data : Target object ( a dict or a dict - like object ) to query : param options : Keyword option may include ' ac _ query ...
expression = options . get ( "ac_query" , None ) if expression is None or not expression : return data try : pexp = jmespath . compile ( expression ) return pexp . search ( data ) except ValueError as exc : # jmespath . exceptions . * Error inherit from it . LOGGER . warning ( "Failed to compile or sear...
def path ( self ) : """Returns the directory for this target ."""
if not self . path_ : if self . action_ : p = self . action_ . properties ( ) ( target_path , relative_to_build_dir ) = p . target_path ( ) if relative_to_build_dir : # Indicates that the path is relative to # build dir . target_path = os . path . join ( self . project_ ....
def dispatch_event ( self , event : "Event" ) -> None : """Dispatches the given event . It is the duty of this method to set the target of the dispatched event by calling ` event . set _ target ( self ) ` . Args : event ( Event ) : The event to dispatch . Must not be ` None ` . Raises : TypeError : If t...
# Set the target of the event if it doesn ' t have one already . It could happen that # we are simply redispatching an event . if event . target is None : event . set_target ( self ) listeners : dict [ types . MethodType , bool ] = self . _registered_listeners . get ( event . type ) if listeners is None : retur...
def _load_schema_for_record ( data , schema = None ) : """Load the schema from a given record . Args : data ( dict ) : record data . schema ( Union [ dict , str ] ) : schema to validate against . Returns : dict : the loaded schema . Raises : SchemaNotFound : if the given schema was not found . Schem...
if schema is None : if '$schema' not in data : raise SchemaKeyNotFound ( data = data ) schema = data [ '$schema' ] if isinstance ( schema , six . string_types ) : schema = load_schema ( schema_name = schema ) return schema
def read_parameters ( infile = '../parameters/EQcorrscan_parameters.txt' ) : """Read the default parameters from file . : type infile : str : param infile : Full path to parameter file . : returns : parameters read from file . : rtype : : class : ` eqcorrscan . utils . parameters . EQcorrscanParameters `"""
try : import ConfigParser except ImportError : import configparser as ConfigParser import ast f = open ( infile , 'r' ) print ( 'Reading parameters with the following header:' ) for line in f : if line [ 0 ] == '#' : print ( line . rstrip ( '\n' ) . lstrip ( '\n' ) ) f . close ( ) config = ConfigPar...
def _intersect ( self , label , xmin , ymin , xmax , ymax ) : """Calculate intersect areas , normalized ."""
left = np . maximum ( label [ : , 0 ] , xmin ) right = np . minimum ( label [ : , 2 ] , xmax ) top = np . maximum ( label [ : , 1 ] , ymin ) bot = np . minimum ( label [ : , 3 ] , ymax ) invalid = np . where ( np . logical_or ( left >= right , top >= bot ) ) [ 0 ] out = label . copy ( ) out [ : , 0 ] = left out [ : , 1...
def request_videos ( blink , time = None , page = 0 ) : """Perform a request for videos . : param blink : Blink instance . : param time : Get videos since this time . In epoch seconds . : param page : Page number to get videos from ."""
timestamp = get_time ( time ) url = "{}/api/v2/videos/changed?since={}&page={}" . format ( blink . urls . base_url , timestamp , page ) return http_get ( blink , url )
def log_in ( self , username = None , password = None , code = None , redirect_uri = "urn:ietf:wg:oauth:2.0:oob" , refresh_token = None , scopes = __DEFAULT_SCOPES , to_file = None ) : """Get the access token for a user . The username is the e - mail used to log in into mastodon . Can persist access token to fi...
if username is not None and password is not None : params = self . __generate_params ( locals ( ) , [ 'scopes' , 'to_file' , 'code' , 'refresh_token' ] ) params [ 'grant_type' ] = 'password' elif code is not None : params = self . __generate_params ( locals ( ) , [ 'scopes' , 'to_file' , 'username' , 'passw...
def client_id ( self , client ) : """Get a client ' s ID . Uses GET to / clients ? name = < client > interface . : Args : * * client * : ( str ) Client ' s name : Returns : ( str ) Client id"""
params = { "name" : client } response = self . _get ( url . clients , params = params ) self . _check_response ( response , 200 ) return self . _create_response ( response ) . get ( "client_id" )
def defaults ( self ) : """Return the default values of this configuration ."""
return { k : v . default for k , v in self . options ( ) . items ( ) }
def auto_memoize ( func ) : """Based on django . util . functional . memoize . Automatically memoizes instace methods for the lifespan of an object . Only works with methods taking non - keword arguments . Note that the args to the function must be usable as dictionary keys . Also , the first argument MUST be s...
@ wraps ( func ) def wrapper ( * args ) : inst = args [ 0 ] inst . _memoized_values = getattr ( inst , '_memoized_values' , { } ) key = ( func , args [ 1 : ] ) if key not in inst . _memoized_values : inst . _memoized_values [ key ] = func ( * args ) return inst . _memoized_values [ key ] ret...
def ising_energy ( sample , h , J , offset = 0.0 ) : """Calculate the energy for the specified sample of an Ising model . Energy of a sample for a binary quadratic model is defined as a sum , offset by the constant energy offset associated with the model , of the sample multipled by the linear bias of the var...
# add the contribution from the linear biases for v in h : offset += h [ v ] * sample [ v ] # add the contribution from the quadratic biases for v0 , v1 in J : offset += J [ ( v0 , v1 ) ] * sample [ v0 ] * sample [ v1 ] return offset
def get_resources_to_check ( client_site_url , apikey ) : """Return a list of resource IDs to check for broken links . Calls the client site ' s API to get a list of resource IDs . : raises CouldNotGetResourceIDsError : if getting the resource IDs fails for any reason"""
url = client_site_url + u"deadoralive/get_resources_to_check" response = requests . get ( url , headers = dict ( Authorization = apikey ) ) if not response . ok : raise CouldNotGetResourceIDsError ( u"Couldn't get resource IDs to check: {code} {reason}" . format ( code = response . status_code , reason = response ....
def append_id ( expr , id_col = 'append_id' ) : """Append an ID column to current column to form a new DataFrame . : param str id _ col : name of appended ID field . : return : DataFrame with ID field : rtype : DataFrame"""
if hasattr ( expr , '_xflow_append_id' ) : return expr . _xflow_append_id ( id_col ) else : return _append_id ( expr , id_col )
def drawItem ( self , item , painter , option ) : """Draws the inputed item as a bar graph . : param item | < XChartDatasetItem > painter | < QPainter > option | < QStyleOptionGraphicsItem >"""
dataset = item . dataset ( ) painter . save ( ) painter . setRenderHint ( painter . Antialiasing ) center = item . buildData ( 'center' ) radius = item . buildData ( 'radius' ) if int ( option . state ) & QStyle . State_MouseOver != 0 : alpha = 20 mouse_over = True else : alpha = 0 mouse_over = False fo...
def to_ISO8601 ( timeobject ) : """Returns the ISO8601 - formatted string corresponding to the time value conveyed by the specified object , which can be either a UNIXtime , a ` ` datetime . datetime ` ` object or an ISO8601 - formatted string in the format ` YYYY - MM - DD HH : MM : SS + 00 ` ` . : param t...
if isinstance ( timeobject , int ) : if timeobject < 0 : raise ValueError ( "The time value is a negative number" ) return datetime . utcfromtimestamp ( timeobject ) . strftime ( '%Y-%m-%d %H:%M:%S+00' ) elif isinstance ( timeobject , datetime ) : return timeobject . strftime ( '%Y-%m-%d %H:%M:%S+00...
def get ( cls , * args , ** kwargs ) : """Retrieve one instance from db according to given kwargs . Optionnaly , one arg could be used to retrieve it from pk ."""
if len ( args ) == 1 : # Guess it ' s a pk pk = args [ 0 ] elif kwargs : # special case to check for a simple pk if len ( kwargs ) == 1 and cls . _field_is_pk ( list ( kwargs . keys ( ) ) [ 0 ] ) : pk = list ( kwargs . values ( ) ) [ 0 ] else : # case with many filters result = cls . collect...
def _element_charfix ( self , element , charcount ) : """Updates the start and end attributes by charcount for the element ."""
element . start += charcount element . docstart += charcount element . end += charcount element . docend += charcount
def experiments_fmri_get ( self , experiment_id ) : """Get fMRI data object that is associated with the given experiment . Parameters experiment _ id : string unique experiment identifier Returns FMRIDataHandle Handle for fMRI data object of None if ( a ) the experiment is unknown or ( b ) has no fMRI...
# Get experiment to ensure that it exists experiment = self . experiments_get ( experiment_id ) if experiment is None : return None # Check if experiment has fMRI data if experiment . fmri_data_id is None : return None # Get functional data object handle from database . func_data = self . funcdata . get_object ...
def option_from_wire ( otype , wire , current , olen ) : """Build an EDNS option object from wire format @ param otype : The option type @ type otype : int @ param wire : The wire - format message @ type wire : string @ param current : The offet in wire of the beginning of the rdata . @ type current : i...
cls = get_option_class ( otype ) return cls . from_wire ( otype , wire , current , olen )
def from_string ( cls , resource_name ) : """Parse a resource name and return a ResourceName : type resource _ name : str : rtype : ResourceName : raises InvalidResourceName : if the resource name is invalid ."""
# TODO Remote VISA uname = resource_name . upper ( ) for interface_type in _INTERFACE_TYPES : # Loop through all known interface types until we found one # that matches the beginning of the resource name if not uname . startswith ( interface_type ) : continue if len ( resource_name ) == len ( interface_...
def _post_stats ( self , stats ) : '''Fire events with stat info if it ' s time'''
end_time = time . time ( ) if end_time - self . stat_clock > self . opts [ 'master_stats_event_iter' ] : # Fire the event with the stats and wipe the tracker self . aes_funcs . event . fire_event ( { 'time' : end_time - self . stat_clock , 'worker' : self . name , 'stats' : stats } , tagify ( self . name , 'stats' ...
def request_analysis ( self ) : """Requests an analysis ."""
if self . _finished : _logger ( self . __class__ ) . log ( 5 , 'running analysis' ) self . _job_runner . request_job ( self . _request ) elif self . editor : # retry later _logger ( self . __class__ ) . log ( 5 , 'delaying analysis (previous analysis not finished)' ) QtCore . QTimer . singleShot ( 500 ,...
def calculateValues ( self ) : """Overloads the calculate values method to calculate the values for this axis based on the minimum and maximum values , and the number of steps desired . : return [ < variant > , . . ]"""
chart = self . chart ( ) if not chart : return super ( XDatasetAxis , self ) . calculateValues ( ) else : values = [ ] for dataset in chart . datasets ( ) : values . append ( dataset . name ( ) ) values . sort ( ) return values
def _update_application_request ( app_metadata , application_id ) : """Construct the request body to update application . : param app _ metadata : Object containing app metadata : type app _ metadata : ApplicationMetadata : param application _ id : The Amazon Resource Name ( ARN ) of the application : type ...
request = { 'ApplicationId' : application_id , 'Author' : app_metadata . author , 'Description' : app_metadata . description , 'HomePageUrl' : app_metadata . home_page_url , 'Labels' : app_metadata . labels , 'ReadmeUrl' : app_metadata . readme_url } return { k : v for k , v in request . items ( ) if v }
def replicate_per_farm_dbs ( cloud_url = None , local_url = None , farm_name = None ) : """Sete up replication of the per - farm databases from the local server to the cloud server . : param str cloud _ url : Used to override the cloud url from the global configuration in case the calling function is in the p...
cloud_url = cloud_url or config [ "cloud_server" ] [ "url" ] local_url = local_url or config [ "local_server" ] [ "url" ] farm_name = farm_name or config [ "cloud_server" ] [ "farm_name" ] username = config [ "cloud_server" ] [ "username" ] password = config [ "cloud_server" ] [ "password" ] # Add credentials to the cl...
def do_set_hub_connection ( self , args ) : """Set Hub connection parameters . Usage : set _ hub _ connection username password host [ port ] Arguments : username : Hub username password : Hub password host : host name or IP address port : IP port [ default 25105]"""
params = args . split ( ) username = None password = None host = None port = None try : username = params [ 0 ] password = params [ 1 ] host = params [ 2 ] port = params [ 3 ] except IndexError : pass if username and password and host : if not port : port = 25105 self . tools . usern...
def initialize_pymol ( options ) : """Initializes PyMOL"""
import pymol # Pass standard arguments of function to prevent PyMOL from printing out PDB headers ( workaround ) pymol . finish_launching ( args = [ 'pymol' , options , '-K' ] ) pymol . cmd . reinitialize ( )
def addPlot ( self , xdata , ydata , xlabel = None , ylabel = None , title = None , xunits = None , yunits = None ) : """Adds a new plot for the given set of data and / or labels , Generates a SimplePlotWidget : param xdata : index values for data , plotted on x - axis : type xdata : numpy . ndarray : param y...
p = SimplePlotWidget ( xdata , ydata ) p . setLabels ( xlabel , ylabel , title , xunits , yunits ) # self . plots . append ( p ) self . stacker . addWidget ( p )
def convert ( self ) : """Convert file in mp3 format ."""
if self . downloaded is False : raise serror ( "Track not downloaded, can't convert file.." ) filetype = magic . from_file ( self . filepath , mime = True ) if filetype == "audio/mpeg" : print ( "File is already in mp3 format. Skipping convert." ) return False rootpath = os . path . dirname ( os . path . di...
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_remaining_life ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_lldp_neighbor_detail = ET . Element ( "get_lldp_neighbor_detail" ) config = get_lldp_neighbor_detail output = ET . SubElement ( get_lldp_neighbor_detail , "output" ) lldp_neighbor_detail = ET . SubElement ( output , "lldp-neighbor-detail" ) local_interface_name_key = ET . SubEleme...
def GaussianCdfInverse ( p , mu = 0 , sigma = 1 ) : """Evaluates the inverse CDF of the gaussian distribution . See http : / / en . wikipedia . org / wiki / Normal _ distribution # Quantile _ function Args : p : float mu : mean parameter sigma : standard deviation parameter Returns : float"""
x = ROOT2 * erfinv ( 2 * p - 1 ) return mu + x * sigma
def clone ( self , ** kwargs ) : """Clone a part . . . versionadded : : 2.3 : param kwargs : ( optional ) additional keyword = value arguments : type kwargs : dict : return : cloned : class : ` models . Part ` : raises APIError : if the ` Part ` could not be cloned Example > > > bike = client . model ...
parent = self . parent ( ) return self . _client . _create_clone ( parent , self , ** kwargs )
def exponential_backoff ( fn , sleeptime_s_max = 30 * 60 ) : """Calls ` fn ` until it returns True , with an exponentially increasing wait time between calls"""
sleeptime_ms = 500 while True : if fn ( ) : return True else : print ( 'Sleeping {} ms' . format ( sleeptime_ms ) ) time . sleep ( sleeptime_ms / 1000.0 ) sleeptime_ms *= 2 if sleeptime_ms / 1000.0 > sleeptime_s_max : return False
def umode ( self , nick , modes = '' ) : """Sets / gets user modes . Required arguments : * nick - Nick to set / get user modes for . Optional arguments : * modes = ' ' - Sets these user modes on a nick ."""
with self . lock : if not modes : self . send ( 'MODE %s' % nick ) if self . readable ( ) : msg = self . _recv ( expected_replies = ( '221' , ) ) if msg [ 0 ] == '221' : modes = msg [ 2 ] . replace ( '+' , '' ) . replace ( ':' , '' , 1 ) return modes ...
def _get_interpretation_function ( interpretation , dtype ) : """Retrieves the interpretation function used ."""
type_string = dtype . __name__ name = "%s__%s" % ( interpretation , type_string ) global _interpretations if not hasattr ( _interpretations , name ) : raise ValueError ( "No transform available for type '%s' with interpretation '%s'." % ( type_string , interpretation ) ) return getattr ( _interpretations , name )
def write ( parsed_obj , spec = None , filename = None ) : """Writes an object created by ` parse ` to either a file or a bytearray . If the object doesn ' t end on a byte boundary , zeroes are appended to it until it does ."""
if not isinstance ( parsed_obj , BreadStruct ) : raise ValueError ( 'Object to write must be a structure created ' 'by bread.parse' ) if filename is not None : with open ( filename , 'wb' ) as fp : parsed_obj . _data_bits [ : parsed_obj . _length ] . tofile ( fp ) else : return bytearray ( parsed_ob...
def paragraph ( content ) : """emit a paragraph , stripping out any leading or following empty paragraphs"""
# if the content contains a top - level div then don ' t wrap it in a < p > # tag if content . startswith ( '<div' ) and content . endswith ( '</div>' ) : return '\n' + content + '\n' text = '<p>' + content + '</p>' text = re . sub ( r'<p>\s*</p>' , r'' , text ) return text or ' '
def get_download_url ( self , instance , default = None ) : """Calculate the download url"""
download = default # calculate the download url download = "{url}/at_download/{fieldname}" . format ( url = instance . absolute_url ( ) , fieldname = self . get_field_name ( ) ) return download
def _recreate_list_with_indices ( indices1 , values1 , indices2 , values2 ) : """Create a list in the right order . : param list indices1 : contains the list of indices corresponding to the values in values1. : param list values1 : contains the first list of values . : param list indices2 : contains the lis...
# Test if indices are continuous list_indices = sorted ( indices1 + indices2 ) for i , index in enumerate ( list_indices ) : if i != index : raise CraftAiInternalError ( "The agents's indices are not continuous" ) full_list = [ None ] * ( len ( indices1 ) + len ( indices2 ) ) for i , index in enumerate ( in...
def gauss_jordan ( A , x , b ) : """Linear equation system Ax = b by Gauss - Jordan : param A : n by m matrix : param x : table of size n : param b : table of size m : modifies : x will contain solution if any : returns int : 0 if no solution , 1 if solution unique , 2 otherwise : complexity : : m...
n = len ( x ) m = len ( b ) assert len ( A ) == m and len ( A [ 0 ] ) == n S = [ ] # put linear system in a single matrix S for i in range ( m ) : S . append ( A [ i ] [ : ] + [ b [ i ] ] ) S . append ( list ( range ( n ) ) ) # indices in x k = diagonalize ( S , n , m ) if k < m : for i in range ( k , m ) : ...
def chglog ( amend : bool = False , stage : bool = False , next_version : str = None , auto_next_version : bool = False ) : """Writes the changelog Args : amend : amend last commit with changes stage : stage changes next _ version : indicates next version auto _ next _ version : infer next version from VC...
changed_files = CTX . repo . changed_files ( ) changelog_file_path : Path = config . CHANGELOG_FILE_PATH ( ) changelog_file_name = changelog_file_path . name if changelog_file_name in changed_files : LOGGER . error ( 'changelog has changed; cannot update it' ) exit ( - 1 ) _chglog ( amend , stage , next_version...
def load ( self , callables_fname ) : r"""Load traced modules information from a ` JSON < http : / / www . json . org / > ` _ file . The loaded module information is merged with any existing module information : param callables _ fname : File name : type callables _ fname : : ref : ` FileNameExists ` : rais...
# Validate file name _validate_fname ( callables_fname ) if not os . path . exists ( callables_fname ) : raise OSError ( "File {0} could not be found" . format ( callables_fname ) ) with open ( callables_fname , "r" ) as fobj : fdict = json . load ( fobj ) if sys . hexversion < 0x03000000 : # pragma : no cover ...
def gen_res ( args , resource , inflow , outflow ) : """Returns a line of text to add to an environment file , initializing a standard resource with the specified name ( string ) , inflow ( int ) , and outflow ( int )"""
return "" . join ( [ "RESOURCE " , resource , ":inflow=" , str ( inflow ) , ":outflow=" , str ( outflow ) , "\n" ] )
def listReleaseVersions ( self , release_version = "" , dataset = '' , logical_file_name = '' ) : """List release versions"""
if dataset and ( '%' in dataset or '*' in dataset ) : dbsExceptionHandler ( 'dbsException-invalid-input' , " DBSReleaseVersion/listReleaseVersions. No wildcards are" + " allowed in dataset.\n." ) if logical_file_name and ( '%' in logical_file_name or '*' in logical_file_name ) : dbsExceptionHandler ( 'dbsExcept...
def copy ( self , name = None , prefix = None ) : """A copy of this : class : ` Config ` container . If ` ` prefix ` ` is given , it prefixes all non : ref : ` global settings < setting - section - global - server - settings > ` with it . Used when multiple applications are loaded ."""
cls = self . __class__ me = cls . __new__ ( cls ) me . __dict__ . update ( self . __dict__ ) if prefix : me . prefix = prefix settings = me . settings me . settings = { } for setting in settings . values ( ) : setting = setting . copy ( name , prefix ) me . settings [ setting . name ] = setting me . params ...
def set_attr ( self ) : """set the data for this column"""
setattr ( self . attrs , self . kind_attr , self . values ) setattr ( self . attrs , self . meta_attr , self . meta ) if self . dtype is not None : setattr ( self . attrs , self . dtype_attr , self . dtype )
def _Open ( self , path_spec = None , mode = 'rb' ) : """Opens the file - like object defined by path specification . Args : path _ spec ( PathSpec ) : path specification . mode ( Optional [ str ] ) : file access mode . Raises : AccessError : if the access to open the file was denied . IOError : if the ...
if not path_spec : raise ValueError ( 'Missing path specification.' ) data_stream = getattr ( path_spec , 'data_stream' , None ) if data_stream : raise errors . NotSupported ( 'Open data stream: {0:s} not supported.' . format ( data_stream ) ) self . _file_system = resolver . Resolver . OpenFileSystem ( path_sp...
def request_headers ( self ) : '''Fill request headers from the environ dictionary and modify them via the list of : attr : ` headers _ middleware ` . The returned headers will be sent to the target uri .'''
headers = CIMultiDict ( ) for k in self . environ : if k . startswith ( 'HTTP_' ) : head = k [ 5 : ] . replace ( '_' , '-' ) headers [ head ] = self . environ [ k ] for head in ENVIRON_HEADERS : k = head . replace ( '-' , '_' ) . upper ( ) v = self . environ . get ( k ) if v : he...
def upper_band ( close_data , high_data , low_data , period ) : """Upper Band . Formula : UB = CB + BW"""
cb = center_band ( close_data , high_data , low_data , period ) bw = band_width ( high_data , low_data , period ) ub = cb + bw return ub
def write_type_dumps ( self , operations , preserve_order , output_dir ) : """Splits the list of SQL operations by type and dumps these to separate files"""
by_type = { SqlType . INDEX : [ ] , SqlType . FUNCTION : [ ] , SqlType . TRIGGER : [ ] } for operation in operations : by_type [ operation . sql_type ] . append ( operation ) # optionally sort each operation list by the object name if not preserve_order : for obj_type , ops in by_type . items ( ) : by_t...