signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def new_tbl ( cls , rows , cols , width ) : """Return a new ` w : tbl ` element having * rows * rows and * cols * columns with * width * distributed evenly between the columns ."""
return parse_xml ( cls . _tbl_xml ( rows , cols , width ) )
def turn_on ( self , time ) : """( Helper ) Turn on an output"""
self . _elk . send ( cn_encode ( self . _index , time ) )
def text_base64decode ( data ) : '''Base64 decode to unicode text . : param str data : String data to decode to unicode . : return : Base64 decoded string . : rtype : str'''
try : return b64decode ( data . encode ( 'utf-8' ) ) . decode ( 'utf-8' ) except ( ValueError , TypeError ) : # ValueError for Python 3 , TypeError for Python 2 raise ValueError ( _ERROR_MESSAGE_NOT_BASE64 )
def LCHab_to_Lab ( cobj , * args , ** kwargs ) : """Convert from LCH ( ab ) to Lab ."""
lab_l = cobj . lch_l lab_a = math . cos ( math . radians ( cobj . lch_h ) ) * cobj . lch_c lab_b = math . sin ( math . radians ( cobj . lch_h ) ) * cobj . lch_c return LabColor ( lab_l , lab_a , lab_b , illuminant = cobj . illuminant , observer = cobj . observer )
def run_mcl ( matrix , expansion = 2 , inflation = 2 , loop_value = 1 , iterations = 100 , pruning_threshold = 0.001 , pruning_frequency = 1 , convergence_check_frequency = 1 , verbose = False ) : """Perform MCL on the given similarity matrix : param matrix : The similarity matrix to cluster : param expansion :...
assert expansion > 1 , "Invalid expansion parameter" assert inflation > 1 , "Invalid inflation parameter" assert loop_value >= 0 , "Invalid loop_value" assert iterations > 0 , "Invalid number of iterations" assert pruning_threshold >= 0 , "Invalid pruning_threshold" assert pruning_frequency > 0 , "Invalid pruning_frequ...
def order_market_buy ( self , ** params ) : """Send in a new market buy order : param symbol : required : type symbol : str : param quantity : required : type quantity : decimal : param newClientOrderId : A unique id for the order . Automatically generated if not sent . : type newClientOrderId : str :...
params . update ( { 'side' : self . SIDE_BUY } ) return self . order_market ( ** params )
def stop ( self ) : """Shutdown pyro naming server ."""
args = self . getShutdownArgs ( ) + [ 'shutdown' ] Pyro . nsc . main ( args ) self . join ( )
def sub_list ( self , from_index , to_index ) : """Returns a sublist from this list , whose range is specified with from _ index ( inclusive ) and to _ index ( exclusive ) . The returned list is backed by this list , so non - structural changes in the returned list are reflected in this list , and vice - versa ...
return self . _encode_invoke ( list_sub_codec , from_ = from_index , to = to_index )
def get_stack ( self , stack ) : """获取服务组 查看服务组的属性信息 。 Args : - stack : 服务所属的服务组名称 Returns : 返回一个tuple对象 , 其格式为 ( < result > , < ResponseInfo > ) - result 成功返回stack信息 , 失败返回 { " error " : " < errMsg string > " } - ResponseInfo 请求的Response信息"""
url = '{0}/v3/stacks/{1}' . format ( self . host , stack ) return self . __get ( url )
def from_events ( self , instance , ev_args , ctx ) : """Like : meth : ` . ChildList . from _ events ` , but the object is appended to the list associated with its tag in the dict ."""
tag = ev_args [ 0 ] , ev_args [ 1 ] cls = self . _tag_map [ tag ] obj = yield from cls . parse_events ( ev_args , ctx ) mapping = self . __get__ ( instance , type ( instance ) ) mapping [ self . key ( obj ) ] . append ( obj )
def from_name_re ( cls , path : PathOrStr , fnames : FilePathList , pat : str , valid_pct : float = 0.2 , ** kwargs ) : "Create from list of ` fnames ` in ` path ` with re expression ` pat ` ."
pat = re . compile ( pat ) def _get_label ( fn ) : if isinstance ( fn , Path ) : fn = fn . as_posix ( ) res = pat . search ( str ( fn ) ) assert res , f'Failed to find "{pat}" in "{fn}"' return res . group ( 1 ) return cls . from_name_func ( path , fnames , _get_label , valid_pct = valid_pct , *...
def RB_to_OPLS ( c0 , c1 , c2 , c3 , c4 , c5 ) : """Converts Ryckaert - Bellemans type dihedrals to OPLS type . Parameters c0 , c1 , c2 , c3 , c4 , c5 : Ryckaert - Belleman coefficients ( in kcal / mol ) Returns opls _ coeffs : np . array , shape = ( 4 , ) Array containing the OPLS dihedrals coeffs f1 , f...
f1 = ( - 1.5 * c3 ) - ( 2 * c1 ) f2 = c0 + c1 + c3 f3 = - 0.5 * c3 f4 = - 0.25 * c4 return np . array ( [ f1 , f2 , f3 , f4 ] )
def _process_get_cal_resp ( url , post_response , campus ) : """: return : a dictionary of { calenderid , TrumbaCalendar } None if error , { } if not exists If the request is successful , process the response data and load the json data into the return object ."""
request_id = "%s %s" % ( campus , url ) calendar_dict = { } data = _load_json ( request_id , post_response ) if data [ 'd' ] [ 'Calendars' ] is not None and len ( data [ 'd' ] [ 'Calendars' ] ) > 0 : _load_calendar ( campus , data [ 'd' ] [ 'Calendars' ] , calendar_dict , None ) return calendar_dict
def get_projected_plots_dots ( self , dictio , zero_to_efermi = True , ylim = None , vbm_cbm_marker = False ) : """Method returning a plot composed of subplots along different elements and orbitals . Args : dictio : The element and orbitals you want a projection on . The format is { Element : [ Orbitals ] }...
band_linewidth = 1.0 fig_number = sum ( [ len ( v ) for v in dictio . values ( ) ] ) proj = self . _get_projections_by_branches ( dictio ) data = self . bs_plot_data ( zero_to_efermi ) plt = pretty_plot ( 12 , 8 ) e_min = - 4 e_max = 4 if self . _bs . is_metal ( ) : e_min = - 10 e_max = 10 count = 1 for el in d...
def qualNorm ( data , qualitative ) : """Generates starting points using binarized data . If qualitative data is missing for a given gene , all of its entries should be - 1 in the qualitative matrix . Args : data ( array ) : 2d array of genes x cells qualitative ( array ) : 2d array of numerical data - genes ...
genes , cells = data . shape clusters = qualitative . shape [ 1 ] output = np . zeros ( ( genes , clusters ) ) missing_indices = [ ] qual_indices = [ ] thresholds = qualitative . min ( 1 ) + ( qualitative . max ( 1 ) - qualitative . min ( 1 ) ) / 2.0 for i in range ( genes ) : if qualitative [ i , : ] . max ( ) == ...
def get_current_project ( self ) : """Get name of current project using ` oc project ` command . Raise ConuException in case of an error . : return : str , project name"""
try : command = self . _oc_command ( [ "project" , "-q" ] ) output = run_cmd ( command , return_output = True ) except subprocess . CalledProcessError as ex : raise ConuException ( "Failed to obtain current project name : %s" % ex ) try : return output . rstrip ( ) # remove ' \ n ' except IndexError...
def validate ( self ) : """Validate process descriptor ."""
required_fields = ( 'slug' , 'name' , 'process_type' , 'version' ) for field in required_fields : if getattr ( self . metadata , field , None ) is None : raise ValidationError ( "process '{}' is missing required meta attribute: {}" . format ( self . metadata . slug or '<unknown>' , field ) ) if not PROCESSO...
def purge_all ( self , rate_limit_delay = 60 ) : '''Purge all pending URLs , waiting for API rate - limits if necessary !'''
for batch , response in self . purge ( ) : if response . status_code == 507 : details = response . json ( ) . get ( 'detail' , '<response did not contain "detail">' ) logger . info ( 'Will retry request in %d seconds due to API rate-limit: %s' , rate_limit_delay , details ) time . sleep ( ra...
def post ( self , action , data = None , headers = None ) : """Makes a GET request"""
return self . request ( make_url ( self . endpoint , action ) , method = 'POST' , data = data , headers = headers )
def searchadmin ( self , searchstring = None ) : """search user page"""
self . _check_auth ( must_admin = True ) is_admin = self . _check_admin ( ) if searchstring is not None : res = self . _search ( searchstring ) else : res = None attrs_list = self . attributes . get_search_attributes ( ) return self . temp [ 'searchadmin.tmpl' ] . render ( searchresult = res , attrs_list = attr...
def _ensure_format ( rule , attribute , res_dict ) : """Verifies that attribute in res _ dict is properly formatted . Since , in the . ini - files , lists are specified as ' : ' separated text and UUID values can be plain integers we need to transform any such values into proper format . Empty strings are con...
if rule == 'type:uuid' or ( rule == 'type:uuid_or_none' and res_dict [ attribute ] ) : res_dict [ attribute ] = uuidify ( res_dict [ attribute ] ) elif rule == 'type:uuid_list' : if not res_dict [ attribute ] : res_dict [ attribute ] = [ ] else : temp_list = res_dict [ attribute ] . split ( ...
def fix_display ( self ) : """If this is being run on a headless system the Matplotlib backend must be changed to one that doesn ' t need a display ."""
try : tkinter . Tk ( ) except ( tkinter . TclError , NameError ) : # If there is no display . try : import matplotlib as mpl except ImportError : pass else : print ( "Setting matplotlib backend to Agg" ) mpl . use ( 'Agg' )
def delete ( self , force = False , volumes = False ) : """delete underlying image : param force : bool - force delete , do not care about errors : param volumes : not used anyhow : return : None"""
try : self . image . rmi ( ) except ConuException as ime : if not force : raise ime else : pass
def speak ( self , sentence ) : """Speak a sentence using Google TTS . : param sentence : the sentence to speak ."""
temp_dir = "/tmp/" filename = "gtts.mp3" file_path = "{}/{}" . format ( temp_dir , filename ) if not os . path . exists ( temp_dir ) : os . makedirs ( temp_dir ) def delete_file ( ) : try : os . remove ( file_path ) if not os . listdir ( temp_dir ) : try : os . rmdir ...
def row_number ( series , ascending = True ) : """Returns row number based on column rank Equivalent to ` series . rank ( method = ' first ' , ascending = ascending ) ` . Args : series : column to rank . Kwargs : ascending ( bool ) : whether to rank in ascending order ( default is ` True ` ) . Usage : ...
series_rank = series . rank ( method = 'first' , ascending = ascending ) return series_rank
def acquire_reader ( self ) : """Acquire a read lock , several threads can hold this type of lock ."""
with self . mutex : while self . rwlock < 0 or self . rwlock == self . max_reader_concurrency or self . writers_waiting : self . readers_ok . wait ( ) self . rwlock += 1
def setMaximumWidth ( self , width ) : """Sets the maximum width value to the inputed width and emits the sizeConstraintChanged signal . : param width | < int >"""
super ( XView , self ) . setMaximumWidth ( width ) if ( not self . signalsBlocked ( ) ) : self . sizeConstraintChanged . emit ( )
def where ( self , field , value = None , operator = None ) : """Establece condiciones para la consulta unidas por AND"""
if field is None : return self conjunction = None if value is None and isinstance ( field , dict ) : for f , v in field . items ( ) : if self . where_criteria . size ( ) > 0 : conjunction = 'AND' self . where_criteria . append ( expressions . ConditionExpression ( f , v , operator = ...
def check_valid ( var , key , expected ) : r"""Check that a variable ' s attribute has the expected value . Warn user otherwise ."""
att = getattr ( var , key , None ) if att is None : e = 'Variable does not have a `{}` attribute.' . format ( key ) warn ( e ) elif att != expected : e = 'Variable has a non-conforming {}. Got `{}`, expected `{}`' . format ( key , att , expected ) warn ( e )
def copy_data_item ( self , data_item : DataItem ) -> DataItem : """Copy a data item . . . versionadded : : 1.0 Scriptable : No"""
data_item = copy . deepcopy ( data_item . _data_item ) self . __document_model . append_data_item ( data_item ) return DataItem ( data_item )
def scaled_dot_product_attention_simple ( q , k , v , bias , name = None ) : """Scaled dot - product attention . One head . One spatial dimension . Args : q : a Tensor with shape [ batch , length _ q , depth _ k ] k : a Tensor with shape [ batch , length _ kv , depth _ k ] v : a Tensor with shape [ batch , ...
with tf . variable_scope ( name , default_name = "scaled_dot_product_attention_simple" ) : scalar = tf . rsqrt ( tf . to_float ( common_layers . shape_list ( q ) [ 2 ] ) ) logits = tf . matmul ( q * scalar , k , transpose_b = True ) if bias is not None : logits += bias weights = tf . nn . softma...
def show_queue ( self , name = None , count = 10 , delete = False ) : """Show up to ` ` count ` ` messages from the queue named ` ` name ` ` . If ` ` name ` ` is None , show for each queue in our config . If ` ` delete ` ` is True , delete the messages after showing them . : param name : queue name , or None ...
logger . debug ( 'Connecting to SQS API' ) conn = client ( 'sqs' ) if name is not None : queues = [ name ] else : queues = self . _all_queue_names for q_name in queues : try : self . _show_one_queue ( conn , q_name , count , delete = delete ) except Exception : logger . error ( "Error sh...
async def _sem_crawl ( self , sem , res ) : """use semaphore ` ` encapsulate ` ` the crawl _ media \n with async crawl , should avoid crawl too fast to become DDos attack to the crawled server should set the ` ` semaphore size ` ` , and take ` ` a little gap ` ` between each crawl behavior . : param sem : the...
async with sem : st_ = await self . crawl_raw ( res ) if st_ : self . result [ 'ok' ] += 1 else : self . result [ 'fail' ] += 1 # take a little gap await asyncio . sleep ( random . randint ( 0 , 1 ) )
def function_to_serializable_representation ( fn ) : """Converts a Python function into a serializable representation . Does not currently work for methods or functions with closure data ."""
if type ( fn ) not in ( FunctionType , BuiltinFunctionType ) : raise ValueError ( "Can't serialize %s : %s, must be globally defined function" % ( fn , type ( fn ) , ) ) if hasattr ( fn , "__closure__" ) and fn . __closure__ is not None : raise ValueError ( "No serializable representation for closure %s" % ( fn...
def _yarn_init ( self , rm_address , requests_config , tags ) : """Return a dictionary of { app _ id : ( app _ name , tracking _ url ) } for running Spark applications ."""
running_apps = self . _yarn_get_running_spark_apps ( rm_address , requests_config , tags ) # Report success after gathering all metrics from ResourceManager self . service_check ( YARN_SERVICE_CHECK , AgentCheck . OK , tags = [ 'url:%s' % rm_address ] + tags , message = 'Connection to ResourceManager "%s" was successfu...
def rrmdir ( directory ) : """Recursivly delete a directory : param directory : directory to remove"""
for root , dirs , files in os . walk ( directory , topdown = False ) : for name in files : os . remove ( os . path . join ( root , name ) ) for name in dirs : os . rmdir ( os . path . join ( root , name ) ) os . rmdir ( directory )
def delete_disk ( kwargs = None , call = None ) : '''Permanently delete a persistent disk . CLI Example : . . code - block : : bash salt - cloud - f delete _ disk gce disk _ name = pd'''
if call != 'function' : raise SaltCloudSystemExit ( 'The delete_disk function must be called with -f or --function.' ) if not kwargs or 'disk_name' not in kwargs : log . error ( 'A disk_name must be specified when deleting a disk.' ) return False conn = get_conn ( ) disk = conn . ex_get_volume ( kwargs . ge...
def load_isd_hourly_temp_data ( self , start , end , read_from_cache = True , write_to_cache = True , error_on_missing_years = True , ) : """Load resampled hourly ISD temperature data from start date to end date ( inclusive ) . This is the primary convenience method for loading resampled hourly ISD temperature da...
return load_isd_hourly_temp_data ( self . usaf_id , start , end , read_from_cache = read_from_cache , write_to_cache = write_to_cache , error_on_missing_years = error_on_missing_years , )
def _load_ini_based_io ( path , recursive = False , ini = None , subini = { } , include_core = True , only_coefficients = False ) : """DEPRECATED : For convert a previous version to the new json format Loads a IOSystem or Extension from a ini files This function can be used to load a IOSystem or Extension speci...
# check path and given parameter ini_file_name = None path = os . path . abspath ( os . path . normpath ( path ) ) if os . path . splitext ( path ) [ 1 ] == '.ini' : ( path , ini_file_name ) = os . path . split ( path ) if ini : ini_file_name = ini if not os . path . exists ( path ) : raise ReadError ( 'Giv...
def get_service_task_ids ( service_name , task_predicate = None , inactive = False , completed = False ) : """Get a list of task IDs associated with a service : param service _ name : the service name : type service _ name : str : param task _ predicate : filter function which accepts a task object and return...
tasks = get_service_tasks ( service_name , inactive , completed ) if task_predicate : return [ t [ 'id' ] for t in tasks if task_predicate ( t ) ] else : return [ t [ 'id' ] for t in tasks ]
def listFiletypes ( targetfilename , directory ) : """Looks for all occurences of a specified filename in a directory and returns a list of all present file extensions of this filename . In this cas everything after the first dot is considered to be the file extension : ` ` " filename . txt " - > " txt " ` ` ...
targetextensions = list ( ) for filename in os . listdir ( directory ) : if not os . path . isfile ( joinpath ( directory , filename ) ) : continue splitname = filename . split ( '.' ) basename = splitname [ 0 ] extension = '.' . join ( splitname [ 1 : ] ) if basename == targetfilename : ...
def setDataRdyInt ( self , int_cfg = 0x20 ) : """\~english Set to enabled Data Ready Interrupt int _ cfg : Register 55 ( 0x37 ) – INT Pin / Bypass Enable Configuration , page 26 \~chinese 启用数据就绪中断 @ param int _ cfg : 寄存器 55 ( 0x37 ) – INT Pin / Bypass Enable Configuration , page 26"""
self . _sendCmd ( self . REG_INT_PIN_CFG , int_cfg ) self . _sendCmd ( self . REG_INT_ENABLE , self . VAL_INT_ENABLE_DATA_RDY )
def get_quality ( cell ) : """Gets the quality of a network / cell . @ param string cell A network / cell from iwlist scan . @ return string The quality of the network ."""
quality = matching_line ( cell , "Quality=" ) if quality is None : return "" quality = quality . split ( ) [ 0 ] . split ( "/" ) quality = matching_line ( cell , "Quality=" ) . split ( ) [ 0 ] . split ( "/" ) return str ( int ( round ( float ( quality [ 0 ] ) / float ( quality [ 1 ] ) * 100 ) ) )
def _process_scrape_info ( self , scraper : BaseScraper , scrape_result : ScrapeResult , item_session : ItemSession ) : '''Collect the URLs from the scrape info dict .'''
if not scrape_result : return 0 , 0 num_inline = 0 num_linked = 0 for link_context in scrape_result . link_contexts : url_info = self . parse_url ( link_context . link ) if not url_info : continue url_info = self . rewrite_url ( url_info ) child_url_record = item_session . child_url_record (...
def get_roles ( self ) : """Return all the roles ( IAM or User Groups ) that can be granted to a safe deposit box . Roles are permission levels that are granted to IAM or User Groups . Associating the id for the write role would allow that IAM or User Group to write in the safe deposit box ."""
roles_resp = get_with_retry ( self . cerberus_url + '/v1/role' , headers = self . HEADERS ) throw_if_bad_response ( roles_resp ) return roles_resp . json ( )
def get_parent ( self ) : """Get Parent . Fetch parent product if it exists . Use ` parent _ asin ` to check if a parent exist before fetching . : return : An instance of : class : ` ~ . AmazonProduct ` representing the parent product ."""
if not self . parent : parent = self . _safe_get_element ( 'ParentASIN' ) if parent : self . parent = self . api . lookup ( ItemId = parent ) return self . parent
def execute ( self ) : """Pause the cluster if it is running ."""
cluster_name = self . params . cluster creator = make_creator ( self . params . config , storage_path = self . params . storage ) try : cluster = creator . load_cluster ( cluster_name ) except ( ClusterNotFound , ConfigurationError ) as e : log . error ( "Cannot load cluster `%s`: %s" , cluster_name , e ) r...
def read_string ( source , offset , length ) : """Reads a string from a byte string . : param bytes source : Source byte string : param int offset : Point in byte string to start reading : param int length : Length of string to read : returns : Read string and offset at point after read data : rtype : tup...
end = offset + length try : return ( codecs . decode ( source [ offset : end ] , aws_encryption_sdk . internal . defaults . ENCODING ) , end ) except Exception : raise SerializationError ( "Bad format of serialized context." )
def add_to_inventory ( self ) : """Adds lb IPs to stack inventory"""
if self . lb_attrs : self . lb_attrs = self . consul . lb_details ( self . lb_attrs [ A . loadbalancer . ID ] ) host = self . lb_attrs [ 'virtualIps' ] [ 0 ] [ 'address' ] self . stack . add_lb_secgroup ( self . name , [ host ] , self . backend_port ) self . stack . add_host ( host , [ self . name ] , s...
def block ( self , before = '' , # type : typing . Text after = '' , # type : typing . Text delim = ( '{' , '}' ) , # type : DelimTuple dent = None , # type : typing . Optional [ int ] allman = False # type : bool ) : # type : ( . . . ) - > typing . Iterator [ None ] """A context manager that emits configurable lin...
assert len ( delim ) == 2 , 'delim must be a tuple of length 2' assert ( isinstance ( delim [ 0 ] , ( six . text_type , type ( None ) ) ) and isinstance ( delim [ 1 ] , ( six . text_type , type ( None ) ) ) ) , ( 'delim must be a tuple of two optional strings.' ) if before and not allman : if delim [ 0 ] is not Non...
def action ( self , includes : dict , variables : dict ) -> tuple : """Call external script . : param includes : testcase ' s includes : param variables : variables : return : script ' s output"""
json_args = fill_template_str ( json . dumps ( self . data ) , variables ) p = subprocess . Popen ( [ self . module , json_args ] , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) if p . wait ( ) == 0 : out = p . stdout . read ( ) . decode ( ) debug ( out ) return variables , json . loads ( out ...
async def send_and_receive ( self , message , generate_identifier = True , timeout = 5 ) : """Send a message and wait for a response ."""
await self . _connect_and_encrypt ( ) # Some messages will respond with the same identifier as used in the # corresponding request . Others will not and one example is the crypto # message ( for pairing ) . They will never include an identifer , but it # it is in turn only possible to have one of those message outstand...
def register_precmd_hook ( self , func : Callable [ [ plugin . PrecommandData ] , plugin . PrecommandData ] ) -> None : """Register a hook to be called before the command function ."""
self . _validate_prepostcmd_hook ( func , plugin . PrecommandData ) self . _precmd_hooks . append ( func )
def find ( file_node , dirs = ICON_DIRS , default_name = None , file_ext = '.png' ) : """Iterating all icon dirs , try to find a file called like the node ' s extension / mime subtype / mime type ( in that order ) . For instance , for an MP3 file ( " audio / mpeg " ) , this would look for : " mp3 . png " / " ...
names = [ ] for attr_name in ( 'extension' , 'mimetype' , 'mime_supertype' ) : attr = getattr ( file_node , attr_name ) if attr : names . append ( attr ) if default_name : names . append ( default_name ) icon_path = StaticPathFinder . find ( names , dirs , file_ext ) if icon_path : return Static...
def shader_substring ( body , stack_frame = 1 ) : """Call this method from a function that defines a literal shader string as the " body " argument . Dresses up a shader string in two ways : 1 ) Insert # line number declaration 2 ) un - indents The line number information can help debug glsl compile errors ...
line_count = len ( body . splitlines ( True ) ) line_number = inspect . stack ( ) [ stack_frame ] [ 2 ] + 1 - line_count return """\ #line %d %s """ % ( line_number , textwrap . dedent ( body ) )
def get_capabilities ( self ) : """Gets capabilities . This is a simulation of a GetCapabilities WFS request . Returns a python dict with LatLongBoundingBox and Name keys defined ."""
d = { } ext = self . _layer . GetExtent ( ) # @ TODO if a filter is on this may give different results llbb = [ round ( float ( v ) , 4 ) for v in ext ] d [ 'LatLongBoundingBox' ] = box ( llbb [ 0 ] , llbb [ 2 ] , llbb [ 1 ] , llbb [ 3 ] ) d [ 'Name' ] = self . _file . split ( '/' ) [ - 1 ] . split ( '.' ) [ 0 ] return...
def communicate_path ( self , path ) : """Communicates ` path ` to this peer if it qualifies . Checks if ` path ` should be shared / communicated with this peer according to various conditions : like bgp state , transmit side loop , local and remote AS path , community attribute , etc ."""
LOG . debug ( 'Peer %s asked to communicate path' , self ) if not path : raise ValueError ( 'Invalid path %s given.' % path ) # We do not send anything to peer who is not in established state . if not self . in_established ( ) : LOG . debug ( 'Skipping sending path as peer is not in ' 'ESTABLISHED state %s' , p...
def has_key ( self , key ) : """Does the key exist ? This method will check to see if it has expired too ."""
if key in self . _dict : try : self [ key ] return True except ValueError : return False except KeyError : return False return False
def get_version ( version = None ) : """Returns a PEP 386 - compliant version number from VERSION . : param version : A tuple that represent a version . : type version : tuple : returns : a PEP 386 - compliant version number . : rtype : str"""
if version is None : version_list = inasafe_version . split ( '.' ) version = tuple ( version_list + [ inasafe_release_status ] + [ '0' ] ) if len ( version ) != 5 : msg = 'Version must be a tuple of length 5. I got %s' % ( version , ) raise RuntimeError ( msg ) if version [ 3 ] not in ( 'alpha' , 'beta...
def run_analysis ( self , argv ) : """Run this analysis"""
args = self . _parser . parse_args ( argv ) exttype = splitext ( args . infile ) [ - 1 ] if exttype in [ '.fits' , '.npy' ] : castro_data = CastroData . create_from_sedfile ( args . infile ) elif exttype in [ '.yaml' ] : castro_data = CastroData . create_from_yamlfile ( args . infile ) else : raise ValueErr...
def align_seqprop_to_structprop ( self , seqprop , structprop , chains = None , outdir = None , engine = 'needle' , structure_already_parsed = False , parse = True , force_rerun = False , ** kwargs ) : """Run and store alignments of a SeqProp to chains in the ` ` mapped _ chains ` ` attribute of a StructProp . Al...
if not outdir : outdir = self . sequence_dir if not structure_already_parsed : # Parse the structure so chain sequences are stored structprop . parse_structure ( ) # XTODO : remove and use the " parsed " attribute in a structprop instead if chains : chains_to_align_to = ssbio . utils . force_list ( chai...
def setLogSettings ( state ) : """Update the current log settings . This can restore an old saved log settings object returned by getLogSettings @ param state : the settings to set"""
global _DEBUG global _log_handlers global _log_handlers_limited ( _DEBUG , categories , _log_handlers , _log_handlers_limited ) = state for category in categories : registerCategory ( category )
def _fetch_secret ( pass_path ) : '''Fetch secret from pass based on pass _ path . If there is any error , return back the original pass _ path value'''
cmd = "pass show {0}" . format ( pass_path . strip ( ) ) log . debug ( 'Fetching secret: %s' , cmd ) proc = Popen ( cmd . split ( ' ' ) , stdout = PIPE , stderr = PIPE ) pass_data , pass_error = proc . communicate ( ) # The version of pass used during development sent output to # stdout instead of stderr even though it...
async def close ( self , exception : BaseException = None ) -> None : """Close this context and call any necessary resource teardown callbacks . If a teardown callback returns an awaitable , the return value is awaited on before calling any further teardown callbacks . All callbacks will be processed , even i...
self . _check_closed ( ) self . _closed = True exceptions = [ ] for callback , pass_exception in reversed ( self . _teardown_callbacks ) : try : retval = callback ( exception ) if pass_exception else callback ( ) if isawaitable ( retval ) : await retval except Exception as e : ...
def template_list ( call = None ) : '''Return available Xen template information . This returns the details of each template to show number cores , memory sizes , etc . . . . code - block : : bash salt - cloud - f template _ list myxen'''
templates = { } session = _get_session ( ) vms = session . xenapi . VM . get_all ( ) for vm in vms : record = session . xenapi . VM . get_record ( vm ) if record [ 'is_a_template' ] : templates [ record [ 'name_label' ] ] = record return templates
def drawRightStatus ( self , scr , vs ) : 'Draw right side of status bar . Return length displayed .'
rightx = self . windowWidth - 1 ret = 0 for rstatcolor in self . callHook ( 'rstatus' , vs ) : if rstatcolor : try : rstatus , coloropt = rstatcolor rstatus = ' ' + rstatus attr = colors . get_color ( coloropt ) . attr statuslen = clipdraw ( scr , self . windo...
def write_stems ( audio , filename , rate = 44100 , bitrate = 256000 , codec = None , ffmpeg_params = None ) : """Write stems from numpy Tensor Parameters audio : array _ like The tensor of Matrix of stems . The data shape is formatted as : code : ` stems x channels x samples ` . filename : str Output f...
if int ( stempeg . ffmpeg_version ( ) [ 0 ] ) < 3 : warnings . warn ( "Writing STEMS with FFMPEG version < 3 is unsupported" , UserWarning ) if codec is None : avail = check_available_aac_encoders ( ) if avail is not None : if 'libfdk_aac' in avail : codec = 'libfdk_aac' else : ...
def _add_new_ide_controller_helper ( ide_controller_label , controller_key , bus_number ) : '''Helper function for adding new IDE controllers . . versionadded : : 2016.3.0 Args : ide _ controller _ label : label of the IDE controller controller _ key : if not None , the controller key to use ; otherwise it ...
if controller_key is None : controller_key = randint ( - 200 , 250 ) ide_spec = vim . vm . device . VirtualDeviceSpec ( ) ide_spec . device = vim . vm . device . VirtualIDEController ( ) ide_spec . operation = vim . vm . device . VirtualDeviceSpec . Operation . add ide_spec . device . key = controller_key ide_spec ...
def sort_dict ( dict_ , part = 'keys' , key = None , reverse = False ) : """sorts a dictionary by its values or its keys Args : dict _ ( dict _ ) : a dictionary part ( str ) : specifies to sort by keys or values key ( Optional [ func ] ) : a function that takes specified part and returns a sortable value ...
if part == 'keys' : index = 0 elif part in { 'vals' , 'values' } : index = 1 else : raise ValueError ( 'Unknown method part=%r' % ( part , ) ) if key is None : _key = op . itemgetter ( index ) else : def _key ( item ) : return key ( item [ index ] ) sorted_items = sorted ( six . iteritems ( ...
def hazeDriver ( ) : """Process the command line arguments and run the appropriate haze subcommand . We want to be able to do git - style handoffs to subcommands where if we do ` haze aws foo bar ` and the executable haze - aws - foo exists , we ' ll call it with the argument bar . We deliberately don ' t d...
try : ( command , args ) = findSubCommand ( sys . argv ) # If we can ' t construct a subcommand from sys . argv , it ' ll still be able # to find this haze driver script , and re - running ourself isn ' t useful . if os . path . basename ( command ) == "haze" : print "Could not find a subcommand...
def make_node ( cls , node , * args ) : '''Creates an array BOUND LIST .'''
if node is None : return cls . make_node ( SymbolBOUNDLIST ( ) , * args ) if node . token != 'BOUNDLIST' : return cls . make_node ( None , node , * args ) for arg in args : if arg is None : continue node . appendChild ( arg ) return node
def call_cmd ( self , cmd , cwd ) : """Calls a command with Popen . Writes stdout , stderr , and the command to separate files . : param cmd : A string or array of strings . : param tempdir : : return : The pid of the command ."""
with open ( self . cmdfile , 'w' ) as f : f . write ( str ( cmd ) ) stdout = open ( self . outfile , 'w' ) stderr = open ( self . errfile , 'w' ) logging . info ( 'Calling: ' + ' ' . join ( cmd ) ) process = subprocess . Popen ( cmd , stdout = stdout , stderr = stderr , close_fds = True , cwd = cwd ) stdout . close...
def write ( self , presets_path ) : """Write this preset to disk in JSON notation . : param presets _ path : the directory where the preset will be written ."""
if self . builtin : raise TypeError ( "Cannot write built-in preset" ) # Make dictionaries of PresetDefaults values odict = self . opts . dict ( ) pdict = { self . name : { DESC : self . desc , NOTE : self . note , OPTS : odict } } if not os . path . exists ( presets_path ) : os . makedirs ( presets_path , mode...
def moving_average_value ( self , date ) : """計算 n 日成交股數均量與持續天數 : param int date : n 日 : rtype : tuple ( 序列 舊 → 新 , 持續天數 )"""
val , conti = self . __calculate_moving_average ( date , 1 ) val = ( round ( i / 1000 , 3 ) for i in val ) return list ( val ) , conti
def length_of_overlap ( first_start , first_end , second_start , second_end ) : """Find the length of the overlapping part of two segments . Args : first _ start ( float ) : Start of the first segment . first _ end ( float ) : End of the first segment . second _ start ( float ) : Start of the second segment...
if first_end <= second_start or first_start >= second_end : return 0.0 if first_start < second_start : if first_end < second_end : return abs ( first_end - second_start ) else : return abs ( second_end - second_start ) if first_start > second_start : if first_end > second_end : r...
def leaking ( self , z , module , name , node , context , * data ) : '''an expression leaking . . . assignment nodes into the nearest block list of nodes c + + guys , stay calm'''
# input ( node . y ) args = [ node . receiver ] + node . args if node . type == 'standard_method_call' else node . args z = z ( module , name , args ) if context == 'expression' : if isinstance ( z , NormalLeakingNode ) : leaked_nodes , exp = z . as_expression ( ) else : leaked_nodes , exp = z ....
def find_global ( self , pattern ) : """Searches for the pattern in the whole process memory space and returns the first occurrence . This is exhaustive !"""
pos_s = self . reader . search ( pattern ) if len ( pos_s ) == 0 : return - 1 return pos_s [ 0 ]
def open ( safe_file ) : """Return a SentinelDataSet object ."""
if os . path . isdir ( safe_file ) or os . path . isfile ( safe_file ) : return SentinelDataSet ( safe_file ) else : raise IOError ( "file not found: %s" % safe_file )
def encode_username_password ( username : Union [ str , bytes ] , password : Union [ str , bytes ] ) -> bytes : """Encodes a username / password pair in the format used by HTTP auth . The return value is a byte string in the form ` ` username : password ` ` . . . versionadded : : 5.1"""
if isinstance ( username , unicode_type ) : username = unicodedata . normalize ( "NFC" , username ) if isinstance ( password , unicode_type ) : password = unicodedata . normalize ( "NFC" , password ) return utf8 ( username ) + b":" + utf8 ( password )
def explore ( layer = None ) : """Function used to discover the Scapy layers and protocols . It helps to see which packets exists in contrib or layer files . params : - layer : If specified , the function will explore the layer . If not , the GUI mode will be activated , to browse the available layers exa...
if layer is None : # GUI MODE if not conf . interactive : raise Scapy_Exception ( "explore() GUI-mode cannot be run in " "interactive mode. Please provide a " "'layer' parameter !" ) # 0 - Imports try : import prompt_toolkit except ImportError : raise ImportError ( "prompt_toolki...
def get_valid_fns ( self ) -> Tuple [ List [ str ] , List [ str ] ] : """Fetches the validation set of the corpus ."""
return self . prefixes_to_fns ( self . valid_prefixes )
def make_public ( self , container , ttl = None ) : """Enables CDN access for the specified container , and optionally sets the TTL for the container ."""
return self . _set_cdn_access ( container , public = True , ttl = ttl )
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) : """See : meth : ` superclass method < . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > ` for spec of input and result values ."""
assert all ( stddev_type in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types ) C = self . COEFFS [ imt ] mag = self . _convert_magnitude ( rup . mag ) mean = ( C [ 'c1' ] + C [ 'c2' ] * mag + C [ 'c10' ] * ( mag - 6 ) ** 2 + ( C [ 'c6' ] + C [ 'c7' ] * mag ) * np . log ( dists . rjb + np . ex...
def __get_course_html ( self ) : """获得课表页面 : return : 已转码的html"""
self . _headers [ 'Referer' ] = 'http://jwc.wyu.edu.cn/student/menu.asp' r = requests . get ( 'http://jwc.wyu.edu.cn/student/f3.asp' , headers = self . _headers , cookies = self . _cookies ) return r . content . decode ( _ . get_charset ( r . content ) )
def _post_request ( self , url , data = None , files = None ) : '''a helper method for sending post requests to telegram api https : / / core . telegram . org / bots / api # making - requests https : / / requests . readthedocs . io / en / master / user / quickstart / : param url : string with url for post req...
import requests # construct request fields request_kwargs = { 'url' : url } if data : request_kwargs [ 'data' ] = data if files : request_kwargs [ 'files' ] = files # send request try : response = requests . post ( ** request_kwargs ) except Exception : if self . requests_handler : request_kwarg...
def show_fabric_trunk_info_input_rbridge_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_fabric_trunk_info = ET . Element ( "show_fabric_trunk_info" ) config = show_fabric_trunk_info input = ET . SubElement ( show_fabric_trunk_info , "input" ) rbridge_id = ET . SubElement ( input , "rbridge-id" ) rbridge_id . text = kwargs . pop ( 'rbridge_id' ) callback = kwargs . p...
def __slice_key_val ( line ) : """Get the key and value items from a line by looking for and lines that have a " : " : param str line : : return str str : Key , Value"""
position = line . find ( ":" ) # If value is - 1 , that means the item was not found in the string . if position != - 1 : key = line [ : position ] value = line [ position + 1 : ] value = value . lstrip ( ) return key , value else : key = line value = None return key , value
def check_subset ( arr , size , divisor ) : """This function checks if a subset of ' arr ' has a sum that can be divided by ' divisor ' with no remainder . > > > check _ subset ( [ 3 , 1 , 7 , 5 ] , 4 , 6) True > > > check _ subset ( [ 1 , 7 ] , 2 , 5) False > > > check _ subset ( [ 1 , 6 ] , 2 , 5) Fal...
if ( size > divisor ) : return True modulerCheck = [ False for _ in range ( divisor ) ] for i in range ( size ) : if modulerCheck [ 0 ] : return True tempArr = [ False for _ in range ( divisor ) ] for j in range ( divisor ) : if ( modulerCheck [ j ] == True ) : if ( modulerCh...
def check_next_match ( self , match , new_relations , subject_graph , one_match ) : """Check if the ( onset for a ) match can be a valid ( part of a ) ring"""
if not CustomPattern . check_next_match ( self , match , new_relations , subject_graph , one_match ) : return False if self . strong : # can this ever become a strong ring ? vertex1_start = match . forward [ self . pattern_graph . central_vertex ] for vertex1 in new_relations . values ( ) : paths = ...
def preflightInfo ( info ) : """Returns a dict containing two items . The value for each item will be a list of info attribute names . missingRequired Required data that is missing . missingRecommended Recommended data that is missing ."""
missingRequired = set ( ) missingRecommended = set ( ) for attr in requiredAttributes : if not hasattr ( info , attr ) or getattr ( info , attr ) is None : missingRequired . add ( attr ) for attr in recommendedAttributes : if not hasattr ( info , attr ) or getattr ( info , attr ) is None : missi...
def monitor ( name ) : '''Get the summary from module monit and try to see if service is being monitored . If not then monitor the service .'''
ret = { 'result' : None , 'name' : name , 'comment' : '' , 'changes' : { } } result = __salt__ [ 'monit.summary' ] ( name ) try : for key , value in result . items ( ) : if 'Running' in value [ name ] : ret [ 'comment' ] = ( '{0} is being being monitored.' ) . format ( name ) ret [ '...
def get_db ( db_name = None ) : """GetDB - simple function to wrap getting a database connection from the connection pool ."""
import pymongo return pymongo . Connection ( host = DB_HOST , port = DB_PORT ) [ db_name ]
def insert_completions ( self , e ) : u"""Insert all completions of the text before point that would have been generated by possible - completions ."""
completions = self . _get_completions ( ) b = self . begidx e = self . endidx for comp in completions : rep = [ c for c in comp ] rep . append ( ' ' ) self . l_buffer [ b : e ] = rep b += len ( rep ) e = b self . line_cursor = b self . finalize ( )
def reset_index ( self , dims_or_levels , drop = False , inplace = None ) : """Reset the specified index ( es ) or multi - index level ( s ) . Parameters dims _ or _ levels : str or list Name ( s ) of the dimension ( s ) and / or multi - index level ( s ) that will be reset . drop : bool , optional If T...
inplace = _check_inplace ( inplace ) coords , _ = split_indexes ( dims_or_levels , self . _coords , set ( ) , self . _level_coords , drop = drop ) if inplace : self . _coords = coords else : return self . _replace ( coords = coords )
def get_output ( self ) : '''Get file content , selecting only lines we are interested in'''
if not os . path . isfile ( self . real_path ) : logger . debug ( 'File %s does not exist' , self . real_path ) return cmd = [ ] cmd . append ( 'sed' ) cmd . append ( '-rf' ) cmd . append ( constants . default_sed_file ) cmd . append ( self . real_path ) sedcmd = Popen ( cmd , stdout = PIPE ) if self . exclude ...
def list ( self , marker = None , limit = None , prefix = None , delimiter = None , end_marker = None , full_listing = False , return_raw = False ) : """List the objects in this container , using the parameters to control the number and content of objects . Note that this is limited by the absolute request limi...
if full_listing : return self . list_all ( prefix = prefix ) else : return self . object_manager . list ( marker = marker , limit = limit , prefix = prefix , delimiter = delimiter , end_marker = end_marker , return_raw = return_raw )
def brightness ( frames ) : """parse a brightness message"""
reader = MessageReader ( frames ) res = reader . string ( "command" ) . uint32 ( "brightness" ) . assert_end ( ) . get ( ) if res . command != "brightness" : raise MessageParserError ( "Command is not 'brightness'" ) return ( res . brightness / 1000 , )
def make_data ( self ) : """Return data of the field in a format that can be converted to JSON Returns : data ( dict ) : A dictionary of dictionaries , such that for a given x , y pair , data [ x ] [ y ] = { " dx " : dx , " dy " : dy } . Note that this is transposed from the matrix representation in DX and ...
X , Y , DX , DY = self . _calc_partials ( ) data = { } import pdb for x in self . xrange : data [ x ] = { } for y in self . yrange : data [ x ] [ y ] = { "dx" : DX [ y , x ] , "dy" : DY [ y , x ] } return data
def sync_model ( self , comment = '' , compact_central = False , release_borrowed = True , release_workset = True , save_local = False ) : """Append a sync model entry to the journal . This instructs Revit to sync the currently open workshared model . Args : comment ( str ) : comment to be provided for the sy...
self . _add_entry ( templates . FILE_SYNC_START ) if compact_central : self . _add_entry ( templates . FILE_SYNC_COMPACT ) if release_borrowed : self . _add_entry ( templates . FILE_SYNC_RELEASE_BORROWED ) if release_workset : self . _add_entry ( templates . FILE_SYNC_RELEASE_USERWORKSETS ) if save_local : ...
def check_attr ( node , n ) : """Check if ATTR has to be normalized after this instruction has been translated to intermediate code ."""
if len ( node . children ) > n : return node . children [ n ]