signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_network_instances ( self , name = "" ) : """get _ network _ instances implementation for NX - OS"""
# command ' show vrf detail ' returns all VRFs with detailed information # format : list of dictionaries with keys such as ' vrf _ name ' and ' rd ' command = "show vrf detail" vrf_table_raw = self . _get_command_table ( command , "TABLE_vrf" , "ROW_vrf" ) # command ' show vrf interface ' returns all interfaces includi...
def list_platform_sets ( server_url ) : '''To list all ASAM platform sets present on the Novell Fan - Out Driver CLI Example : . . code - block : : bash salt - run asam . list _ platform _ sets prov1 . domain . com'''
config = _get_asam_configuration ( server_url ) if not config : return False url = config [ 'platformset_config_url' ] data = { 'manual' : 'false' , } auth = ( config [ 'username' ] , config [ 'password' ] ) try : html_content = _make_post_request ( url , data , auth , verify = False ) except Exception as exc :...
def get_decomposition_energy ( self , entry , pH , V ) : """Finds decomposition to most stable entry Args : entry ( PourbaixEntry ) : PourbaixEntry corresponding to compound to find the decomposition for pH ( float ) : pH at which to find the decomposition V ( float ) : voltage at which to find the decomp...
# Find representative multientry if self . _multielement and not isinstance ( entry , MultiEntry ) : possible_entries = self . _generate_multielement_entries ( self . _filtered_entries , forced_include = [ entry ] ) # Filter to only include materials where the entry is only solid if entry . phase_type == "s...
def remove ( self , cls , originalMemberNameList , memberName , classNamingConvention ) : """: type cls : type : type originalMemberNameList : list ( str ) : type memberName : str : type classNamingConvention : INamingConvention | None"""
accessorDict = self . _accessorDict ( memberName , classNamingConvention ) for accessorName , _ in accessorDict . items ( ) : if accessorName not in originalMemberNameList and hasattr ( cls , accessorName ) : delattr ( cls , accessorName )
def _set_mpl_backend ( self , backend , pylab = False ) : """Set a backend for Matplotlib . backend : A parameter that can be passed to % matplotlib ( e . g . ' inline ' or ' tk ' ) ."""
import traceback from IPython . core . getipython import get_ipython generic_error = ( "\n" + "=" * 73 + "\n" "NOTE: The following error appeared when setting " "your Matplotlib backend!!\n" + "=" * 73 + "\n\n" "{0}" ) magic = 'pylab' if pylab else 'matplotlib' error = None try : get_ipython ( ) . run_line_magic ( ...
def cancelMktData ( self , contract : Contract ) : """Unsubscribe from realtime streaming tick data . Args : contract : The exact contract object that was used to subscribe with ."""
ticker = self . ticker ( contract ) reqId = self . wrapper . endTicker ( ticker , 'mktData' ) if reqId : self . client . cancelMktData ( reqId ) else : self . _logger . error ( 'cancelMktData: ' f'No reqId found for contract {contract}' )
def parse_impl ( self ) : """Parses the HTML content as a stream . This is far less memory intensive than loading the entire HTML file into memory , like BeautifulSoup does ."""
# Cast to str to ensure not unicode under Python 2 , as the parser # doesn ' t like that . parser = XMLParser ( encoding = str ( 'UTF-8' ) ) element_iter = ET . iterparse ( self . handle , events = ( "start" , "end" ) , parser = parser ) for pos , element in element_iter : tag , class_attr = _tag_and_class_attr ( e...
def handleRestartRequest ( self , req : Request ) -> None : """Handles transaction of type POOL _ RESTART Can schedule or cancel restart to a newer version at specified time : param req :"""
txn = req . operation if txn [ TXN_TYPE ] != POOL_RESTART : return action = txn [ ACTION ] if action == START : when = dateutil . parser . parse ( txn [ DATETIME ] ) if DATETIME in txn . keys ( ) and txn [ DATETIME ] not in [ "0" , "" , None ] else None fail_timeout = txn . get ( TIMEOUT , self . defaultAct...
def _add_genotype_calls ( self , variant_obj , variant_line , case_obj ) : """Add the genotype calls for the variant Args : variant _ obj ( puzzle . models . Variant ) variant _ dict ( dict ) : A variant dictionary case _ obj ( puzzle . models . Case )"""
variant_line = variant_line . split ( '\t' ) # if there is gt calls we have no individuals to add if len ( variant_line ) > 8 : gt_format = variant_line [ 8 ] . split ( ':' ) for individual in case_obj . individuals : sample_id = individual . ind_id index = individual . ind_index gt_call...
def split_expr ( expr , op ) : """Returns a list containing the top - level AND or OR operands in the expression ' expr ' , in the same ( left - to - right ) order as they appear in the expression . This can be handy e . g . for splitting ( weak ) reverse dependencies from ' select ' and ' imply ' into indi...
res = [ ] def rec ( subexpr ) : if subexpr . __class__ is tuple and subexpr [ 0 ] is op : rec ( subexpr [ 1 ] ) rec ( subexpr [ 2 ] ) else : res . append ( subexpr ) rec ( expr ) return res
def id_to_name ( id ) : """Convert a PDG ID to a printable string ."""
name = pdgid_names . get ( id ) if not name : name = repr ( id ) return name
def __item_descriptor ( self , config ) : """Builds an item descriptor for a service configuration . Args : config : A dictionary containing the service configuration to describe . Returns : A dictionary that describes the service configuration ."""
descriptor = { 'kind' : 'discovery#directoryItem' , 'icons' : { 'x16' : 'https://www.gstatic.com/images/branding/product/1x/' 'googleg_16dp.png' , 'x32' : 'https://www.gstatic.com/images/branding/product/1x/' 'googleg_32dp.png' , } , 'preferred' : True , } description = config . get ( 'description' ) root_url = config ...
def create ( cls , name , address , proxy_port = 8080 , username = None , password = None , secondary = None , comment = None ) : """Create a new HTTP Proxy service . Proxy must define at least one primary address but can optionally also define a list of secondary addresses . : param str name : Name of the pr...
json = { 'name' : name , 'address' : address , 'comment' : comment , 'http_proxy_port' : proxy_port , 'http_proxy_username' : username if username else '' , 'http_proxy_password' : password if password else '' , 'secondary' : secondary if secondary else [ ] } return ElementCreator ( cls , json )
def unquote ( text ) : """Replace all percent - encoded entities in text ."""
while '%' in text : newtext = url_unquote ( text ) if newtext == text : break text = newtext return text
def parse_finalize ( self ) : """Raises errors for incomplete buffered data that could not be parsed because the end of the input data has been reached . Raises ~ ipfsapi . exceptions . DecodingError Returns tuple : Always empty"""
try : try : # Raise exception for remaining bytes in bytes decoder self . _decoder1 . decode ( b'' , True ) except UnicodeDecodeError as error : raise exceptions . DecodingError ( 'json' , error ) # Late raise errors that looked like they could have been fixed if # the caller had provide...
def handle_startendtag ( self , tag , attrs ) : """Function called for empty tags ( e . g . < br / > )"""
if tag . lower ( ) in self . allowed_tag_whitelist : self . result += '<' + tag for ( attr , value ) in attrs : if attr . lower ( ) in self . allowed_attribute_whitelist : self . result += ' %s="%s"' % ( attr , self . handle_attribute_value ( value ) ) self . result += ' />' else : i...
def page ( self , language = values . unset , model_build = values . unset , status = values . unset , page_token = values . unset , page_number = values . unset , page_size = values . unset ) : """Retrieve a single page of QueryInstance records from the API . Request is executed immediately : param unicode lan...
params = values . of ( { 'Language' : language , 'ModelBuild' : model_build , 'Status' : status , 'PageToken' : page_token , 'Page' : page_number , 'PageSize' : page_size , } ) response = self . _version . page ( 'GET' , self . _uri , params = params , ) return QueryPage ( self . _version , response , self . _solution ...
def start_element ( self , tag , attrs ) : """Search for meta robots . txt " nofollow " and " noindex " flags ."""
if tag == 'meta' and attrs . get ( 'name' ) == 'robots' : val = attrs . get_true ( 'content' , u'' ) . lower ( ) . split ( u',' ) self . follow = u'nofollow' not in val self . index = u'noindex' not in val raise StopParse ( "found <meta name=robots> tag" ) elif tag == 'body' : raise StopParse ( "fou...
def etree_to_dict ( t , trim = True , ** kw ) : u"""Converts an lxml . etree object to Python dict . > > > etree _ to _ dict ( etree . Element ( ' root ' ) ) { ' root ' : None } : param etree . Element t : lxml tree to convert : returns d : a dict representing the lxml tree ` ` t ` ` : rtype : dict"""
d = { t . tag : { } if t . attrib else None } children = list ( t ) etree_to_dict_w_args = partial ( etree_to_dict , trim = trim , ** kw ) if children : dd = defaultdict ( list ) d = { t . tag : { } } for dc in map ( etree_to_dict_w_args , children ) : for k , v in dc . iteritems ( ) : # do not add ...
async def get_sound_settings ( self , target = "" ) -> List [ Setting ] : """Get the current sound settings . : param str target : settings target , defaults to all ."""
res = await self . services [ "audio" ] [ "getSoundSettings" ] ( { "target" : target } ) return [ Setting . make ( ** x ) for x in res ]
def write_index ( data , group , append ) : """Write the data index to the given group . : param h5features . Data data : The that is being indexed . : param h5py . Group group : The group where to write the index . : param bool append : If True , append the created index to the existing one in the ` group ...
# build the index from data nitems = group [ 'items' ] . shape [ 0 ] if 'items' in group else 0 last_index = group [ 'index' ] [ - 1 ] if nitems > 0 else - 1 index = last_index + cumindex ( data . _entries [ 'features' ] ) if append : nidx = group [ 'index' ] . shape [ 0 ] # # in case we append to the end of an...
def accept ( self , value , silent = False ) : '''Accepts a value from the form , calls : meth : ` to _ python ` method , checks ` required ` condition , applies filters and validators , catches ValidationError . : param value : a value to be accepted : param silent = False : write errors to ` form . errors...
try : value = self . to_python ( value ) for v in self . validators : value = v ( self , value ) if self . required and self . _is_empty ( value ) : raise ValidationError ( self . error_required ) except ValidationError as e : if not silent : e . fill_errors ( self . field ) ...
def remove_object ( self , instance , bucket_name , object_name ) : """Remove an object from a bucket . : param str instance : A Yamcs instance name . : param str bucket _ name : The name of the bucket . : param str object _ name : The object to remove ."""
url = '/buckets/{}/{}/{}' . format ( instance , bucket_name , object_name ) self . _client . delete_proto ( url )
def load_data_batch ( self , data_batch ) : """Load data and labels into arrays ."""
if self . sym_gen is not None : key = data_batch . bucket_key if key not in self . execgrp_bucket : # create new bucket entry symbol = self . sym_gen ( key ) execgrp = DataParallelExecutorGroup ( symbol , self . arg_names , self . param_names , self . ctx , self . slices , data_batch , shared_gr...
def _get_parts_list ( to_go , so_far = [ [ ] ] , ticker = None ) : """Iterates over to _ go , building the list of parts . To provide items for the beginning , use so _ far ."""
try : part = to_go . pop ( 0 ) except IndexError : return so_far , ticker # Lists of input groups if isinstance ( part , list ) and any ( isinstance ( e , list ) for e in part ) : while len ( part ) > 0 : so_far , ticker = _get_parts_list ( part , so_far , ticker ) ticker . tick ( ) # Input ...
def transformations ( self , relationship = "all" ) : """Get all the transformations of this info . Return a list of transformations involving this info . ` ` relationship ` ` can be " parent " ( in which case only transformations where the info is the ` ` info _ in ` ` are returned ) , " child " ( in which c...
if relationship not in [ "all" , "parent" , "child" ] : raise ValueError ( "You cannot get transformations of relationship {}" . format ( relationship ) + "Relationship can only be parent, child or all." ) if relationship == "all" : return Transformation . query . filter ( and_ ( Transformation . failed == fals...
def set_image ( self , image ) : """Set display buffer to Python Image Library image . Image will be converted to 1 bit color and non - zero color values will light the LEDs ."""
imwidth , imheight = image . size if imwidth != 8 or imheight != 16 : raise ValueError ( 'Image must be an 8x16 pixels in size.' ) # Convert image to 1 bit color and grab all the pixels . pix = image . convert ( '1' ) . load ( ) # Loop through each pixel and write the display buffer pixel . for x in xrange ( 8 ) : ...
def get_plugin_actions ( self ) : """Return a list of actions related to plugin"""
self . new_project_action = create_action ( self , _ ( "New Project..." ) , triggered = self . create_new_project ) self . open_project_action = create_action ( self , _ ( "Open Project..." ) , triggered = lambda v : self . open_project ( ) ) self . close_project_action = create_action ( self , _ ( "Close Project" ) , ...
def sims_by_vec ( self , vec , normalize = None ) : """Find the most similar documents to a given vector ( = already processed document ) ."""
if normalize is None : normalize = self . qindex . normalize norm , self . qindex . normalize = self . qindex . normalize , normalize # store old value self . qindex . num_best = self . topsims sims = self . qindex [ vec ] self . qindex . normalize = norm # restore old value of qindex . normalize return self . sims...
def solve ( A , b ) : r"""Solve for the linear equations : math : ` \ mathrm A \ mathbf x = \ mathbf b ` . Args : A ( array _ like ) : Coefficient matrix . b ( array _ like ) : Ordinate values . Returns : : class : ` numpy . ndarray ` : Solution ` ` x ` ` ."""
A = asarray ( A , float ) b = asarray ( b , float ) if A . shape [ 0 ] == 1 : with errstate ( divide = "ignore" ) : A_ = array ( [ [ 1.0 / A [ 0 , 0 ] ] ] ) if not isfinite ( A_ [ 0 , 0 ] ) : raise LinAlgError ( "Division error." ) return dot ( A_ , b ) elif A . shape [ 0 ] == 2 : a = A ...
def authors ( self , * usernames ) : """Return the entries written by the given usernames When multiple tags are provided , they operate as " OR " query ."""
if len ( usernames ) == 1 : return self . filter ( ** { "author__{}" . format ( User . USERNAME_FIELD ) : usernames [ 0 ] } ) else : return self . filter ( ** { "author__{}__in" . format ( User . USERNAME_FIELD ) : usernames } )
def _positionalArgumentKeyValueList ( self , originalConstructorExpectedArgList , syntheticMemberList , argTuple ) : """Transforms args tuple to a dictionary mapping argument names to values using original constructor positional args specification , then it adds synthesized members at the end if they are not alre...
# First , the list of expected arguments is set to original constructor ' s arg spec . expectedArgList = copy . copy ( originalConstructorExpectedArgList ) # . . . then we append members that are not already present . for syntheticMember in syntheticMemberList : memberName = syntheticMember . memberName ( ) if ...
def landing_target_encode ( self , time_usec , target_num , frame , angle_x , angle_y , distance , size_x , size_y ) : '''The location of a landing area captured from a downward facing camera time _ usec : Timestamp ( micros since boot or Unix epoch ) ( uint64 _ t ) target _ num : The ID of the target if multip...
return MAVLink_landing_target_message ( time_usec , target_num , frame , angle_x , angle_y , distance , size_x , size_y )
def _adjust_overlap ( positions_list , index , direction ) : '''Increase overlap to the right or left of an index . : param positions _ list : list of overlap positions : type positions _ list : list : param index : index of the overlap to increase . : type index : int : param direction : which side of th...
if direction == 'left' : positions_list [ index + 1 ] -= 1 elif direction == 'right' : positions_list [ index ] += 1 else : raise ValueError ( 'direction must be \'left\' or \'right\'.' ) return positions_list
def genKw ( w , msk , z ) : """Generates key Kw using key - selector @ w , master secret key @ msk , and table value @ z . @ returns Kw as a BigInt ."""
# Hash inputs into a string of bytes b = hmac ( msk , z + w , tag = "TAG_PYTHIA_KW" ) # Convert the string into a long value ( no larger than the order of Gt ) , # then return a BigInt value . return BigInt ( longFromString ( b ) % long ( orderGt ( ) ) )
def _randomize_speed ( base_speed : int , sigma : int = None ) -> int : """Creates a variation in wind speed Args : base _ speed : base wind speed sigma : sigma value for gaussian variation Returns : random wind speed"""
if sigma is None : int_sigma = int ( base_speed / 4 ) else : int_sigma = sigma val = MissionWeather . _gauss ( base_speed , int_sigma ) if val < 0 : return 0 return min ( val , 50 )
def write_omega_scan_config ( channellist , fobj , header = True ) : """Write a ` ChannelList ` to an Omega - pipeline scan configuration file This method is dumb and assumes the channels are sorted in the right order already"""
if isinstance ( fobj , FILE_LIKE ) : close = False else : fobj = open ( fobj , 'w' ) close = True try : # print header if header : print ( '# Q Scan configuration file' , file = fobj ) print ( '# Generated with GWpy from a ChannelList' , file = fobj ) group = None for channel in ...
def run_clingo ( draco_query : List [ str ] , constants : Dict [ str , str ] = None , files : List [ str ] = None , relax_hard = False , silence_warnings = False , debug = False , ) -> Tuple [ str , str ] : """Run draco and return stderr and stdout"""
# default args files = files or DRACO_LP if relax_hard and "hard-integrity.lp" in files : files . remove ( "hard-integrity.lp" ) constants = constants or { } options = [ "--outf=2" , "--quiet=1,2,2" ] if silence_warnings : options . append ( "--warn=no-atom-undefined" ) for name , value in constants . items ( )...
def filtered ( self , indices ) : """: param indices : a subset of indices in the range [ 0 . . tot _ sites - 1] : returns : a filtered SiteCollection instance if ` indices ` is a proper subset of the available indices , otherwise returns the full SiteCollection"""
if indices is None or len ( indices ) == len ( self ) : return self new = object . __new__ ( self . __class__ ) indices = numpy . uint32 ( sorted ( indices ) ) new . array = self . array [ indices ] new . complete = self . complete return new
async def schemes ( dev : Device ) : """Print supported uri schemes ."""
schemes = await dev . get_schemes ( ) for scheme in schemes : click . echo ( scheme )
def _get_rule_changes ( rules , _rules ) : '''given a list of desired rules ( rules ) and existing rules ( _ rules ) return a list of rules to delete ( to _ delete ) and to create ( to _ create )'''
to_delete = [ ] to_create = [ ] # for each rule in state file # 1 . validate rule # 2 . determine if rule exists in existing security group rules for rule in rules : try : ip_protocol = six . text_type ( rule . get ( 'ip_protocol' ) ) except KeyError : raise SaltInvocationError ( 'ip_protocol, t...
def get_string_scope ( self , code , resource = None ) : """Returns a ` Scope ` object for the given code"""
return rope . base . libutils . get_string_scope ( code , resource )
def export_csv ( self , filename , delimiter = ',' , line_terminator = '\n' , header = True , quote_level = csv . QUOTE_NONNUMERIC , double_quote = True , escape_char = '\\' , quote_char = '\"' , na_rep = '' , file_header = '' , file_footer = '' , line_prefix = '' , _no_prefix_on_first_value = False , ** kwargs ) : ...
# Pandas argument compatibility if "sep" in kwargs : delimiter = kwargs [ 'sep' ] del kwargs [ 'sep' ] if "quotechar" in kwargs : quote_char = kwargs [ 'quotechar' ] del kwargs [ 'quotechar' ] if "doublequote" in kwargs : double_quote = kwargs [ 'doublequote' ] del kwargs [ 'doublequote' ] if "l...
def _sortValueIntoGroup ( groupKeys , groupLimits , value ) : """returns the Key of the group a value belongs to : param groupKeys : a list / tuple of keys ie [ ' 1-3 ' , ' 3-5 ' , ' 5-8 ' , ' 8-10 ' , ' 10 + ' ] : param groupLimits : a list of the limits for the group [ 1,3,5,8,10 , float ( ' inf ' ) ] note th...
if not len ( groupKeys ) == len ( groupLimits ) - 1 : raise ValueError ( 'len(groupKeys) must equal len(grouplimits)-1 got \nkeys:{0} \nlimits:{1}' . format ( groupKeys , groupLimits ) ) if math . isnan ( value ) : return 'Uncertain' # TODO add to other if bad value or outside limits keyIndex = None if value ==...
def NextPage ( self , page = None ) : """Sets the LIMIT clause of the AWQL to the next page . This method is meant to be used with HasNext ( ) . When using DataService , page is needed , as its paging mechanism is different from other services . For details , see https : / / developers . google . com / adwo...
if self . _start_index is None : raise ValueError ( 'Cannot page through query with no LIMIT clause.' ) # DataService has a different paging mechanism , resulting in different # method of determining if there is still a page left . page_size = None if ( page and self . _PAGE_TYPE in page and page [ self . _PAGE_TYP...
def min_base_quality ( self ) : '''The minimum of the base qualities . In the case of a deletion , in which case there are no bases in this PileupElement , the minimum is taken over the sequenced bases immediately before and after the deletion .'''
try : return min ( self . base_qualities ) except ValueError : # We are mid - deletion . We return the minimum of the adjacent bases . assert self . offset_start == self . offset_end adjacent_qualities = [ self . alignment . query_qualities [ offset ] for offset in [ self . offset_start - 1 , self . offset_...
def _get_fault_type_dummy_variables ( self , rup ) : """Fault type ( Strike - slip , Normal , Thrust / reverse ) is derived from rake angle . Rakes angles within 30 of horizontal are strike - slip , angles from 30 to 150 are reverse , and angles from -30 to - 150 are normal . Note that the ' Unspecified '...
U , SS , NS , RS = 0 , 0 , 0 , 0 if np . abs ( rup . rake ) <= 30.0 or ( 180.0 - np . abs ( rup . rake ) ) <= 30.0 : # strike - slip SS = 1 elif rup . rake > 30.0 and rup . rake < 150.0 : # reverse RS = 1 else : # normal NS = 1 return U , SS , NS , RS
def get_collections_for_image ( self , image_id ) : """Get identifier of all collections that contain a given image . Parameters image _ id : string Unique identifierof image object Returns List ( string ) List of image collection identifier"""
result = [ ] # Get all active collections that contain the image identifier for document in self . collection . find ( { 'active' : True , 'images.identifier' : image_id } ) : result . append ( str ( document [ '_id' ] ) ) return result
def _send ( self , method , route , data , params , ** kwargs ) : """Send request of type ` method ` to ` route ` ."""
route = self . _fmt_route ( route , params ) log ( _ ( "sending {} request to {}" ) . format ( method . upper ( ) , route ) ) try : self . response = getattr ( self . _client , method . lower ( ) ) ( route , data = data , ** kwargs ) except BaseException as e : # Catch all exceptions thrown by app log ( _ ( "ex...
def send_ack ( self ) : """Send an ack message"""
if self . last_ack == self . proto . max_id : return LOGGER . debug ( "ack (%d)" , self . proto . max_id ) self . last_ack = self . proto . max_id self . send_message ( f"4{to_json([self.proto.max_id])}" )
def create ( self , ** kwargs ) : """Creates a new statement matching the keyword arguments specified . Returns the created statement ."""
Statement = self . get_model ( 'statement' ) Tag = self . get_model ( 'tag' ) session = self . Session ( ) tags = set ( kwargs . pop ( 'tags' , [ ] ) ) if 'search_text' not in kwargs : kwargs [ 'search_text' ] = self . tagger . get_bigram_pair_string ( kwargs [ 'text' ] ) if 'search_in_response_to' not in kwargs : ...
def ensure_mapping_format ( variables ) : """ensure variables are in mapping format . Args : variables ( list / dict ) : original variables Returns : dict : ensured variables in dict format Examples : > > > variables = [ { " a " : 1 } , { " b " : 2} > > > print ( ensure _ mapping _ format ( variab...
if isinstance ( variables , list ) : variables_dict = { } for map_dict in variables : variables_dict . update ( map_dict ) return variables_dict elif isinstance ( variables , dict ) : return variables else : raise exceptions . ParamsError ( "variables format error!" )
def expect_token ( lexer : Lexer , kind : TokenKind ) -> Token : """Expect the next token to be of the given kind . If the next token is of the given kind , return that token after advancing the lexer . Otherwise , do not change the parser state and throw an error ."""
token = lexer . token if token . kind == kind : lexer . advance ( ) return token raise GraphQLSyntaxError ( lexer . source , token . start , f"Expected {kind.value}, found {token.kind.value}" )
def is_dataframe ( obj ) : """Returns True if the given object is a Pandas Data Frame . Parameters obj : instance The object to test whether or not is a Pandas DataFrame ."""
try : # This is the best method of type checking from pandas import DataFrame return isinstance ( obj , DataFrame ) except ImportError : # Pandas is not a dependency , so this is scary return obj . __class__ . __name__ == "DataFrame"
def unsubscribe ( self , destination = None , id = None , headers = None , ** keyword_headers ) : """Unsubscribe from a destination by either id or the destination name . : param str destination : the name of the topic or queue to unsubscribe from : param str id : the unique identifier of the topic or queue to ...
assert id is not None or destination is not None , "'id' or 'destination' is required" headers = utils . merge_headers ( [ headers , keyword_headers ] ) if id : headers [ HDR_ID ] = id if destination : headers [ HDR_DESTINATION ] = destination self . send_frame ( CMD_UNSUBSCRIBE , headers )
def import_data ( self , data ) : """Import additional data for tuning Parameters data : a list of dictionarys , each of which has at least two keys , ' parameter ' and ' value '"""
_completed_num = 0 for trial_info in data : logger . info ( "Importing data, current processing progress %s / %s" % ( _completed_num , len ( data ) ) ) _completed_num += 1 assert "parameter" in trial_info _params = trial_info [ "parameter" ] assert "value" in trial_info _value = trial_info [ 'va...
def set ( string , target_level , indent_string = " " , indent_empty_lines = False ) : """Sets indentation of a single / multi - line string ."""
lines = string . splitlines ( ) set_lines ( lines , target_level , indent_string = indent_string , indent_empty_lines = indent_empty_lines ) result = "\n" . join ( lines ) return result
def name ( self ) : """The name of this instance"""
try : return self . _name except AttributeError : self . _name = "%s.%s[%i]" % ( self . __module__ , self . __class__ . __name__ , next ( Loggable . __ids ) ) return self . _name
def btc_make_p2sh_address ( script_hex ) : """Make a P2SH address from a hex script"""
h = hashing . bin_hash160 ( binascii . unhexlify ( script_hex ) ) addr = bin_hash160_to_address ( h , version_byte = multisig_version_byte ) return addr
def truncate_loc ( self , character , location , branch , turn , tick ) : """Remove future data about a particular location Return True if I deleted anything , False otherwise ."""
r = False branches_turns = self . branches [ character , location ] [ branch ] branches_turns . truncate ( turn ) if turn in branches_turns : bttrn = branches_turns [ turn ] if bttrn . future ( tick ) : bttrn . truncate ( tick ) r = True keyses = self . keys [ character , location ] for keysbran...
def xyz ( self ) : """Return all particle coordinates in this compound . Returns pos : np . ndarray , shape = ( n , 3 ) , dtype = float Array with the positions of all particles ."""
if not self . children : pos = np . expand_dims ( self . _pos , axis = 0 ) else : arr = np . fromiter ( itertools . chain . from_iterable ( particle . pos for particle in self . particles ( ) ) , dtype = float ) pos = arr . reshape ( ( - 1 , 3 ) ) return pos
def bind_column ( model , name , column , force = False , recursive = False , copy = False ) -> Column : """Bind a column to the model with the given name . This method is primarily used during BaseModel . _ _ init _ subclass _ _ , although it can be used to easily attach a new column to an existing model : ....
if not subclassof ( model , BaseModel ) : raise InvalidModel ( f"{model} is not a subclass of BaseModel" ) meta = model . Meta if copy : column = copyfn ( column ) # TODO elif column . model is not None : logger . warning ( f " Trying to rebind column bound to { column . model } " ) column . _name = name safe_r...
def memoize_nullary ( f ) : """Memoizes a function that takes no arguments . The memoization lasts only as long as we hold a reference to the returned function ."""
def func ( ) : if not hasattr ( func , 'retval' ) : func . retval = f ( ) return func . retval return func
def _bake_css ( link ) : """Takes a link element and turns it into an inline style link if applicable"""
if "href" in link . attrs and ( re . search ( "\.css$" , link [ "href" ] ) ) or ( "rel" in link . attrs and link [ "rel" ] is "stylesheet" ) or ( "type" in link . attrs and link [ "type" ] is "text/css" ) : if re . match ( "https?://" , link [ "href" ] ) : css_data = _load_url ( link [ "href" ] ) . read ( )...
def _vec_lnqmed_residuals ( self , catchments ) : """Return ln ( QMED ) model errors for a list of catchments : param catchments : List of gauged catchments : type catchments : list of : class : ` Catchment ` : return : Model errors : rtype : list of float"""
result = np . empty ( len ( catchments ) ) for index , donor in enumerate ( catchments ) : result [ index ] = self . _lnqmed_residual ( donor ) return result
def sg_get_context ( ) : r"""Get current context information Returns : tf . sg _ opt class object which contains all context information"""
global _context # merge current context res = tf . sg_opt ( ) for c in _context : res += c return res
def extract_dmg ( self , path = '.' ) : """Extract builds with . dmg extension Will only work if ` hdiutil ` is available . @ type path : @ param path :"""
dmg_fd , dmg_fn = tempfile . mkstemp ( prefix = 'fuzzfetch-' , suffix = '.dmg' ) os . close ( dmg_fd ) out_tmp = tempfile . mkdtemp ( prefix = 'fuzzfetch-' , suffix = '.tmp' ) try : _download_url ( self . artifact_url ( 'dmg' ) , dmg_fn ) if std_platform . system ( ) == 'Darwin' : LOG . info ( '.. extra...
def process_file ( f , stop_tag = DEFAULT_STOP_TAG , details = True , strict = False , debug = False ) : """Process an image file ( expects an open file object ) . This is the function that has to deal with all the arbitrary nasty bits of the EXIF standard ."""
# by default do not fake an EXIF beginning fake_exif = 0 # determine whether it ' s a JPEG or TIFF data = f . read ( 12 ) if data [ 0 : 4 ] in [ b'II*\x00' , b'MM\x00*' ] : # it ' s a TIFF file logger . debug ( "TIFF format recognized in data[0:4]" ) f . seek ( 0 ) endian = f . read ( 1 ) f . read ( 1 )...
def get_instance ( self , payload ) : """Build an instance of SyncListPermissionInstance : param dict payload : Payload response from the API : returns : twilio . rest . sync . v1 . service . sync _ list . sync _ list _ permission . SyncListPermissionInstance : rtype : twilio . rest . sync . v1 . service . sy...
return SyncListPermissionInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , list_sid = self . _solution [ 'list_sid' ] , )
def get_queryset ( self ) : """Check that the queryset is defined and call it ."""
if self . queryset is None : raise ImproperlyConfigured ( "'%s' must define 'queryset'" % self . __class__ . __name__ ) return self . queryset ( )
def render ( self , flags : Flags ) -> List [ Text ] : """Returns a list of randomly chosen outcomes for each sentence of the list ."""
return [ x . render ( flags ) for x in self . sentences ]
def get_top_level_categories ( parser , token ) : """Retrieves an alphabetical list of all the categories that have no parents . Syntax : : { % get _ top _ level _ categories [ using " app . Model " ] as categories % } Returns an list of categories [ < category > , < category > , < category , . . . ]"""
bits = token . split_contents ( ) usage = 'Usage: {%% %s [using "app.Model"] as <variable> %%}' % bits [ 0 ] if len ( bits ) == 3 : if bits [ 1 ] != 'as' : raise template . TemplateSyntaxError ( usage ) varname = bits [ 2 ] model = "categories.category" elif len ( bits ) == 5 : if bits [ 1 ] not...
def allocate_ip_for_subnet ( self , subnet_id , mac , port_id ) : """Allocates an IP from the specified subnet and creates a port"""
# Get an available IP and mark it as used before someone else does # If there ' s no IP , , log it and return an error # If we successfully get an IP , create a port with the specified MAC and device data # If port creation fails , deallocate the IP subnet = self . get_subnet ( subnet_id ) ip , mask , port_id = self . ...
def propagate_lithology_cols ( self ) : """Propagate any data from lithologies , geologic _ types , or geologic _ classes from the sites table to the samples and specimens table . In the samples / specimens tables , null or " Not Specified " values will be overwritten based on the data from their parent site ...
cols = [ 'lithologies' , 'geologic_types' , 'geologic_classes' ] # for table in [ ' specimens ' , ' samples ' ] : # convert " Not Specified " to blank # self . tables [ table ] . df . replace ( " ^ [ Nn ] ot [ Ss ] pecified " , ' ' , # regex = True , inplace = True ) self . propagate_cols ( cols , 'samples' , 'sites' )...
def drawing_end ( self ) : '''end line drawing'''
from MAVProxy . modules . mavproxy_map import mp_slipmap if self . draw_callback is None : return self . draw_callback ( self . draw_line ) self . draw_callback = None self . map . add_object ( mp_slipmap . SlipDefaultPopup ( self . default_popup , combine = True ) ) self . map . add_object ( mp_slipmap . SlipClear...
def main ( args ) : """Main program"""
( ribo_file , rna_file , transcript_name , transcriptome_fasta , read_lengths , read_offsets , output_path , html_file ) = ( args . ribo_file , args . rna_file , args . transcript_name , args . transcriptome_fasta , args . read_lengths , args . read_offsets , args . output_path , args . html_file ) # error messages ( s...
def count_sources_in_cluster ( n_src , cdict , rev_dict ) : """Make a vector of sources in each cluster Parameters n _ src : number of sources cdict : dict ( int : [ int , ] ) A dictionary of clusters . Each cluster is a source index and the list of other source in the cluster . rev _ dict : dict ( int ...
ret_val = np . zeros ( ( n_src ) , int ) for i in range ( n_src ) : try : key = rev_dict [ i ] except KeyError : key = i try : n = len ( cdict [ key ] ) except : n = 0 ret_val [ i ] = n return ret_val
def _send_command ( self , command ) : """Wrapper for self . device . send . command ( ) . If command is a list will iterate through commands until valid command ."""
try : if isinstance ( command , list ) : for cmd in command : output = self . device . send_command ( cmd ) if "% Invalid" not in output : break else : output = self . device . send_command ( command ) return self . _send_command_postprocess ( output )...
def set_distributed_assembled ( self , irn_loc , jcn_loc , a_loc ) : """Set the distributed assembled matrix . Distributed assembled matrices require setting icntl ( 18 ) ! = 0."""
self . set_distributed_assembled_rows_cols ( irn_loc , jcn_loc ) self . set_distributed_assembled_values ( a_loc )
def prepare_exclude_file ( items , base_file , chrom = None ) : """Prepare a BED file for exclusion . Excludes high depth and centromere regions which contribute to long run times and false positive structural variant calls ."""
items = shared . add_highdepth_genome_exclusion ( items ) out_file = "%s-exclude%s.bed" % ( utils . splitext_plus ( base_file ) [ 0 ] , "-%s" % chrom if chrom else "" ) if not utils . file_exists ( out_file ) and not utils . file_exists ( out_file + ".gz" ) : with shared . bedtools_tmpdir ( items [ 0 ] ) : ...
def _nodedev_event_lifecycle_cb ( conn , dev , event , detail , opaque ) : '''Node device lifecycle events handler'''
_salt_send_event ( opaque , conn , { 'nodedev' : { 'name' : dev . name ( ) } , 'event' : _get_libvirt_enum_string ( 'VIR_NODE_DEVICE_EVENT_' , event ) , 'detail' : 'unknown' # currently unused } )
def get_media_url ( self , context ) : """Checks to see whether to use the normal or the secure media source , depending on whether the current page view is being sent over SSL . The USE _ SSL setting can be used to force HTTPS ( True ) or HTTP ( False ) . NOTE : Not all backends implement SSL media . In this...
use_ssl = msettings [ 'USE_SSL' ] is_secure = use_ssl if use_ssl is not None else self . is_secure ( context ) return client . media_url ( with_ssl = True ) if is_secure else client . media_url ( )
def to_json ( self , root_id = 0 , output = { } ) : """Recursive function to dump this tree as a json blob . Parameters root _ id : Root id of the sub - tree output : Carry over output from the previous sub - trees . Returns dict : A tree in JSON format . Starts at the root node and recursively represen...
_raise_error_if_not_of_type ( root_id , [ int , long ] , "root_id" ) _numeric_param_check_range ( "root_id" , root_id , 0 , self . num_nodes - 1 ) node = self . nodes [ root_id ] output = node . to_dict ( ) if node . left_id is not None : j = node . left_id output [ 'left' ] = self . to_json ( j , output ) if n...
def socket ( self ) : '''Lazily create the socket .'''
if not hasattr ( self , '_socket' ) : # create a new one self . _socket = self . context . socket ( zmq . REQ ) if hasattr ( zmq , 'RECONNECT_IVL_MAX' ) : self . _socket . setsockopt ( zmq . RECONNECT_IVL_MAX , 5000 ) self . _set_tcp_keepalive ( ) if self . master . startswith ( 'tcp://[' ) : # ...
def FlatArrow ( line1 , line2 , c = "m" , alpha = 1 , tipSize = 1 , tipWidth = 1 ) : """Build a 2D arrow in 3D space by joining two close lines . . . hint : : | flatarrow | | flatarrow . py | _"""
if isinstance ( line1 , Actor ) : line1 = line1 . coordinates ( ) if isinstance ( line2 , Actor ) : line2 = line2 . coordinates ( ) sm1 , sm2 = np . array ( line1 [ - 1 ] ) , np . array ( line2 [ - 1 ] ) v = ( sm1 - sm2 ) / 3 * tipWidth p1 = sm1 + v p2 = sm2 - v pm1 = ( sm1 + sm2 ) / 2 pm2 = ( np . array ( line...
def splitext ( path ) : "Same as os . path . splitext ( ) but faster ."
sep = rightmost_separator ( path , os . sep ) dot = path . rfind ( '.' ) # An ext is only real if it has at least one non - digit char if dot > sep and not containsOnly ( path [ dot : ] , "0123456789." ) : return path [ : dot ] , path [ dot : ] else : return path , ""
def _get_options_for_model ( self , model , opts_class = None , ** options ) : """Returns an instance of translation options with translated fields defined for the ` ` model ` ` and inherited from superclasses ."""
if model not in self . _registry : # Create a new type for backwards compatibility . opts = type ( "%sTranslationOptions" % model . __name__ , ( opts_class or TranslationOptions , ) , options ) ( model ) # Fields for translation may be inherited from abstract # superclasses , so we need to look at all paren...
def apply_entities_as_html ( text , entities ) : """Format text as HTML . Also take care of escaping special characters . Returned value can be passed to : meth : ` . Bot . sendMessage ` with appropriate ` ` parse _ mode ` ` . : param text : plain text : param entities : a list of ` MessageEntity < http...
escapes = { '<' : '&lt;' , '>' : '&gt;' , '&' : '&amp;' , } formatters = { 'bold' : lambda s , e : '<b>' + s + '</b>' , 'italic' : lambda s , e : '<i>' + s + '</i>' , 'text_link' : lambda s , e : '<a href="' + e [ 'url' ] + '">' + s + '</a>' , 'text_mention' : lambda s , e : '<a href="tg://user?id=' + str ( e [ 'user' ...
def with_ ( contextmanager , do ) : """Emulate a ` with ` ` statement , performing an operation within context . : param contextmanager : Context manager to use for ` ` with ` ` statement : param do : Operation to perform : callable that receives the ` ` as ` ` value : return : Result of the operation Examp...
ensure_contextmanager ( contextmanager ) ensure_callable ( do ) with contextmanager as value : return do ( value )
def warning ( self , msg , * args , ** kwargs ) : """Log ' msg % args ' with the warning severity level"""
self . _log ( "WARNING" , msg , args , kwargs )
def fit ( self , X , y = None ) : """X : data matrix , ( n x d ) y : unused"""
X = self . _prepare_inputs ( X , ensure_min_samples = 2 ) M = np . cov ( X , rowvar = False ) if M . ndim == 0 : M = 1. / M else : M = np . linalg . inv ( M ) self . transformer_ = transformer_from_metric ( np . atleast_2d ( M ) ) return self
def _remove_trailing_spaces ( text : str ) -> str : """Remove trailing spaces and tabs : param text : Text to clean up : return :"""
clean_text = str ( ) for line in text . splitlines ( True ) : # remove trailing spaces ( 0x20 ) and tabs ( 0x09) clean_text += line . rstrip ( "\x09\x20" ) return clean_text
def _write_training_metrics ( self ) : """Write all CSV metrics : return :"""
for brain_name in self . trainers . keys ( ) : if brain_name in self . trainer_metrics : self . trainers [ brain_name ] . write_training_metrics ( )
def check_stripe_api_key ( app_configs = None , ** kwargs ) : """Check the user has configured API live / test keys correctly ."""
from . import settings as djstripe_settings messages = [ ] if not djstripe_settings . STRIPE_SECRET_KEY : msg = "Could not find a Stripe API key." hint = "Add STRIPE_TEST_SECRET_KEY and STRIPE_LIVE_SECRET_KEY to your settings." messages . append ( checks . Critical ( msg , hint = hint , id = "djstripe.C001"...
def fit_transform ( self , X , y = None ) : """Fit the imputer and then transform input ` X ` Note : all imputations should have a ` fit _ transform ` method , but only some ( like IterativeImputer ) also support inductive mode using ` fit ` or ` fit _ transform ` on ` X _ train ` and then ` transform ` on ...
X_original , missing_mask = self . prepare_input_data ( X ) observed_mask = ~ missing_mask X = X_original . copy ( ) if self . normalizer is not None : X = self . normalizer . fit_transform ( X ) X_filled = self . fill ( X , missing_mask , inplace = True ) if not isinstance ( X_filled , np . ndarray ) : raise T...
def create_alert_policy ( self , policy_name ) : """Creates an alert policy in NewRelic"""
policy_data = { 'policy' : { 'incident_preference' : 'PER_POLICY' , 'name' : policy_name } } create_policy = requests . post ( 'https://api.newrelic.com/v2/alerts_policies.json' , headers = self . auth_header , data = json . dumps ( policy_data ) ) create_policy . raise_for_status ( ) policy_id = create_policy . json (...
def convert_tree ( self , element1 , element2 = None ) : '''convert _ tree High - level api : Convert cxml tree to an internal schema tree . This method is recursive . Parameters element1 : ` Element ` The node to be converted . element2 : ` Element ` A new node being constructed . Returns Element...
if element2 is None : attributes = deepcopy ( element1 . attrib ) tag = attributes [ 'name' ] del attributes [ 'name' ] element2 = etree . Element ( tag , attributes ) for e1 in element1 . findall ( 'node' ) : attributes = deepcopy ( e1 . attrib ) tag = self . prefix_to_url ( attributes [ 'name'...
def get_trips ( self , timestamp , start , via , destination , departure = True , prev_advices = 1 , next_advices = 1 ) : """Fetch trip possibilities for these parameters http : / / webservices . ns . nl / ns - api - treinplanner ? < parameters > fromStation toStation dateTime : 2012-02-21T15:50 departure...
timezonestring = '+0100' if is_dst ( 'Europe/Amsterdam' ) : timezonestring = '+0200' url = 'http://webservices.ns.nl/ns-api-treinplanner?' url = url + 'fromStation=' + start url = url + '&toStation=' + destination if via : url = url + '&via=' + via if len ( timestamp ) == 5 : # Format of HH : MM - api needs yyy...
def refresh ( self ) : """Refresh the server and it ' s child objects . This method removes all the cache information in the server and it ' s child objects , and fetches the information again from the server using hpssacli / ssacli command . : raises : HPSSAOperationError , if hpssacli / ssacli operation f...
config = self . _get_all_details ( ) raid_info = _convert_to_dict ( config ) self . controllers = [ ] for key , value in raid_info . items ( ) : self . controllers . append ( Controller ( key , value , self ) ) self . last_updated = time . time ( )
def enrich_relations ( rdf , enrich_mappings , use_narrower , use_transitive ) : """Enrich the SKOS relations according to SKOS semantics , including subproperties of broader and symmetric related properties . If use _ narrower is True , include inverse narrower relations for all broader relations . If use _ ...
# 1 . first enrich mapping relationships ( because they affect regular ones ) if enrich_mappings : infer . skos_symmetric_mappings ( rdf ) infer . skos_hierarchical_mappings ( rdf , use_narrower ) # 2 . then enrich regular relationships # related < - > related infer . skos_related ( rdf ) # broaderGeneric - > b...