signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def serve_private_file ( request , path ) : """Serve private files to users with read permission ."""
logger . debug ( 'Serving {0} to {1}' . format ( path , request . user ) ) if not permissions . has_read_permission ( request , path ) : if settings . DEBUG : raise PermissionDenied else : raise Http404 ( 'File not found' ) return server . serve ( request , path = path )
def search_biosamples ( self , dataset_id , name = None , individual_id = None ) : """Returns an iterator over the Biosamples fulfilling the specified conditions . : param str dataset _ id : The dataset to search within . : param str name : Only Biosamples matching the specified name will be returned . : ...
request = protocol . SearchBiosamplesRequest ( ) request . dataset_id = dataset_id request . name = pb . string ( name ) request . individual_id = pb . string ( individual_id ) request . page_size = pb . int ( self . _page_size ) return self . _run_search_request ( request , "biosamples" , protocol . SearchBiosamplesRe...
def listar ( self , id_divisao = None , id_ambiente_logico = None ) : """Lista os ambientes filtrados conforme parâmetros informados . Se os dois parâmetros têm o valor None então retorna todos os ambientes . Se o id _ divisao é diferente de None então retorna os ambientes filtrados pelo valor de id _ d...
url = 'ambiente/' if is_valid_int_param ( id_divisao ) and not is_valid_int_param ( id_ambiente_logico ) : url = 'ambiente/divisao_dc/' + str ( id_divisao ) + '/' elif is_valid_int_param ( id_divisao ) and is_valid_int_param ( id_ambiente_logico ) : url = 'ambiente/divisao_dc/' + str ( id_divisao ) + '/ambiente...
def jsonify ( obj , pretty = False ) : """Turn a nested object into a ( compressed ) JSON string . Parameters obj : dict Any kind of dictionary structure . pretty : bool , optional Whether to format the resulting JSON in a more legible way ( default False ) ."""
if pretty : params = dict ( sort_keys = True , indent = 2 , allow_nan = False , separators = ( "," , ": " ) , ensure_ascii = False ) else : params = dict ( sort_keys = False , indent = None , allow_nan = False , separators = ( "," , ":" ) , ensure_ascii = False ) try : return json . dumps ( obj , ** params ...
def _make_sprite_image ( images , save_path ) : """Given an NDArray as a batch images , make a sprite image out of it following the rule defined in https : / / www . tensorflow . org / programmers _ guide / embedding and save it in sprite . png under the path provided by the user ."""
if isinstance ( images , np . ndarray ) : images = nd . array ( images , dtype = images . dtype , ctx = current_context ( ) ) elif not isinstance ( images , ( NDArray , np . ndarray ) ) : raise TypeError ( 'images must be an MXNet NDArray or numpy.ndarray,' ' while received type {}' . format ( str ( type ( imag...
def get_historical_base_info ( event ) : """Gets the base details from the CloudWatch Event ."""
data = { 'principalId' : get_principal ( event ) , 'userIdentity' : get_user_identity ( event ) , 'accountId' : event [ 'account' ] , 'userAgent' : event [ 'detail' ] . get ( 'userAgent' ) , 'sourceIpAddress' : event [ 'detail' ] . get ( 'sourceIPAddress' ) , 'requestParameters' : event [ 'detail' ] . get ( 'requestPar...
def addTaxonToFeature ( self , taxonid ) : """Given the taxon id , this will add the following triple : feature in _ taxon taxonid : param graph : : param taxonid : : return :"""
self . taxon = taxonid self . graph . addTriple ( self . fid , self . globaltt [ 'in taxon' ] , self . taxon ) return
def get_signature_request_file ( self , signature_request_id , path_or_file = None , file_type = None , filename = None ) : '''Download the PDF copy of the current documents Args : signature _ request _ id ( str ) : Id of the signature request path _ or _ file ( str or file ) : A writable File - like object o...
request = self . _get_request ( ) url = self . SIGNATURE_REQUEST_DOWNLOAD_PDF_URL + signature_request_id if file_type : url += '?file_type=%s' % file_type return request . get_file ( url , path_or_file or filename )
def update ( self , key = values . unset , value = values . unset ) : """Update the VariableInstance : param unicode key : The key : param unicode value : The value : returns : Updated VariableInstance : rtype : twilio . rest . serverless . v1 . service . environment . variable . VariableInstance"""
return self . _proxy . update ( key = key , value = value , )
def register_rate_producer ( self , rate_name : str , source : Callable [ ... , pd . DataFrame ] = None ) -> Pipeline : """Marks a ` ` Callable ` ` as the producer of a named rate . This is a convenience wrapper around ` ` register _ value _ producer ` ` that makes sure rate data is appropriately scaled to the ...
return self . _value_manager . register_rate_producer ( rate_name , source )
def retrieve_download_path ( self ) : """Retrieves the download path ( looks first into config _ filename _ global then into the [ DEFAULT ] , then the [ feed ] , section of config _ filename _ user . The latest takes preeminence )"""
section = self . name if self . config . has_section ( self . name ) else self . config . default_section download_path = self . config . get ( section , 'Download directory' , fallback = '~/Podcasts' ) subdirectory = self . config . get ( section , 'Create subdirectories' , fallback = 'no' ) return [ os . path . expan...
def debug_derivative ( self , guess ) : """returns ( explicit , auto )"""
from . lmmin import check_derivative return check_derivative ( self . component . npar , self . data . size , self . lm_model , self . lm_deriv , guess )
def get_definition_with_regex ( source , token , start_line = - 1 ) : """Find the definition of an object within a source closest to a given line"""
if not token : return None if DEBUG_EDITOR : t0 = time . time ( ) patterns = [ # python / cython keyword definitions r'^c?import.*\W{0}{1}' , r'from.*\W{0}\W.*c?import ' , r'from .* c?import.*\W{0}{1}' , r'class\s*{0}{1}' , r'c?p?def[^=]*\W{0}{1}' , r'cdef.*\[.*\].*\W{0}{1}' , # enaml keyword definitions r'enam...
def verify_time ( self , now ) : '''Verify the time'''
return now . time ( ) >= self . start_time and now . time ( ) <= self . end_time
def _comprise ( dict1 , dict2 ) : '''dict1 = { ' a ' : 1 , ' b ' : 2 , ' c ' : 3 , ' d ' : 4} dict2 = { ' b ' : 2 , ' c ' : 3} _ comprise ( dict1 , dict2)'''
len_1 = dict1 . __len__ ( ) len_2 = dict2 . __len__ ( ) if ( len_2 > len_1 ) : return ( False ) else : for k2 in dict2 : v2 = dict2 [ k2 ] if ( k2 in dict1 ) : v1 = dict1 [ k2 ] if ( v1 == v2 ) : return ( True ) else : return ( ...
def summary ( self , name , description , labels = None , ** kwargs ) : """Use a Summary to track the execution time and invocation count of the method . : param name : the name of the metric : param description : the description of the metric : param labels : a dictionary of ` { labelname : callable _ or _...
return self . _track ( Summary , lambda metric , time : metric . observe ( time ) , kwargs , name , description , labels , registry = self . registry )
def merge_models ( self , store_in_memory = False , outdir = None , outname = None , force_rerun = False ) : """Merge all existing models into a Structure ' s first _ model attribute . This directly modifies the Biopython Structure object . Chains IDs will start from A and increment for each new chain ( which i...
if store_in_memory : if self . structure : parsed = copy ( self . structure ) else : parsed = self . parse_structure ( ) self . structure = merge_all_models_into_first_model ( parsed ) else : new_structure_path = write_merged_bioassembly ( inpath = self . structure_path , outdir = outdir...
def _split_license ( license ) : '''Returns all individual licenses in the input'''
return ( x . strip ( ) for x in ( l for l in _regex . split ( license ) if l ) )
def getCurrentStrDatetime ( ) : """Generating the current Datetime with a given format Returns : string : The string of a date ."""
# Generating current time i = datetime . datetime . now ( ) strTime = "%s-%s-%s_%sh%sm" % ( i . year , i . month , i . day , i . hour , i . minute ) return strTime
def prune_clade ( self , node_id ) : """Prune ` node _ id ` and the edges and nodes that are tipward of it . Caller must delete the edge to node _ id ."""
to_del_nodes = [ node_id ] while bool ( to_del_nodes ) : node_id = to_del_nodes . pop ( 0 ) self . _flag_node_as_del_and_del_in_by_target ( node_id ) ebsd = self . _edge_by_source . get ( node_id ) if ebsd is not None : child_edges = list ( ebsd . values ( ) ) to_del_nodes . extend ( [ i...
def om ( self , breath , conscious = True ) : """Print the string passed via argument ' breath ' , and store the string for saving in prosodic . being . om . [ accessed interactively using the ' / save ' command ] ( The string just prior to this one will remain available at prosodic . being . omm ) ."""
# import prosodic if ( not conscious ) and bool ( being . config [ 'print_to_screen' ] ) : if not type ( breath ) in [ str , unicode ] : breath = unicode ( breath ) being . om += breath + "\n" print self . u2s ( breath ) return breath
def build_parser ( parser ) : """Generate a subparser"""
parser . add_argument ( 'sequence_file' , type = FileType ( 'r' ) , help = """Input fastq file. A fasta-format file may also be provided if --input-qual is also specified.""" ) parser . add_argument ( '--input-qual' , type = FileType ( 'r' ) , help = """The quality scores associated with the input file. Onl...
def _prepare ( self , data , groupname ) : """Clear the group if existing and initialize empty datasets ."""
if groupname in self . h5file : del self . h5file [ groupname ] group = self . h5file . create_group ( groupname ) group . attrs [ 'version' ] = self . version data . init_group ( group , self . chunk_size , self . compression , self . compression_opts ) return group
def _send_err ( self , msg , errName , errMsg ) : """Helper method for sending error messages"""
r = message . ErrorMessage ( errName , msg . serial , body = [ errMsg ] , signature = 's' , destination = msg . sender , ) self . conn . sendMessage ( r )
def generate_values ( self , * args , ** kwargs ) : """Instantiate a random variable and apply annual growth factors . : return :"""
values = super ( ) . generate_values ( * args , ** kwargs , size = ( len ( self . times ) * self . size , ) ) alpha = self . cagr # @ todo - fill to cover the entire time : define rules for filling first ref_date = self . ref_date if self . ref_date else self . times [ 0 ] . to_pydatetime ( ) # assert ref _ date > = se...
def t_escaped_FORM_FEED_CHAR ( self , t ) : r'\ x66'
t . lexer . pop_state ( ) t . value = unichr ( 0x000c ) return t
def sa_indices ( num_states , num_actions ) : """Generate ` s _ indices ` and ` a _ indices ` for ` DiscreteDP ` , for the case where all the actions are feasible at every state . Parameters num _ states : scalar ( int ) Number of states . num _ actions : scalar ( int ) Number of actions . Returns s...
L = num_states * num_actions dtype = np . int_ s_indices = np . empty ( L , dtype = dtype ) a_indices = np . empty ( L , dtype = dtype ) i = 0 for s in range ( num_states ) : for a in range ( num_actions ) : s_indices [ i ] = s a_indices [ i ] = a i += 1 return s_indices , a_indices
def read_excel ( filename , dataset_class = dataset . pandas_dataset . PandasDataset , expectations_config = None , autoinspect_func = None , * args , ** kwargs ) : """Read a file using Pandas read _ excel and return a great _ expectations dataset . Args : filename ( string ) : path to file to read dataset _ ...
df = pd . read_excel ( filename , * args , ** kwargs ) if isinstance ( df , dict ) : for key in df : df [ key ] = _convert_to_dataset_class ( df [ key ] , dataset_class , expectations_config , autoinspect_func ) else : df = _convert_to_dataset_class ( df , dataset_class , expectations_config , autoinspe...
def _get_revision ( self ) : """Validate and return the revision to use for current command"""
assert self . _revisions , "no migration revision exist" revision = self . _rev or self . _revisions [ - 1 ] # revision count must be less or equal since revisions are ordered assert revision in self . _revisions , "invalid revision specified" return revision
def newNsProp ( self , node , name , value ) : """Create a new property tagged with a namespace and carried by a node ."""
if node is None : node__o = None else : node__o = node . _o ret = libxml2mod . xmlNewNsProp ( node__o , self . _o , name , value ) if ret is None : raise treeError ( 'xmlNewNsProp() failed' ) __tmp = xmlAttr ( _obj = ret ) return __tmp
def unparse ( self , pieces , defaults = None ) : """Join the parts of a URI back together to form a valid URI . pieces is a tuble of URI pieces . The scheme must be in pieces [ 0 ] so that the rest of the pieces can be interpreted ."""
return self . parser_for ( pieces [ 0 ] ) ( defaults ) . unparse ( pieces )
def psetex ( self , key , milliseconds , value ) : """: meth : ` ~ tredis . RedisClient . psetex ` works exactly like : meth : ` ~ tredis . RedisClient . psetex ` with the sole difference that the expire time is specified in milliseconds instead of seconds . . . versionadded : : 0.2.0 . . note : : * * Time ...
return self . _execute ( [ b'PSETEX' , key , ascii ( milliseconds ) , value ] , b'OK' )
def sliceit ( iterable , lower = 0 , upper = None ) : """Apply a slice on input iterable . : param iterable : object which provides the method _ _ getitem _ _ or _ _ iter _ _ . : param int lower : lower bound from where start to get items . : param int upper : upper bound from where finish to get items . : ...
if upper is None : upper = len ( iterable ) try : result = iterable [ lower : upper ] except TypeError : # if iterable does not implement the slice method result = [ ] if lower < 0 : # ensure lower is positive lower += len ( iterable ) if upper < 0 : # ensure upper is positive upper ...
def interact ( self , banner = None ) : """Closely emulate the interactive Python console . The optional banner argument specify the banner to print before the first interaction ; by default it prints a banner similar to the one printed by the real Python interpreter , followed by the current class name in ...
try : sys . ps1 # @ UndefinedVariable except AttributeError : sys . ps1 = ">>> " try : sys . ps2 # @ UndefinedVariable except AttributeError : sys . ps2 = "... " cprt = 'Type "help", "copyright", "credits" or "license" for more information.' if banner is None : self . write ( "Python %s on %...
def list_common_lookups ( kwargs = None , call = None ) : '''List common lookups for a particular type of item . . versionadded : : 2015.8.0'''
if kwargs is None : kwargs = { } args = { } if 'lookup' in kwargs : args [ 'lookup' ] = kwargs [ 'lookup' ] response = _query ( 'common' , 'lookup/list' , args = args ) return response
def unique ( lst ) : """Return unique elements : class : ` pandas . unique ` and : class : ` numpy . unique ` cast mixed type lists to the same type . They are faster , but some times we want to maintain the type . Parameters lst : list - like List of items Returns out : list Unique items in the o...
seen = set ( ) def make_seen ( x ) : seen . add ( x ) return x return [ make_seen ( x ) for x in lst if x not in seen ]
def _start_execution ( self , args , stdin , stdout , stderr , env , cwd , temp_dir , cgroups , parent_setup_fn , child_setup_fn , parent_cleanup_fn ) : """Actually start the tool and the measurements . @ param parent _ setup _ fn a function without parameters that is called in the parent process immediately be...
def pre_subprocess ( ) : # Do some other setup the caller wants . child_setup_fn ( ) # put us into the cgroup ( s ) pid = os . getpid ( ) cgroups . add_task ( pid ) # Set HOME and TMPDIR to fresh directories . tmp_dir = os . path . join ( temp_dir , "tmp" ) home_dir = os . path . join ( temp_dir , "home...
def _parsed_cmd ( self ) : """We need to take into account two cases : - [ ' python code . py foo bar ' ] : Used mainly with dvc as a library - [ ' echo ' , ' foo bar ' ] : List of arguments received from the CLI The second case would need quoting , as it was passed through : dvc run echo " foo bar " """
if len ( self . args . command ) < 2 : return " " . join ( self . args . command ) return " " . join ( self . _quote_argument ( arg ) for arg in self . args . command )
def delete_keyring ( service ) : """Delete an existing Ceph keyring ."""
keyring = _keyring_path ( service ) if not os . path . exists ( keyring ) : log ( 'Keyring does not exist at %s' % keyring , level = WARNING ) return os . remove ( keyring ) log ( 'Deleted ring at %s.' % keyring , level = INFO )
def load_pid ( pidfile ) : """read pid from pidfile ."""
if pidfile and os . path . isfile ( pidfile ) : with open ( pidfile , "r" , encoding = "utf-8" ) as fobj : return int ( fobj . readline ( ) . strip ( ) ) return 0
def CopyNoFail ( src , root = None ) : """Just copy fName into the current working directory , if it exists . No action is executed , if fName does not exist . No Hash is checked . Args : src : The filename we want to copy to ' . ' . root : The optional source dir we should pull fName from . Defaults to b...
if root is None : root = str ( CFG [ "tmp_dir" ] ) src_path = local . path ( root ) / src if src_path . exists ( ) : Copy ( src_path , '.' ) return True return False
def pkginfo_unicode ( pkg_info , field ) : """Hack to coax Unicode out of an email Message ( ) - Python 3.3 +"""
text = pkg_info [ field ] field = field . lower ( ) if not isinstance ( text , str ) : if not hasattr ( pkg_info , 'raw_items' ) : # Python 3.2 return str ( text ) for item in pkg_info . raw_items ( ) : if item [ 0 ] . lower ( ) == field : text = item [ 1 ] . encode ( 'ascii' , 'surr...
def run_with_standalone_parser ( self ) : """Will run the operation as standalone with a new ArgumentParser"""
parser = argparse . ArgumentParser ( description = self . description ( ) ) self . configure_parser ( parser ) self . run ( parser . parse_args ( ) )
def update_search_letters ( self , text ) : """Update search letters with text input in search box ."""
self . letters = text names = [ shortcut . name for shortcut in self . shortcuts ] results = get_search_scores ( text , names , template = '<b>{0}</b>' ) self . normal_text , self . rich_text , self . scores = zip ( * results ) self . reset ( )
def get_default_keystone_session ( self , keystone_sentry , openstack_release = None , api_version = 2 ) : """Return a keystone session object and client object assuming standard default settings Example call in amulet tests : self . keystone _ session , self . keystone = u . get _ default _ keystone _ sessio...
self . log . debug ( 'Authenticating keystone admin...' ) # 11 = > xenial _ queens if api_version == 3 or ( openstack_release and openstack_release >= 11 ) : client_class = keystone_client_v3 . Client api_version = 3 else : client_class = keystone_client . Client keystone_ip = keystone_sentry . info [ 'publ...
def silhouette_samples ( X , labels , metric = 'euclidean' , ** kwds ) : """Compute the Silhouette Coefficient for each sample . The Silhouette Coefficient is a measure of how well samples are clustered with samples that are similar to themselves . Clustering models with a high Silhouette Coefficient are said...
X , labels = check_X_y ( X , labels , accept_sparse = [ 'csc' , 'csr' ] ) le = LabelEncoder ( ) labels = le . fit_transform ( labels ) check_number_of_labels ( len ( le . classes_ ) , X . shape [ 0 ] ) distances = pairwise_distances ( X , metric = metric , ** kwds ) unique_labels = le . classes_ n_samples_per_label = n...
def call ( self , callsite_addr , addr , retn_target = None , stack_pointer = None ) : """Push a stack frame into the call stack . This method is called when calling a function in CFG recovery . : param int callsite _ addr : Address of the call site : param int addr : Address of the call target : param int or...
frame = CallStack ( call_site_addr = callsite_addr , func_addr = addr , ret_addr = retn_target , stack_ptr = stack_pointer ) return self . push ( frame )
def _read_encrypt_auth ( self ) : """Read Authentication field when Cryptographic Authentication is employed . Structure of Cryptographic Authentication [ RFC 2328 ] : 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 | 0 | Key ID | Auth Data Len | | Cryptographic sequence number | ...
_resv = self . _read_fileng ( 2 ) _keys = self . _read_unpack ( 1 ) _alen = self . _read_unpack ( 1 ) _seqn = self . _read_unpack ( 4 ) auth = dict ( key_id = _keys , len = _alen , seq = _seqn , ) return auth
def strip_context_items ( self , a_string ) : """Strip Juniper - specific output . Juniper will also put a configuration context : [ edit ] and various chassis contexts : { master : 0 } , { backup : 1} This method removes those lines ."""
strings_to_strip = [ r"\[edit.*\]" , r"\{master:.*\}" , r"\{backup:.*\}" , r"\{line.*\}" , r"\{primary.*\}" , r"\{secondary.*\}" , ] response_list = a_string . split ( self . RESPONSE_RETURN ) last_line = response_list [ - 1 ] for pattern in strings_to_strip : if re . search ( pattern , last_line ) : return...
def wait_for_success ( self , interval = 1 ) : """Wait for instance to complete , and check if the instance is successful . : param interval : time interval to check : return : None : raise : : class : ` odps . errors . ODPSError ` if the instance failed"""
self . wait_for_completion ( interval = interval ) if not self . is_successful ( retry = True ) : for task_name , task in six . iteritems ( self . get_task_statuses ( ) ) : exc = None if task . status == Instance . Task . TaskStatus . FAILED : exc = errors . parse_instance_error ( self ....
def status ( self , repository = None , snapshot = None , params = None ) : """Return information about all currently running snapshots . By specifying a repository name , it ' s possible to limit the results to a particular repository . ` < http : / / www . elastic . co / guide / en / elasticsearch / referen...
return self . transport . perform_request ( 'GET' , _make_path ( '_snapshot' , repository , snapshot , '_status' ) , params = params )
async def load_uvarint ( reader ) : """Monero portable _ binary _ archive boost integer serialization : param reader : : return :"""
buffer = _UVARINT_BUFFER await reader . areadinto ( buffer ) size = buffer [ 0 ] if size == 0 : return 0 negative = size < 0 size = - size if negative else size result = 0 shift = 0 if size > 8 : raise ValueError ( 'Varint size too big: %s' % size ) # TODO : endianity , rev bytes if needed for _ in range ( size...
def get_context ( template , line , num_lines = 5 , marker = None ) : '''Returns debugging context around a line in a given string Returns : : string'''
template_lines = template . splitlines ( ) num_template_lines = len ( template_lines ) # In test mode , a single line template would return a crazy line number like , # 357 . Do this sanity check and if the given line is obviously wrong , just # return the entire template if line > num_template_lines : return templ...
def _luminance ( self , rgb ) : """Determine the liminanace of an RGB colour"""
a = [ ] for v in rgb : v = v / float ( 255 ) if v < 0.03928 : result = v / 12.92 else : result = math . pow ( ( ( v + 0.055 ) / 1.055 ) , 2.4 ) a . append ( result ) return a [ 0 ] * 0.2126 + a [ 1 ] * 0.7152 + a [ 2 ] * 0.0722
def _run_check ( self , check_method , ds , max_level ) : """Runs a check and appends a result to the values list . @ param bound method check _ method : a given check method @ param netCDF4 dataset ds @ param int max _ level : check level @ return list : list of Result objects"""
val = check_method ( ds ) if isinstance ( val , list ) : check_val = [ ] for v in val : res = fix_return_value ( v , check_method . __func__ . __name__ , check_method , check_method . __self__ ) if max_level is None or res . weight > max_level : check_val . append ( res ) return ...
def ip ( ip_addr , return_tuple = True ) : """Function to check if a address is good Args : ip _ addr : IP address in the following format 192.168.1.1 return _ tuple : Set to True it returns a IP , set to False returns True or False Returns : see return _ tuple for return options"""
regex_ip = __re . compile ( "^((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))$" ) if return_tuple : while not regex_ip . match ( ip_addr ) : ...
def list_objects ( self , query = None , limit = - 1 , offset = - 1 ) : """List of all objects in the database . Optinal parameter limit and offset for pagination . A dictionary of key , value - pairs can be given as addictional query condition for document properties . Parameters query : Dictionary Filte...
result = [ ] # Build the document query doc = { 'active' : True } if not query is None : for key in query : doc [ key ] = query [ key ] # Iterate over all objects in the MongoDB collection and add them to # the result coll = self . collection . find ( doc ) . sort ( [ ( 'timestamp' , pymongo . DESCENDING ) ...
def set_speech_text ( self , text ) : """Set response output speech as plain text type . Args : text : str . Response speech used when type is ' PlainText ' . Cannot exceed 8,000 characters ."""
self . response . outputSpeech . type = 'PlainText' self . response . outputSpeech . text = text
def cancel ( self , subscription_id , data = { } , ** kwargs ) : """Cancel subscription given by subscription _ id Args : subscription _ id : Id for which subscription has to be cancelled Returns : Subscription Dict for given subscription id"""
url = "{}/{}/cancel" . format ( self . base_url , subscription_id ) return self . post_url ( url , data , ** kwargs )
def get_device_statistics ( self , begin_date , end_date , device_id = None , uuid = None , major = None , minor = None ) : """以设备为维度的数据统计接口 http : / / mp . weixin . qq . com / wiki / 0/8a24bcacad40fe7ee98d1573cb8a6764 . html : param begin _ date : 起始时间 , 最长时间跨度为30天 : param end _ date : 结束时间 , 最长时间跨度为30天 : ...
data = { 'device_identifier' : { 'device_id' : device_id , 'uuid' : uuid , 'major' : major , 'minor' : minor } , 'begin_date' : self . _to_timestamp ( begin_date ) , 'end_date' : self . _to_timestamp ( end_date ) } res = self . _post ( 'shakearound/statistics/device' , data = data , result_processor = lambda x : x [ 'd...
def get_config_file ( ) : # type : ( ) - > AnyStr """Get model configuration file name from argv"""
parser = argparse . ArgumentParser ( description = "Read configuration file." ) parser . add_argument ( '-ini' , help = "Full path of configuration file" ) args = parser . parse_args ( ) ini_file = args . ini if not FileClass . is_file_exists ( ini_file ) : print ( "Usage: -ini <full path to the configuration file....
def place_docker ( self , docker , area = 'top' ) : """IN DEVELOPMENT Places a DockWindow instance at the specified area ( ' top ' , ' bottom ' , ' left ' , ' right ' , or None )"""
# map of options m = dict ( top = _g . QtCore . Qt . TopDockWidgetArea , bottom = _g . QtCore . Qt . BottomDockWidgetArea , left = _g . QtCore . Qt . LeftDockWidgetArea , right = _g . QtCore . Qt . RightDockWidgetArea ) # set the parent docker . set_parent ( self ) # events docker . _window . resizeEvent = self . _even...
def get_portchannel_info_by_intf_output_lacp_actor_port ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_portchannel_info_by_intf = ET . Element ( "get_portchannel_info_by_intf" ) config = get_portchannel_info_by_intf output = ET . SubElement ( get_portchannel_info_by_intf , "output" ) lacp = ET . SubElement ( output , "lacp" ) actor_port = ET . SubElement ( lacp , "actor-port" ) act...
def full_name_natural_split ( full_name ) : """This function splits a full name into a natural first name , last name and middle initials ."""
parts = full_name . strip ( ) . split ( ' ' ) first_name = "" if parts : first_name = parts . pop ( 0 ) if first_name . lower ( ) == "el" and parts : first_name += " " + parts . pop ( 0 ) last_name = "" if parts : last_name = parts . pop ( ) if ( last_name . lower ( ) == 'i' or last_name . lower ( ) == 'ii'...
def available_composite_ids ( self , available_datasets = None ) : """Get names of compositors that can be generated from the available datasets . Returns : generator of available compositor ' s names"""
if available_datasets is None : available_datasets = self . available_dataset_ids ( composites = False ) else : if not all ( isinstance ( ds_id , DatasetID ) for ds_id in available_datasets ) : raise ValueError ( "'available_datasets' must all be DatasetID objects" ) all_comps = self . all_composite_ids...
def ansi_code ( name ) : """Return ansi color or style codes or ' ' if colorama is not available ."""
try : obj = colorama for part in name . split ( "." ) : obj = getattr ( obj , part ) return obj except AttributeError : return ""
def parse_uinput_mapping ( name , mapping ) : """Parses a dict of mapping options ."""
axes , buttons , mouse , mouse_options = { } , { } , { } , { } description = "ds4drv custom mapping ({0})" . format ( name ) for key , attr in mapping . items ( ) : key = key . upper ( ) if key . startswith ( "BTN_" ) or key . startswith ( "KEY_" ) : buttons [ key ] = attr elif key . startswith ( "A...
def load_from_path ( local_path = None , parser = None , all_load = False ) : """Loads the data from a local path into a GMQLDataset . The loading of the files is " lazy " , which means that the files are loaded only when the user does a materialization ( see : func : ` ~ gmql . dataset . GMQLDataset . GMQLData...
from . . import GDataframe from . . import GMQLDataset pmg = get_python_manager ( ) local_path = preprocess_path ( local_path ) if all_load : # load directly the metadata for exploration meta = MetaLoaderFile . load_meta_from_path ( local_path ) if isinstance ( parser , RegionParser ) : # region data re...
def plot_eps_data_hist ( self , dfs ) : """Plot histograms of data residuals and data error weighting TODO : * add percentage of data below / above the RMS value"""
# check if this is a DC inversion if 'datum' in dfs [ 0 ] : dc_inv = True else : dc_inv = False nr_y = len ( dfs ) size_y = 5 / 2.54 * nr_y if dc_inv : nr_x = 1 else : nr_x = 3 size_x = 15 / 2.54 fig , axes = plt . subplots ( nr_y , nr_x , figsize = ( size_x , size_y ) ) axes = np . atleast_2d ( axes ) ...
def get_file_port ( self ) : """Returns ports list can be used by File File ports includes ethernet ports and link aggregation ports ."""
eths = self . get_ethernet_port ( bond = False ) las = self . get_link_aggregation ( ) return eths + las
def load ( self , data ) : """Function load Store the object data"""
self . clear ( ) self . update ( data ) self . enhance ( )
def mul ( self , o ) : """Binary operation : multiplication : param o : The other operand : return : self * o"""
if self . is_integer and o . is_integer : # Two integers ! a , b = self . lower_bound , o . lower_bound ret = StridedInterval ( bits = self . bits , stride = 0 , lower_bound = a * b , upper_bound = a * b ) if a * b > ( 2 ** self . bits - 1 ) : logger . warning ( 'Overflow in multiplication detected....
def format_hyperlink ( val , hlx , hxl , xhl ) : """Formats an html hyperlink into other forms . @ hlx , hxl , xhl : values returned by set _ output _ format"""
if '<a href="' in str ( val ) and hlx != '<a href="' : val = val . replace ( '<a href="' , hlx ) . replace ( '">' , hxl , 1 ) . replace ( '</a>' , xhl ) return val
def __read_and_render_yaml_file ( source , template , saltenv ) : '''Read a yaml file and , if needed , renders that using the specifieds templating . Returns the python objects defined inside of the file .'''
sfn = __salt__ [ 'cp.cache_file' ] ( source , saltenv ) if not sfn : raise CommandExecutionError ( 'Source file \'{0}\' not found' . format ( source ) ) with salt . utils . files . fopen ( sfn , 'r' ) as src : contents = src . read ( ) if template : if template in salt . utils . templates . TEMPLATE...
def convert_single ( ID , from_type , to_type ) : '''Convenience function wrapper for convert . Takes a single ID and converts it from from _ type to to _ type . The return value is the ID in the scheme of to _ type .'''
if from_type not in converter_types : raise PubMedConverterTypeException ( from_type ) if to_type not in converter_types : raise PubMedConverterTypeException ( to_type ) results = convert ( [ ID ] , from_type ) if ID in results : return results [ ID ] . get ( to_type ) else : return results [ ID . upper...
def get_multi_dataset ( datasets , pmf = None ) : """Returns a Dataset that samples records from one or more Datasets . Args : datasets : A list of one or more Dataset objects to sample from . pmf : A tensor of shape [ len ( datasets ) ] , the probabilities to sample each dataset with . This tensor is often...
pmf = tf . fill ( [ len ( datasets ) ] , 1.0 / len ( datasets ) ) if pmf is None else pmf samplers = [ d . repeat ( ) . make_one_shot_iterator ( ) . get_next for d in datasets ] sample = lambda _ : categorical_case ( pmf , samplers ) return tf . data . Dataset . from_tensors ( [ ] ) . repeat ( ) . map ( sample )
def label_faces ( network , tol = 0.0 , label = 'surface' ) : r"""Finds pores on the surface of the network and labels them according to whether they are on the * top * , * bottom * , etc . This function assumes the network is cubic in shape ( i . e . with six flat sides ) Parameters network : OpenPNM Netwo...
if label not in network . labels ( ) : find_surface_pores ( network , label = label ) Psurf = network [ 'pore.' + label ] crds = network [ 'pore.coords' ] xmin , xmax = sp . amin ( crds [ : , 0 ] ) , sp . amax ( crds [ : , 0 ] ) xspan = xmax - xmin ymin , ymax = sp . amin ( crds [ : , 1 ] ) , sp . amax ( crds [ : ,...
def delete_instance ( model , instance_id , _commit = True ) : """Delete instance . : param model : a string , model name in rio . models . : param instance _ id : integer , instance id . : param _ commit : control whether commit data to database or not . Default True ."""
try : model = get_model ( model ) except ImportError : return instance = model . query . get ( instance_id ) if not instance : return db . session . delete ( instance ) try : if _commit : db . session . commit ( ) else : db . session . flush ( ) except Exception as exception : db...
def get_basis ( name , elements = None , version = None , fmt = None , uncontract_general = False , uncontract_spdf = False , uncontract_segmented = False , make_general = False , optimize_general = False , data_dir = None , header = True ) : '''Obtain a basis set This is the main function for getting basis set i...
data_dir = fix_data_dir ( data_dir ) bs_data = _get_basis_metadata ( name , data_dir ) # If version is not specified , use the latest if version is None : version = bs_data [ 'latest_version' ] else : version = str ( version ) # Version may be an int if not version in bs_data [ 'versions' ] : raise KeyError...
def recoverURL ( self , url ) : """Public method to recover a resource . Args : url : The URL to be collected . Returns : Returns a resource that has to be read , for instance , with html = self . br . read ( )"""
# Configuring user agents . . . self . setUserAgent ( ) # Configuring proxies if "https://" in url : self . setProxy ( protocol = "https" ) else : self . setProxy ( protocol = "http" ) # Giving special treatment for . onion platforms if ".onion" in url : try : # TODO : configuring manually the tor bundle ...
def compare_and_set ( self , expected , updated ) : """Atomically sets the value to the given updated value only if the current value = = the expected value . : param expected : ( object ) , the expected value . : param updated : ( object ) , the new value . : return : ( bool ) , ` ` true ` ` if successful ; ...
return self . _encode_invoke ( atomic_reference_compare_and_set_codec , expected = self . _to_data ( expected ) , updated = self . _to_data ( updated ) )
def grain_funcs ( opts , proxy = None ) : '''Returns the grain functions . . code - block : : python import salt . config import salt . loader _ _ opts _ _ = salt . config . minion _ config ( ' / etc / salt / minion ' ) grainfuncs = salt . loader . grain _ funcs ( _ _ opts _ _ )'''
ret = LazyLoader ( _module_dirs ( opts , 'grains' , 'grain' , ext_type_dirs = 'grains_dirs' , ) , opts , tag = 'grains' , ) ret . pack [ '__utils__' ] = utils ( opts , proxy = proxy ) return ret
def graphql_requests ( self , * queries ) : """: param queries : Zero or more GraphQL objects : type queries : GraphQL : raises : FBchatException if request failed : return : A tuple containing json graphql queries : rtype : tuple"""
data = { "method" : "GET" , "response_format" : "json" , "queries" : graphql_queries_to_json ( * queries ) , } return tuple ( self . _post ( self . req_url . GRAPHQL , data , fix_request = True , as_graphql = True ) )
def call ( self , name , * args , ** kwargs ) : """Asynchronously call a method of the external environment . Args : name : Name of the method to call . * args : Positional arguments to forward to the method . * * kwargs : Keyword arguments to forward to the method . Returns : Promise object that blocks...
payload = name , args , kwargs self . _conn . send ( ( self . _CALL , payload ) ) return self . _receive
def ParsePageVisitedRow ( self , parser_mediator , query , row , cache = None , database = None , ** unused_kwargs ) : """Parses a page visited row . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . query ( str ) : query t...
query_hash = hash ( query ) from_visit = self . _GetRowValue ( query_hash , row , 'from_visit' ) hidden = self . _GetRowValue ( query_hash , row , 'hidden' ) rev_host = self . _GetRowValue ( query_hash , row , 'rev_host' ) typed = self . _GetRowValue ( query_hash , row , 'typed' ) # TODO : make extra conditional format...
def register_images ( im0 , im1 , * , rmMean = True , correctScale = True ) : """Finds the rotation , scaling and translation of im1 relative to im0 Parameters im0 : First image im1 : Second image rmMean : Set to true to remove the mean ( Default ) Returns angle : The angle difference scale : The scal...
# sanitize input im0 = np . asarray ( im0 , dtype = np . float32 ) im1 = np . asarray ( im1 , dtype = np . float32 ) if rmMean : # remove mean im0 = im0 - im0 . mean ( ) im1 = im1 - im1 . mean ( ) # Compute DFT ( THe images are resized to the same size ) f0 , f1 = dft_optsize_same ( im0 , im1 ) # Get rotation a...
def _generate_standard_methods ( cls ) : """Generate standard setters , getters and checkers ."""
for state in cls . context . states_enum : getter_name = 'is_{name}' . format ( name = state . value ) cls . context . new_methods [ getter_name ] = utils . generate_getter ( state ) setter_name = 'set_{name}' . format ( name = state . value ) cls . context . new_methods [ setter_name ] = utils . genera...
def resize ( self , size , interp = 'nearest' ) : """Resize the image . Parameters size : int , float , or tuple * int - Percentage of current size . * float - Fraction of current size . * tuple - Size of the output image . interp : : obj : ` str ` , optional Interpolation to use for re - sizing ( ' n...
resized_data_0 = sm . imresize ( self . _data [ : , : , 0 ] , size , interp = interp , mode = 'F' ) resized_data_1 = sm . imresize ( self . _data [ : , : , 1 ] , size , interp = interp , mode = 'F' ) resized_data_2 = sm . imresize ( self . _data [ : , : , 2 ] , size , interp = interp , mode = 'F' ) resized_data = np . ...
def insert_characters ( self , count = None ) : """Insert the indicated # of blank characters at the cursor position . The cursor does not move and remains at the beginning of the inserted blank characters . Data on the line is shifted forward . : param int count : number of characters to insert ."""
self . dirty . add ( self . cursor . y ) count = count or 1 line = self . buffer [ self . cursor . y ] for x in range ( self . columns , self . cursor . x - 1 , - 1 ) : if x + count <= self . columns : line [ x + count ] = line [ x ] line . pop ( x , None )
def import_directory ( module_basename : str , directory : str , sort_key = None ) -> None : '''Load all python modules in directory and directory ' s children . Parameters : ` ` module _ basename ` ` : module name prefix for loaded modules : ` ` directory ` ` : directory to load python modules from : ` ` s...
logger . info ( 'loading submodules of %s' , module_basename ) logger . info ( 'loading modules from %s' , directory ) filenames = itertools . chain ( * [ [ os . path . join ( _ [ 0 ] , filename ) for filename in _ [ 2 ] ] for _ in os . walk ( directory ) if len ( _ [ 2 ] ) ] ) modulenames = _filenames_to_modulenames (...
def sflow_enable ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) sflow = ET . SubElement ( config , "sflow" , xmlns = "urn:brocade.com:mgmt:brocade-sflow" ) enable = ET . SubElement ( sflow , "enable" ) callback = kwargs . pop ( 'callback' , self . _callback ) return callback ( config )
def _get_longest_hl ( self , highlights ) : """Given a list of highlighted text , returns the longest highlight For example : " < em > Muscle < / em > < em > atrophy < / em > , generalized " , " Generalized < em > muscle < / em > degeneration " , " Diffuse skeletal < em > " > muscle < / em > wasting " a...
len_dict = OrderedDict ( ) for hl in highlights : # dummy tags to make it valid xml dummy_xml = "<p>" + hl + "</p>" try : element_tree = ET . fromstring ( dummy_xml ) hl_length = 0 for emph in element_tree . findall ( 'em' ) : hl_length += len ( emph . text ) len_dict...
def distinguish ( self , id_ , how = True ) : """Login required . Sends POST to distinguish a submission or comment . Returns : class : ` things . Link ` or : class : ` things . Comment ` , or raises : class : ` exceptions . UnexpectedResponse ` otherwise . URL : ` ` http : / / www . reddit . com / api / distingu...
if how == True : h = 'yes' elif how == False : h = 'no' elif how == 'admin' : h = 'admin' else : raise ValueError ( "how must be either True, False, or 'admin'" ) data = dict ( id = id_ ) j = self . post ( 'api' , 'distinguish' , h , data = data ) try : return self . _thingify ( j [ 'json' ] [ 'data...
def make_fileitem_filepath ( filepath , condition = 'contains' , negate = False , preserve_case = False ) : """Create a node for FileItem / FilePath : return : A IndicatorItem represented as an Element node"""
document = 'FileItem' search = 'FileItem/FilePath' content_type = 'string' content = filepath ii_node = ioc_api . make_indicatoritem_node ( condition , document , search , content_type , content , negate = negate , preserve_case = preserve_case ) return ii_node
def sky_centroid ( self ) : """The sky coordinates of the centroid within the source segment , returned as a ` ~ astropy . coordinates . SkyCoord ` object . The output coordinate frame is the same as the input WCS ."""
if self . _wcs is not None : return pixel_to_skycoord ( self . xcentroid . value , self . ycentroid . value , self . _wcs , origin = 0 ) else : return None
def source_hashed ( source_filename , prepared_options , thumbnail_extension , ** kwargs ) : """Generate a thumbnail filename of the source filename and options separately hashed , along with the size . The format of the filename is a 12 character base64 sha1 hash of the source filename , the size surrounded ...
source_sha = hashlib . sha1 ( source_filename . encode ( 'utf-8' ) ) . digest ( ) source_hash = base64 . urlsafe_b64encode ( source_sha [ : 9 ] ) . decode ( 'utf-8' ) parts = ':' . join ( prepared_options [ 1 : ] ) parts_sha = hashlib . sha1 ( parts . encode ( 'utf-8' ) ) . digest ( ) options_hash = base64 . urlsafe_b6...
def get_public_cms_page_urls ( * , language_code ) : """: param language _ code : e . g . : " en " or " de " : return : Tuple with all public urls in the given language"""
pages = Page . objects . public ( ) urls = [ page . get_absolute_url ( language = language_code ) for page in pages ] urls . sort ( ) return tuple ( urls )
def read_tvips_header ( fh , byteorder , dtype , count , offsetsize ) : """Read TVIPS EM - MENU headers and return as dict ."""
result = { } header = fh . read_record ( TIFF . TVIPS_HEADER_V1 , byteorder = byteorder ) for name , typestr in TIFF . TVIPS_HEADER_V1 : result [ name ] = header [ name ] . tolist ( ) if header [ 'Version' ] == 2 : header = fh . read_record ( TIFF . TVIPS_HEADER_V2 , byteorder = byteorder ) if header [ 'Mag...
def _get_path_pattern_tornado4 ( self ) : """Return the path pattern used when routing a request . ( Tornado < 4.5) : rtype : str"""
for host , handlers in self . application . handlers : if host . match ( self . request . host ) : for handler in handlers : if handler . regex . match ( self . request . path ) : return handler . regex . pattern
def get_playlists ( self , search , start = 0 , max_items = 100 ) : """Search for playlists . See get _ music _ service _ information for details on the arguments . Note : Un - intuitively this method returns MSAlbumList items . See note in class doc string for details ."""
return self . get_music_service_information ( 'playlists' , search , start , max_items )