signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _set_access_mac_vlan_classification ( self , v , load = False ) : """Setter method for access _ mac _ vlan _ classification , mapped from YANG variable / interface / ethernet / switchport / access _ mac _ vlan _ classification ( container ) If this variable is read - only ( config : false ) in the source YA...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = access_mac_vlan_classification . access_mac_vlan_classification , is_container = 'container' , presence = False , yang_name = "access-mac-vlan-classification" , rest_name = "access-mac-vlan-classification" , parent = self , p...
def replace_unicode ( cls , replacement_string ) : """This method will iterate over every character in ` ` replacement _ string ` ` and see if it mathces any of the unicode codepoints that we recognize . If it does then it will replace that codepoint with an image just like ` ` replace ` ` . NOTE : This wil...
e = cls ( ) output = [ ] surrogate_character = None if settings . EMOJI_REPLACE_HTML_ENTITIES : replacement_string = cls . replace_html_entities ( replacement_string ) for i , character in enumerate ( replacement_string ) : if character in cls . _unicode_modifiers : continue # Check whether this is ...
def _sample_conditional ( Xnew , feat , kern , f , * , full_cov = False , full_output_cov = False , q_sqrt = None , white = False , num_samples = None ) : """` sample _ conditional ` will return a sample from the conditinoal distribution . In most cases this means calculating the conditional mean m and variance v...
logger . debug ( "sample conditional: (MixedKernelSharedMof, MixedKernelSeparateMof), SeparateMixedMok" ) if full_cov : raise NotImplementedError ( "full_cov not yet implemented" ) if full_output_cov : raise NotImplementedError ( "full_output_cov not yet implemented" ) independent_cond = conditional . dispatch ...
def get ( self , key ) : """because memcached does not provide a function to check if a key is existed so here is a heck way , if the value is None , then raise Exception"""
if isinstance ( key , unicode ) : key = key . encode ( 'utf-8' ) v = self . client . get ( key ) if v is None : raise KeyError ( "Cache key [%s] not found" % key ) else : return v
def grouping_delta ( old , new , pure = True ) : r"""Finds what happened to the old groups to form the new groups . Args : old ( set of frozensets ) : old grouping new ( set of frozensets ) : new grouping pure ( bool ) : hybrids are separated from pure merges and splits if pure is True , otherwise hybrid ...
import utool as ut _old = { frozenset ( _group ) for _group in old } _new = { frozenset ( _group ) for _group in new } _new_items = set ( ut . flatten ( _new ) ) _old_items = set ( ut . flatten ( _old ) ) assert _new_items == _old_items , 'new and old sets must be the same' # Find the groups that are exactly the same u...
def quit ( self , message = None ) : """Quit from the server ."""
if message is None : message = 'Quit' if self . connected : self . send ( 'QUIT' , params = [ message ] )
def findAttr ( self , svgNode , name ) : """Search an attribute with some name in some node or above . First the node is searched , then its style attribute , then the search continues in the node ' s parent node . If no such attribute is found , ' ' is returned ."""
# This needs also to lookup values like " url ( # SomeName ) " . . . if self . css_rules is not None and not svgNode . attrib . get ( '__rules_applied' , False ) : if isinstance ( svgNode , NodeTracker ) : svgNode . apply_rules ( self . css_rules ) else : ElementWrapper ( svgNode ) . apply_rules...
def construct_payload ( self , registration_ids , data = None , collapse_key = None , delay_while_idle = False , time_to_live = None , is_json = True , dry_run = False ) : """Construct the dictionary mapping of parameters . Encodes the dictionary into JSON if for json requests . Helps appending ' data . ' prefi...
if time_to_live : if not ( 0 <= time_to_live <= self . GCM_TTL ) : raise GCMInvalidTtlException ( "Invalid time to live value" ) payload = { } if is_json : payload [ 'registration_ids' ] = registration_ids if data : payload [ 'data' ] = data else : payload [ 'registration_id' ] = registr...
def to_json ( self ) : """Returns an input shard state for the remaining inputs . Returns : A json - izable version of the remaining InputReader ."""
return { self . BLOB_KEY_PARAM : self . _blob_key , self . START_FILE_INDEX_PARAM : self . _start_file_index , self . END_FILE_INDEX_PARAM : self . _end_file_index , self . OFFSET_PARAM : self . _next_offset ( ) }
def get_marker_size ( self ) : """Gets the size of a message marker . : return : QSize"""
h = self . get_marker_height ( ) if h < 1 : h = 1 return QtCore . QSize ( self . sizeHint ( ) . width ( ) / 2 , h )
def __send_run ( self ) : """Send request thread"""
while not self . __end . is_set ( ) : try : with Connection ( userid = self . __prefix + self . __epid , password = self . __passwd , virtual_host = self . __vhost , heartbeat = self . __heartbeat , connect_timeout = self . __socket_timeout , operation_timeout = self . __socket_timeout , ssl = self . __get_...
def dump ( self , fields = None , exclude = None ) : """Dump current object to dict , but the value is string for manytomany fields will not automatically be dumpped , only when they are given in fields parameter"""
exclude = exclude or [ ] d = { } if fields and self . _primary_field not in fields : fields = list ( fields ) fields . append ( self . _primary_field ) for k , v in self . properties . items ( ) : if ( ( not fields ) or ( k in fields ) ) and ( not exclude or ( k not in exclude ) ) : if not isinstanc...
def unmount_medium ( self , name , controller_port , device , force ) : """Unmounts any currently mounted medium ( : py : class : ` IMedium ` , identified by the given UUID @ a id ) to the given storage controller ( : py : class : ` IStorageController ` , identified by @ a name ) , at the indicated port and d...
if not isinstance ( name , basestring ) : raise TypeError ( "name can only be an instance of type basestring" ) if not isinstance ( controller_port , baseinteger ) : raise TypeError ( "controller_port can only be an instance of type baseinteger" ) if not isinstance ( device , baseinteger ) : raise TypeError...
def update_variant_by_id ( cls , variant_id , variant , ** kwargs ) : """Update Variant Update attributes of Variant This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . update _ variant _ by _ id ( variant _ id , vari...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _update_variant_by_id_with_http_info ( variant_id , variant , ** kwargs ) else : ( data ) = cls . _update_variant_by_id_with_http_info ( variant_id , variant , ** kwargs ) return data
def scp_get ( remote_path , local_path = '' , recursive = False , preserve_times = False , ** kwargs ) : '''. . versionadded : : 2019.2.0 Transfer files and directories from remote network device to the localhost of the Minion . . . note : : This function is only available only when the underlying library ...
conn_args = netmiko_args ( ** kwargs ) conn_args [ 'hostname' ] = conn_args [ 'host' ] kwargs . update ( conn_args ) return __salt__ [ 'scp.get' ] ( remote_path , local_path = local_path , recursive = recursive , preserve_times = preserve_times , ** kwargs )
def _process_comparison_filter_directive ( filter_operation_info , location , context , parameters , operator = None ) : """Return a Filter basic block that performs the given comparison against the property field . Args : filter _ operation _ info : FilterOperationInfo object , containing the directive and fie...
comparison_operators = { u'=' , u'!=' , u'>' , u'<' , u'>=' , u'<=' } if operator not in comparison_operators : raise AssertionError ( u'Expected a valid comparison operator ({}), but got ' u'{}' . format ( comparison_operators , operator ) ) filtered_field_type = filter_operation_info . field_type filtered_field_n...
def getPeopleTags ( self ) : """Return a sequence of tags which have been applied to L { Person } items . @ rtype : C { set }"""
query = self . store . query ( Tag , Tag . object == Person . storeID ) return set ( query . getColumn ( 'name' ) . distinct ( ) )
def dense_relu_dense ( inputs , filter_size , output_size , output_activation = None , dropout = 0.0 , dropout_broadcast_dims = None , layer_collection = None , name = None ) : """Hidden layer with RELU activation followed by linear projection ."""
# layer _ name is appended with " conv1 " or " conv2 " in this method only for # historical reasons . These are in fact dense layers . layer_name = "%s_{}" % name if name else "{}" h = dense ( inputs , filter_size , use_bias = True , activation = tf . nn . relu , layer_collection = layer_collection , name = layer_name ...
def sub_base_uri ( self ) : """This will return the sub _ base _ uri parsed from the base _ uri : return : str of the sub _ base _ uri"""
return self . base_uri and self . base_uri . split ( '://' ) [ - 1 ] . split ( '.' ) [ 0 ] or self . base_uri
def g_voigt ( self ) : """returns the G _ v shear modulus"""
return ( 2. * self . voigt [ : 3 , : 3 ] . trace ( ) - np . triu ( self . voigt [ : 3 , : 3 ] ) . sum ( ) + 3 * self . voigt [ 3 : , 3 : ] . trace ( ) ) / 15.
def get_var_data ( self , fmt = None ) : ''': param dict fmt : Format expected by the DAP ( keys : ' hex ' : bool , ' rawString ' : bool )'''
safe_repr = SafeRepr ( ) if fmt is not None : safe_repr . convert_to_hex = fmt . get ( 'hex' , False ) safe_repr . raw_value = fmt . get ( 'rawString' , False ) type_name , _type_qualifier , _is_exception_on_eval , resolver , value = get_variable_details ( self . value , to_string = safe_repr ) is_raw_string = ...
def set_wait ( self , wait ) : """set the waiting time . : Parameters : # . wait ( number ) : The time delay between each attempt to lock . By default it ' s set to 0 to keeping the aquiring mechanism trying to acquire the lock without losing any time waiting . Setting wait to a higher value suchs as 0.05 s...
try : wait = float ( wait ) assert wait >= 0 except : raise Exception ( 'wait must be a positive number' ) self . __wait = wait
def inline ( self ) -> str : """Return an inline string of the Identity : return :"""
return "{pubkey}:{signature}:{timestamp}:{uid}" . format ( pubkey = self . pubkey , signature = self . signatures [ 0 ] , timestamp = self . timestamp , uid = self . uid )
def getParameters ( self , phoneNumber ) : """Return a C { list } of two liveform parameters , one for editing C { phoneNumber } ' s I { number } attribute , and one for editing its I { label } attribute . @ type phoneNumber : L { PhoneNumber } or C { NoneType } @ param phoneNumber : If not C { None } , an ...
defaultNumber = u'' defaultLabel = PhoneNumber . LABELS . HOME if phoneNumber is not None : defaultNumber = phoneNumber . number defaultLabel = phoneNumber . label labelChoiceParameter = liveform . ChoiceParameter ( 'label' , [ liveform . Option ( label , label , label == defaultLabel ) for label in PhoneNumber...
def _subtractSky ( image , skyValue , memmap = False ) : """subtract the given sky value from each the data array that has been passed . image is a fits object that contains the data and header for one image extension"""
try : np . subtract ( image . data , skyValue , image . data ) except IOError : print ( "Unable to perform sky subtraction on data array" ) raise IOError
async def widget ( self ) : """| coro | Returns the widget of the guild . . . note : : The guild must have the widget enabled to get this information . Raises Forbidden The widget for this guild is disabled . HTTPException Retrieving the widget failed . Returns : class : ` Widget ` The guild '...
data = await self . _state . http . get_widget ( self . id ) return Widget ( state = self . _state , data = data )
def database_names ( self , session = None ) : """* * DEPRECATED * * : Get a list of the names of all databases on the connected server . : Parameters : - ` session ` ( optional ) : a : class : ` ~ pymongo . client _ session . ClientSession ` . . . versionchanged : : 3.7 Deprecated . Use : meth : ` list...
warnings . warn ( "database_names is deprecated. Use list_database_names " "instead." , DeprecationWarning , stacklevel = 2 ) return self . list_database_names ( session )
def init ( self ) : """Init the connection to the OpenTSDB server ."""
if not self . export_enable : return None try : db = potsdb . Client ( self . host , port = int ( self . port ) , check_host = True ) except Exception as e : logger . critical ( "Cannot connect to OpenTSDB server %s:%s (%s)" % ( self . host , self . port , e ) ) sys . exit ( 2 ) return db
def prebuild_arch ( self , arch ) : '''Run any pre - build tasks for the Recipe . By default , this checks if any prebuild _ archname methods exist for the archname of the current architecture , and runs them if so .'''
prebuild = "prebuild_{}" . format ( arch . arch . replace ( '-' , '_' ) ) if hasattr ( self , prebuild ) : getattr ( self , prebuild ) ( ) else : info ( '{} has no {}, skipping' . format ( self . name , prebuild ) )
def get_kwargs ( self , ** kwargs ) : """If : meth : ` detect ` returned : data : ` True ` , plan for the module ' s execution , including granting access to or delivering any files to it that are known to be absent , and finally return a dict : : # Name of the class from runners . py that implements the # ...
new = dict ( ( mitogen . core . UnicodeType ( k ) , kwargs [ k ] ) for k in kwargs ) new . setdefault ( 'good_temp_dir' , self . _inv . connection . get_good_temp_dir ( ) ) new . setdefault ( 'cwd' , self . _inv . connection . get_default_cwd ( ) ) new . setdefault ( 'extra_env' , self . _inv . connection . get_default...
def fromFile ( cls , filename ) : """From File Loads a JSON file and creates a Node instance from it Args : filename ( str ) : The filename to load Returns : _ NodeInterface"""
# Load the file oFile = open ( filename ) # Convert it to a dictionary dDetails = JSON . decodef ( oFile ) # Create and return the new instance return cls ( dDetails )
def _subscribe ( self ) : """Start the subscription to the channel list . If self . _ keep _ alive _ function isn ' t None start timer thread to run self . _ keep _ alive _ function every self . _ keep _ alive amount of seconds ."""
_LOGGER . info ( "PubNub subscribing" ) self . _pubnub . subscribe ( ) . channels ( CHANNELS ) . execute ( ) if self . _keep_alive_function is not None : threading . Timer ( self . _keep_alive , self . _run_keep_alive ) . start ( ) self . _subscribed = True
def _read_atlas_zonefile ( zonefile_path , zonefile_hash ) : """Read and verify an atlas zone file"""
with open ( zonefile_path , "rb" ) as f : data = f . read ( ) # sanity check if zonefile_hash is not None : if not verify_zonefile ( data , zonefile_hash ) : log . debug ( "Corrupt zonefile '%s'" % zonefile_hash ) return None return data
def get_mongo_cursor ( self , bulk = False ) : """Returns Mongo cursor using the class variables : param bulk : bulk writer option : type bulk : boolean : return : mongo collection for which cursor will be created : rtype : mongo colection object"""
try : if self . host : if self . port : client = MongoClient ( self . host , self . port ) else : client = MongoClient ( self . host , MongoCollection . DEFAULT_PORT ) else : client = MongoClient ( self . mongo_uri ) db = client [ self . db_name ] cursor =...
def yield_connections ( sock ) : """Run a server on the specified socket ."""
while True : log . debug ( 'waiting for connection on %s' , sock . getsockname ( ) ) try : conn , _ = sock . accept ( ) except KeyboardInterrupt : return conn . settimeout ( None ) log . debug ( 'accepted connection on %s' , sock . getsockname ( ) ) yield conn
def compile ( self , mod_y , ref_y , regterm = None ) : """Compute the loss function tensor . Parameters mode _ y : tf . Tensor model output tensor ref _ y : tf . Tensor reference input tensor regterm : tf . Tensor , optional ( default = None ) Regularization term tensor Returns Loss function tens...
with tf . name_scope ( self . name ) : if self . lfunc == 'cross_entropy' : clip_inf = tf . clip_by_value ( mod_y , 1e-10 , float ( 'inf' ) ) clip_sup = tf . clip_by_value ( 1 - mod_y , 1e-10 , float ( 'inf' ) ) cost = - tf . reduce_mean ( tf . add ( tf . multiply ( ref_y , tf . log ( clip_i...
def parse ( name ) : """Return dict of parts forming ` name ` . Raise ` ValueError ` if string ` name ` cannot be correctly parsed . The default implementation uses ` NodeNamingPolicy . _ NODE _ NAME _ RE ` to parse the name back into constituent parts . This is ideally the inverse of : meth : ` format ` ...
match = NodeNamingPolicy . _NODE_NAME_RE . match ( name ) if match : return match . groupdict ( ) else : raise ValueError ( "Cannot parse node name `{name}`" . format ( name = name ) )
def set_phases ( self , literals = [ ] ) : """Sets polarities of a given list of variables ."""
if self . minicard : pysolvers . minicard_setphases ( self . minicard , literals )
def _append_path ( new_path ) : # type : ( str ) - > None """Given a path string , append it to sys . path"""
for path in sys . path : path = os . path . abspath ( path ) if new_path == path : return sys . path . append ( new_path )
def client ( self , service_name , version , component , ** kw ) : """Safely initialize a repository class to a property . Args : repository _ class ( class ) : The class to initialize . version ( str ) : The gcp service version for the repository . Returns : object : An instance of repository _ class .""...
service = _create_service_api ( self . _credentials , service_name , version , kw . get ( 'developer_key' ) , kw . get ( 'cache_discovery' , False ) , self . _http or _build_http ( ) ) return ServiceClient ( gcp_service = service , component = component , credentials = self . _credentials , rate_limiter = self . _rate_...
def _convert_to_degress ( self , value ) : """Helper function to convert the GPS coordinates stored in the EXIF to degress in float format"""
d0 = value [ 0 ] [ 0 ] d1 = value [ 0 ] [ 1 ] d = float ( d0 ) / float ( d1 ) m0 = value [ 1 ] [ 0 ] m1 = value [ 1 ] [ 1 ] m = float ( m0 ) / float ( m1 ) s0 = value [ 2 ] [ 0 ] s1 = value [ 2 ] [ 1 ] s = float ( s0 ) / float ( s1 ) return d + ( m / 60.0 ) + ( s / 3600.0 )
def _combine_rest_push ( self ) : """Combining Rest and Push States"""
new = [ ] change = 0 # DEBUG # logging . debug ( ' Combining Rest and Push ' ) i = 0 examinetypes = self . quickresponse_types [ 3 ] for state in examinetypes : if state . type == 3 : for nextstate_id in state . trans . keys ( ) : found = 0 # if nextstate _ id ! = state . id : ...
def create ( self , params = None , headers = None ) : """Create a creditor bank account . Creates a new creditor bank account object . Args : params ( dict , optional ) : Request body . Returns : ListResponse of CreditorBankAccount instances"""
path = '/creditor_bank_accounts' if params is not None : params = { self . _envelope_key ( ) : params } try : response = self . _perform_request ( 'POST' , path , params , headers , retry_failures = True ) except errors . IdempotentCreationConflictError as err : return self . get ( identity = err . conflict...
def _check_copy_for ( self ) : """Check the value of copy _ for and make appropriate copies ."""
if not self . _bundle : return # read the following at your own risk - I just wrote it and it still # confuses me and baffles me that it works for param in self . to_list ( ) : if param . copy_for : # copy _ for tells us how to filter and what set of attributes # needs a copy of this parameter # copy _ ...
def is_uniform ( self , verbose = True ) : """Check to make sure phenotype calls , or scored calls are consistent across all images / samples"""
uni = pd . Series ( self [ 'phenotype_calls' ] . apply ( lambda x : json . dumps ( x ) ) . unique ( ) ) . apply ( lambda x : json . loads ( x ) ) . apply ( lambda x : tuple ( sorted ( x . keys ( ) ) ) ) . unique ( ) if len ( uni ) > 1 : if verbose : sys . stderr . write ( "WARNING: phenotypes differ across ...
def search ( table , * args , ** kwargs ) : """Perform a regular expression search , returning rows that match a given pattern , either anywhere in the row or within a specific field . E . g . : : > > > import petl as etl > > > table1 = [ [ ' foo ' , ' bar ' , ' baz ' ] , . . . [ ' orange ' , 12 , ' oranges...
if len ( args ) == 1 : field = None pattern = args [ 0 ] elif len ( args ) == 2 : field = args [ 0 ] pattern = args [ 1 ] else : raise ArgumentError ( 'expected 1 or 2 positional arguments' ) return SearchView ( table , pattern , field = field , ** kwargs )
def convex_decomposition ( self , maxhulls = 20 , ** kwargs ) : """Compute an approximate convex decomposition of a mesh . testVHACD Parameters which can be passed as kwargs : Name Default resolution 100000 max . concavity 0.001 plane down - sampling 4 convex - hull down - sampling 4 alpha 0.05 beta...
result = decomposition . convex_decomposition ( self , maxhulls = maxhulls , ** kwargs ) return result
def s3_read ( source , profile_name = None ) : """Read a file from an S3 source . Parameters source : str Path starting with s3 : / / , e . g . ' s3 : / / bucket - name / key / foo . bar ' profile _ name : str , optional AWS profile Returns content : bytes Raises botocore . exceptions . NoCredenti...
session = boto3 . Session ( profile_name = profile_name ) s3 = session . client ( 's3' ) bucket_name , key = _s3_path_split ( source ) s3_object = s3 . get_object ( Bucket = bucket_name , Key = key ) body = s3_object [ 'Body' ] return body . read ( )
def getEdges ( self , fromVol ) : """Return the edges available from fromVol ."""
if fromVol is None : for toVol in self . paths : yield Store . Diff ( self , toVol , fromVol , toVol . size ) return if fromVol not in self . paths : return fromBVol = self . butterVolumes [ fromVol . uuid ] parentUUID = fromBVol . parent_uuid butterDir = os . path . dirname ( fromBVol . fullPath ) ...
def write ( self , file , text , subvars = { } , trim_leading_lf = True ) : '''write to a file with variable substitution'''
file . write ( self . substitute ( text , subvars = subvars , trim_leading_lf = trim_leading_lf ) )
def CheckPermissions ( self , username , subject ) : """Checks if a given user has access to a given subject ."""
if subject in self . authorized_users : return ( ( username in self . authorized_users [ subject ] ) or self . group_access_manager . MemberOfAuthorizedGroup ( username , subject ) ) # In case the subject is not found , the safest thing to do is to raise . # It ' s up to the users of this class to handle this excep...
def send ( message , asynchronous = False , ip_pool = None , send_at = None , api_url = None , api_version = None , api_key = None , ** kwargs ) : '''Send out the email using the details from the ` ` message ` ` argument . message The information on the message to send . This argument must be sent as dictiona...
if 'async' in kwargs : # Remove this in Sodium salt . utils . versions . warn_until ( 'Sodium' , 'Parameter "async" is renamed to "asynchronous" ' 'and will be removed in version {version}.' ) asynchronous = bool ( kwargs [ 'async' ] ) params = _get_api_params ( api_url = api_url , api_version = api_version , a...
def join_topics ( self , member_id , topics ) : '''a method to add topics to member profile details on meetup : param member _ id : integer with member id from member profile : param topics : list of integer meetup ids for topics : return : dictionary with list of topic details inside [ json ] key topic _ d...
# https : / / www . meetup . com / meetup _ api / docs / members / : member _ id / # edit title = '%s.join_topics' % self . __class__ . __name__ # validate permissions if not 'profile_edit' in self . service_scope : raise ValueError ( '%s requires group_join as part of oauth2 service_scope permissions.' % title ) #...
def append ( self , future ) : """Append a future to the queue ."""
if future . _ended ( ) and future . index is None : self . inprogress . add ( future ) elif future . _ended ( ) and future . index is not None : self . ready . append ( future ) elif future . greenlet is not None : self . inprogress . add ( future ) else : self . movable . append ( future ) # Send t...
def encode_utf8 ( s , f ) : """UTF - 8 encodes string ` s ` to file - like object ` f ` according to the MQTT Version 3.1.1 specification in section 1.5.3. The maximum length for the encoded string is 2 * * 16-1 ( 65535 ) bytes . An assertion error will result if the encoded string is longer . Parameters ...
encode = codecs . getencoder ( 'utf8' ) encoded_str_bytes , num_encoded_chars = encode ( s ) num_encoded_str_bytes = len ( encoded_str_bytes ) assert 0 <= num_encoded_str_bytes <= 2 ** 16 - 1 num_encoded_bytes = num_encoded_str_bytes + 2 f . write ( FIELD_U8 . pack ( ( num_encoded_str_bytes & 0xff00 ) >> 8 ) ) f . writ...
def validate ( self , input_data , path_to_root = '' , object_title = '' ) : '''a core method for validating input against the model input _ data is only returned if all data is valid : param input _ data : list , dict , string , number , or boolean to validate : param path _ to _ root : [ optional ] string w...
__name__ = '%s.validate' % self . __class__ . __name__ _path_arg = '%s(path_to_root="...")' % __name__ _title_arg = '%s(object_title="...")' % __name__ # validate input copy_path = path_to_root if path_to_root : if not isinstance ( path_to_root , str ) : raise ModelValidationError ( '%s must be a string.' %...
def _is_used_deprecated ( self ) : '''Returns True , if a component configuration explicitly is asking to use an old version of the deprecated function . : return :'''
func_path = "{m_name}.{f_name}" . format ( m_name = self . _globals . get ( self . MODULE_NAME , '' ) or self . _globals [ '__name__' ] . split ( '.' ) [ - 1 ] , f_name = self . _orig_f_name ) return func_path in self . _globals . get ( '__opts__' ) . get ( self . CFG_USE_DEPRECATED , list ( ) ) or func_path in self . ...
def init ( name , config = None , cpuset = None , cpushare = None , memory = None , profile = None , network_profile = None , nic_opts = None , cpu = None , autostart = True , password = None , password_encrypted = None , users = None , dnsservers = None , searchdomains = None , bridge = None , gateway = None , pub_key...
ret = { 'name' : name , 'changes' : { } } profile = get_container_profile ( copy . deepcopy ( profile ) ) if not network_profile : network_profile = profile . get ( 'network_profile' ) if not network_profile : network_profile = DEFAULT_NIC # Changes is a pointer to changes _ dict [ ' init ' ] . This method is u...
def addResourceFile ( self , pid , resource_file , resource_filename = None , progress_callback = None ) : """Add a new file to an existing resource : param pid : The HydroShare ID of the resource : param resource _ file : a read - only binary file - like object ( i . e . opened with the flag ' rb ' ) or a stri...
url = "{url_base}/resource/{pid}/files/" . format ( url_base = self . url_base , pid = pid ) params = { } close_fd = self . _prepareFileForUpload ( params , resource_file , resource_filename ) encoder = MultipartEncoder ( params ) if progress_callback is None : progress_callback = default_progress_callback monitor ...
def _read ( self ) : """Actually read the response and parse it , returning a Response ."""
with sw ( "read_response" ) : with catch_websocket_connection_errors ( ) : response_str = self . _sock . recv ( ) if not response_str : raise ProtocolError ( "Got an empty response from SC2." ) response = sc_pb . Response ( ) with sw ( "parse_response" ) : response . ParseFromString ( response_str )...
def get_strategy ( name_or_cls ) : """Return the strategy identified by its name . If ` ` name _ or _ class ` ` is a class , it will be simply returned ."""
if isinstance ( name_or_cls , six . string_types ) : if name_or_cls not in STRATS : raise MutationError ( "strat is not defined" ) return STRATS [ name_or_cls ] ( ) return name_or_cls ( )
def mann_whitney ( a_distribution , b_distribution , use_continuity = True ) : """Returns ( u , p _ value )"""
MINIMUM_VALUES = 20 all_values = sorted ( set ( a_distribution ) | set ( b_distribution ) ) count_so_far = 0 a_rank_sum = 0 b_rank_sum = 0 a_count = 0 b_count = 0 variance_adjustment = 0 for v in all_values : a_for_value = a_distribution . get ( v , 0 ) b_for_value = b_distribution . get ( v , 0 ) total_for...
def set_plugin_directories ( self , paths , except_blacklisted = True ) : """Sets the plugin directories to ` directories ` . This will delete the previous state stored in ` self . plugin _ directories ` in favor of the ` directories ` passed in . ` directories ` may be either a single object or an iterable ....
self . directory_manager . set_directories ( paths , except_blacklisted )
def process_args ( ) : """Parse command - line arguments ."""
parser = argparse . ArgumentParser ( ) parser . add_argument ( '-I' , type = str , metavar = '<Include directory>' , action = 'append' , help = 'Directory to be searched for included files' ) parser . add_argument ( 'lems_file' , type = str , metavar = '<LEMS file>' , help = 'LEMS file to be simulated' ) parser . add_a...
def render_page ( path ) : """Internal interface to the page view . : param path : Page path . : returns : The rendered template ."""
try : page = Page . get_by_url ( request . path ) except NoResultFound : abort ( 404 ) return render_template ( [ page . template_name , current_app . config [ 'PAGES_DEFAULT_TEMPLATE' ] ] , page = page )
def range_r ( self ) : """Current interpolation range of radius"""
return self . radius - self . dr , self . radius + self . dr
def edges ( inputtiles , parsenames ) : """For a stream of [ < x > , < y > , < z > ] tiles , return only those tiles that are on the edge ."""
try : inputtiles = click . open_file ( inputtiles ) . readlines ( ) except IOError : inputtiles = [ inputtiles ] # parse the input stream into an array tiles = edge_finder . findedges ( inputtiles , parsenames ) for t in tiles : click . echo ( t . tolist ( ) )
def create ( cls , elements , role , domain = None ) : """Create a permission . : param list granted _ elements : Elements for this permission . Can be engines , policies or ACLs : type granted _ elements : list ( str , Element ) : param str , Role role : role for this permission : param str , Element dom...
if not domain : domain = AdminDomain ( 'Shared Domain' ) return Permission ( granted_elements = elements , role_ref = role , granted_domain_ref = domain )
def insert_many ( self , table_name , records , attr_names = None ) : """Send an INSERT query with multiple records to the database . : param str table : Table name of executing the query . : param records : Records to be inserted . : type records : list of | dict | / | namedtuple | / | list | / | tuple | :...
self . validate_access_permission ( [ "w" , "a" ] ) self . verify_table_existence ( table_name ) if attr_names : logger . debug ( "insert {number} records into {table}({attrs})" . format ( number = len ( records ) if records else 0 , table = table_name , attrs = attr_names ) ) else : logger . debug ( "insert {n...
def _get_variant_regions ( items ) : """Retrieve variant regions defined in any of the input items ."""
return list ( filter ( lambda x : x is not None , [ tz . get_in ( ( "config" , "algorithm" , "variant_regions" ) , data ) for data in items if tz . get_in ( [ "config" , "algorithm" , "coverage_interval" ] , data ) != "genome" ] ) )
def show_item_top_border ( self , item_text , flag ) : """Sets a flag that will show a top border for an item with the specified text . : param item _ text : the text property of the item : param flag : boolean specifying if the border should be shown ."""
if flag : self . __top_border_dict [ item_text ] = True else : self . __top_border_dict . pop ( item_text , None )
def get_long_description ( ) : """Return this projects description ."""
with open ( "README.rst" , "r" ) as f : readme = f . read ( ) with open ( "CHANGELOG.rst" , "r" ) as f : changelog = f . read ( ) changelog = changelog . replace ( "\nUnreleased\n------------------" , "" ) return "\n" . join ( [ readme , changelog ] )
def _escape ( value ) : """Escape a string ( key or value ) for InfluxDB ' s line protocol . : param str | int | float | bool value : The value to be escaped : rtype : str"""
value = str ( value ) for char , escaped in { ' ' : '\ ' , ',' : '\,' , '"' : '\"' } . items ( ) : value = value . replace ( char , escaped ) return value
def eval ( self , expr , lineno = 0 , show_errors = True ) : """Evaluate a single statement ."""
self . lineno = lineno self . error = [ ] self . start_time = time . time ( ) try : node = self . parse ( expr ) except : errmsg = exc_info ( ) [ 1 ] if len ( self . error ) > 0 : errmsg = "\n" . join ( self . error [ 0 ] . get_error ( ) ) if not show_errors : try : exc = sel...
def count_jobs_to_dequeue ( self ) : """Returns the number of jobs that can be dequeued right now from the queue ."""
# timed ZSET if self . is_timed : return context . connections . redis . zcount ( self . redis_key , "-inf" , time . time ( ) ) # In all other cases , it ' s the same as . size ( ) else : return self . size ( )
def get ( dataset = None , include_metadata = False , mnemonics = None , ** dim_values ) : """Use this function to get data from Knoema dataset ."""
if not dataset and not mnemonics : raise ValueError ( 'Dataset id is not specified' ) if mnemonics and dim_values : raise ValueError ( 'The function does not support specifying mnemonics and selection in a single call' ) config = ApiConfig ( ) client = ApiClient ( config . host , config . app_id , config . app_...
def value ( board , who = 'x' ) : """Returns the value of a board > > > b = Board ( ) ; b . _ rows = [ [ ' x ' , ' x ' , ' x ' ] , [ ' x ' , ' x ' , ' x ' ] , [ ' x ' , ' x ' , ' x ' ] ] > > > value ( b ) > > > b = Board ( ) ; b . _ rows = [ [ ' o ' , ' o ' , ' o ' ] , [ ' o ' , ' o ' , ' o ' ] , [ ' o ' , ' ...
w = board . winner ( ) if w == who : return 1 if w == opp ( who ) : return - 1 if board . turn == 9 : return 0 if who == board . whose_turn : return max ( [ value ( b , who ) for b in board . possible ( ) ] ) else : return min ( [ value ( b , who ) for b in board . possible ( ) ] )
def __add_span_tier ( self , tier ) : """adds a tier to the document graph in which each event annotates a span of one or more tokens ."""
tier_id = tier . attrib [ 'id' ] # add the tier ' s root node with an inbound edge from the document root self . add_node ( tier_id , layers = { self . ns , self . ns + ':tier' } , attr_dict = { self . ns + ':category' : tier . attrib [ 'category' ] , self . ns + ':type' : tier . attrib [ 'type' ] , self . ns + ':displ...
def track_description_list ( head ) : """Convert a TrackDescription linked list to a Python list ( and release the former ) ."""
r = [ ] if head : item = head while item : item = item . contents r . append ( ( item . id , item . name ) ) item = item . next try : libvlc_track_description_release ( head ) except NameError : libvlc_track_description_list_release ( head ) return r
def convert_frame_to_node ( pyvlx , frame ) : """Convert FrameGet [ All ] Node [ s ] InformationNotification into Node object ."""
# pylint : disable = too - many - return - statements if frame . node_type == NodeTypeWithSubtype . WINDOW_OPENER : return Window ( pyvlx = pyvlx , node_id = frame . node_id , name = frame . name , rain_sensor = False ) if frame . node_type == NodeTypeWithSubtype . WINDOW_OPENER_WITH_RAIN_SENSOR : return Window...
def selectComponent ( self , component , index = None , command = QtGui . QItemSelectionModel . Toggle ) : """Selects the given * component * according to * command * policy ( actually , only toggle supported ) . If index is None , looks up index of component in model"""
if command == QtGui . QItemSelectionModel . Toggle : if component in self . _selectedComponents : self . _selectedComponents . remove ( component ) if index is None : index = self . model ( ) . indexByComponent ( component ) self . selectionChanged . emit ( self . selection ( ) ,...
def read_match_config_from_file ( match_config_path : Path ) -> MatchConfig : """Parse the rlbot . cfg file on disk into the python datastructure ."""
config_obj = create_bot_config_layout ( ) config_obj . parse_file ( match_config_path , max_index = MAX_PLAYERS ) return parse_match_config ( config_obj , match_config_path , { } , { } )
def QA_fetch_stock_xdxr ( code , format = 'pd' , collections = DATABASE . stock_xdxr ) : '获取股票除权信息 / 数据库'
code = QA_util_code_tolist ( code ) data = pd . DataFrame ( [ item for item in collections . find ( { 'code' : { '$in' : code } } , batch_size = 10000 ) ] ) . drop ( [ '_id' ] , axis = 1 ) data [ 'date' ] = pd . to_datetime ( data [ 'date' ] ) return data . set_index ( 'date' , drop = False )
def triangle_intersects_plane ( mesh , tid , plane ) : """Returns true if the given triangle is cut by the plane . This will return false if a single vertex of the triangle lies on the plane"""
dists = [ point_to_plane_dist ( mesh . verts [ vid ] , plane ) for vid in mesh . tris [ tid ] ] side = np . sign ( dists ) return not ( side [ 0 ] == side [ 1 ] == side [ 2 ] )
def _reorder_types ( self , types_script ) : """Takes type scripts and reorders them to avoid Type doesn ' t exist exception"""
self . _logger . debug ( 'Running types definitions scripts' ) self . _logger . debug ( 'Reordering types definitions scripts to avoid "type does not exist" exceptions' ) _type_statements = sqlparse . split ( types_script ) # TODO : move up to classes _type_statements_dict = { } # dictionary that store statements with ...
def _get_service_port ( self , instance ) : """Get the ntp server port"""
host = instance . get ( 'host' , DEFAULT_HOST ) port = instance . get ( 'port' , DEFAULT_PORT ) # default port is the name of the service but lookup would fail # if the / etc / services file is missing . In that case , fallback to numeric try : socket . getaddrinfo ( host , port ) except socket . gaierror : por...
def get_course_completions ( cls , user , course_key ) : """Returns a dictionary mapping BlockKeys to completion values for all BlockCompletion records for the given user and course _ key . Return value : dict [ BlockKey ] = float"""
user_course_completions = cls . user_course_completion_queryset ( user , course_key ) return cls . completion_by_block_key ( user_course_completions )
def names_singleton ( self ) : """Returns True if this URI names a file or if URI represents input / output stream ."""
if self . stream : return True else : return os . path . isfile ( self . object_name )
def visit ( self , url = '' ) : """Driver gets the provided url in the browser , returns True if successful url - - An absolute or relative url stored as a string"""
def _visit ( url ) : if len ( url ) > 0 and url [ 0 ] == '/' : # url ' s first character is a forward slash ; treat as relative path path = url full_url = self . driver . current_url parsed_url = urlparse ( full_url ) base_url = str ( parsed_url . scheme ) + '://' + str ( parsed_url ...
def open_filechooser ( title , parent = None , patterns = None , folder = None , filter = None , multiple = False , _before_run = None , action = None ) : """An open dialog . : param parent : window or None : param patterns : file match patterns : param folder : initial folder : param filter : file filter ...
assert not ( patterns and filter ) if multiple : if action is not None and action != gtk . FILE_CHOOSER_ACTION_OPEN : raise ValueError ( '`multiple` is only valid for the action ' '`gtk.FILE_CHOOSER_ACTION_OPEN`.' ) action = gtk . FILE_CHOOSER_ACTION_OPEN else : assert action is not None filechooser...
def encode ( self , value ) : """Encodes the given value according to this AIT Argument Definition ."""
if type ( value ) == str and self . enum and value in self . enum : value = self . enum [ value ] return self . type . encode ( value ) if self . type else bytearray ( )
def list_nic ( self , instance_id ) : """List all Network Interface Controller"""
# NOTE : interfaces a list of novaclient . v2 . servers . Server interfaces = self . client . servers . interface_list ( instance_id ) return interfaces
def get_binary_annotations ( request , response ) : """Helper method for getting all binary annotations from the request . : param request : the Pyramid request object : param response : the Pyramid response object : returns : binary annotation dict of { str : str }"""
route = request . matched_route . pattern if request . matched_route else '' annotations = { 'http.uri' : request . path , 'http.uri.qs' : request . path_qs , 'http.route' : route , 'response_status_code' : str ( response . status_code ) , } settings = request . registry . settings if 'zipkin.set_extra_binary_annotatio...
def new ( cls , alias , sealed_obj , algorithm , key , key_size ) : """Helper function to create a new SecretKeyEntry . : returns : A loaded : class : ` SecretKeyEntry ` instance , ready to be placed in a keystore ."""
timestamp = int ( time . time ( ) ) * 1000 raise NotImplementedError ( "Creating Secret Keys not implemented" )
def after_batch ( self , stream_name : str , batch_data ) -> None : """If initialized to check after each batch , stop the training once the batch data contains a monitored variable equal to NaN . : param stream _ name : name of the stream to be checked : param batch _ data : batch data to be checked"""
if self . _after_batch : self . _check_nan ( { stream_name : batch_data } )
def approximating_model ( self , beta , T , Z , R , Q , h_approx , data ) : """Creates approximating Gaussian state space model for Poisson measurement density Parameters beta : np . array Contains untransformed starting values for latent variables T , Z , R , Q : np . array State space matrices used in K...
H = np . ones ( data . shape [ 0 ] ) mu = np . zeros ( data . shape [ 0 ] ) alpha = np . array ( [ np . zeros ( data . shape [ 0 ] ) ] ) tol = 100.0 it = 0 while tol > 10 ** - 7 and it < 5 : old_alpha = alpha [ 0 ] alpha , V = nl_univariate_KFS ( data , Z , H , T , Q , R , mu ) H = np . exp ( - alpha [ 0 ] ...
def add_operation ( op , func_name , db ) : """Registers the given operation within the Ibis SQL translation toolchain Parameters op : operator class name : used in issuing statements to SQL engine database : database the relevant operator is registered to"""
full_name = '{0}.{1}' . format ( db , func_name ) # TODO # if op . input _ type is rlz . listof : # translator = comp . varargs ( full _ name ) # else : arity = len ( op . signature ) translator = comp . fixed_arity ( full_name , arity ) comp . _operation_registry [ op ] = translator
def last_modified_time ( path ) : """Get the last modified time of path as a Timestamp ."""
return pd . Timestamp ( os . path . getmtime ( path ) , unit = 's' , tz = 'UTC' )
def next_frame_sv2p_discrete ( ) : """SV2P discrete model hparams ."""
hparams = next_frame_sv2p ( ) hparams . action_injection = "multiplicative" hparams . small_mode = True hparams . add_hparam ( "bottleneck_bits" , 128 ) hparams . add_hparam ( "bottleneck_noise" , 0.02 ) hparams . add_hparam ( "discrete_warmup_steps" , 40000 ) hparams . add_hparam ( "full_latent_tower" , False ) hparam...
def get_normalized_grid ( self ) : """Analyzes subcell structure"""
log = logging . getLogger ( __name__ ) # Resolve multirow mentions , TODO : validate against all PDFs # subcol _ count = 0 mega_rows = [ ] for row_id , row in enumerate ( self . _grid ) : # maps yc _ grid - > [ mentions ] subrow_across_cell = defaultdict ( list ) for col_id , cell in enumerate ( row ) : # Keep ...