signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def trees_to_dict ( trees_list ) : """Convert a list of ` TreeNode ` s to an expansion dictionary . : param trees _ list : A list of ` TreeNode ` instances : type trees _ list : list [ TreeNode ] : return : An expansion dictionary that represents the expansions detailed in the provided expansions tree nodes ...
result = { } for tree in trees_list : result . update ( tree . to_dict ( ) ) return result
def connect ( self ) : """establish a connection to the Instrument"""
if not driver_ok : logger . error ( "Visa driver NOT ok" ) return False visa_backend = '@py' # use PyVISA - py as backend if hasattr ( settings , 'VISA_BACKEND' ) : visa_backend = settings . VISA_BACKEND try : self . rm = visa . ResourceManager ( visa_backend ) except : logger . error ( "Visa Resour...
def detect_balance_proof_change ( old_state : ChainState , current_state : ChainState , ) -> Iterator [ Union [ BalanceProofSignedState , BalanceProofUnsignedState ] ] : """Compare two states for any received balance _ proofs that are not in ` old _ state ` ."""
if old_state == current_state : return for payment_network_identifier in current_state . identifiers_to_paymentnetworks : try : old_payment_network = old_state . identifiers_to_paymentnetworks . get ( payment_network_identifier , ) except AttributeError : old_payment_network = None curre...
def unique_slug_required ( form , slug ) : """Enforce a unique slug accross all pages and websistes ."""
if hasattr ( form , 'instance' ) and form . instance . id : if Content . objects . exclude ( page = form . instance ) . filter ( body = slug , type = "slug" ) . count ( ) : raise forms . ValidationError ( error_dict [ 'another_page_error' ] ) elif Content . objects . filter ( body = slug , type = "slug" ) ....
def add_method_drop_down ( self , col_number , col_label ) : """Add drop - down - menu options for magic _ method _ codes columns"""
if self . data_type == 'age' : method_list = vocab . age_methods elif '++' in col_label : method_list = vocab . pmag_methods elif self . data_type == 'result' : method_list = vocab . pmag_methods else : method_list = vocab . er_methods self . choices [ col_number ] = ( method_list , True )
def open ( self , baudrate = None , no_reader_thread = False ) : """Opens the device . : param baudrate : baudrate to use : type baudrate : int : param no _ reader _ thread : whether or not to automatically open the reader thread . : type no _ reader _ thread : bool : raises : : py : class : ` ~ alarmde...
try : self . _read_thread = Device . ReadThread ( self ) self . _device = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) if self . _use_ssl : self . _init_ssl ( ) self . _device . connect ( ( self . _host , self . _port ) ) if self . _use_ssl : while True : t...
def _find_usage_environments ( self ) : """find usage for ElasticBeanstalk environments"""
environments = self . conn . describe_environments ( ) self . limits [ 'Environments' ] . _add_current_usage ( len ( environments [ 'Environments' ] ) , aws_type = 'AWS::ElasticBeanstalk::Environment' , )
def add_moving_element ( self , element ) : """Add elements to the board"""
element . initialize ( self . canvas ) self . elements . append ( element )
def GetValueByName ( self , name ) : """Retrieves a value by name . Args : name ( str ) : name of the value or an empty string for the default value . Returns : WinRegistryValue : Windows Registry value or None if not found ."""
if not self . _registry_key and self . _registry : self . _GetKeyFromRegistry ( ) if not self . _registry_key : return None return self . _registry_key . GetValueByName ( name )
def close ( self ) : """Close any open channels ."""
self . consumer . close ( ) self . publisher . close ( ) self . _closed = True
def _exception_raise ( self ) : """Raises a pending exception that was recorded while getting a Task ready for execution ."""
exc = self . exc_info ( ) [ : ] try : exc_type , exc_value , exc_traceback = exc except ValueError : exc_type , exc_value = exc exc_traceback = None # raise exc _ type ( exc _ value ) . with _ traceback ( exc _ traceback ) if sys . version_info [ 0 ] == 2 : exec ( "raise exc_type, exc_value, exc_traceba...
def _compute_version_info ( ) : """Compute the versions of Python , pyarrow , and Ray . Returns : A tuple containing the version information ."""
ray_version = ray . __version__ python_version = "." . join ( map ( str , sys . version_info [ : 3 ] ) ) pyarrow_version = pyarrow . __version__ return ray_version , python_version , pyarrow_version
def to_unicode ( text ) : """Convert to unicode ."""
if isinstance ( text , unicode ) : return text if isinstance ( text , six . string_types ) : return decode_to_unicode ( text ) return unicode ( text )
def _write_particle_information ( xml_file , structure , xyz , forcefield , ref_distance , ref_mass , ref_energy ) : """Write out the particle information . Parameters xml _ file : file object The file object of the hoomdxml file being written structure : parmed . Structure Parmed structure object xyz :...
xml_file . write ( '<position units="sigma" num="{}">\n' . format ( xyz . shape [ 0 ] ) ) for pos in xyz : xml_file . write ( '{}\t{}\t{}\n' . format ( * pos / ref_distance ) ) xml_file . write ( '</position>\n' ) if forcefield : types = [ atom . type for atom in structure . atoms ] else : types = [ atom . ...
def run ( self , dw , m ) : """run ( self , dw , m ) - > PyObject *"""
CheckParent ( self ) return _fitz . Page_run ( self , dw , m )
def take_at_most_n_seconds ( time_s , func , * args , ** kwargs ) : """A function that returns whether a function call took less than time _ s . NOTE : The function call is not killed and will run indefinitely if hung . Args : time _ s : Maximum amount of time to take . func : Function to call . * args : ...
thread = threading . Thread ( target = func , args = args , kwargs = kwargs ) thread . start ( ) thread . join ( time_s ) if thread . is_alive ( ) : return False return True
def param_list_to_dict ( list , param_struct , skeys ) : """convert from param dictionary to list param _ struct : structure of parameter array"""
RV = [ ] i0 = 0 for key in skeys : val = param_struct [ key ] shape = SP . array ( val ) np = shape . prod ( ) i1 = i0 + np params = list [ i0 : i1 ] . reshape ( shape ) RV . append ( ( key , params ) ) i0 = i1 return dict ( RV )
def whitespace_around_comma ( logical_line ) : r"""Avoid extraneous whitespace after a comma or a colon . Note : these checks are disabled by default Okay : a = ( 1 , 2) E241 : a = ( 1 , 2) E242 : a = ( 1 , \ t2)"""
line = logical_line for m in WHITESPACE_AFTER_COMMA_REGEX . finditer ( line ) : found = m . start ( ) + 1 if '\t' in m . group ( ) : yield found , "E242 tab after '%s'" % m . group ( ) [ 0 ] else : yield found , "E241 multiple spaces after '%s'" % m . group ( ) [ 0 ]
def upload ( identifier , files , metadata = None , headers = None , access_key = None , secret_key = None , queue_derive = None , verbose = None , verify = None , checksum = None , delete = None , retries = None , retries_sleep = None , debug = None , request_kwargs = None , ** get_item_kwargs ) : """Upload files ...
item = get_item ( identifier , ** get_item_kwargs ) return item . upload ( files , metadata = metadata , headers = headers , access_key = access_key , secret_key = secret_key , queue_derive = queue_derive , verbose = verbose , verify = verify , checksum = checksum , delete = delete , retries = retries , retries_sleep =...
def describe_message ( message_definition ) : """Build descriptor for Message class . Args : message _ definition : Message class to provide descriptor for . Returns : Initialized MessageDescriptor instance describing the Message class ."""
message_descriptor = MessageDescriptor ( ) message_descriptor . name = message_definition . definition_name ( ) . split ( '.' ) [ - 1 ] fields = sorted ( message_definition . all_fields ( ) , key = lambda v : v . number ) if fields : message_descriptor . fields = [ describe_field ( field ) for field in fields ] try...
def read_cz_lsm_info ( fd , byte_order , dtype , count ) : """Read CS _ LSM _ INFO tag from file and return as numpy . rec . array ."""
result = numpy . rec . fromfile ( fd , CZ_LSM_INFO , 1 , byteorder = byte_order ) [ 0 ] { 50350412 : '1.3' , 67127628 : '2.0' } [ result . magic_number ] # validation return result
def _get_bmdl_ratio ( self , models ) : """Return BMDL ratio in list of models ."""
bmdls = [ model . output [ "BMDL" ] for model in models if model . output [ "BMDL" ] > 0 ] return max ( bmdls ) / min ( bmdls ) if len ( bmdls ) > 0 else 0
def divide_chain ( self , chain = 0 ) : """Returns a ChainConsumer instance containing all the walks of a given chain as individual chains themselves . This method might be useful if , for example , your chain was made using MCMC with 4 walkers . To check the sampling of all 4 walkers agree , you could call...
indexes = self . _get_chain ( chain ) con = ChainConsumer ( ) for index in indexes : chain = self . chains [ index ] assert chain . walkers is not None , "The chain you have selected was not added with any walkers!" num_walkers = chain . walkers data = np . split ( chain . chain , num_walkers ) ws =...
def notify_launch ( self , log_level = 'ERROR' ) : """logs launcher message before startup Args : log _ level ( str ) : level to notify at"""
if not self . debug : self . logger . log ( logging . getLevelName ( log_level ) , 'LAUNCHING %s -- %s' , self . PROGNAME , platform . node ( ) ) flask_options = { key : getattr ( self , key ) for key in OPTION_ARGS } flask_options [ 'host' ] = self . get_host ( ) self . logger . info ( 'OPTIONS: %s' , flask_option...
def cancel_grab ( self ) : """This is called when the user cancels a recording . Canceling is done by clicking with the left mouse button ."""
logger . debug ( "User canceled hotkey recording." ) self . recording_finished . emit ( True ) self . _setKeyLabel ( self . key if self . key is not None else "(None)" )
def save_datasets ( self , datasets , filename = None , fill_value = None , compute = True , ** kwargs ) : """Save all datasets to one or more files ."""
LOG . debug ( "Starting in mitiff save_datasets ... " ) def _delayed_create ( create_opts , datasets ) : LOG . debug ( "create_opts: %s" , create_opts ) try : if 'platform_name' not in kwargs : kwargs [ 'platform_name' ] = datasets . attrs [ 'platform_name' ] if 'name' not in kwargs ...
def extra_args_parser ( parser = None , skip_args = None , ** kwargs ) : """Adds - - temps to MCMCIO parser ."""
if skip_args is None : skip_args = [ ] parser , actions = MCMCMetadataIO . extra_args_parser ( parser = parser , skip_args = skip_args , ** kwargs ) if 'temps' not in skip_args : act = parser . add_argument ( "--temps" , nargs = "+" , default = 0 , action = ParseTempsArg , help = "Get the given temperatures. Ma...
def gym_env_wrapper ( env , rl_env_max_episode_steps , maxskip_env , rendered_env , rendered_env_resize_to , sticky_actions ) : """Wraps a gym environment . see make _ gym _ env for details ."""
# rl _ env _ max _ episode _ steps is None or int . assert ( ( not rl_env_max_episode_steps ) or isinstance ( rl_env_max_episode_steps , int ) ) wrap_with_time_limit = ( ( not rl_env_max_episode_steps ) or rl_env_max_episode_steps >= 0 ) if wrap_with_time_limit : env = remove_time_limit_wrapper ( env ) if sticky_ac...
def make_python_xref_nodes_for_type ( py_type , state , hide_namespace = False ) : """Make docutils nodes containing a cross - reference to a Python object , given the object ' s type . Parameters py _ type : ` obj ` Type of an object . For example ` ` mypackage . mymodule . MyClass ` ` . If you have inst...
if py_type . __module__ == 'builtins' : typestr = py_type . __name__ else : typestr = '.' . join ( ( py_type . __module__ , py_type . __name__ ) ) return make_python_xref_nodes ( typestr , state , hide_namespace = hide_namespace )
def get_task_db ( self , source_path ) : '''从数据库中查询source _ path的信息 . 如果存在的话 , 就返回这条记录 ; 如果没有的话 , 就返回None'''
sql = 'SELECT * FROM upload WHERE source_path=?' req = self . cursor . execute ( sql , [ source_path , ] ) if req : return req . fetchone ( ) else : None
def has_kingside_castling_rights ( self , color : Color ) -> bool : """Checks if the given side has kingside ( that is h - side in Chess960) castling rights ."""
backrank = BB_RANK_1 if color == WHITE else BB_RANK_8 king_mask = self . kings & self . occupied_co [ color ] & backrank & ~ self . promoted if not king_mask : return False castling_rights = self . clean_castling_rights ( ) & backrank while castling_rights : rook = castling_rights & - castling_rights if roo...
def is_usable ( host , port , timeout = 3 ) : """测试代理是否可用 params host ip地址 port 端口号 timeout 默认值为3 , 通过设置这个参数可以过滤掉一些速度慢的代理 example is _ usable ( ' 222.180.24.13 ' , ' 808 ' , timeout = 3)"""
try : proxies = { 'http' : 'http://%s:%s' % ( host , port ) , 'https' : 'https://%s:%s' % ( host , port ) } requests . get ( 'http://www.baidu.com/' , proxies = proxies , timeout = timeout ) except HTTPError : print ( 'failed: ' , host , port ) return False else : print ( 'success: ' , host , port )...
def findreplaceables ( Class , parent , set , ** kwargs ) : # pylint : disable = bad - classmethod - argument """( Method for internal usage , see AbstractElement )"""
# some extra behaviour for text content elements , replace also based on the ' corrected ' attribute : if 'cls' not in kwargs : kwargs [ 'cls' ] = 'current' replace = super ( PhonContent , Class ) . findreplaceables ( parent , set , ** kwargs ) replace = [ x for x in replace if x . cls == kwargs [ 'cls' ] ] del kwa...
def get_sample_dataset ( dataset_properties ) : """Returns sample dataset Args : dataset _ properties ( dict ) : Dictionary corresponding to the properties of the dataset used to verify the estimator and metric generators . Returns : X ( array - like ) : Features array y ( array - like ) : Labels array ...
kwargs = dataset_properties . copy ( ) data_type = kwargs . pop ( 'type' ) if data_type == 'multiclass' : try : X , y = datasets . make_classification ( random_state = 8 , ** kwargs ) splits = model_selection . StratifiedKFold ( n_splits = 2 , random_state = 8 ) . split ( X , y ) except Exceptio...
def postscriptBlueScaleFallback ( info ) : """Fallback to a calculated value : 3 / ( 4 * * maxZoneHeight * ) where * maxZoneHeight * is the tallest zone from * postscriptBlueValues * and * postscriptOtherBlues * . If zones are not set , return 0.039625."""
blues = getAttrWithFallback ( info , "postscriptBlueValues" ) otherBlues = getAttrWithFallback ( info , "postscriptOtherBlues" ) maxZoneHeight = 0 blueScale = 0.039625 if blues : assert len ( blues ) % 2 == 0 for x , y in zip ( blues [ : - 1 : 2 ] , blues [ 1 : : 2 ] ) : maxZoneHeight = max ( maxZoneHei...
def _compute_precision_recall ( input_ , labels , threshold , per_example_weights ) : """Returns the numerator of both , the denominator of precision and recall ."""
# To apply per _ example _ weights , we need to collapse each row to a scalar , but # we really want the sum . labels . get_shape ( ) . assert_is_compatible_with ( input_ . get_shape ( ) ) relevant = tf . to_float ( tf . greater ( labels , 0 ) ) retrieved = tf . to_float ( tf . greater ( input_ , threshold ) ) selected...
def _get_fastq_in_region ( region , align_bam , out_base ) : """Retrieve fastq files in region as single end . Paired end is more complicated since pairs can map off the region , so focus on local only assembly since we ' ve previously used paired information for mapping ."""
out_file = "{0}.fastq" . format ( out_base ) if not file_exists ( out_file ) : with pysam . Samfile ( align_bam , "rb" ) as in_pysam : with file_transaction ( out_file ) as tx_out_file : with open ( tx_out_file , "w" ) as out_handle : contig , start , end = region ...
def _compile_control_flow_expression ( self , expr : Expression , scope : Dict [ str , TensorFluent ] , batch_size : Optional [ int ] = None , noise : Optional [ List [ tf . Tensor ] ] = None ) -> TensorFluent : '''Compile a control flow expression ` expr ` into a TensorFluent in the given ` scope ` with optional...
etype = expr . etype args = expr . args if etype [ 1 ] == 'if' : condition = self . _compile_expression ( args [ 0 ] , scope , batch_size , noise ) true_case = self . _compile_expression ( args [ 1 ] , scope , batch_size , noise ) false_case = self . _compile_expression ( args [ 2 ] , scope , batch_size , n...
def template_exception_handler ( fn , error_context , filename = None ) : """Calls the given function , attempting to catch any template - related errors , and converts the error to a Statik TemplateError instance . Returns the result returned by the function itself ."""
error_message = None if filename : error_context . update ( filename = filename ) try : return fn ( ) except jinja2 . TemplateSyntaxError as exc : error_context . update ( filename = exc . filename , line_no = exc . lineno ) error_message = exc . message except jinja2 . TemplateError as exc : error_...
def _protobuf_value_type ( value ) : """Returns the type of the google . protobuf . Value message as an api . DataType . Returns None if the type of ' value ' is not one of the types supported in api _ pb2 . DataType . Args : value : google . protobuf . Value message ."""
if value . HasField ( "number_value" ) : return api_pb2 . DATA_TYPE_FLOAT64 if value . HasField ( "string_value" ) : return api_pb2 . DATA_TYPE_STRING if value . HasField ( "bool_value" ) : return api_pb2 . DATA_TYPE_BOOL return None
def triangle_unaddress ( fx , tr ) : '''triangle _ unaddress ( FX , tr ) yields the point P , inside the reference triangle given by the (3 x d ) - sized coordinate matrix FX , that is addressed by the address coordinate tr , which may either be a 2 - d vector or a ( 2 x n ) - sized matrix .'''
fx = np . asarray ( fx ) tr = np . asarray ( tr ) # the triangle vectors . . . ab = fx [ 1 ] - fx [ 0 ] ac = fx [ 2 ] - fx [ 0 ] bc = fx [ 2 ] - fx [ 1 ] return np . asarray ( [ ax + tr [ 1 ] * ( abx + tr [ 0 ] * bcx ) for ( ax , bcx , abx ) in zip ( fx [ 0 ] , bc , ab ) ] )
def get_domain_and_name ( self , domain_or_name ) : """Given a ` ` str ` ` or : class : ` boto . sdb . domain . Domain ` , return a ` ` tuple ` ` with the following members ( in order ) : * In instance of : class : ` boto . sdb . domain . Domain ` for the requested domain * The domain ' s name as a ` ` str ...
if ( isinstance ( domain_or_name , Domain ) ) : return ( domain_or_name , domain_or_name . name ) else : return ( self . get_domain ( domain_or_name ) , domain_or_name )
def expiration_datetime ( self ) : """Returns the expiration datetime : return datetime : The datetime this token expires"""
expires_at = self . get ( 'expires_at' ) if expires_at is None : # consider it is expired return dt . datetime . now ( ) - dt . timedelta ( seconds = 10 ) expires_on = dt . datetime . fromtimestamp ( expires_at ) - dt . timedelta ( seconds = EXPIRES_ON_THRESHOLD ) if self . is_long_lived : expires_on = expires_...
def is_consecutive ( self , rtol : float = 1.e-5 , atol : float = 1.e-8 ) -> bool : """Whether all bins are in a growing order . Parameters rtol , atol : numpy tolerance parameters"""
if self . inconsecutive_allowed : if self . _consecutive is None : if self . _numpy_bins is not None : self . _consecutive = True self . _consecutive = is_consecutive ( self . bins , rtol , atol ) return self . _consecutive else : return True
def mendel_errors ( parent_genotypes , progeny_genotypes ) : """Locate genotype calls not consistent with Mendelian transmission of alleles . Parameters parent _ genotypes : array _ like , int , shape ( n _ variants , 2 , 2) Genotype calls for the two parents . progeny _ genotypes : array _ like , int , s...
# setup parent_genotypes = GenotypeArray ( parent_genotypes ) progeny_genotypes = GenotypeArray ( progeny_genotypes ) check_ploidy ( parent_genotypes . ploidy , 2 ) check_ploidy ( progeny_genotypes . ploidy , 2 ) # transform into per - call allele counts max_allele = max ( parent_genotypes . max ( ) , progeny_genotypes...
def from_conll ( this_class , text ) : """Construct a Token from a line in CoNLL - X format ."""
fields = text . split ( '\t' ) fields [ 0 ] = int ( fields [ 0 ] ) # index fields [ 6 ] = int ( fields [ 6 ] ) # head index if fields [ 5 ] != '_' : # feats fields [ 5 ] = tuple ( fields [ 5 ] . split ( '|' ) ) fields = [ value if value != '_' else None for value in fields ] fields . append ( None ) # for extra ret...
def parent ( self ) : # type : ( ) - > Any """Retrieve the parent of this ` Part ` . : return : the parent : class : ` Part ` of this part : raises APIError : if an Error occurs Example > > > part = project . part ( ' Frame ' ) > > > bike = part . parent ( )"""
if self . parent_id : return self . _client . part ( pk = self . parent_id , category = self . category ) else : return None
def transformer_base_vq1_16_nb1_packed_nda_b01_scales ( ) : """Set of hyperparameters ."""
hparams = transformer_base_vq_ada_32ex_packed ( ) hparams . use_scales = int ( True ) hparams . moe_num_experts = 16 hparams . moe_k = 1 hparams . beta = 0.1 hparams . layer_preprocess_sequence = "n" hparams . layer_postprocess_sequence = "da" hparams . ema = False return hparams
def cycle_dist ( x , y , n ) : """Find Distance between x , y by means of a n - length cycle . Example : cycle _ dist ( 1 , 23 , 24 ) = 2 cycle _ dist ( 5 , 13 , 24 ) = 8 cycle _ dist ( 0.0 , 2.4 , 1.0 ) = 0.4 cycle _ dist ( 0.0 , 2.6 , 1.0 ) = 0.4"""
dist = abs ( x - y ) % n if dist >= 0.5 * n : dist = n - dist return dist
def p_pvar_inst_def ( self , p ) : '''pvar _ inst _ def : IDENT LPAREN lconst _ list RPAREN SEMI | IDENT SEMI | NOT IDENT LPAREN lconst _ list RPAREN SEMI | NOT IDENT SEMI | IDENT LPAREN lconst _ list RPAREN ASSIGN _ EQUAL range _ const SEMI | IDENT ASSIGN _ EQUAL range _ const SEMI'''
if len ( p ) == 6 : p [ 0 ] = ( ( p [ 1 ] , p [ 3 ] ) , True ) elif len ( p ) == 3 : p [ 0 ] = ( ( p [ 1 ] , None ) , True ) elif len ( p ) == 7 : p [ 0 ] = ( ( p [ 2 ] , p [ 4 ] ) , False ) elif len ( p ) == 4 : p [ 0 ] = ( ( p [ 2 ] , None ) , False ) elif len ( p ) == 8 : p [ 0 ] = ( ( p [ 1 ] , ...
def _validate_num_units ( num_units , service_name , add_error ) : """Check that the given num _ units is valid . Use the given service name to describe possible errors . Use the given add _ error callable to register validation error . If no errors are encountered , return the number of units as an integer ....
if num_units is None : # This should be a subordinate charm . return 0 try : num_units = int ( num_units ) except ( TypeError , ValueError ) : add_error ( 'num_units for service {} must be a digit' . format ( service_name ) ) return if num_units < 0 : add_error ( 'num_units {} for service {} must be...
def draw_circle ( self , center , radius , array , value , mode = "set" ) : """Draws a circle of specified radius on the input array and fills it with specified value : param center : a tuple for the center of the circle : type center : tuple ( x , y ) : param radius : how many pixels in radius the circle is ...
ri , ci = draw . circle ( center [ 0 ] , center [ 1 ] , radius = radius , shape = array . shape ) if mode == "add" : array [ ri , ci ] += value elif mode == "set" : array [ ri , ci ] = value else : raise ValueError ( "draw_circle mode must be 'set' or 'add' but {} used" . format ( mode ) ) return ri , ci , ...
def view_release ( ) : """Page for viewing all tests runs in a release ."""
build = g . build if request . method == 'POST' : form = forms . ReleaseForm ( request . form ) else : form = forms . ReleaseForm ( request . args ) form . validate ( ) ops = operations . BuildOps ( build . id ) release , run_list , stats_dict , approval_log = ops . get_release ( form . name . data , form . num...
def get_fault ( self , reply ) : """Extract the fault from the specified soap reply . If I { faults } is True , an exception is raised . Otherwise , the I { unmarshalled } fault L { Object } is returned . This method is called when the server raises a I { web fault } . @ param reply : A soap reply message ....
reply = self . replyfilter ( reply ) sax = Parser ( ) faultroot = sax . parse ( string = reply ) soapenv = faultroot . getChild ( 'Envelope' ) soapbody = soapenv . getChild ( 'Body' ) fault = soapbody . getChild ( 'Fault' ) unmarshaller = self . unmarshaller ( False ) p = unmarshaller . process ( fault ) if self . opti...
def add_nic ( self , instance_id , net_id ) : """Add a Network Interface Controller"""
# TODO : upgrade with port _ id and fixed _ ip in future self . client . servers . interface_attach ( instance_id , None , net_id , None ) return True
def load_rules ( self , filename ) : """Load rules from YAML configuration in the given stream object : param filename : Filename of rule YAML file : return : rules object"""
self . logger . debug ( 'Reading rules from %s' , filename ) try : in_file = open ( filename ) except IOError : self . logger . error ( 'Error opening {0}' . format ( filename ) ) raise y = None try : y = yaml . load ( in_file ) except yaml . YAMLError as exc : if hasattr ( exc , 'problem_mark' ) : ...
def _transfer_data ( self , remote_path , data ) : """Used by the base _ execute _ module ( ) , and in < 2.4 also by the template action module , and probably others ."""
if isinstance ( data , dict ) : data = jsonify ( data ) if not isinstance ( data , bytes ) : data = to_bytes ( data , errors = 'surrogate_or_strict' ) LOG . debug ( '_transfer_data(%r, %s ..%d bytes)' , remote_path , type ( data ) , len ( data ) ) self . _connection . put_data ( remote_path , data ) return remo...
def isoratio_init ( self , isos ) : '''This file returns the isotopic ratio of two isotopes specified as iso1 and iso2 . The isotopes are given as , e . g . , [ ' Fe ' , 56 , ' Fe ' , 58 ] or [ ' Fe - 56 ' , ' Fe - 58 ' ] ( for compatibility ) - > list .'''
if len ( isos ) == 2 : dumb = [ ] dumb = isos [ 0 ] . split ( '-' ) dumb . append ( isos [ 1 ] . split ( '-' ) [ 0 ] ) dumb . append ( isos [ 1 ] . split ( '-' ) [ 1 ] ) isos = dumb ssratio = old_div ( self . habu [ isos [ 0 ] . ljust ( 2 ) . lower ( ) + str ( int ( isos [ 1 ] ) ) . rjust ( 3 ) ] , ...
def queryset_iterator ( queryset , chunksize = 1000 ) : """The queryset iterator helps to keep the memory consumption down . And also making it easier to process for weaker computers ."""
if queryset . exists ( ) : primary_key = 0 last_pk = queryset . order_by ( '-pk' ) [ 0 ] . pk queryset = queryset . order_by ( 'pk' ) while primary_key < last_pk : for row in queryset . filter ( pk__gt = primary_key ) [ : chunksize ] : primary_key = row . pk yield row ...
def list_certificates ( self , ** kwargs ) : """List certificates registered to organisation . Currently returns partially populated certificates . To obtain the full certificate object : ` [ get _ certificate ( certificate _ id = cert [ ' id ' ] ) for cert in list _ certificates ] ` : param int limit : The n...
kwargs = self . _verify_sort_options ( kwargs ) kwargs = self . _verify_filters ( kwargs , Certificate ) if "service__eq" in kwargs : if kwargs [ "service__eq" ] == CertificateType . bootstrap : pass elif kwargs [ "service__eq" ] == CertificateType . developer : kwargs [ "device_execution_mode__...
def get_language ( self ) : """Get the language parameter from the current request ."""
return get_language_parameter ( self . request , self . query_language_key , default = self . get_default_language ( object = object ) )
def superseeded_by ( self , other_service ) : """Return True if input service has login id and this has not ."""
if not other_service or other_service . __class__ != self . __class__ or other_service . protocol != self . protocol or other_service . port != self . port : return False # If this service does not have a login id but the other one does , then # we should return True here return not self . device_credentials and ot...
def average ( self , rows : List [ Row ] , column : NumberColumn ) -> Number : """Takes a list of rows and a column and returns the mean of the values under that column in those rows ."""
cell_values = [ row . values [ column . name ] for row in rows ] if not cell_values : return 0.0 # type : ignore return sum ( cell_values ) / len ( cell_values )
def get_sub_menu_template_names ( self ) : """Returns a list of template names to search for when rendering a a sub menu for a specific flat menu object ( making use of self . handle )"""
site = self . _contextual_vals . current_site level = self . _contextual_vals . current_level handle = self . handle template_names = [ ] if settings . SITE_SPECIFIC_TEMPLATE_DIRS and site : hostname = site . hostname template_names . extend ( [ "menus/%s/flat/%s/level_%s.html" % ( hostname , handle , level ) ,...
def execute ( self , command ) : '''Execute a subprocess yielding output lines'''
process = Popen ( command , stdout = PIPE , stderr = STDOUT , universal_newlines = True ) while True : if process . poll ( ) is not None : self . returncode = process . returncode # pylint : disable = W0201 break yield process . stdout . readline ( )
def createCommit ( self , varBind , ** context ) : """Create Managed Object Instance . Implements the second of the multi - step workflow similar to the SNMP SET command processing ( : RFC : ` 1905 # section - 4.2.5 ` ) . The goal of the second phase is to actually create requested Managed Object Instance ....
name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: writeCommit(%s, %r)' % ( self , name , val ) ) ) cbFun = context [ 'cbFun' ] instances = context [ 'instances' ] . setdefault ( self . name , { self . ST_CREATE : { } , self . ST_DESTROY : { } } ) idx = context [ 'idx' ] if name in self ...
def ns ( symbol ) : '''generates a namespace x : : y : : z statement from a symbol'''
if symbol . type and symbol . type . is_primitive : return '' return '{0}::' . format ( '::' . join ( symbol . module . name_parts ) )
def typechecked ( memb ) : """Decorator applicable to functions , methods , properties , classes or modules ( by explicit call ) . If applied on a module , memb must be a module or a module name contained in sys . modules . See pytypes . set _ global _ typechecked _ decorator to apply this on all modules . ...
if not pytypes . checking_enabled : return memb if is_no_type_check ( memb ) : return memb if type_util . _check_as_func ( memb ) : return typechecked_func ( memb ) if isclass ( memb ) : return typechecked_class ( memb ) if ismodule ( memb ) : return typechecked_module ( memb , True ) if memb in sys...
def convenience_calc_log_likelihood ( self , params ) : """Calculates the log - likelihood for this model and dataset ."""
shapes , intercepts , betas = self . convenience_split_params ( params ) args = [ betas , self . design_3d , self . alt_id_vector , self . rows_to_obs , self . rows_to_alts , self . rows_to_mixers , self . choice_vector , self . utility_transform ] kwargs = { "ridge" : self . ridge , "weights" : self . weights } log_li...
def get_whitelisted_statements ( self , addr ) : """: returns : True if all statements are whitelisted"""
if addr in self . _run_statement_whitelist : if self . _run_statement_whitelist [ addr ] is True : return None # This is the default value used to say # we execute all statements in this basic block . A # little weird . . . else : return self . _run_statement_whitelist [ addr ] else ...
def rel_horz_pos ( self , amount ) : '''Calling this function sets the relative horizontal position for the next data , this is the position from the current position . The next character will be printed ( x / 180 ) inches away from the current position . The relative position CANNOT be specified to the left . ...
n1 = amount % 256 n2 = amount / 256 self . send ( chr ( 27 ) + '\{n1}{n2}' . format ( n1 = chr ( n1 ) , n2 = chr ( n2 ) ) )
def split_given_spans ( self , spans , sep = ' ' ) : """Split the text into several pieces . Resulting texts have all the layers that are present in the text instance that is splitted . The elements are copied to resulting pieces that are covered by their spans . However , this can result in empty layers if n...
N = len ( spans ) results = [ { TEXT : text } for text in self . texts_from_spans ( spans , sep = sep ) ] for elem in self : if isinstance ( self [ elem ] , list ) : splits = divide_by_spans ( self [ elem ] , spans , translate = True , sep = sep ) for idx in range ( N ) : results [ idx ]...
def setAttributes ( self , node ) : """Sets up attribute dictionary , checks for required attributes and sets default attribute values . attr is for default attribute values determined at runtime . structure of attributes dictionary [ ' xmlns ' ] [ xmlns _ key ] - - xmlns namespace [ ' xmlns ' ] [ prefix ...
self . attributes = { XMLSchemaComponent . xmlns : { } } for k , v in node . getAttributeDictionary ( ) . items ( ) : prefix , value = SplitQName ( k ) if value == XMLSchemaComponent . xmlns : self . attributes [ value ] [ prefix or XMLSchemaComponent . xmlns_key ] = v elif prefix : ns = nod...
def to_motevo ( self ) : """Return motif formatted in MotEvo ( TRANSFAC - like ) format Returns m : str String of motif in MotEvo format ."""
m = "//\n" m += "NA {}\n" . format ( self . id ) m += "P0\tA\tC\tG\tT\n" for i , row in enumerate ( self . pfm ) : m += "{}\t{}\n" . format ( i , "\t" . join ( [ str ( int ( x ) ) for x in row ] ) ) m += "//" return m
def distance_centimeters_ping ( self ) : """Measurement of the distance detected by the sensor , in centimeters . The sensor will take a single measurement then stop broadcasting . If you use this property too frequently ( e . g . every 100msec ) , the sensor will sometimes lock up and writing to the mo...
# This mode is special ; setting the mode causes the sensor to send out # a " ping " , but the mode isn ' t actually changed . self . mode = self . MODE_US_SI_CM return self . value ( 0 ) * self . _scale ( 'US_DIST_CM' )
def acl ( self ) : """Get the access control list for this workspace ."""
r = fapi . get_workspace_acl ( self . namespace , self . name , self . api_url ) fapi . _check_response_code ( r , 200 ) return r . json ( )
def piper ( self , in_sock , out_sock , out_addr , onkill ) : "Worker thread for data reading"
try : while True : written = in_sock . recv ( 32768 ) if not written : try : out_sock . shutdown ( socket . SHUT_WR ) except socket . error : self . threads [ onkill ] . kill ( ) break try : out_sock . sendall ( ...
def list_items ( item , details = False , group_by = 'UUID' ) : '''Return a list of a specific type of item . The following items are available : vms runningvms ostypes hostdvds hostfloppies intnets bridgedifs hostonlyifs natnets dhcpservers hostinfo hostcpuids hddbackends hdds dvds ...
types = ( 'vms' , 'runningvms' , 'ostypes' , 'hostdvds' , 'hostfloppies' , 'intnets' , 'bridgedifs' , 'hostonlyifs' , 'natnets' , 'dhcpservers' , 'hostinfo' , 'hostcpuids' , 'hddbackends' , 'hdds' , 'dvds' , 'floppies' , 'usbhost' , 'usbfilters' , 'systemproperties' , 'extpacks' , 'groups' , 'webcams' , 'screenshotform...
def _tokenize ( self , text ) : """Tokenize the text into a list of sentences with a list of words . : param text : raw text : return : tokenized text : rtype : list"""
sentences = [ ] tokens = [ ] for word in self . _clean_accents ( text ) . split ( ' ' ) : tokens . append ( word ) if '.' in word : sentences . append ( tokens ) tokens = [ ] return sentences
def _fluent_size ( self , fluents , ordering ) -> Sequence [ Sequence [ int ] ] : '''Returns the sizes of ` fluents ` following the given ` ordering ` . Returns : Sequence [ Sequence [ int ] ] : A tuple of tuple of integers representing the shape and size of each fluent .'''
shapes = [ ] for name in ordering : fluent = fluents [ name ] shape = self . _param_types_to_shape ( fluent . param_types ) shapes . append ( shape ) return tuple ( shapes )
def generator ( ngf , nc , no_bias = True , fix_gamma = True , eps = 1e-5 + 1e-12 , z_dim = 100 , activation = 'sigmoid' ) : '''The genrator is a CNN which takes 100 dimensional embedding as input and reconstructs the input image given to the encoder'''
BatchNorm = mx . sym . BatchNorm rand = mx . sym . Variable ( 'rand' ) rand = mx . sym . Reshape ( rand , shape = ( - 1 , z_dim , 1 , 1 ) ) g1 = mx . sym . Deconvolution ( rand , name = 'gen1' , kernel = ( 5 , 5 ) , stride = ( 2 , 2 ) , target_shape = ( 2 , 2 ) , num_filter = ngf * 8 , no_bias = no_bias ) gbn1 = BatchN...
def sort ( self , * args , ** kwargs ) : """Sort the MultiMap . Takes the same arguments as list . sort , and operates on tuples of ( key , value ) pairs . > > > m = MutableMultiMap ( ) > > > m [ ' c ' ] = 1 > > > m [ ' b ' ] = 3 > > > m [ ' a ' ] = 2 > > > m . sort ( ) > > > m . keys ( ) [ ' a ' ...
self . _pairs . sort ( * args , ** kwargs ) self . _rebuild_key_ids ( )
def xVal_xml ( self ) : """Return the ` ` < c : xVal > ` ` element for this series as unicode text . This element contains the X values for this series ."""
return self . _xVal_tmpl . format ( ** { 'nsdecls' : '' , 'numRef_xml' : self . numRef_xml ( self . _series . x_values_ref , self . _series . number_format , self . _series . x_values ) , } )
def run_node ( self , node , stim ) : '''Executes the Transformer at a specific node . Args : node ( str , Node ) : If a string , the name of the Node in the current Graph . Otherwise the Node instance to execute . stim ( str , stim , list ) : Any valid input to the Transformer stored at the target node ....
if isinstance ( node , string_types ) : node = self . nodes [ node ] result = node . transformer . transform ( stim ) if node . is_leaf ( ) : return listify ( result ) stim = result # If result is a generator , the first child will destroy the # iterable , so cache via list conversion if len ( node . children )...
def put_file ( self , in_path , out_path ) : '''transfer a file from local to remote'''
vvv ( "PUT %s TO %s" % ( in_path , out_path ) , host = self . host ) if not os . path . exists ( in_path ) : raise errors . AnsibleFileNotFound ( "file or module does not exist: %s" % in_path ) cmd = self . _password_cmd ( ) if C . DEFAULT_SCP_IF_SSH : cmd += [ "scp" ] + self . common_args cmd += [ in_path ...
def add ( self , entity ) : """Adds the supplied dict as a new entity"""
result = self . _http_req ( 'connections' , method = 'POST' , payload = entity ) status = result [ 'status' ] if not status == 201 : raise ServiceRegistryError ( status , "Couldn't add entity" ) self . debug ( 0x01 , result ) return result [ 'decoded' ]
def write_random_state ( self , group = None , state = None ) : """Writes the state of the random number generator from the file . The random state is written to ` ` sampler _ group ` ` / random _ state . Parameters group : str Name of group to write random state to . state : tuple , optional Specify th...
group = self . sampler_group if group is None else group dataset_name = "/" . join ( [ group , "random_state" ] ) if state is None : state = numpy . random . get_state ( ) s , arr , pos , has_gauss , cached_gauss = state if dataset_name in self : self [ dataset_name ] [ : ] = arr else : self . create_datase...
def _new ( self , dx_hash , ** kwargs ) : """: param dx _ hash : Standard hash populated in : func : ` dxpy . bindings . DXDataObject . new ( ) ` containing attributes common to all data object classes . : type dx _ hash : dict : param title : Workflow title ( optional ) : type title : string : param summar...
def _set_dx_hash ( kwargs , dxhash , key , new_key = None ) : new_key = key if new_key is None else new_key if key in kwargs : if kwargs [ key ] is not None : dxhash [ new_key ] = kwargs [ key ] del kwargs [ key ] if "init_from" in kwargs : if kwargs [ "init_from" ] is not None :...
def run ( self ) : """prepares the api and starts the tornado funcserver"""
self . log_id = 0 # all active websockets and their state self . websocks = { } # all active python interpreter sessions self . pysessions = { } if self . DISABLE_REQUESTS_DEBUG_LOGS : disable_requests_debug_logs ( ) self . threadpool = ThreadPool ( self . THREADPOOL_WORKERS ) self . api = None # tornado app object...
def dump_dict ( self , dump = None ) : """Dump all the PE header information into a dictionary ."""
dump_dict = dict ( ) warnings = self . get_warnings ( ) if warnings : dump_dict [ 'Parsing Warnings' ] = warnings dump_dict [ 'DOS_HEADER' ] = self . DOS_HEADER . dump_dict ( ) dump_dict [ 'NT_HEADERS' ] = self . NT_HEADERS . dump_dict ( ) dump_dict [ 'FILE_HEADER' ] = self . FILE_HEADER . dump_dict ( ) image_flags...
def stop ( self ) : """Stop the DbServer and the zworkers if any"""
if ZMQ : logging . warning ( self . master . stop ( ) ) z . context . term ( ) self . db . close ( )
def to_api_repr ( self ) : """Build an API representation of this object . Returns : Dict [ str , Any ] : A dictionary in the format used by the BigQuery API ."""
config = copy . deepcopy ( self . _properties ) if self . options is not None : r = self . options . to_api_repr ( ) if r != { } : config [ self . options . _RESOURCE_NAME ] = r return config
def create_lb ( kwargs = None , call = None ) : '''Create a load - balancer configuration . CLI Example : . . code - block : : bash salt - cloud - f create _ lb gce name = lb region = us - central1 ports = 80'''
if call != 'function' : raise SaltCloudSystemExit ( 'The create_lb function must be called with -f or --function.' ) if not kwargs or 'name' not in kwargs : log . error ( 'A name must be specified when creating a health check.' ) return False if 'ports' not in kwargs : log . error ( 'A port or port-rang...
def get_fas ( config ) : """Return a fedora . client . fas2 . AccountSystem object if the provided configuration contains a FAS username and password ."""
global _FAS if _FAS is not None : return _FAS # In some development environments , having fas _ credentials around is a # pain . . so , let things proceed here , but emit a warning . try : creds = config [ 'fas_credentials' ] except KeyError : log . warn ( "No fas_credentials available. Unable to query FAS...
def modification_time ( self ) : """dfdatetime . DateTimeValues : modification time or None if not available ."""
timestamp = self . _fsntfs_file_entry . get_modification_time_as_integer ( ) return dfdatetime_filetime . Filetime ( timestamp = timestamp )
def order_preserving_single_index_shift ( arr , index , new_index ) : """Moves a list element to a new index while preserving order . Parameters arr : list The list in which to shift an element . index : int The index of the element to shift . new _ index : int The index to which to shift the element ...
if new_index == 0 : return [ arr [ index ] ] + arr [ 0 : index ] + arr [ index + 1 : ] if new_index == len ( arr ) - 1 : return arr [ 0 : index ] + arr [ index + 1 : ] + [ arr [ index ] ] if index < new_index : return arr [ 0 : index ] + arr [ index + 1 : new_index + 1 ] + [ arr [ index ] ] + arr [ new_inde...
def plot ( self , xdata , ydata = [ ] , logScale = False , disp = True , ** kwargs ) : '''Graphs a line plot . xdata : list of independent variable data . Can optionally include a header , see testGraph . py in https : / / github . com / Dfenestrator / GooPyCharts for an example . ydata : list of dependent vari...
# combine data into proper format # check if only 1 vector was sent , then plot against a count if ydata : data = combineData ( xdata , ydata , self . xlabel ) else : data = combineData ( range ( len ( xdata ) ) , xdata , self . xlabel ) # determine log scale parameter if logScale : logScaleStr = 'true' els...
def is_static_etcd ( self ) : '''Determine if we are on a node running etcd'''
return os . path . exists ( os . path . join ( self . static_pod_dir , "etcd.yaml" ) )
def is_multisig_script ( script , blockchain = 'bitcoin' , ** blockchain_opts ) : """Is the given script a multisig script ?"""
if blockchain == 'bitcoin' : return btc_is_multisig_script ( script , ** blockchain_opts ) else : raise ValueError ( 'Unknown blockchain "{}"' . format ( blockchain ) )
def _prepare_wsdl_objects ( self ) : """Create the data structure and get it ready for the WSDL request ."""
self . CarrierCode = 'FDXE' self . RoutingCode = 'FDSD' self . Address = self . client . factory . create ( 'Address' ) self . ShipDateTime = datetime . datetime . now ( ) . isoformat ( )