signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def handle_remove_readonly ( func , path , exc ) : """Error handler for shutil . rmtree . Windows source repo folders are read - only by default , so this error handler attempts to set them as writeable and then proceed with deletion ."""
# Check for read - only attribute default_warning_message = ( "Unable to remove file due to permissions restriction: {!r}" ) # split the initial exception out into its type , exception , and traceback exc_type , exc_exception , exc_tb = exc if is_readonly_path ( path ) : # Apply write permission and call original funct...
def _get_info_dir ( ) : """Get path to directory in which to store info files . The directory returned by this function is " owned " by this module . If the contents of the directory are modified other than via the public functions of this module , subsequent behavior is undefined . The directory will be cr...
path = os . path . join ( tempfile . gettempdir ( ) , ".tensorboard-info" ) try : os . makedirs ( path ) except OSError as e : if e . errno == errno . EEXIST and os . path . isdir ( path ) : pass else : raise else : os . chmod ( path , 0o777 ) return path
def get_sources_by_position ( self , skydir , dist , min_dist = None , square = False , coordsys = 'CEL' ) : """Retrieve sources within a certain angular distance of a sky coordinate . This function supports two types of geometric selections : circular ( square = False ) and square ( square = True ) . The cir...
msk = get_skydir_distance_mask ( self . _src_skydir , skydir , dist , min_dist = min_dist , square = square , coordsys = coordsys ) radius = self . _src_skydir . separation ( skydir ) . deg radius = radius [ msk ] srcs = [ self . _srcs [ i ] for i in np . nonzero ( msk ) [ 0 ] ] isort = np . argsort ( radius ) radius =...
def _reduced_kernel_size_for_small_input ( input_tensor , kernel_size ) : """Define kernel size which is automatically reduced for small input . If the shape of the input images is unknown at graph construction time this function assumes that the input images are is large enough . Args : input _ tensor : in...
shape = input_tensor . get_shape ( ) . as_list ( ) if shape [ 1 ] is None or shape [ 2 ] is None : kernel_size_out = kernel_size else : kernel_size_out = [ min ( shape [ 1 ] , kernel_size [ 0 ] ) , min ( shape [ 2 ] , kernel_size [ 1 ] ) ] return kernel_size_out
def clear_cycles ( self ) : """Remove all cycle markers in current rater ."""
if self . rater is None : raise IndexError ( 'You need to have at least one rater' ) cycles = self . rater . find ( 'cycles' ) for cyc in list ( cycles ) : cycles . remove ( cyc ) self . save ( )
def next ( self , match , predicate = None , index = None ) : """Retrieves the nearest next matches . : param match : : type match : : param predicate : : type predicate : : param index : : type index : int : return : : rtype :"""
current = match . start + 1 while current <= self . _max_end : next_matches = self . starting ( current ) if next_matches : return filter_index ( next_matches , predicate , index ) current += 1 return filter_index ( _BaseMatches . _base ( ) , predicate , index )
def error ( self , message ) : """Prints error message , then help ."""
sys . stderr . write ( 'error: %s\n\n' % message ) self . print_help ( ) sys . exit ( 2 )
def call_fdel ( self , obj ) -> None : """Remove the predefined custom value and call the delete function ."""
self . fdel ( obj ) try : del vars ( obj ) [ self . name ] except KeyError : pass
def _normalized_mutual_info_score ( reference_indices , estimated_indices ) : """Compute the mutual information between two sequence labelings , adjusted for chance . Parameters reference _ indices : np . ndarray Array of reference indices estimated _ indices : np . ndarray Array of estimated indices ...
ref_classes = np . unique ( reference_indices ) est_classes = np . unique ( estimated_indices ) # Special limit cases : no clustering since the data is not split . # This is a perfect match hence return 1.0. if ( ref_classes . shape [ 0 ] == est_classes . shape [ 0 ] == 1 or ref_classes . shape [ 0 ] == est_classes . s...
def get_contact_method ( self , id , ** kwargs ) : """Get a contact method for this user ."""
endpoint = '{0}/{1}/contact_methods/{2}' . format ( self . endpoint , self [ 'id' ] , id , ) result = self . request ( 'GET' , endpoint = endpoint , query_params = kwargs ) return result [ 'contact_method' ]
def launch_cif_import ( group , database , max_entries , number_species , skip_partial_occupancies , importer_server , importer_db_host , importer_db_name , importer_db_password , importer_api_url , importer_api_key , count_entries , batch_count , dry_run , verbose ) : """Import cif files from various structural da...
# pylint : disable = too - many - arguments , too - many - locals , too - many - statements , too - many - branches , import - error import inspect from CifFile . StarFile import StarError from datetime import datetime from six . moves . urllib . error import HTTPError from aiida import orm from aiida . plugins import ...
def query_directory ( self , pattern , file_information_class , flags = None , file_index = 0 , max_output = 65536 , send = True ) : """Run a Query / Find on an opened directory based on the params passed in . Supports out of band send function , call this function with send = False to return a tuple of ( SMB2Q...
query = SMB2QueryDirectoryRequest ( ) query [ 'file_information_class' ] = file_information_class query [ 'flags' ] = flags query [ 'file_index' ] = file_index query [ 'file_id' ] = self . file_id query [ 'output_buffer_length' ] = max_output query [ 'buffer' ] = pattern . encode ( 'utf-16-le' ) if not send : retur...
def autodiscover_modules ( packages , related_name_re = '.+' , ignore_exceptions = False ) : """Autodiscover function follows the pattern used by Celery . : param packages : List of package names to auto discover modules in . : type packages : list of str : param related _ name _ re : Regular expression used ...
warnings . warn ( 'autodiscover_modules has been deprecated. ' 'Use Flask-Registry instead.' , DeprecationWarning ) global _RACE_PROTECTION if _RACE_PROTECTION : return [ ] _RACE_PROTECTION = True modules = [ ] try : tmp = [ find_related_modules ( pkg , related_name_re , ignore_exceptions ) for pkg in packages ...
def update_peak_magnitudes ( self ) : """* update peak magnitudes * * * Key Arguments : * * * * Return : * * - None * * Usage : * * . . todo : : - add usage info - create a sublime snippet for usage - write a command - line tool for this method - update package tutorial with command - line tool in...
self . log . debug ( 'starting the ``update_peak_magnitudes`` method' ) sqlQuery = self . settings [ "database settings" ] [ "transients" ] [ "transient peak magnitude query" ] sqlQuery = """UPDATE sherlock_crossmatches s, (%(sqlQuery)s) t SET s.transientAbsMag = ROUND(t.mag - IFNULL(dir...
def QA_util_getBetweenQuarter ( begin_date , end_date ) : """# 加上每季度的起始日期 、 结束日期"""
quarter_list = { } month_list = QA_util_getBetweenMonth ( begin_date , end_date ) for value in month_list : tempvalue = value . split ( "-" ) year = tempvalue [ 0 ] if tempvalue [ 1 ] in [ '01' , '02' , '03' ] : quarter_list [ year + "Q1" ] = [ '%s-01-01' % year , '%s-03-31' % year ] elif tempva...
def mutual_information ( i1 , i2 , bins = 256 ) : r"""Computes the mutual information ( MI ) ( a measure of entropy ) between two images . MI is not real metric , but a symmetric and nonnegative similarity measures that takes high values for similar images . Negative values are also possible . Intuitively , m...
# pre - process function arguments i1 = numpy . asarray ( i1 ) i2 = numpy . asarray ( i2 ) # validate function arguments if not i1 . shape == i2 . shape : raise ArgumentError ( 'the two supplied array-like sequences i1 and i2 must be of the same shape' ) # compute i1 and i2 histogram range i1_range = __range ( i1 ,...
def load ( cls , stream ) : """Load a serialized version of self from text stream . Expects the format used by mongooplog ."""
data = json . load ( stream ) [ 'ts' ] return cls ( data [ 'time' ] , data [ 'inc' ] )
def verify_fft_options ( opt , parser ) : """Parses the FFT options and verifies that they are reasonable . Parameters opt : object Result of parsing the CLI with OptionParser , or any object with the required attributes . parser : object OptionParser instance ."""
if len ( opt . fft_backends ) > 0 : _all_backends = get_backend_names ( ) for backend in opt . fft_backends : if backend not in _all_backends : parser . error ( "Backend {0} is not available" . format ( backend ) ) for backend in get_backend_modules ( ) : try : backend . verify_f...
def validate_creds ( creds ) : """Parse and validate user credentials whether format is right : param creds : User credentials : returns : Auth _ type class instance and parsed user credentials in dict : raises ValueError : If credential format is wrong ( eg : bad auth _ type )"""
try : auth_type , auth_rest = creds . split ( ':' , 1 ) except ValueError : raise ValueError ( "Missing ':' in %s" % creds ) authtypes = sys . modules [ __name__ ] auth_encoder = getattr ( authtypes , auth_type . title ( ) , None ) if auth_encoder is None : raise ValueError ( 'Invalid auth_type: %s' % auth_...
def get_column_listing ( self , table ) : """Get the column listing for a given table . : param table : The table : type table : str : rtype : list"""
sql = self . _grammar . compile_column_exists ( ) database = self . _connection . get_database_name ( ) table = self . _connection . get_table_prefix ( ) + table results = self . _connection . select ( sql , [ database , table ] ) return self . _connection . get_post_processor ( ) . process_column_listing ( results )
def _get_cache_key ( self , args , kwargs ) : """Returns key to be used in cache"""
hash_input = json . dumps ( { 'name' : self . name , 'args' : args , 'kwargs' : kwargs } , sort_keys = True ) # md5 is used for internal caching , not need to care about security return hashlib . md5 ( hash_input ) . hexdigest ( )
def upload_file_handle ( self , bucket : str , key : str , src_file_handle : typing . BinaryIO , content_type : str = None , metadata : dict = None ) : """Saves the contents of a file handle as the contents of an object in a bucket ."""
raise NotImplementedError ( )
def fence_draw_callback ( self , points ) : '''callback from drawing a fence'''
self . fenceloader . clear ( ) if len ( points ) < 3 : return self . fenceloader . target_system = self . target_system self . fenceloader . target_component = self . target_component bounds = mp_util . polygon_bounds ( points ) ( lat , lon , width , height ) = bounds center = ( lat + width / 2 , lon + height / 2 )...
def bind ( self , callback : typing . Union [ typing . Callable , AbstractFilter ] , validator : typing . Optional [ typing . Callable ] = None , event_handlers : typing . Optional [ typing . List [ Handler ] ] = None , exclude_event_handlers : typing . Optional [ typing . Iterable [ Handler ] ] = None ) : """Regis...
record = FilterRecord ( callback , validator , event_handlers , exclude_event_handlers ) self . _registered . append ( record )
def check_value ( config , section , option , jinja_pattern = JINJA_PATTERN , ) : """try to figure out if value is valid or jinja2 template value Args : config ( : obj : ` configparser . ConfigParser ` ) : config object to read key from section ( str ) : name of section in configparser option ( str ) : name...
value = config [ section ] [ option ] if re . match ( jinja_pattern , value ) : return None return value
def get_ruleset_file ( ruleset = None ) : """Get the ruleset file from name : param ruleset : str : return : str"""
ruleset = ruleset or "default" ruleset_dirs = get_ruleset_dirs ( ) for ruleset_directory in ruleset_dirs : possible_ruleset_files = [ os . path . join ( ruleset_directory , ruleset + ext ) for ext in EXTS ] for ruleset_file in possible_ruleset_files : if os . path . isfile ( ruleset_file ) : ...
def reset_option ( key ) : """Reset one or more options to their default value . Pass " all " as argument to reset all options . Available options : parse . full _ codestream print . xml print . codestream print . short Parameter key : str Name of a single option ."""
global _options if key == 'all' : _options = copy . deepcopy ( _original_options ) else : if key not in _options . keys ( ) : raise KeyError ( '{key} not valid.' . format ( key = key ) ) _options [ key ] = _original_options [ key ]
def write_stilde ( self , stilde_dict , group = None ) : """Writes stilde for each IFO to file . Parameters stilde : { dict , FrequencySeries } A dict of FrequencySeries where the key is the IFO . group : { None , str } The group to write the strain to . If None , will write to the top level ."""
subgroup = self . data_group + "/{ifo}/stilde" if group is None : group = subgroup else : group = '/' . join ( [ group , subgroup ] ) for ifo , stilde in stilde_dict . items ( ) : self [ group . format ( ifo = ifo ) ] = stilde self [ group . format ( ifo = ifo ) ] . attrs [ 'delta_f' ] = stilde . delta_...
def get_year ( self ) : """Return the year from the database in the format expected by the URL ."""
year = super ( BuildableYearArchiveView , self ) . get_year ( ) fmt = self . get_year_format ( ) return date ( int ( year ) , 1 , 1 ) . strftime ( fmt )
def send_deferred ( self , auth ) : """Send all deferred requests for a particular CIK / auth ."""
if self . deferred . has_requests ( auth ) : method_arg_pairs = self . deferred . get_method_args_pairs ( auth ) calls = self . _composeCalls ( method_arg_pairs ) # should this call be made with no timeout ? ( e . g . is there a # wait ( ) ) notimeout = self . deferred . get_notimeout ( auth ) t...
def convertor ( geometry , method = "wgs2gcj" ) : """convert wgs84 to gcj referencing by https : / / github . com / wandergis / coordTransform _ py"""
if geometry [ 'type' ] == 'Point' : coords = geometry [ 'coordinates' ] coords [ 0 ] , coords [ 1 ] = methods [ method ] ( coords [ 0 ] , coords [ 1 ] ) elif geometry [ 'type' ] == 'LineString' or geometry [ 'type' ] == 'MutliPoint' : coordinates = geometry [ 'coordinates' ] for coords in coordinates : ...
def bss_eval_sources_framewise ( reference_sources , estimated_sources , window = 30 * 44100 , hop = 15 * 44100 , compute_permutation = False ) : """BSS Eval v3 bss _ eval _ sources _ framewise Wrapper to ` ` bss _ eval ` ` with the right parameters . The call to this function is not recommended . See the descr...
( sdr , isr , sir , sar , perm ) = bss_eval ( reference_sources , estimated_sources , window = window , hop = hop , compute_permutation = compute_permutation , filters_len = 512 , framewise_filters = True , bsseval_sources_version = True ) return ( sdr , sir , sar , perm )
def set_admin ( email ) : '''Set an user as administrator'''
user = datastore . get_user ( email ) log . info ( 'Adding admin role to user %s (%s)' , user . fullname , user . email ) role = datastore . find_or_create_role ( 'admin' ) datastore . add_role_to_user ( user , role ) success ( 'User %s (%s) is now administrator' % ( user . fullname , user . email ) )
def _sanitize_input_structure ( input_structure ) : """Sanitize our input structure by removing magnetic information and making primitive . Args : input _ structure : Structure Returns : Structure"""
input_structure = input_structure . copy ( ) # remove any annotated spin input_structure . remove_spin ( ) # sanitize input structure : first make primitive . . . input_structure = input_structure . get_primitive_structure ( use_site_props = False ) # . . . and strip out existing magmoms , which can cause conflicts # w...
def build_sdk_span ( self , span ) : """Takes a BasicSpan and converts into an SDK type JsonSpan"""
custom_data = CustomData ( tags = span . tags , logs = self . collect_logs ( span ) ) sdk_data = SDKData ( name = span . operation_name , custom = custom_data , Type = self . get_span_kind_as_string ( span ) ) if "arguments" in span . tags : sdk_data . arguments = span . tags [ "arguments" ] if "return" in span . t...
def chunked ( iterable , n ) : """Break an iterable into lists of a given length : : > > > list ( chunked ( [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] , 3 ) ) [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 ] ] If the length of ` ` iterable ` ` is not evenly divisible by ` ` n ` ` , the last returned list will be shorter . This...
# Doesn ' t seem to run into any number - of - args limits . for group in ( list ( g ) for g in zip_longest ( * [ iter ( iterable ) ] * n , fillvalue = _marker ) ) : if group [ - 1 ] is _marker : # If this is the last group , shuck off the padding : del group [ group . index ( _marker ) : ] yield group
def set_save_directory ( base , source ) : """Sets the root save directory for saving screenshots . Screenshots will be saved in subdirectories under this directory by browser window size ."""
root = os . path . join ( base , source ) if not os . path . isdir ( root ) : os . makedirs ( root ) world . screenshot_root = root
def getLogger ( name = 'generalLoggerName' , dr = '' , lvl = 20 , addFH = True , addSH = True , ) : """This will either return the logging object already instantiated , or instantiate a new one and return it . * * Use this function to both create and return any logger * * to avoid accidentally adding addition...
log = False try : log = log_dict [ name ] except : log = setUpLogger ( name , dr , lvl , addFH , addSH ) return log
def human_size ( bytes , units = [ ' bytes' , 'KB' , 'MB' , 'GB' , 'TB' , 'PB' , 'EB' ] ) : """Returns a human readable string reprentation of bytes"""
return str ( bytes ) + units [ 0 ] if bytes < 1024 else human_size ( bytes >> 10 , units [ 1 : ] )
def first_ ( self ) : """Select the first row"""
try : val = self . df . iloc [ 0 ] return val except Exception as e : self . err ( e , "Can not select first row" )
def get_commit_date ( commit , tz_name ) : '''Get datetime of commit comitted _ date'''
return set_date_tzinfo ( datetime . fromtimestamp ( mktime ( commit . committed_date ) ) , tz_name = tz_name )
def append ( self , listname , xy_idx , var_name , element_name ) : """Append variable names to the name lists"""
self . resize ( ) string = '{0} {1}' if listname not in [ 'unamex' , 'unamey' , 'fnamex' , 'fnamey' ] : logger . error ( 'Wrong list name for varname.' ) return elif listname in [ 'fnamex' , 'fnamey' ] : string = '${0}\\ {1}$' if isinstance ( element_name , list ) : for i , j in zip ( xy_idx , element_n...
def setBendLength ( self , x ) : """set bend length : param x : new bend length to be assigned , [ m ] : return : None"""
if x != self . bend_length : self . bend_length = x self . refresh = True
def current_access ( self ) : """Wraps : meth : ` access _ for ` with : obj : ` ~ coaster . auth . current _ auth ` to return a proxy for the currently authenticated user ."""
return self . access_for ( actor = current_auth . actor , anchors = current_auth . anchors )
def set_preserver_info ( self , sample ) : """Updates the Preserver and the Date Preserved with the values provided in the request . If neither Preserver nor DatePreserved are present in the request , returns False"""
if sample . getPreserver ( ) and sample . getDatePreserved ( ) : # Preserver and Date Preserved already set . This is correct return True preserver = self . get_form_value ( "Preserver" , sample , sample . getPreserver ( ) ) preserved = self . get_form_value ( "getDatePreserved" , sample . getDatePreserved ( ) ) if...
def linkedin ( self , qs ) : """CSV format suitable for importing into linkedin Groups . perfect for pre - approving members of a linkedin group ."""
csvf = writer ( sys . stdout ) csvf . writerow ( [ 'First Name' , 'Last Name' , 'Email' ] ) for ent in qs : csvf . writerow ( [ ent [ 'first_name' ] , ent [ 'last_name' ] , ent [ 'email' ] ] )
def set_mode_label_to_keywords_creation ( self ) : """Set the mode label to the Keywords Creation / Update mode ."""
self . setWindowTitle ( self . keyword_creation_wizard_name ) if self . get_existing_keyword ( 'layer_purpose' ) : mode_name = tr ( 'Keywords update wizard for layer <b>{layer_name}</b>' ) . format ( layer_name = self . layer . name ( ) ) else : mode_name = tr ( 'Keywords creation wizard for layer <b>{layer_nam...
def update_api_mappings ( self ) : """Create a cname for the API deployment ."""
response_provider = None response_action = None domain = self . generated . apigateway ( ) [ 'domain' ] try : response_provider = self . client . create_base_path_mapping ( domainName = domain , basePath = self . _format_base_path ( self . trigger_settings [ 'api_name' ] ) , restApiId = self . api_id , stage = self...
def add_callback ( self , callback , * callback_args , ** callback_kwargs ) : """Add a callback without an associated errback ."""
return self . add_callbacks ( callback , callback_args = callback_args , callback_kwargs = callback_kwargs )
def make_url ( path , protocol = None , hosts = None ) : """Make an URL given a path , and optionally , a protocol and set of hosts to select from randomly . : param path : The Archive . org path . : type path : str : param protocol : ( optional ) The HTTP protocol to use . " https : / / " is used by defa...
protocol = 'https://' if not protocol else protocol host = hosts [ random . randrange ( len ( hosts ) ) ] if hosts else 'archive.org' return protocol + host + path . strip ( )
def close ( correlation_id , components ) : """Closes multiple components . To be closed components must implement [ [ ICloseable ] ] interface . If they don ' t the call to this method has no effect . : param correlation _ id : ( optional ) transaction id to trace execution through call chain . : param com...
if components == None : return for component in components : Closer . close_one ( correlation_id , component )
def ratio_split ( amount , ratios ) : """Split in _ value according to the ratios specified in ` ratios ` This is special in that it ensures the returned values always sum to in _ value ( i . e . we avoid losses or gains due to rounding errors ) . As a result , this method returns a list of ` Decimal ` values...
ratio_total = sum ( ratios ) divided_value = amount / ratio_total values = [ ] for ratio in ratios : value = divided_value * ratio values . append ( value ) # Now round the values , keeping track of the bits we cut off rounded = [ v . quantize ( Decimal ( "0.01" ) ) for v in values ] remainders = [ v - rounded ...
def range_validator ( minval = None , maxval = None ) : """Generates a function that validates that a number is within range Parameters minval : numeric , optional : Values strictly lesser than ` minval ` are rejected maxval : numeric , optional : Values strictly greater than ` maxval ` are rejected Ret...
def checker_func ( value ) : if minval is not None and value < minval : msg = "must be >= {}" . format ( minval ) raise ValidationError ( msg ) if maxval is not None and value > maxval : msg = "must be <= {}" . format ( maxval ) raise ValidationError ( msg ) return value retu...
def rnaQuantificationsGenerator ( self , request ) : """Returns a generator over the ( rnaQuantification , nextPageToken ) pairs defined by the specified request ."""
if len ( request . rna_quantification_set_id ) < 1 : raise exceptions . BadRequestException ( "Rna Quantification Set Id must be specified" ) else : compoundId = datamodel . RnaQuantificationSetCompoundId . parse ( request . rna_quantification_set_id ) dataset = self . getDataRepository ( ) . getDataset ( c...
def iam_device_info ( self , apdu ) : """Create a device information record based on the contents of an IAmRequest and put it in the cache ."""
if _debug : DeviceInfoCache . _debug ( "iam_device_info %r" , apdu ) # make sure the apdu is an I - Am if not isinstance ( apdu , IAmRequest ) : raise ValueError ( "not an IAmRequest: %r" % ( apdu , ) ) # get the device instance device_instance = apdu . iAmDeviceIdentifier [ 1 ] # get the existing cache record ...
def parse ( args : typing . List [ str ] = None , arg_parser : ArgumentParser = None ) -> dict : """Parses the arguments for the cauldron server"""
parser = arg_parser or create_parser ( ) return vars ( parser . parse_args ( args ) )
def page_string ( str_to_page , pager_cmd ) : """Page str _ to _ page via the pager ."""
# By default , we expect the command to be ` less - R ` . If that is the # pager _ cmd , but they don ' t have less on their machine , odds are they ' re # just using the default value . In this case the pager will fail , so we ' ll # just go via pydoc . pager , which tries to do smarter checking that we don ' t # want...
def Recv ( self ) : """Accept a message from Fleetspeak . Returns : A tuple ( common _ pb2 . Message , size of the message in bytes ) . Raises : ProtocolError : If we receive unexpected data from Fleetspeak ."""
size = struct . unpack ( _STRUCT_FMT , self . _ReadN ( _STRUCT_LEN ) ) [ 0 ] if size > MAX_SIZE : raise ProtocolError ( "Expected size to be at most %d, got %d" % ( MAX_SIZE , size ) ) with self . _read_lock : buf = self . _ReadN ( size ) self . _ReadMagic ( ) res = common_pb2 . Message ( ) res . ParseFromS...
def wasSolvedBy ( self , user ) : """Checks if this exercise has previously been solved by the user ."""
thisExercise = _Solution . what == self byThisUser = _Solution . who == user condition = q . AND ( thisExercise , byThisUser ) return self . store . query ( _Solution , condition , limit = 1 ) . count ( ) == 1
def mk_token ( ** load ) : r'''Create an eauth token using provided credentials Non - root users may specify an expiration date - - if allowed via the : conf _ master : ` token _ expire _ user _ override ` setting - - by passing an additional ` ` token _ expire ` ` param . This overrides the : conf _ master...
# This will hang if the master daemon is not running . netapi = salt . netapi . NetapiClient ( __opts__ ) if not netapi . _is_master_running ( ) : raise salt . exceptions . SaltDaemonNotRunning ( 'Salt Master must be running.' ) auth = salt . auth . Resolver ( __opts__ ) return auth . mk_token ( load )
def maxNotchSize ( self , orientation ) : """Returns the maximum size for this ruler based on its notches and the given orientation . : param orientation | < Qt . Orientation > : return < int >"""
metrics = QFontMetrics ( QApplication . font ( ) ) if orientation == Qt . Vertical : notch = '' for n in self . notches ( ) : if len ( nativestring ( n ) ) > len ( nativestring ( notch ) ) : notch = nativestring ( n ) return metrics . width ( notch ) else : return metrics . height ( ...
def _read_baseline_from_info ( self ) : """Tries to find and return baseline number from either tileInfo or productInfo file . : return : Baseline ID : rtype : str : raises : ValueError"""
if hasattr ( self , 'tile_info' ) : return self . tile_info [ 'datastrip' ] [ 'id' ] [ - 5 : ] if hasattr ( self , 'product_info' ) : return self . product_info [ 'datastrips' ] [ 0 ] [ 'id' ] [ - 5 : ] raise ValueError ( 'No info file has been obtained yet.' )
async def rpc ( self , msg , encoder = None ) : '''Make an RPC to the API . The message is encoded as JSON using the given encoder if any . : param msg : Parameters for the call ( will be encoded as JSON ) . : param encoder : Encoder to be used when encoding the message . : return : The result of the call ....
self . __request_id__ += 1 msg [ 'request-id' ] = self . __request_id__ if 'params' not in msg : msg [ 'params' ] = { } if "version" not in msg : msg [ 'version' ] = self . facades [ msg [ 'type' ] ] outgoing = json . dumps ( msg , indent = 2 , cls = encoder ) log . debug ( 'connection {} -> {}' . format ( id (...
def process_file ( self , filename = None , format = None ) : """Parse a file into an ontology object , using rdflib"""
rdfgraph = rdflib . Graph ( ) if format is None : if filename . endswith ( ".ttl" ) : format = 'turtle' elif filename . endswith ( ".rdf" ) : format = 'xml' rdfgraph . parse ( filename , format = format ) return self . process_rdfgraph ( rdfgraph )
def prepare_stateseries ( self , ramflag : bool = True ) -> None : """Call method | Element . prepare _ stateseries | of all handled | Element | objects ."""
for element in printtools . progressbar ( self ) : element . prepare_stateseries ( ramflag )
def _get_previous_mz ( self , mzs ) : '''given an mz array , return the mz _ data ( disk location ) if the mz array was not previously written , write to disk first'''
mzs = tuple ( mzs ) # must be hashable if mzs in self . lru_cache : return self . lru_cache [ mzs ] # mz not recognized . . . check hash mz_hash = "%s-%s-%s" % ( hash ( mzs ) , sum ( mzs ) , len ( mzs ) ) if mz_hash in self . hashes : for mz_data in self . hashes [ mz_hash ] : test_mz = self . _read_mz ...
def get_kline_data ( self , symbol , kline_type = '5min' , start = None , end = None ) : """Get kline data For each query , the system would return at most 1500 pieces of data . To obtain more data , please page the data by time . : param symbol : Name of symbol e . g . KCS - BTC : type symbol : string : ...
data = { 'symbol' : symbol } if kline_type is not None : data [ 'type' ] = kline_type if start is not None : data [ 'startAt' ] = start else : data [ 'startAt' ] = calendar . timegm ( datetime . utcnow ( ) . date ( ) . timetuple ( ) ) if end is not None : data [ 'endAt' ] = end else : data [ 'endAt'...
def rebuild_proxies ( self , prepared_request , proxies ) : """This method re - evaluates the proxy configuration by considering the environment variables . If we are redirected to a URL covered by NO _ PROXY , we strip the proxy configuration . Otherwise , we set missing proxy keys for this URL ( in case the...
proxies = proxies if proxies is not None else { } headers = prepared_request . headers url = prepared_request . url scheme = urlparse ( url ) . scheme new_proxies = proxies . copy ( ) no_proxy = proxies . get ( 'no_proxy' ) bypass_proxy = should_bypass_proxies ( url , no_proxy = no_proxy ) if self . trust_env and not b...
def read_table ( fstream ) : """Read a likwid table info from the text stream . Args : fstream : Likwid ' s filestream . Returns ( dict ( str : str ) ) : A dict containing likwid ' s table info as key / value pairs ."""
pos = fstream . tell ( ) line = fstream . readline ( ) . strip ( ) fragments = line . split ( "," ) fragments = [ x for x in fragments if x is not None ] partition = dict ( ) if not len ( fragments ) >= 4 : return None partition [ "table" ] = fragments [ 0 ] partition [ "group" ] = fragments [ 1 ] partition [ "set"...
def get_service_packages ( self ) : """Get all service packages"""
api = self . _get_api ( billing . DefaultApi ) package_response = api . get_service_packages ( ) packages = [ ] for state in PACKAGE_STATES : # iterate states in order items = getattr ( package_response , state ) or [ ] for item in ensure_listable ( items ) : params = item . to_dict ( ) params [...
def ReadPathInfos ( self , client_id , path_type , components_list ) : """Retrieves path info records for given paths ."""
result = { } for components in components_list : try : path_record = self . path_records [ ( client_id , path_type , components ) ] result [ components ] = path_record . GetPathInfo ( ) except KeyError : result [ components ] = None return result
def check_running_job_count ( ) : """Check upper limit on running jobs ."""
try : job_list = current_k8s_batchv1_api_client . list_job_for_all_namespaces ( ) if len ( job_list . items ) > K8S_MAXIMUM_CONCURRENT_JOBS : return False except ApiException as e : log . error ( 'Something went wrong while getting running job list.' ) log . error ( e ) return False return T...
def _clean_dict ( row ) : """Transform empty strings values of dict ` row ` to None ."""
row_cleaned = { } for key , val in row . items ( ) : if val is None or val == '' : row_cleaned [ key ] = None else : row_cleaned [ key ] = val return row_cleaned
def rouge_l_fscore ( predictions , labels , ** unused_kwargs ) : """ROUGE scores computation between labels and predictions . This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output . Args : predictions : tensor , model predictions labels : te...
outputs = tf . to_int32 ( tf . argmax ( predictions , axis = - 1 ) ) # Convert the outputs and labels to a [ batch _ size , input _ length ] tensor . outputs = tf . squeeze ( outputs , axis = [ - 1 , - 2 ] ) labels = tf . squeeze ( labels , axis = [ - 1 , - 2 ] ) rouge_l_f_score = tf . py_func ( rouge_l_sentence_level ...
def reshape ( self , data_shapes , label_shapes = None ) : """Reshapes both modules for new input shapes . Parameters data _ shapes : list of ( str , tuple ) Typically is ` ` data _ iter . provide _ data ` ` . label _ shapes : list of ( str , tuple ) Typically is ` ` data _ iter . provide _ label ` ` ."""
super ( SVRGModule , self ) . reshape ( data_shapes , label_shapes = label_shapes ) self . _mod_aux . reshape ( data_shapes , label_shapes = label_shapes )
def requiredIfGroup ( col_name , arg , dm , df , * args ) : """Col _ name is required if other columns of the group arg are present ."""
group_name = arg groups = set ( ) columns = df . columns for col in columns : if col not in dm . index : continue group = dm . loc [ col ] [ 'group' ] groups . add ( group ) if group_name in groups : if col_name in columns : return None else : return "{} column is required if...
def M ( self ) : """Contact frequency matrix . Each cell contains how many inter - contig links between i - th and j - th contigs ."""
N = self . N tig_to_idx = self . tig_to_idx M = np . zeros ( ( N , N ) , dtype = int ) for ( at , bt ) , links in self . contacts . items ( ) : if not ( at in tig_to_idx and bt in tig_to_idx ) : continue ai = tig_to_idx [ at ] bi = tig_to_idx [ bt ] M [ ai , bi ] = M [ bi , ai ] = links return M
def getSet ( self , name ) : """Get the set with the corresponding name . Args : name : Name of the set to be found . Raises : TypeError : if the specified set does not exist ."""
return lock_and_call ( lambda : Set ( self . _impl . getSet ( name ) ) , self . _lock )
def get_entity_group_version ( key ) : """Return the version of the entity group containing key . Args : key : a key for an entity group whose _ _ entity _ group _ _ key you want . Returns : The version of the entity group containing key . This version is guaranteed to increase on every change to the enti...
eg = EntityGroup . key_for_entity_group ( key ) . get ( ) if eg : return eg . version else : return None
def get_location ( address = "" ) : """Retrieve location coordinates from an address introduced ."""
coordinates = None try : geolocator = Nominatim ( ) location = geolocator . geocode ( address ) coordinates = ( location . latitude , location . longitude ) except Exception as ex : logger . error ( 'Fail get location - {}' . format ( ex ) ) return coordinates
def to_python ( obj , in_dict , str_keys = None , date_keys = None , int_keys = None , object_map = None , bool_keys = None , dict_keys = None , ** kwargs ) : """Extends a given object for API Consumption . : param obj : Object to extend . : param in _ dict : Dict to extract data from . : param string _ keys ...
d = dict ( ) if str_keys : for in_key in str_keys : d [ in_key ] = in_dict . get ( in_key ) if date_keys : for in_key in date_keys : in_date = in_dict . get ( in_key ) try : out_date = parse_datetime ( in_date ) except TypeError as e : raise e ...
def stationary_distributions ( self , max_iter = 200 , tol = 1e-5 ) : r"""Compute the moments of the stationary distributions of : math : ` x _ t ` and : math : ` y _ t ` if possible . Computation is by iteration , starting from the initial conditions self . mu _ 0 and self . Sigma _ 0 Parameters max _ iter...
# = = Initialize iteration = = # m = self . moment_sequence ( ) mu_x , mu_y , Sigma_x , Sigma_y = next ( m ) i = 0 error = tol + 1 # = = Loop until convergence or failure = = # while error > tol : if i > max_iter : fail_message = 'Convergence failed after {} iterations' raise ValueError ( fail_messa...
def set_request ( self , method = None , sub_url = "" , data = None , params = None , proxies = None ) : """: param method : str of the method of the api _ call : param sub _ url : str of the url after the uri : param data : dict of form data to be sent with the request : param params : dict of additional dat...
self . method = method or self . method self . url = self . base_uri and ( self . base_uri + sub_url ) or sub_url self . params . update ( params or { } ) self . proxies = proxies or self . proxies if self . params : self . url += '?' + '&' . join ( [ '%s=%s' % ( k , v ) for k , v in self . params . items ( ) ] ) s...
def DeleteSnapshot ( self , names = None ) : """Removes an existing Hypervisor level snapshot . Supply one or more snapshot names to delete them concurrently . If no snapshot names are supplied will delete all existing snapshots . > > > clc . v2 . Server ( alias = ' BTDI ' , id = ' WA1BTDIKRT02 ' ) . DeleteSn...
if names is None : names = self . GetSnapshots ( ) requests_lst = [ ] for name in names : name_links = [ obj [ 'links' ] for obj in self . data [ 'details' ] [ 'snapshots' ] if obj [ 'name' ] == name ] [ 0 ] requests_lst . append ( clc . v2 . Requests ( clc . v2 . API . Call ( 'DELETE' , [ obj [ 'href' ] fo...
def read ( self , n ) : """Receive * n * bytes from the socket . Args : n ( int ) : The number of bytes to read . Returns : bytes : * n * bytes read from the socket . Raises : EOFError : If the socket was closed ."""
d = b'' while n : try : block = self . _socket . recv ( n ) except socket . error : block = None if not block : raise EOFError ( 'Socket closed' ) d += block n -= len ( block ) return d
def operations ( self ) : """All of the operations that are done by this functions ."""
return [ op for block in self . blocks for op in block . vex . operations ]
def read_scamp_head ( fname , header = None ) : """read a SCAMP . head file as a fits header FITSHDR object parameters fname : string The path to the SCAMP . head file header : FITSHDR , optional Optionally combine the header with the input one . The input can be any object convertable to a FITSHDR obje...
with open ( fname ) as fobj : lines = fobj . readlines ( ) lines = [ l . strip ( ) for l in lines if l [ 0 : 3 ] != 'END' ] # if header is None an empty FITSHDR is created hdr = FITSHDR ( header ) for l in lines : hdr . add_record ( l ) return hdr
def change_password ( ctx ) : """Change password of an existing user"""
username , passhash = _get_credentials ( ctx . obj [ 'username' ] , ctx . obj [ 'password' ] , ctx . obj [ 'db' ] ) change_user = ctx . obj [ 'db' ] . objectmodels [ 'user' ] . find_one ( { 'name' : username } ) if change_user is None : log ( 'No such user' , lvl = warn ) return change_user . passhash = passhas...
def listPrimaryDSTypes ( self , primary_ds_type = "" , dataset = "" ) : """Returns all primary dataset types if dataset or primary _ ds _ type are not passed ."""
conn = self . dbi . connection ( ) try : result = self . primdstypeList . execute ( conn , primary_ds_type , dataset ) if conn : conn . close ( ) return result finally : if conn : conn . close ( )
def setStimDuration ( self ) : """Sets the duration of the StimulusModel from values pulled from this widget"""
duration = self . ui . durSpnbx . value ( ) self . tone . setDuration ( duration )
def live_chat_banner ( context ) : """Display any available live chats as advertisements ."""
context = copy ( context ) # Find any upcoming or current live chat . The Chat date must be less than 5 # days away , or currently in progress . oldchat = LiveChat . chat_finder . get_last_live_chat ( ) if oldchat : context [ 'last_live_chat' ] = { 'title' : oldchat . title , 'chat_ends_at' : oldchat . chat_ends_at...
def nla_ok ( nla , remaining ) : """Check if the attribute header and payload can be accessed safely . https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / attr . c # L148 Verifies that the header and payload do not exceed the number of bytes left in the attribute stream . This function mus...
return remaining . value >= nla . SIZEOF and nla . SIZEOF <= nla . nla_len <= remaining . value
def draw ( self , mode = "triangle_strip" ) : """Draw collection"""
gl . glDepthMask ( gl . GL_FALSE ) Collection . draw ( self , mode ) gl . glDepthMask ( gl . GL_TRUE )
def set_fallback ( self , target ) : """Sets a fallback configuration for section . Re - exec uWSGI with the specified config when exit code is 1. : param str | unicode | Section target : File path or Section to include ."""
if isinstance ( target , Section ) : target = ':' + target . name self . _set ( 'fallback-config' , target ) return self
def _register_arguments ( cls , subparser ) : """this is a special method that gets called to construct the argparse parser . it uses the python inspect module to introspect the _ _ init _ _ method of ` klass ` , and add an argument for each parameter . it also uses numpydoc to read the class docstring of kla...
assert cls . klass is not None sig = get_init_argspec ( cls . klass ) doc = numpydoc . docscrape . ClassDoc ( cls . klass ) # mapping from the name of the argument to the helptext helptext = { d [ 0 ] : ' ' . join ( d [ 2 ] ) for d in doc [ 'Parameters' ] } # mapping from the name of the argument to the type typemap = ...
def sign_request ( private_key , method , endpoint , body_bytes , headers ) : """: type private _ key : RSA . RsaKey : type method : str : type endpoint : str : type body _ bytes : bytes : type headers : dict [ str , str ] : rtype : str"""
head_bytes = _generate_request_head_bytes ( method , endpoint , headers ) bytes_to_sign = head_bytes + body_bytes signer = PKCS1_v1_5 . new ( private_key ) digest = SHA256 . new ( ) digest . update ( bytes_to_sign ) sign = signer . sign ( digest ) return b64encode ( sign )
def asl_obctrl_encode ( self , timestamp , uElev , uThrot , uThrot2 , uAilL , uAilR , uRud , obctrl_status ) : '''Off - board controls / commands for ASLUAVs timestamp : Time since system start [ us ] ( uint64 _ t ) uElev : Elevator command [ ~ ] ( float ) uThrot : Throttle command [ ~ ] ( float ) uThrot2 :...
return MAVLink_asl_obctrl_message ( timestamp , uElev , uThrot , uThrot2 , uAilL , uAilR , uRud , obctrl_status )
def partial_schema ( schema , filtered_fields ) : """Validator for part of a schema , ignoring some fields : param schema : the Schema : param filtered _ fields : fields to filter out"""
return Schema ( { k : v for k , v in schema . schema . items ( ) if getattr ( k , 'schema' , k ) not in filtered_fields } , extra = ALLOW_EXTRA )
def splitdrive ( self ) : """p . splitdrive ( ) - > Return ( p . drive , < the rest of p > ) . Split the drive specifier from this path . If there is no drive specifier , p . drive is empty , so the return value is simply ( path ( ' ' ) , p ) . This is always the case on Unix ."""
drive , rel = os . path . splitdrive ( self ) return self . __class__ ( drive ) , rel
def make_constants ( builtin_only = False , stoplist = None , verbose = None ) : """Return a decorator for optimizing global references . Replaces global references with their currently defined values . If not defined , the dynamic ( runtime ) global lookup is left undisturbed . If builtin _ only is True , th...
if stoplist is None : stoplist = [ ] if isinstance ( builtin_only , type ( make_constants ) ) : raise ValueError ( "The bind_constants decorator must have arguments." ) return lambda func : _make_constants ( func , builtin_only , stoplist , verbose )