signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def slerp ( cls , q0 , q1 , amount = 0.5 ) : """Spherical Linear Interpolation between quaternions . Implemented as described in https : / / en . wikipedia . org / wiki / Slerp Find a valid quaternion rotation at a specified distance along the minor arc of a great circle passing through any two existing quate...
# Ensure quaternion inputs are unit quaternions and 0 < = amount < = 1 q0 . _fast_normalise ( ) q1 . _fast_normalise ( ) amount = np . clip ( amount , 0 , 1 ) dot = np . dot ( q0 . q , q1 . q ) # If the dot product is negative , slerp won ' t take the shorter path . # Note that v1 and - v1 are equivalent when the negat...
def from_json ( payload ) : """Build a ` ` Place ` ` instance from the specified JSON object . @ param payload : JSON representation of a place : : " area _ id " : string , " address " : { component _ type : string , " locale " : string , component _ type : string , " category " : string , " contact...
return payload and Place ( [ ( float ( lon ) , float ( lat ) , float ( alt ) ) for ( lon , lat , alt ) in payload [ 'boundaries' ] ] if payload . get ( 'boundaries' ) else GeoPoint . from_json ( payload [ 'location' ] ) , address = payload . get ( 'address' ) and ( Place . __parse_address__ ( payload [ 'address' ] ) if...
def render ( element , level = 0 ) : """Renders the HTML builder ` element ` and it ' s children to a string . Example : : > > > print ( . . . render ( . . . html . form ( action = ' / search ' , name = ' f ' ) ( . . . html . input ( name = ' q ' ) , . . . html . input ( name = ' search _ button ' , typ...
if hasattr ( element , 'render' ) : return element . render ( level ) elif isinstance ( element , basestring ) : return _render_string ( element , level ) elif hasattr ( element , '__iter__' ) : return _render_iteratable ( element , level ) elif element is None : return '' raise TypeError ( 'Cannot rend...
def render ( self , horizontal_spacing : int = 1 , vertical_spacing : int = 1 , crossing_char : str = None , use_unicode_characters : bool = True ) -> str : """Outputs text containing the diagram ."""
block_diagram = BlockDiagramDrawer ( ) w = self . width ( ) h = self . height ( ) # Communicate padding into block diagram . for x in range ( 0 , w - 1 ) : block_diagram . set_col_min_width ( x * 2 + 1 , # Horizontal separation looks narrow , so partials round up . int ( np . ceil ( self . horizontal_padding . ...
def after_this_request ( func : Callable ) -> Callable : """Schedule the func to be called after the current request . This is useful in situations whereby you want an after request function for a specific route or circumstance only , for example , . . code - block : : python def index ( ) : @ after _ thi...
_request_ctx_stack . top . _after_request_functions . append ( func ) return func
def _validate_dependencies_met ( ) : """Verifies that PyOpenSSL ' s package - level dependencies have been met . Throws ` ImportError ` if they are not met ."""
# Method added in ` cryptography = = 1.1 ` ; not available in older versions from cryptography . x509 . extensions import Extensions if getattr ( Extensions , "get_extension_for_class" , None ) is None : raise ImportError ( "'cryptography' module missing required functionality. " "Try upgrading to v1.3.4 or newer....
def copyCurrentLayout ( self , sourceViewSUID , targetViewSUID , body , verbose = None ) : """Copy one network view layout onto another , setting the node location and view scale to match . This makes visually comparing networks simple . : param sourceViewSUID : Source network view SUID ( or " current " ) : par...
response = api ( url = self . ___url + 'apply/layouts/copycat/' + str ( sourceViewSUID ) + '/' + str ( targetViewSUID ) + '' , method = "PUT" , body = body , verbose = verbose ) return response
def file_md5 ( filename ) : """Generate the md5 checksum for a file Args : filename ( Str ) : The file to be checksummed . Returns : ( Str ) : The hex checksum Notes : If the file is gzipped , the md5 checksum returned is for the uncompressed ASCII file ."""
with zopen ( filename , 'r' ) as f : file_string = f . read ( ) try : # attempt to decode byte object file_string = file_string . decode ( ) except AttributeError : pass return ( md5sum ( file_string ) )
def change_status ( self , status ) : """Change the user ' s status : param user : : param email : : return :"""
def cb ( ) : self . user . update ( status = status ) return status return signals . user_update ( self , ACTIONS [ "STATUS" ] , cb , data = { "status" : self . status } )
def isconsistent ( self ) : '''Check if the timeseries is consistent'''
for dt1 , dt0 in laggeddates ( self ) : if dt1 <= dt0 : return False return True
def create_record_sets ( self , record_set_dicts ) : """Accept list of record _ set dicts . Return list of record _ set objects ."""
record_set_objects = [ ] for record_set_dict in record_set_dicts : # pop removes the ' Enabled ' key and tests if True . if record_set_dict . pop ( 'Enabled' , True ) : record_set_objects . append ( self . create_record_set ( record_set_dict ) ) return record_set_objects
def update ( self , request , datum ) : """Switches the action verbose name , if needed ."""
if getattr ( self , 'action_present' , False ) : self . verbose_name = self . _get_action_name ( ) self . verbose_name_plural = self . _get_action_name ( 'plural' )
def makedbthreads ( self ) : """Setup and create threads for class"""
# Find all the target folders in the analysis and add them to the targetfolders set for sample in self . metadata : if sample [ self . analysistype ] . combinedtargets != 'NA' : self . targetfolders . add ( sample [ self . analysistype ] . targetpath ) # Create and start threads for each fasta file in the l...
def verify ( self , smessage , signature = None , encoder = encoding . RawEncoder ) : """Verifies the signature of a signed message , returning the message if it has not been tampered with else raising : class : ` ~ ValueError ` . : param smessage : [ : class : ` bytes ` ] Either the original messaged or a ...
if signature is not None : # If we were given the message and signature separately , combine # them . smessage = signature + smessage # Decode the signed message smessage = encoder . decode ( smessage ) return libnacl . crypto_sign_open ( smessage , self . _key )
def _check_lsm_input ( self , data_var_map_array ) : """This function checks the input var map array to ensure the required input variables exist"""
REQUIRED_HMET_VAR_LIST = [ 'Prcp' , 'Pres' , 'Temp' , 'Clod' , 'RlHm' , 'Drad' , 'Grad' , 'WndS' ] # make sure all required variables exist given_hmet_var_list = [ ] for gssha_data_var , lsm_data_var in data_var_map_array : gssha_data_hmet_name = self . netcdf_attributes [ gssha_data_var ] [ 'hmet_name' ] if gs...
def get_child_objective_banks ( self , objective_bank_id ) : """Gets the children of the given objective bank . arg : objective _ bank _ id ( osid . id . Id ) : the ` ` Id ` ` to query return : ( osid . learning . ObjectiveBankList ) - the children of the objective bank raise : NotFound - ` ` objective _ ba...
# Implemented from template for # osid . resource . BinHierarchySession . get _ child _ bins if self . _catalog_session is not None : return self . _catalog_session . get_child_catalogs ( catalog_id = objective_bank_id ) return ObjectiveBankLookupSession ( self . _proxy , self . _runtime ) . get_objective_banks_by_...
def _clean_files_only ( self , files ) : '''if a user only wants to process one or more specific files , instead of a full sosreport'''
try : if not ( os . path . exists ( self . origin_path ) ) : self . logger . info ( "Creating Origin Path - %s" % self . origin_path ) os . makedirs ( self . origin_path ) # create the origin _ path directory if not ( os . path . exists ( self . dir_path ) ) : self . logger . inf...
def create_config ( allow_insecure_config_file = False ) : """Create config based on / etc / ddsclient . conf and ~ / . ddsclient . conf ( $ DDSCLIENT _ CONF ) : param allow _ insecure _ config _ file : bool : when true we will not check ~ / . ddsclient permissions . : return : Config with the configuration to ...
config = Config ( ) config . add_properties ( GLOBAL_CONFIG_FILENAME ) user_config_filename = get_user_config_filename ( ) if user_config_filename == LOCAL_CONFIG_FILENAME and not allow_insecure_config_file : verify_file_private ( user_config_filename ) config . add_properties ( user_config_filename ) return config
def CrearCertificacionCabecera ( self , pto_emision = 1 , nro_orden = None , tipo_certificado = None , nro_planta = None , nro_ing_bruto_depositario = None , titular_grano = None , cuit_depositante = None , nro_ing_bruto_depositante = None , cuit_corredor = None , cod_grano = None , campania = None , datos_adicionales ...
self . certificacion = { } self . certificacion [ 'cabecera' ] = dict ( ptoEmision = pto_emision , nroOrden = nro_orden , tipoCertificado = tipo_certificado , nroPlanta = nro_planta or None , # opcional nroIngBrutoDepositario = nro_ing_bruto_depositario , titularGrano = titular_grano , cuitDepositante = cuit_depositant...
def get_first_non_null_value ( self , ind_name , col_name ) : """For a given index and column , find the first non - null value . Parameters self : MagicDataFrame ind _ name : str index name for indexing col _ name : str column name for indexing Returns single value of str , float , or int"""
short_df = self . df . loc [ ind_name , col_name ] mask = pd . notnull ( short_df ) print ( short_df [ mask ] ) try : val = short_df [ mask ] . unique ( ) [ 0 ] except IndexError : val = None return val
def filter_string ( self , word ) : """Return a string like the input but containing only legal IPA segments Args : word ( unicode ) : input string to be filtered Returns : unicode : string identical to ` word ` but with invalid IPA segments absent"""
segs = [ m . group ( 0 ) for m in self . seg_regex . finditer ( word ) ] return '' . join ( segs )
def get_dataset ( self , key , info ) : """Get the data from the files ."""
logger . debug ( "Getting raw data" ) res = super ( HRITGOESFileHandler , self ) . get_dataset ( key , info ) self . mda [ 'calibration_parameters' ] = self . _get_calibration_params ( ) res = self . calibrate ( res , key . calibration ) new_attrs = info . copy ( ) new_attrs . update ( res . attrs ) res . attrs = new_a...
def _process_response ( self , response ) : """Parse response"""
forward_raw = False content_type = response . headers [ 'Content-Type' ] if content_type != 'application/json' : logger . debug ( "headers: %s" , response . headers ) # API BUG : text / xml content - type with json payload # http : / / forum . mediafiredev . com / showthread . php ? 136 if content_type ...
def generate_combined_fasta ( self , genome_list , genome_dir ) : '''Generate a combined fasta using the genbank files . Args genome _ list ( list ) genome _ dir ( string )'''
fasta = [ ] for genome in genome_list : full_path = genome_dir + genome handle = open ( full_path , "rU" ) print 'making combined fasta for' , genome try : seq_record = SeqIO . read ( handle , 'genbank' ) org_accession = seq_record . name except AssertionError , e : print str...
def _brentq_cdf ( self , value ) : """Helper function to compute percent _ point . As scipy . stats . gaussian _ kde doesn ' t provide this functionality out of the box we need to make a numerical approach : - First we scalarize and bound cumulative _ distribution . - Then we define a function ` f ( x ) = c...
# The decorator expects an instance method , but usually are decorated before being bounded bound_cdf = partial ( scalarize ( GaussianKDE . cumulative_distribution ) , self ) def f ( x ) : return bound_cdf ( x ) - value return f
def timezone ( zone ) : """Try to get timezone using pytz or python - dateutil : param zone : timezone str : return : timezone tzinfo or None"""
try : import pytz return pytz . timezone ( zone ) except ImportError : pass try : from dateutil . tz import gettz return gettz ( zone ) except ImportError : return None
def get_descriptor_for_layer ( self , layer ) : """Returns the standard JSON descriptor for the layer . There is a lot of usefule information in there ."""
if not layer in self . _layer_descriptor_cache : params = { 'f' : 'pjson' } if self . token : params [ 'token' ] = self . token response = requests . get ( self . _build_request ( layer ) , params = params ) self . _layer_descriptor_cache [ layer ] = response . json ( ) return self . _layer_desc...
def get ( self , specification , * args , ** kwargs ) : """A more convenient version of : py : meth : ` acquire ( ) ` for when you can provide positional arguments in a right order ."""
arguments = dict ( enumerate ( args ) ) arguments . update ( kwargs ) return self . acquire ( specification , arguments = arguments )
async def delete ( self , key ) : """Deletes the Key Parameters : key ( str ) : Key to delete Response : bool : ` ` True ` ` on success"""
response = await self . _discard ( key ) return response . body is True
def clear_info ( self ) : """Clear the device info ."""
self . _version_text = None self . _inventory_text = None self . _users_text = None self . os_version = None self . os_type = None self . family = None self . platform = None self . udi = None # self . is _ console = None self . prompt = None self . prompt_re = None
def query ( self , query ) : '''Returns a sequence of objects matching criteria expressed in ` query `'''
query = query . copy ( ) query . key = self . _transform ( query . key ) return self . child_datastore . query ( query )
def p_version_def ( t ) : """version _ def : VERSION ID LBRACE procedure _ def procedure _ def _ list RBRACE EQUALS constant SEMI"""
global name_dict id = t [ 2 ] value = t [ 8 ] lineno = t . lineno ( 1 ) if id_unique ( id , 'version' , lineno ) : name_dict [ id ] = const_info ( id , value , lineno )
def get_load ( jid ) : '''Return the load data that marks a specified jid'''
log . debug ( 'sdstack_etcd returner <get_load> called jid: %s' , jid ) read_profile = __opts__ . get ( 'etcd.returner_read_profile' ) client , path = _get_conn ( __opts__ , read_profile ) return salt . utils . json . loads ( client . get ( '/' . join ( ( path , 'jobs' , jid , '.load.p' ) ) ) . value )
def get_user_configured_modules ( self ) : """Get a dict of all available and configured py3status modules in the user ' s i3status . conf ."""
user_modules = { } if not self . py3_modules : return user_modules for module_name , module_info in self . get_user_modules ( ) . items ( ) : for module in self . py3_modules : if module_name == module . split ( " " ) [ 0 ] : include_path , f_name = module_info user_modules [ mod...
def _eval_model ( self ) : """Convenience method for evaluating the model with the current parameters : return : named tuple with results"""
arguments = self . _x_grid . copy ( ) arguments . update ( { param : param . value for param in self . model . params } ) return self . model ( ** key2str ( arguments ) )
def get_or_create ( session , model , ** kwargs ) : """Get or create sqlalchemy instance . Args : session ( Sqlalchemy session ) : model ( sqlalchemy model ) : kwargs ( dict ) : kwargs to lookup or create instance . Returns : Tuple : first element is found or created instance , second is boolean - True ...
instance = session . query ( model ) . filter_by ( ** kwargs ) . first ( ) if instance : return instance , False else : instance = model ( ** kwargs ) if 'dataset' in kwargs : instance . update_sequence_id ( session , kwargs [ 'dataset' ] ) session . add ( instance ) session . commit ( ) ...
def set_widgets ( self ) : """Set widgets on the Exposure Layer From Browser tab ."""
self . tvBrowserExposure_selection_changed ( ) # Set icon exposure = self . parent . step_fc_functions1 . selected_value ( layer_purpose_exposure [ 'key' ] ) icon_path = get_image_path ( exposure ) self . lblIconIFCWExposureFromBrowser . setPixmap ( QPixmap ( icon_path ) )
def fetch ( self ) : """Lazily trigger download of the data when requested ."""
if self . _file_path is not None : return self . _file_path temp_path = self . context . work_path if self . _content_hash is not None : self . _file_path = storage . load_file ( self . _content_hash , temp_path = temp_path ) return self . _file_path if self . response is not None : self . _file_path = ...
def get_assignable_bin_ids ( self , bin_id ) : """Gets a list of bins including and under the given bin node in which any resource can be assigned . arg : bin _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Bin ` ` return : ( osid . id . IdList ) - list of assignable bin ` ` Ids ` ` raise : NullArgument -...
# Implemented from template for # osid . resource . ResourceBinAssignmentSession . get _ assignable _ bin _ ids # This will likely be overridden by an authorization adapter mgr = self . _get_provider_manager ( 'RESOURCE' , local = True ) lookup_session = mgr . get_bin_lookup_session ( proxy = self . _proxy ) bins = loo...
def uniqify ( func ) : """Make sure that a method returns a unique name ."""
@ six . wraps ( func ) def unique ( self , * args , ** kwargs ) : return self . unique ( func ( self , * args , ** kwargs ) ) return unique
def _raise_connection_failure ( address , error ) : """Convert a socket . error to ConnectionFailure and raise it ."""
host , port = address # If connecting to a Unix socket , port will be None . if port is not None : msg = '%s:%d: %s' % ( host , port , error ) else : msg = '%s: %s' % ( host , error ) if isinstance ( error , socket . timeout ) : raise NetworkTimeout ( msg ) elif isinstance ( error , SSLError ) and 'timed ou...
def create ( self , name , plugin_data_dir , gzip = False ) : """Create a new plugin . Args : name ( string ) : The name of the plugin . The ` ` : latest ` ` tag is optional , and is the default if omitted . plugin _ data _ dir ( string ) : Path to the plugin data directory . Plugin data directory must co...
self . client . api . create_plugin ( name , plugin_data_dir , gzip ) return self . get ( name )
def _gap_progenitor_setup ( self ) : """Setup an Orbit instance that ' s the progenitor integrated backwards"""
self . _gap_progenitor = self . _progenitor ( ) . flip ( ) # new orbit , flip velocities # Make sure we do not use physical coordinates self . _gap_progenitor . turn_physical_off ( ) # Now integrate backward in time until tdisrupt ts = numpy . linspace ( 0. , self . _tdisrupt , 1001 ) self . _gap_progenitor . integrate...
def hazard_class_style ( layer , classification , display_null = False ) : """Set colors to the layer according to the hazard . : param layer : The layer to style . : type layer : QgsVectorLayer : param display _ null : If we should display the null hazard zone . Default to False . : type display _ null :...
categories = [ ] # Conditional styling attribute_table_styles = [ ] for hazard_class , ( color , label ) in list ( classification . items ( ) ) : if hazard_class == not_exposed_class [ 'key' ] and not display_null : # We don ' t want to display the null value ( not exposed ) . # We skip it . continue ...
def generate_tokens ( lines , flags ) : """This is a rewrite of pypy . module . parser . pytokenize . generate _ tokens since the original function is not RPYTHON ( uses yield ) It was also slightly modified to generate Token instances instead of the original 5 - tuples - - it ' s now a 4 - tuple of * the T...
token_list = [ ] lnum = parenlev = continued = 0 namechars = NAMECHARS numchars = NUMCHARS contstr , needcont = '' , 0 contline = None indents = [ 0 ] altindents = [ 0 ] last_comment = '' parenlevstart = ( 0 , 0 , "" ) # make the annotator happy endDFA = automata . DFA ( [ ] , [ ] ) # make the annotator happy line = ''...
def InputDNAQuantitySplines ( seq_length , n_bases = 10 , name = "DNASmoothPosition" , ** kwargs ) : """Convenience wrapper around keras . layers . Input : ` Input ( ( seq _ length , n _ bases ) , name = name , * * kwargs ) `"""
return Input ( ( seq_length , n_bases ) , name = name , ** kwargs )
def update_sql ( table , filter , updates ) : '''> > > update _ sql ( ' tbl ' , { ' foo ' : ' a ' , ' bar ' : 1 } , { ' bar ' : 2 , ' baz ' : ' b ' } ) ( ' UPDATE tbl SET bar = $ 1 , baz = $ 2 WHERE bar = $ 3 AND foo = $ 4 ' , [ 2 , ' b ' , 1 , ' a ' ] )'''
where_keys , where_vals = _split_dict ( filter ) up_keys , up_vals = _split_dict ( updates ) changes = _pairs ( up_keys , sep = ', ' ) where = _pairs ( where_keys , start = len ( up_keys ) + 1 ) sql = 'UPDATE {} SET {} WHERE {}' . format ( table , changes , where ) return sql , up_vals + where_vals
def tokens ( self , instance ) : """Just display current acceptable TOTP tokens"""
if not instance . pk : # e . g . : Use will create a new TOTP entry return "-" totp = TOTP ( instance . bin_key , instance . step , instance . t0 , instance . digits ) tokens = [ ] for offset in range ( - instance . tolerance , instance . tolerance + 1 ) : totp . drift = instance . drift + offset tokens . a...
def Process ( self , path ) : """Processes a given path . Args : path : Path ( as a string ) to post - process . Returns : A list of paths with environment variables replaced with their values . If the mapping had a list of values for a particular variable , instead of just one value , then all possible...
path = re . sub ( self . SYSTEMROOT_RE , r"%systemroot%" , path , count = 1 ) path = re . sub ( self . SYSTEM32_RE , r"%systemroot%\\system32" , path , count = 1 ) matches_iter = self . WIN_ENVIRON_REGEX . finditer ( path ) var_names = set ( m . group ( 1 ) . lower ( ) for m in matches_iter ) results = [ path ] for var...
def envvar_constructor ( loader , node ) : """Tag constructor to use environment variables in YAML files . Usage : - ! TAG VARIABLE raise while loading the document if variable does not exists - ! TAG VARIABLE : = DEFAULT _ VALUE For instance : credentials : user : ! env USER : = root group : ! env GR...
value = loader . construct_python_unicode ( node ) data = value . split ( ':=' , 1 ) if len ( data ) == 2 : var , default = data return os . environ . get ( var , default ) else : return os . environ [ value ]
def get_transcript_format ( transcript_content ) : """Returns transcript format . Arguments : transcript _ content ( str ) : Transcript file content ."""
try : sjson_obj = json . loads ( transcript_content ) except ValueError : # With error handling ( set to ' ERROR _ RAISE ' ) , we will be getting # the exception if something went wrong in parsing the transcript . srt_subs = SubRipFile . from_string ( transcript_content , error_handling = SubRipFile . ERROR_RAI...
def parsePortSpec ( spec , separator = '-' ) : '''Parses a port specification in two forms into the same form . In the first form the specification is just an integer . In this case a tuple is returned containing the same integer twice . In the second form the specification is two numbers separated by a hyphe...
x = list ( map ( lambda x : x . strip ( ) , spec . split ( separator ) ) ) return tuple ( map ( int , x * ( 3 - len ( x ) ) ) )
def get_field_info ( self , field ) : """Given an instance of a serializer field , return a dictionary of metadata about it ."""
field_info = collections . OrderedDict ( ) field_info [ 'type' ] = self . label_lookup [ field ] field_info [ 'required' ] = getattr ( field , 'required' , False ) attrs = [ 'read_only' , 'label' , 'help_text' , 'allow_null' , 'min_length' , 'max_length' , 'min_value' , 'max_value' , ] # Handle default attribute defaul...
def minmax_auto_scale ( img , as_uint16 ) : """Utility function for rescaling all pixel values of input image to fit the range of uint8. Rescaling method is min - max , which is all pixel values are normalized to [ 0 , 1 ] by using img . min ( ) and img . max ( ) and then are scaled up by 255 times . If the a...
if as_uint16 : output_high = 65535 output_type = np . uint16 else : output_high = 255 output_type = np . uint8 return rescale_pixel_intensity ( img , input_low = img . min ( ) , input_high = img . max ( ) , output_low = 0 , output_high = output_high , output_type = output_type )
def passthrough ( args ) : """% prog passthrough chrY . vcf chrY . new . vcf Pass through Y and MT vcf ."""
p = OptionParser ( passthrough . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) vcffile , newvcffile = args fp = open ( vcffile ) fw = open ( newvcffile , "w" ) gg = [ "0/0" , "0/1" , "1/1" ] for row in fp : if row [ 0 ] == "#" : print ( row ...
def _add_vcf_header_sample_cl ( in_file , items , base_file ) : """Add phenotype information to a VCF header . Encode tumor / normal relationships in VCF header . Could also eventually handle more complicated pedigree information if useful ."""
paired = vcfutils . get_paired ( items ) if paired : toadd = [ "##SAMPLE=<ID=%s,Genomes=Tumor>" % paired . tumor_name ] if paired . normal_name : toadd . append ( "##SAMPLE=<ID=%s,Genomes=Germline>" % paired . normal_name ) toadd . append ( "##PEDIGREE=<Derived=%s,Original=%s>" % ( paired . tumo...
def create_data_types ( self ) : """Map of standard playbook variable types to create method ."""
return { 'Binary' : self . create_binary , 'BinaryArray' : self . create_binary_array , 'KeyValue' : self . create_key_value , 'KeyValueArray' : self . create_key_value_array , 'String' : self . create_string , 'StringArray' : self . create_string_array , 'TCEntity' : self . create_tc_entity , 'TCEntityArray' : self . ...
def _remove_untraceable ( self ) : """Remove from the tracer those wires that CompiledSimulation cannot track . Create _ probe _ mapping for wires only traceable via probes ."""
self . _probe_mapping = { } wvs = { wv for wv in self . tracer . wires_to_track if self . _traceable ( wv ) } self . tracer . wires_to_track = wvs self . tracer . _wires = { wv . name : wv for wv in wvs } self . tracer . trace . __init__ ( wvs )
def check_no_multiple_handlers ( self , resource ) : '''The same verb cannot be repeated on several endpoints .'''
seen = [ ] errors = [ ] msg = 'HTTP verb "{}" associated to more than one endpoint in "{}".' for method in resource . callbacks : for op in getattr ( method , 'swagger_ops' ) : if op in seen : errors . append ( msg . format ( op , resource . __name__ ) ) else : seen . append ...
def insertFromMimeData ( self , data ) : """Paste the MIME data at the current cursor position . This method also adds another undo - object to the undo - stack ."""
undoObj = UndoPaste ( self , data , self . pasteCnt ) self . pasteCnt += 1 self . qteUndoStack . push ( undoObj )
def main ( ) : """Entry point"""
client_1 = MessageBot ( "verne" , "Jules Verne" ) client_1 . start ( ) client_1 . connect ( "127.0.0.1" ) client_2 = MessageBot ( "adams" , "Douglas Adams" ) client_2 . start ( ) client_2 . connect ( "127.0.0.1" ) herald_1 = Herald ( client_1 ) herald_1 . start ( ) herald_2 = Herald ( client_2 ) herald_2 . start ( ) ha...
def parse_response ( self , block = True , timeout = 0 ) : "Parse the response from a publish / subscribe command"
connection = self . connection if connection is None : raise RuntimeError ( 'pubsub connection not set: ' 'did you forget to call subscribe() or psubscribe()?' ) if not block and not connection . can_read ( timeout = timeout ) : return None return self . _execute ( connection , connection . read_response )
def _new_instance ( cls , children = None , connector = None , negated = False ) : """Create a new instance of this class when new Nodes ( or subclasses ) are needed in the internal code in this class . Normally , it just shadows _ _ init _ _ ( ) . However , subclasses with an _ _ init _ _ signature that aren '...
obj = QBase ( children , connector , negated ) obj . __class__ = cls return obj
def run ( self , from_email , recipients , message ) : """This does the dirty work . Connects to Amazon SES via boto and fires off the message . : param str from _ email : The email address the message will show as originating from . : param list recipients : A list of email addresses to send the message ...
self . _open_ses_conn ( ) try : # We use the send _ raw _ email func here because the Django # EmailMessage object we got these values from constructs all of # the headers and such . self . connection . send_raw_email ( source = from_email , destinations = recipients , raw_message = dkim_sign ( message ) , ) except...
def set_argsx ( self , arguments , * args ) : """Setup the command line arguments , the first item must be an ( absolute ) filename to run . Variadic function , must be NULL terminated ."""
return lib . zproc_set_argsx ( self . _as_parameter_ , arguments , * args )
def validate_value_range ( self , value ) : """Args : value : Throws DsdlException if this value cannot be represented by this type ."""
low , high = self . value_range if not low <= value <= high : error ( 'Value [%s] is out of range %s' , value , self . value_range )
def mpris ( self ) : """Get the current output format and return it ."""
if self . _kill : raise KeyboardInterrupt current_player_id = self . _player_details . get ( "id" ) cached_until = self . py3 . CACHE_FOREVER if self . _player is None : text = self . format_none color = self . py3 . COLOR_BAD composite = [ { "full_text" : text , "color" : color } ] self . _data = {...
def get_auth ( ) : """Return a tuple for authenticating a user If not successful raise ` ` AgileError ` ` ."""
auth = get_auth_from_env ( ) if auth [ 0 ] and auth [ 1 ] : return auth home = os . path . expanduser ( "~" ) config = os . path . join ( home , '.gitconfig' ) if not os . path . isfile ( config ) : raise GithubException ( 'No .gitconfig available' ) parser = configparser . ConfigParser ( ) parser . read ( conf...
def rejectEdit ( self ) : """Cancels the edit for this label ."""
if self . _lineEdit : self . _lineEdit . hide ( ) self . editingCancelled . emit ( )
def open_connection ( func ) : """Decorate a function to create a ` nds2 . connection ` if required"""
@ wraps ( func ) def wrapped_func ( * args , ** kwargs ) : # pylint : disable = missing - docstring if kwargs . get ( 'connection' , None ) is None : try : host = kwargs . pop ( 'host' ) except KeyError : raise TypeError ( "one of `connection` or `host` is required " "to quer...
def inject ( self , other ) : """Add two compatible ` Series ` along their shared x - axis values . Parameters other : ` Series ` a ` Series ` whose xindex intersects with ` self . xindex ` Returns out : ` Series ` the sum of ` self ` and ` other ` along their shared x - axis values Raises ValueErro...
# check Series compatibility self . is_compatible ( other ) if ( self . xunit == second ) and ( other . xspan [ 0 ] < self . xspan [ 0 ] ) : other = other . crop ( start = self . xspan [ 0 ] ) if ( self . xunit == second ) and ( other . xspan [ 1 ] > self . xspan [ 1 ] ) : other = other . crop ( end = self . xs...
def copy ( self ) : """Returns a copy of this UnionProducts . Edits to the copy ' s mappings will not affect the product mappings in the original . The copy is shallow though , so edits to the copy ' s product values will mutate the original ' s product values . : API : public : rtype : : class : ` UnionP...
products_by_target = defaultdict ( OrderedSet ) for key , value in self . _products_by_target . items ( ) : products_by_target [ key ] = OrderedSet ( value ) return UnionProducts ( products_by_target = products_by_target )
def GetMessages ( self , formatter_mediator , event ) : """Determines the formatted message strings for an event object . Args : formatter _ mediator ( FormatterMediator ) : mediates the interactions between formatters and other components , such as storage and Windows EventLog resources . event ( EventOb...
event_values = event . CopyToDict ( ) # TODO : clean up the default formatter and add a test to make sure # it is clear how it is intended to work . text_pieces = [ ] for key , value in event_values . items ( ) : if key in definitions . RESERVED_VARIABLE_NAMES : continue text_pieces . append ( '{0:s}: {...
def has_flag ( conf , atom , flag ) : '''Verify if the given package or DEPEND atom has the given flag . Warning : This only works if the configuration files tree is in the correct format ( the one enforced by enforce _ nice _ config ) CLI Example : . . code - block : : bash salt ' * ' portage _ config . ...
if flag in get_flags_from_package_conf ( conf , atom ) : return True return False
def generation ( self ) : """Returns the number of ancestors that are dictionaries"""
if not self . parent : return 0 elif self . parent . is_dict : return 1 + self . parent . generation else : return self . parent . generation
def get_handler_stats ( self ) : '''Return handler read statistics Returns a dictionary of managed handler data read statistics . The format is primarily controlled by the : func : ` SocketStreamCapturer . dump _ all _ handler _ stats ` function : : < capture address > : < list of handler capture statistics...
return { address : stream_capturer [ 0 ] . dump_all_handler_stats ( ) for address , stream_capturer in self . _stream_capturers . iteritems ( ) }
def get_column ( column_name , node , context ) : """Get a column by name from the selectable . Args : column _ name : str , name of the column to retrieve . node : SqlNode , the node the column is being retrieved for . context : CompilationContext , compilation specific metadata . Returns : column , th...
column = try_get_column ( column_name , node , context ) if column is None : selectable = get_node_selectable ( node , context ) raise AssertionError ( u'Column "{}" not found in selectable "{}". Columns present are {}. ' u'Context is {}.' . format ( column_name , selectable . original , [ col . name for col in...
def sample_truncated_gaussian ( mu = 0 , sigma = 1 , lb = - np . Inf , ub = np . Inf ) : """Sample a truncated normal with the specified params . This is not the most stable way but it works as long as the truncation region is not too far from the mean ."""
# Broadcast arrays to be of the same shape mu , sigma , lb , ub = np . broadcast_arrays ( mu , sigma , lb , ub ) shp = mu . shape if np . allclose ( sigma , 0.0 ) : return mu cdflb = normal_cdf ( lb , mu , sigma ) cdfub = normal_cdf ( ub , mu , sigma ) # Sample uniformly from the CDF cdfsamples = cdflb + np . rando...
def write_moc_fits ( moc , filename , ** kwargs ) : """Write a MOC as a FITS file . Any additional keyword arguments are passed to the astropy . io . fits . HDUList . writeto method ."""
tbhdu = write_moc_fits_hdu ( moc ) prihdr = fits . Header ( ) prihdu = fits . PrimaryHDU ( header = prihdr ) hdulist = fits . HDUList ( [ prihdu , tbhdu ] ) hdulist . writeto ( filename , ** kwargs )
def generate_anchors ( base_size = 16 , ratios = [ 0.5 , 1 , 2 ] , scales = 2 ** np . arange ( 3 , 6 ) ) : """Generate anchor ( reference ) windows by enumerating aspect ratios X scales wrt a reference ( 0 , 0 , 15 , 15 ) window ."""
base_anchor = np . array ( [ 1 , 1 , base_size , base_size ] , dtype = 'float32' ) - 1 ratio_anchors = _ratio_enum ( base_anchor , ratios ) anchors = np . vstack ( [ _scale_enum ( ratio_anchors [ i , : ] , scales ) for i in range ( ratio_anchors . shape [ 0 ] ) ] ) return anchors
def get_user_agent ( ) : """Construct and informative user - agent string . Includes OS version and docker version info Not thread - safe : return :"""
global user_agent_string if user_agent_string is None : # get OS type try : sysinfo = subprocess . check_output ( 'lsb_release -i -r -s' . split ( ' ' ) ) dockerinfo = subprocess . check_output ( 'docker --version' . split ( ' ' ) ) user_agent_string = ' ' . join ( [ sysinfo . replace ( '\t'...
def lint ( session ) : """Run linters . Returns a failure if the linters find linting errors or sufficiently serious code quality issues ."""
session . install ( 'flake8' , * LOCAL_DEPS ) session . install ( '-e' , '.' ) session . run ( 'flake8' , os . path . join ( 'google' , 'cloud' , 'bigquery_storage_v1beta1' ) ) session . run ( 'flake8' , 'tests' )
def xpathNextChild ( self , ctxt ) : """Traversal function for the " child " direction The child axis contains the children of the context node in document order ."""
if ctxt is None : ctxt__o = None else : ctxt__o = ctxt . _o ret = libxml2mod . xmlXPathNextChild ( ctxt__o , self . _o ) if ret is None : raise xpathError ( 'xmlXPathNextChild() failed' ) __tmp = xmlNode ( _obj = ret ) return __tmp
def _process_data ( self , obj ) : """Processes command results ."""
assert len ( self . _waiters ) > 0 , ( type ( obj ) , obj ) waiter , encoding , cb = self . _waiters . popleft ( ) if isinstance ( obj , RedisError ) : if isinstance ( obj , ReplyError ) : if obj . args [ 0 ] . startswith ( 'READONLY' ) : obj = ReadOnlyError ( obj . args [ 0 ] ) _set_excepti...
def activate ( self , token ) : """Make a copy of the received token and call ` self . _ activate ` ."""
if watchers . worth ( 'MATCHER' , 'DEBUG' ) : # pragma : no cover watchers . MATCHER . debug ( "Node <%s> activated with token %r" , self , token ) return self . _activate ( token . copy ( ) )
def get_group_id ( self , uuid = None ) : """Get group id based on uuid . Args : uuid ( str ) : optional uuid . defaults to self . cuuid Raises : PyLmodUnexpectedData : No group data was returned . requests . RequestException : Exception connection error Returns : int : numeric group id"""
group_data = self . get_group ( uuid ) try : return group_data [ 'response' ] [ 'docs' ] [ 0 ] [ 'id' ] except ( KeyError , IndexError ) : failure_message = ( 'Error in get_group response data - ' 'got {0}' . format ( group_data ) ) log . exception ( failure_message ) raise PyLmodUnexpectedData ( failur...
def _is_chinese_char ( self , cp ) : """Checks whether CP is the codepoint of a CJK character ."""
# This defines a " chinese character " as anything in the CJK Unicode block : # https : / / en . wikipedia . org / wiki / CJK _ Unified _ Ideographs _ ( Unicode _ block ) # Note that the CJK Unicode block is NOT all Japanese and Korean characters , # despite its name . The modern Korean Hangul alphabet is a different b...
def _backlog ( self , data ) : """Find all the datagrepper messages between ' then ' and ' now ' . Put those on our work queue . Should be called in a thread so as not to block the hub at startup ."""
try : data = json . loads ( data ) except ValueError as e : self . log . info ( "Status contents are %r" % data ) self . log . exception ( e ) self . log . info ( "Skipping backlog retrieval." ) return last = data [ 'message' ] [ 'body' ] if isinstance ( last , str ) : last = json . loads ( last...
def to_import ( import_ ) : """Serializes import to id string : param import _ : object to serialize : return : string id"""
from sevenbridges . models . storage_import import Import if not import_ : raise SbgError ( 'Import is required!' ) elif isinstance ( import_ , Import ) : return import_ . id elif isinstance ( import_ , six . string_types ) : return import_ else : raise SbgError ( 'Invalid import parameter!' )
def initialize_callbacks ( self ) : """Initializes all callbacks and save the result in the ` ` callbacks _ ` ` attribute . Both ` ` default _ callbacks ` ` and ` ` callbacks ` ` are used ( in that order ) . Callbacks may either be initialized or not , and if they don ' t have a name , the name is inferred ...
callbacks_ = [ ] class Dummy : # We cannot use None as dummy value since None is a # legitimate value to be set . pass for name , cb in self . _uniquely_named_callbacks ( ) : # check if callback itself is changed param_callback = getattr ( self , 'callbacks__' + name , Dummy ) if param_callback is not Dummy...
def _list_packages ( self , args ) : '''List files for an installed package'''
packages = self . _pkgdb_fun ( 'list_packages' , self . db_conn ) for package in packages : if self . opts [ 'verbose' ] : status_msg = ',' . join ( package ) else : status_msg = package [ 0 ] self . ui . status ( status_msg )
def _qsturng ( p , r , v ) : """scalar version of qsturng"""
# # print ' q ' , p # r is interpolated through the q to y here we only need to # account for when p and / or v are not found in the table . global A , p_keys , v_keys if p < .1 or p > .999 : raise ValueError ( 'p must be between .1 and .999' ) if p < .9 : if v < 2 : raise ValueError ( 'v must be > 2 wh...
def run_has_samplesheet ( fc_dir , config , require_single = True ) : """Checks if there ' s a suitable SampleSheet . csv present for the run"""
fc_name , _ = flowcell . parse_dirname ( fc_dir ) sheet_dirs = config . get ( "samplesheet_directories" , [ ] ) fcid_sheet = { } for ss_dir in ( s for s in sheet_dirs if os . path . exists ( s ) ) : with utils . chdir ( ss_dir ) : for ss in glob . glob ( "*.csv" ) : fc_ids = _get_flowcell_id ( s...
def create_partitions ( self , topic_partitions , timeout_ms = None , validate_only = False ) : """Create additional partitions for an existing topic . : param topic _ partitions : A map of topic name strings to NewPartition objects . : param timeout _ ms : Milliseconds to wait for new partitions to be create...
version = self . _matching_api_version ( CreatePartitionsRequest ) timeout_ms = self . _validate_timeout ( timeout_ms ) if version == 0 : request = CreatePartitionsRequest [ version ] ( topic_partitions = [ self . _convert_create_partitions_request ( topic_name , new_partitions ) for topic_name , new_partitions in ...
def gff3_verifier ( entries , line = None ) : """Raises error if invalid GFF3 format detected Args : entries ( list ) : A list of GFF3Entry instances line ( int ) : Line number of first entry Raises : FormatError : Error when GFF3 format incorrect with descriptive message"""
regex = r'^[a-zA-Z0-9.:^*$@!+_?-|]+\t.+\t.+\t\d+\t\d+\t' + r'\d*\.?\d*\t[+-.]\t[.0-2]\t.+{0}$' . format ( os . linesep ) delimiter = r'\t' for entry in entries : try : entry_verifier ( [ entry . write ( ) ] , regex , delimiter ) except FormatError as error : # Format info on what entry error came from ...
def as_dict ( self ) : """json friendly dict representation of Kpoints"""
d = { "comment" : self . comment , "nkpoints" : self . num_kpts , "generation_style" : self . style . name , "kpoints" : self . kpts , "usershift" : self . kpts_shift , "kpts_weights" : self . kpts_weights , "coord_type" : self . coord_type , "labels" : self . labels , "tet_number" : self . tet_number , "tet_weight" : ...
def show ( self , notebook = notebook_display ) : """Display cluster properties and scaling relation parameters ."""
print ( "\nCluster Ensemble:" ) if notebook is True : display ( self . _df ) elif notebook is False : print ( self . _df ) self . massrich_parameters ( )
def next ( self ) : """A ` next ` that caches the returned results . Together with the slightly different ` _ _ iter _ _ ` , these cursors can be iterated over more than once ."""
if self . __tailable : return PymongoCursor . next ( self ) try : ret = PymongoCursor . next ( self ) except StopIteration : self . __fullcache = True raise self . __itercache . append ( ret ) return ret
def ordering_for ( self , term , view ) : """Return ordering ( model field chain ) for term ( serializer field chain ) or None if invalid Raise ImproperlyConfigured if serializer _ class not set on view"""
if not self . _is_allowed_term ( term , view ) : return None serializer = self . _get_serializer_class ( view ) ( ) serializer_chain = term . split ( '.' ) model_chain = [ ] for segment in serializer_chain [ : - 1 ] : field = serializer . get_all_fields ( ) . get ( segment ) if not ( field and field . sourc...
def participating_ec_states ( self ) : '''The state of each execution context this component is participating in .'''
with self . _mutex : if not self . _participating_ec_states : if self . participating_ecs : states = [ ] for ec in self . participating_ecs : states . append ( self . _get_ec_state ( ec ) ) self . _participating_ec_states = states else : ...