signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def mtFeatureExtraction ( signal , fs , mt_win , mt_step , st_win , st_step ) : """Mid - term feature extraction"""
mt_win_ratio = int ( round ( mt_win / st_step ) ) mt_step_ratio = int ( round ( mt_step / st_step ) ) mt_features = [ ] st_features , f_names = stFeatureExtraction ( signal , fs , st_win , st_step ) n_feats = len ( st_features ) n_stats = 2 mt_features , mid_feature_names = [ ] , [ ] # for i in range ( n _ stats * n _ ...
def update ( self , validate = False ) : """Update the DB instance ' s status information by making a call to fetch the current instance attributes from the service . : type validate : bool : param validate : By default , if EC2 returns no data about the instance the update method returns quietly . If the...
rs = self . connection . get_all_dbinstances ( self . id ) if len ( rs ) > 0 : for i in rs : if i . id == self . id : self . __dict__ . update ( i . __dict__ ) elif validate : raise ValueError ( '%s is not a valid Instance ID' % self . id ) return self . status
def hydrate ( self , broker = None ) : """Loads a Broker from a previously saved one . A Broker is created if one isn ' t provided ."""
broker = broker or dr . Broker ( ) for path in glob ( os . path . join ( self . meta_data , "*" ) ) : try : with open ( path ) as f : doc = ser . load ( f ) res = self . _hydrate_one ( doc ) comp , results , exec_time , ser_time = res if results : ...
def add_local_node ( self , child_node , name = None ) : """Append a child that should alter the locals of this scope node . : param child _ node : The child node that will alter locals . : type child _ node : NodeNG : param name : The name of the local that will be altered by the given child node . : typ...
if name != "__class__" : # add _ _ class _ _ node as a child will cause infinite recursion later ! self . _append_node ( child_node ) self . set_local ( name or child_node . name , child_node )
def xorc_constraint ( v = 0 , sense = "maximize" ) : """XOR ( r as variable ) custom constraint"""
assert v in [ 0 , 1 ] , "v must be 0 or 1 instead of %s" % v . __repr__ ( ) model , x , y , z = _init ( ) r = model . addVar ( "r" , "B" ) n = model . addVar ( "n" , "I" ) # auxiliary model . addCons ( r + quicksum ( [ x , y , z ] ) == 2 * n ) model . addCons ( x == v ) model . setObjective ( r , sense = sense ) _optim...
def orbit ( self ) : """Convert TLE to Orbit object , in order to make computations on it Return : ~ beyond . orbits . orbit . Orbit :"""
data = { 'bstar' : self . bstar , 'ndot' : self . ndot , 'ndotdot' : self . ndotdot , 'tle' : self . text } return Orbit ( self . epoch , self . to_list ( ) , "TLE" , "TEME" , 'Sgp4' , ** data )
def download_configuration ( self ) -> str : """downloads the current configuration from the cloud Returns the downloaded configuration or an errorCode"""
return self . _restCall ( "home/getCurrentState" , json . dumps ( self . _connection . clientCharacteristics ) )
def generate_identity_binding_access_token ( self , name , scope , jwt , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) : """Exchange a JWT signed by third party identity provider to an OAuth 2.0 access token Example : ...
# Wrap the transport method to add retry and timeout logic . if "generate_identity_binding_access_token" not in self . _inner_api_calls : self . _inner_api_calls [ "generate_identity_binding_access_token" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . generate_identity_binding_access_t...
def ip_to_bytes ( ip_str , big_endian = True ) : """Converts an IP given as a string to a byte sequence"""
if big_endian : code = '>L' else : code = '<L' return bytes ( struct . unpack ( code , socket . inet_aton ( ip_str ) ) [ 0 ] )
def activate_scene ( self , scene_uuid , duration = 1.0 ) : """Activate a scene . See http : / / api . developer . lifx . com / docs / activate - scene scene _ uuid : required String The UUID for the scene you wish to activate duration : Double The time in seconds to spend performing the scene transition ...
argument_tuples = [ ( "duration" , duration ) , ] return self . client . perform_request ( method = 'put' , endpoint = 'scenes/scene_id:{}/activate' , endpoint_args = [ scene_uuid ] , argument_tuples = argument_tuples )
def write ( self , buf ) : """Inserts a string buffer as a record . Examples > > > record = mx . recordio . MXRecordIO ( ' tmp . rec ' , ' w ' ) > > > for i in range ( 5 ) : . . . record . write ( ' record _ % d ' % i ) > > > record . close ( ) Parameters buf : string ( python2 ) , bytes ( python3) ...
assert self . writable self . _check_pid ( allow_reset = False ) check_call ( _LIB . MXRecordIOWriterWriteRecord ( self . handle , ctypes . c_char_p ( buf ) , ctypes . c_size_t ( len ( buf ) ) ) )
def to_text ( self , tree , force_root = False ) : """Extract text from tags . Skip any selectors specified and include attributes if specified . Ignored tags will not have their attributes scanned either ."""
self . extract_tag_metadata ( tree ) text = [ ] attributes = [ ] comments = [ ] blocks = [ ] if not ( self . ignores . match ( tree ) if self . ignores else None ) : # The root of the document is the BeautifulSoup object capture = self . captures . match ( tree ) if self . captures is not None else None # Check...
def nearest_material ( name , complete = False ) : r'''Returns the nearest hit to a given name from from dictionaries of building , insulating , or refractory material from tables in [ 1 ] _ , [ 2 ] _ , and [ 3 ] _ . Function will pick the closest match based on a fuzzy search . if ` complete ` is True , will...
if complete : hits = difflib . get_close_matches ( name , materials_dict . keys ( ) , n = 1000 , cutoff = 0 ) for hit in hits : if materials_dict [ hit ] == 1 or materials_dict [ hit ] == 3 or ( ASHRAE [ hit ] [ 0 ] and ASHRAE [ hit ] [ 1 ] ) : return hit else : ID = difflib . get_close_...
def get_params ( self , ctx ) : """Sort order of options before displaying . : param click . core . Context ctx : Click context . : return : super ( ) return value ."""
self . params . sort ( key = self . custom_sort ) return super ( ClickGroup , self ) . get_params ( ctx )
def log_url ( self , url_data , priority = None ) : """Log URL data in sitemap format ."""
self . xml_starttag ( u'url' ) self . xml_tag ( u'loc' , url_data . url ) if url_data . modified : self . xml_tag ( u'lastmod' , self . format_modified ( url_data . modified , sep = "T" ) ) self . xml_tag ( u'changefreq' , self . frequency ) self . xml_tag ( u'priority' , "%.2f" % priority ) self . xml_endtag ( u'u...
def load_code ( fp , magic_int , code_objects = { } ) : """marshal . load ( ) written in Python . When the Python bytecode magic loaded is the same magic for the running Python interpreter , we can simply use the Python - supplied marshal . load ( ) . However we need to use this when versions are different si...
global internStrings , internObjects internStrings = [ ] internObjects = [ ] seek_pos = fp . tell ( ) # Do a sanity check . Is this a code type ? b = ord ( fp . read ( 1 ) ) if ( b & 0x80 ) : b = b & 0x7f c = chr ( b ) if c != 'c' : raise TypeError ( "File %s doesn't smell like Python bytecode:\n" "expecting co...
def _get_span_name ( servicer_context ) : """Generates a span name based off of the gRPC server rpc _ request _ info"""
method_name = servicer_context . _rpc_event . call_details . method [ 1 : ] if isinstance ( method_name , bytes ) : method_name = method_name . decode ( 'utf-8' ) method_name = method_name . replace ( '/' , '.' ) return '{}.{}' . format ( RECV_PREFIX , method_name )
def conv2d ( self , x_in : Connection , w_in : Connection , receptive_field_size , filters_number , stride = 1 , padding = 1 , name = "" ) : """Computes a 2 - D convolution given 4 - D input and filter tensors ."""
x_cols = self . tensor_3d_to_cols ( x_in , receptive_field_size , stride = stride , padding = padding ) mul = self . transpose ( self . matrix_multiply ( x_cols , w_in ) , 0 , 2 , 1 ) # output _ width = self . sum ( self . div ( self . sum ( self . sum ( self . shape ( x _ in , 2 ) , self . constant ( - 1 * receptive _...
def dismiss ( self , member_ids ) : """踢人 . 注意别把自己给踢了 . : param member _ ids : 组员 ids : return : bool"""
url = 'http://www.shanbay.com/api/v1/team/member/' data = { 'action' : 'dispel' , } if isinstance ( member_ids , ( list , tuple ) ) : data [ 'ids' ] = ',' . join ( map ( str , member_ids ) ) else : data [ 'ids' ] = member_ids r = self . request ( url , 'put' , data = data ) try : return r . json ( ) [ 'msg'...
def by_id ( self , id ) : """get adapter data by its id ."""
path = partial ( _path , self . adapter ) path = path ( id ) return self . _get ( path )
def __gen_token_anno_file ( self , top_level_layer ) : """creates an etree representation of a < multiFeat > file that describes all the annotations that only span one token ( e . g . POS , lemma etc . ) . Note : discoursegraphs will create one token annotation file for each top level layer ( e . g . conano ,...
base_paula_id = '{0}.{1}.tok' . format ( self . corpus_name , self . name ) paula_id = '{0}.{1}.{2}.tok_multiFeat' . format ( top_level_layer , self . corpus_name , self . name ) E , tree = gen_paula_etree ( paula_id ) mflist = E ( 'multiFeatList' , { XMLBASE : base_paula_id + '.xml' } ) for token_id in self . dg . tok...
def Send ( self , command_id , data = b'' , size = 0 ) : """Send / buffer FileSync packets . Packets are buffered and only flushed when this connection is read from . All messages have a response from the device , so this will always get flushed . Args : command _ id : Command to send . data : Optional da...
if data : if not isinstance ( data , bytes ) : data = data . encode ( 'utf8' ) size = len ( data ) if not self . _CanAddToSendBuffer ( len ( data ) ) : self . _Flush ( ) buf = struct . pack ( b'<2I' , self . id_to_wire [ command_id ] , size ) + data self . send_buffer [ self . send_idx : self . send...
def assets ( self , asset_type = None ) : """Retrieves all of the assets of a given asset _ type Args : asset _ type : ( str ) Either None , PHONE , HANDLER , or URL Returns :"""
if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) if not asset_type : return self . tc_requests . adversary_assets ( self . api_type , self . api_sub_type , self . unique_id ) if asset_type == 'PHONE' : return self . tc_requests . adversary_phone_assets ( self . api_type ,...
def read_buf ( self ) : """Read database file"""
with open ( self . filepath , 'rb' ) as handler : try : buf = handler . read ( ) # There should be a header at least if len ( buf ) < 124 : raise KPError ( 'Unexpected file size. It should be more or' 'equal 124 bytes but it is ' '{0}!' . format ( len ( buf ) ) ) except : ...
def read_args ( src , args = None ) : r"""Read all arguments from buffer . Advances buffer until end of last valid arguments . There can be any number of whitespace characters between command and the first argument . However , after that first argument , the command can only tolerate one successive line bre...
args = args or TexArgs ( ) # Unlimited whitespace before first argument candidate_index = src . num_forward_until ( lambda s : not s . isspace ( ) ) while src . peek ( ) . isspace ( ) : args . append ( read_tex ( src ) ) # Restricted to only one line break after first argument line_breaks = 0 while src . peek ( ) i...
def message ( self , * args , ** kwargs ) : """Build a message . This method is useful if you want to compose actors . See the actor composition documentation for details . Parameters : * args ( tuple ) : Positional arguments to send to the actor . * * kwargs ( dict ) : Keyword arguments to send to the ac...
return self . message_with_options ( args = args , kwargs = kwargs )
def genty_repeat ( count ) : """To use in conjunction with a TestClass wrapped with @ genty . Runs the wrapped test ' count ' times : @ genty _ repeat ( count ) def test _ some _ function ( self ) Can also wrap a test already decorated with @ genty _ dataset @ genty _ repeat ( 3) @ genty _ dataset ( Tru...
if count < 0 : raise ValueError ( "Really? Can't have {0} iterations. Please pick a value >= 0." . format ( count ) ) def wrap ( test_method ) : test_method . genty_repeat_count = count return test_method return wrap
async def _run ( self ) : """后台任务更新时间戳和重置序号"""
tick_gen = _task_idle_ticks ( 0.5 * self . _shard_ttl ) self . _is_running = True self . _ready_event . clear ( ) while True : try : await self . _lease_shard ( ) break except grpc . RpcError as exc : nap = _rand_uniform ( 3 , 15 ) logger . warn ( f'failed in gRPC [{exc.code()}]:...
def vertical_path ( size ) : """Creates a generator for progressing vertically through an image . : param size : A tuple ( width , height ) of the image size : return : A generator that yields a set of columns through the image . Each column is a generator that yields pixel coordinates ."""
width , height = size return ( ( ( x , y ) for y in range ( height ) ) for x in range ( width ) )
def DeleteAttributes ( self , subject , attributes , start = None , end = None , sync = True ) : """Remove some attributes from a subject ."""
_ = sync # Unused if not attributes : return if isinstance ( attributes , string_types ) : raise ValueError ( "String passed to DeleteAttributes (non string iterable expected)." ) for attribute in attributes : timestamp = self . _MakeTimestamp ( start , end ) attribute = utils . SmartUnicode ( attribute...
def get_data ( source , fields = '*' , env = None , first_row = 0 , count = - 1 , schema = None ) : """A utility function to get a subset of data from a Table , Query , Pandas dataframe or List . Args : source : the source of the data . Can be a Table , Pandas DataFrame , List of dictionaries or lists , or a ...
ipy = IPython . get_ipython ( ) if env is None : env = { } env . update ( ipy . user_ns ) if isinstance ( source , basestring ) : source = datalab . utils . get_item ( ipy . user_ns , source , source ) if isinstance ( source , basestring ) : source = datalab . bigquery . Table ( source ) if isinstan...
def from_array ( cls , content_type , extensions = [ ] , encoding = None , system = None , is_obsolete = False , docs = None , url = None , is_registered = False ) : """Creates a MIME : : Type from an array in the form of : [ type - name , [ extensions ] , encoding , system ] + extensions + , + encoding + , and...
mt = cls ( content_type ) mt . extensions = extensions mt . encoding = encoding mt . system = system mt . is_obsolete = is_obsolete mt . docs = docs mt . url = url mt . registered = is_registered return mt
def get_support ( variables , polynomial ) : """Gets the support of a polynomial ."""
support = [ ] if is_number_type ( polynomial ) : support . append ( [ 0 ] * len ( variables ) ) return support for monomial in polynomial . expand ( ) . as_coefficients_dict ( ) : tmp_support = [ 0 ] * len ( variables ) mon , _ = __separate_scalar_factor ( monomial ) symbolic_support = flatten ( spl...
def timescales_ ( self ) : """Implied relaxation timescales of the model . The relaxation of any initial distribution towards equilibrium is given , according to this model , by a sum of terms - - each corresponding to the relaxation along a specific direction ( eigenvector ) in state space - - which decay ...
u , lv , rv = self . _get_eigensystem ( ) # make sure to leave off equilibrium distribution with np . errstate ( invalid = 'ignore' , divide = 'ignore' ) : timescales = - self . lag_time / np . log ( u [ 1 : ] ) return timescales
def p_expr_LT_expr ( p ) : """expr : expr LT expr"""
p [ 0 ] = make_binary ( p . lineno ( 2 ) , 'LT' , p [ 1 ] , p [ 3 ] , lambda x , y : x < y )
def activate ( self , branches , exclusive = False ) : """Activate branches Parameters branches : str or list branch or list of branches to activate exclusive : bool , optional ( default = False ) if True deactivate the remaining branches"""
if exclusive : self . SetBranchStatus ( '*' , 0 ) if isinstance ( branches , string_types ) : branches = [ branches ] for branch in branches : if '*' in branch : matched_branches = self . glob ( branch ) for b in matched_branches : self . SetBranchStatus ( b , 1 ) elif self ....
def _iter_chunk_offsets ( self ) : """Generate a ( chunk _ type , chunk _ offset ) 2 - tuple for each of the chunks in the PNG image stream . Iteration stops after the IEND chunk is returned ."""
chunk_offset = 8 while True : chunk_data_len = self . _stream_rdr . read_long ( chunk_offset ) chunk_type = self . _stream_rdr . read_str ( 4 , chunk_offset , 4 ) data_offset = chunk_offset + 8 yield chunk_type , data_offset if chunk_type == 'IEND' : break # incr offset for chunk len lon...
def checkout ( self , transparent = False , ** kwargs ) : """create a pagseguro checkout"""
self . data [ 'currency' ] = self . config . CURRENCY self . build_checkout_params ( ** kwargs ) if transparent : response = self . post ( url = self . config . TRANSPARENT_CHECKOUT_URL ) else : response = self . post ( url = self . config . CHECKOUT_URL ) return PagSeguroCheckoutResponse ( response . content ,...
def order_by ( self , key ) : """Returns new Enumerable sorted in ascending order by given key : param key : key to sort by as lambda expression : return : new Enumerable object"""
if key is None : raise NullArgumentError ( u"No key for sorting given" ) kf = [ OrderingDirection ( key , reverse = False ) ] return SortedEnumerable ( key_funcs = kf , data = self . _data )
def addAnalyses ( self , analyses ) : """Adds a collection of analyses to the Worksheet at once"""
actions_pool = ActionHandlerPool . get_instance ( ) actions_pool . queue_pool ( ) for analysis in analyses : self . addAnalysis ( api . get_object ( analysis ) ) actions_pool . resume ( )
def json_decoder_to_deserializer ( decoder_cls : Union [ Type [ JSONDecoder ] , Callable [ [ ] , Type [ JSONDecoder ] ] ] ) -> Type [ Deserializer ] : """Converts a ` JSONDecoder ` class into an equivalent ` Deserializer ` class . : param decoder _ cls : the decoder class type or a function that returns the type ...
name = decoder_cls . __name__ if isinstance ( decoder_cls , type ) else "%sLambdaTypeReturn" % id ( decoder_cls ) return type ( "%sAsDeserializer" % name , ( _JSONDecoderAsDeserializer , ) , { "decoder_type" : property ( lambda self : decoder_cls if isinstance ( decoder_cls , type ) else decoder_cls ( ) ) } )
def get_by_user ( cls , user_id , with_deleted = False ) : """Get a community ."""
query = cls . query . filter_by ( id_user = user_id ) if not with_deleted : query = query . filter ( cls . deleted_at . is_ ( None ) ) return query . order_by ( db . asc ( Community . title ) )
def insertPhenotypeAssociationSet ( self , phenotypeAssociationSet ) : """Inserts the specified phenotype annotation set into this repository ."""
datasetId = phenotypeAssociationSet . getParentContainer ( ) . getId ( ) attributes = json . dumps ( phenotypeAssociationSet . getAttributes ( ) ) try : models . Phenotypeassociationset . create ( id = phenotypeAssociationSet . getId ( ) , name = phenotypeAssociationSet . getLocalId ( ) , datasetid = datasetId , da...
def list_file_jobs ( cls , offset = None , limit = None , api = None ) : """Query ( List ) async jobs : param offset : Pagination offset : param limit : Pagination limit : param api : Api instance : return : Collection object"""
api = api or cls . _API return super ( AsyncJob , cls ) . _query ( api = api , url = cls . _URL [ 'list_file_jobs' ] , offset = offset , limit = limit , )
def parse ( self , limit = None ) : """Override Source . parse ( ) Parses version and interaction information from CTD Args : : param limit ( int , optional ) limit the number of rows processed Returns : : return None"""
if limit is not None : LOG . info ( "Only parsing first %d rows" , limit ) LOG . info ( "Parsing files..." ) # pub _ map = dict ( ) # file _ path = ' / ' . join ( ( self . rawdir , # self . static _ files [ ' publications ' ] [ ' file ' ] ) ) # if os . path . exists ( file _ path ) is True : # pub _ map = self . _ ...
def unixtime ( mm = False ) : """返回当前时间的 ` ` unix时间戳 ` ` , 默认返回级别 ` ` second ` ` - 可设置 ` ` mm = True ` ` 来获取毫秒 , 毫秒使用 ` ` ( 秒 + 随机数 ) * 1000 ` ` 来实现 , 尽量防止出现相同 - 使用时间范围限制 : ( 2001/9/9 9:46:40 ~ 2286/11/21 1:46:3) - 样例 . . code : : python # 标准情况直接使用秒 len ( str ( unixtime ( ) ) ) # 输出 10 # 如果需要唯一标识 , ...
if mm : return int ( ( time . mktime ( datetime . datetime . now ( ) . timetuple ( ) ) + random . random ( ) ) * 1000 ) else : return int ( time . mktime ( datetime . datetime . now ( ) . timetuple ( ) ) )
def _basic_login ( self ) : """Obtain a new access token from the vendor . First , try using the refresh _ token , if one is available , otherwise authenticate using the user credentials ."""
_LOGGER . debug ( "No/Expired/Invalid access_token, re-authenticating..." ) self . access_token = self . access_token_expires = None if self . refresh_token : _LOGGER . debug ( "Trying refresh_token..." ) credentials = { 'grant_type' : "refresh_token" , 'scope' : "EMEA-V1-Basic EMEA-V1-Anonymous" , 'refresh_tok...
def _make_win ( n , mono = False ) : """Generate a window for a given length . : param n : an integer for the length of the window . : param mono : True for a mono window , False for a stereo window . : return : an numpy array containing the window value ."""
if mono : win = np . hanning ( n ) + 0.00001 else : win = np . array ( [ np . hanning ( n ) + 0.00001 , np . hanning ( n ) + 0.00001 ] ) win = np . transpose ( win ) return win
def get_stddevs ( self , mag , imt , stddev_types , num_sites ) : """Returns the total standard deviation"""
stddevs = [ ] for stddev_type in stddev_types : assert stddev_type in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const . StdDev . TOTAL : sigma = self . _get_total_sigma ( imt , mag ) stddevs . append ( sigma + np . zeros ( num_sites ) ) return stddevs
def dragEnterEvent ( self , event ) : """Reimplements the : meth : ` QTabWidget . dragEnterEvent ` method . : param event : QEvent . : type event : QEvent"""
LOGGER . debug ( "> '{0}' widget drag enter event accepted!" . format ( self . __class__ . __name__ ) ) event . accept ( )
def forward ( self , ** kwargs ) : """remote http call to api endpoint accept * ONLY * GET and POST"""
# rewrite url path prefix = self . url_prefix path = "" if request . path == "/" else request . path path = path [ len ( prefix ) : ] url = '%s%s' % ( self . url_root [ : - 1 ] , path ) if request . method == 'GET' : resp = requests . get ( url , params = request . args ) data = json . loads ( resp . content ) ...
def predict ( self , u = 0 ) : """Predict next position . Parameters u : ndarray Optional control vector . If non - zero , it is multiplied by B to create the control input into the system ."""
# x = Fx + Bu A = dot ( self . _F_inv . T , self . P_inv ) . dot ( self . _F_inv ) # pylint : disable = bare - except try : AI = self . inv ( A ) invertable = True if self . _no_information : try : self . x = dot ( self . inv ( self . P_inv ) , self . x ) except : sel...
def run ( self , wrappers = [ "" , "" ] ) : '''run the lilypond script on the hierarchy class : param wrappers : this is useful for testing : use wrappers to put something around the outputted " lilypond string " from the hierarchy class . For example if you ' re testing a pitch , you might put \r elative c { }...
opened_file = open ( self . lyfile , 'w' ) lilystring = self . piece_obj . toLily ( ) opened_file . writelines ( wrappers [ 0 ] + "\\version \"2.18.2\" \n" + lilystring + wrappers [ 1 ] ) opened_file . close ( ) # subprocess . Popen ( [ ' sudo ' , self . lily _ script , " - - output = " + # self . folder , self . lyfil...
def _truncate ( self , x , k ) : '''given a vector x , leave its top - k absolute - value entries alone , and set the rest to 0'''
not_F = np . argsort ( np . abs ( x ) ) [ : - k ] x [ not_F ] = 0 return x
def create_key ( kwargs = None , call = None ) : '''Upload a public key'''
if call != 'function' : log . error ( 'The create_key function must be called with -f or --function.' ) return False try : result = query ( method = 'account' , command = 'keys' , args = { 'name' : kwargs [ 'name' ] , 'public_key' : kwargs [ 'public_key' ] } , http_method = 'post' ) except KeyError : lo...
def _set_ping_mpls ( self , v , load = False ) : """Setter method for ping _ mpls , mapped from YANG variable / brocade _ mpls _ rpc / ping _ mpls ( rpc ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ ping _ mpls is considered as a private method . Backends looking ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = ping_mpls . ping_mpls , is_leaf = True , yang_name = "ping-mpls" , rest_name = "ping-mpls" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = False , extensions = { u'tail...
def do_flipper ( parser , token ) : """The flipper tag takes two arguments : the user to look up and the feature to compare against ."""
nodelist = parser . parse ( ( 'endflipper' , ) ) tag_name , user_key , feature = token . split_contents ( ) parser . delete_first_token ( ) return FlipperNode ( nodelist , user_key , feature )
def create_image_summary ( name , val ) : """Args : name ( str ) : val ( np . ndarray ) : 4D tensor of NHWC . assume RGB if C = = 3. Can be either float or uint8 . Range has to be [ 0,255 ] . Returns : tf . Summary :"""
assert isinstance ( name , six . string_types ) , type ( name ) n , h , w , c = val . shape val = val . astype ( 'uint8' ) s = tf . Summary ( ) imparams = [ cv2 . IMWRITE_PNG_COMPRESSION , 9 ] for k in range ( n ) : arr = val [ k ] # CV2 will only write correctly in BGR chanel order if c == 3 : arr ...
def datasets_status ( self , owner_slug , dataset_slug , ** kwargs ) : # noqa : E501 """Get dataset creation status # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . datasets _ status ( owner _ slu...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . datasets_status_with_http_info ( owner_slug , dataset_slug , ** kwargs ) # noqa : E501 else : ( data ) = self . datasets_status_with_http_info ( owner_slug , dataset_slug , ** kwargs ) # noqa : E501 return dat...
def golden_section_search ( fn , a , b , tolerance = 1e-5 ) : """WIKIPEDIA IMPLEMENTATION golden section search to find the minimum of f on [ a , b ] f : a strictly unimodal function on [ a , b ] example : > > > f = lambda x : ( x - 2 ) * * 2 > > > x = gss ( f , 1,5) 2.000009644875678"""
c = b - GOLDEN * ( b - a ) d = a + GOLDEN * ( b - a ) while abs ( c - d ) > tolerance : fc , fd = fn ( c ) , fn ( d ) if fc < fd : b = d d = c # fd = fc ; fc = f ( c ) c = b - GOLDEN * ( b - a ) else : a = c c = d # fc = fd ; fd = f ( d ) d = a...
def profile_detail ( request , username , template_name = accounts_settings . ACCOUNTS_PROFILE_DETAIL_TEMPLATE , extra_context = None , ** kwargs ) : """Detailed view of an user . : param username : String of the username of which the profile should be viewed . : param template _ name : String representing ...
user = get_object_or_404 ( get_user_model ( ) , username__iexact = username ) profile_model = get_profile_model ( ) try : profile = user . get_profile ( ) except profile_model . DoesNotExist : profile = profile_model ( user = user ) profile . save ( ) if not profile . can_view_profile ( request . user ) : ...
def stats_mouse ( events , table ) : """Returns statistics , positions and rescaled events for mouse events ."""
if not events : return [ ] , [ ] , [ ] distance , last , deltas = 0 , None , [ ] HS = conf . MouseHeatmapSize SC = dict ( ( "xy" [ i ] , conf . DefaultScreenSize [ i ] / float ( HS [ i ] ) ) for i in [ 0 , 1 ] ) xymap = collections . defaultdict ( int ) sizes = db . fetch ( "screen_sizes" , order = ( "dt" , ) ) siz...
def lobstr ( args ) : """% prog lobstr lobstr _ index1 lobstr _ index2 . . . Run lobSTR on a big BAM file . There can be multiple lobSTR indices . In addition , bamfile can be S3 location and - - lobstr _ home can be S3 location ( e . g . s3 : / / hli - mv - data - science / htang / str - build / lobSTR / )""...
p = OptionParser ( lobstr . __doc__ ) p . add_option ( "--haploid" , default = "chrY,chrM" , help = "Use haploid model for these chromosomes" ) p . add_option ( "--chr" , help = "Run only this chromosome" ) p . add_option ( "--simulation" , default = False , action = "store_true" , help = "Simulation mode" ) p . set_ho...
def print_mso_auto_shape_type_spec ( ) : """print spec dictionary for msoAutoShapeType"""
auto_shape_types = MsoAutoShapeTypeCollection . load ( sort = 'const_name' ) out = render_mso_auto_shape_type_spec ( auto_shape_types ) print out
def transaction ( self ) : """A context manager for executing a transaction on this Database ."""
conn = self . get_connection ( ) tx = conn . transaction ( ) try : yield conn tx . commit ( ) except : tx . rollback ( ) finally : conn . close ( )
def get_identities ( self , item ) : """Return the identities from an item"""
item = item [ 'data' ] # Changeset owner user = item [ 'owner' ] identity = self . get_sh_identity ( user ) yield identity # Patchset uploader and author if 'patchSets' in item : for patchset in item [ 'patchSets' ] : user = patchset [ 'uploader' ] identity = self . get_sh_identity ( user ) ...
def _determine_username ( self , ip ) : """SSH in as root and determine the username ."""
ssh = subprocess . Popen ( [ "ssh" , "-o" , "UserKnownHostsFile=/dev/null" , "-o" , "StrictHostKeyChecking=no" , "root@%s" % ip ] , stdin = subprocess . DEVNULL , stdout = subprocess . PIPE , stderr = subprocess . DEVNULL ) first_line = ssh . stdout . readline ( ) ssh . kill ( ) ssh . wait ( ) if first_line : match...
def handle_set_citation ( self , line : str , position : int , tokens : ParseResults ) -> ParseResults : """Handle a ` ` SET Citation = { " X " , " Y " , " Z " , . . . } ` ` statement ."""
self . clear_citation ( ) values = tokens [ 'values' ] if len ( values ) < 2 : raise CitationTooShortException ( self . get_line_number ( ) , line , position ) citation_type = values [ 0 ] if citation_type not in CITATION_TYPES : raise InvalidCitationType ( self . get_line_number ( ) , line , position , citatio...
def _bsecurate_cli_compare_basis_files ( args ) : '''Handles compare - basis - files subcommand'''
ret = curate . compare_basis_files ( args . file1 , args . file2 , args . readfmt1 , args . readfmt2 , args . uncontract_general ) if ret : return "No difference found" else : return "DIFFERENCES FOUND. SEE ABOVE"
def real_pathspec ( self ) : """Returns a pathspec for an aff4 object even if there is none stored ."""
pathspec = self . Get ( self . Schema . PATHSPEC ) stripped_components = [ ] parent = self # TODO ( user ) : this code is potentially slow due to multiple separate # aff4 . FACTORY . Open ( ) calls . OTOH the loop below is executed very rarely - # only when we deal with deep files that got fetched alone and then # one ...
def Render ( self ) : """Generates a sequence of points suitable for plotting . An empirical CDF is a step function ; linear interpolation can be misleading . Returns : tuple of ( xs , ps )"""
xs = [ self . xs [ 0 ] ] ps = [ 0.0 ] for i , p in enumerate ( self . ps ) : xs . append ( self . xs [ i ] ) ps . append ( p ) try : xs . append ( self . xs [ i + 1 ] ) ps . append ( p ) except IndexError : pass return xs , ps
def _remove_finder ( importer , finder ) : """Remove an existing finder from pkg _ resources ."""
existing_finder = _get_finder ( importer ) if not existing_finder : return if isinstance ( existing_finder , ChainedFinder ) : try : existing_finder . finders . remove ( finder ) except ValueError : return if len ( existing_finder . finders ) == 1 : pkg_resources . register_finde...
def configure_versioned_classes ( self ) : """Configures all versioned classes that were collected during instrumentation process ."""
for cls in self . pending_classes : self . audit_table ( cls . __table__ , cls . __versioned__ . get ( 'exclude' ) ) assign_actor ( self . base , self . transaction_cls , self . actor_cls )
def get_date ( self , p_tag ) : """Given a date tag , return a date object ."""
string = self . tag_value ( p_tag ) result = None try : result = date_string_to_date ( string ) if string else None except ValueError : pass return result
def login_token ( api , username , password ) : """Login using pre routeros 6.43 authorization method ."""
sentence = api ( '/login' ) token = tuple ( sentence ) [ 0 ] [ 'ret' ] encoded = encode_password ( token , password ) tuple ( api ( '/login' , ** { 'name' : username , 'response' : encoded } ) )
def get_kwargs_index ( target ) -> int : """Returns the index of the " * * kwargs " parameter if such a parameter exists in the function arguments or - 1 otherwise . : param target : The target function for which the kwargs index should be determined : return : The keyword arguments index if it exists or ...
code = target . __code__ if not bool ( code . co_flags & inspect . CO_VARKEYWORDS ) : return - 1 return ( code . co_argcount + code . co_kwonlyargcount + ( 1 if code . co_flags & inspect . CO_VARARGS else 0 ) )
def _parse_response_for_dict ( response ) : '''Extracts name - values from response header . Filter out the standard http headers .'''
if response is None : return None http_headers = [ 'server' , 'date' , 'location' , 'host' , 'via' , 'proxy-connection' , 'connection' ] return_dict = _HeaderDict ( ) if response . headers : for name , value in response . headers : if not name . lower ( ) in http_headers : return_dict [ name...
def show_category ( self ) : """doc : http : / / open . youku . com / docs / doc ? id = 93"""
url = 'https://openapi.youku.com/v2/schemas/show/category.json' r = requests . get ( url ) check_error ( r ) return r . json ( )
def path_upper ( self , object_id , limit_depth = 1000000 , db_session = None , * args , ** kwargs ) : """This returns you path to root node starting from object _ id currently only for postgresql : param object _ id : : param limit _ depth : : param db _ session : : return :"""
return self . service . path_upper ( object_id = object_id , limit_depth = limit_depth , db_session = db_session , * args , ** kwargs )
def write_cfg ( path , value ) -> None : """: param path : example : " / . rwmeta / developer _ settings . json " : param value : dict"""
full_path = __build_path ( path ) with open ( full_path , 'w' ) as myfile : myfile . write ( json . dumps ( value ) )
def TerminateFlow ( client_id , flow_id , reason = None , flow_state = rdf_flow_objects . Flow . FlowState . ERROR ) : """Terminates a flow and all of its children . Args : client _ id : Client ID of a flow to terminate . flow _ id : Flow ID of a flow to terminate . reason : String with a termination reason...
to_terminate = [ data_store . REL_DB . ReadFlowObject ( client_id , flow_id ) ] while to_terminate : next_to_terminate = [ ] for rdf_flow in to_terminate : _TerminateFlow ( rdf_flow , reason = reason , flow_state = flow_state ) next_to_terminate . extend ( data_store . REL_DB . ReadChildFlowObje...
def post_message ( self , msg ) : '''default post message call'''
if '_posted' in msg . __dict__ : return msg . _posted = True msg . _timestamp = time . time ( ) type = msg . get_type ( ) if type != 'HEARTBEAT' or ( msg . type != mavlink . MAV_TYPE_GCS and msg . type != mavlink . MAV_TYPE_GIMBAL ) : self . messages [ type ] = msg if 'usec' in msg . __dict__ : self . uptim...
def statcast_single_game ( game_pk , team = None ) : """Pulls statcast play - level data from Baseball Savant for a single game , identified by its MLB game ID ( game _ pk in statcast data ) INPUTS : game _ pk : 6 - digit integer MLB game ID to retrieve"""
data = single_game_request ( game_pk ) data = postprocessing ( data , team ) return data
def get_conf_update ( self ) : """Get updated config from URL , fallback to local file if download fails ."""
dyn_conf = self . get_collection_rules ( ) if not dyn_conf : return self . get_conf_file ( ) version = dyn_conf . get ( 'version' , None ) if version is None : raise ValueError ( "ERROR: Could not find version in json" ) dyn_conf [ 'file' ] = self . collection_rules_file logger . debug ( "Success reading config...
def steem_instance ( self ) : '''Returns the steem instance if it already exists otherwise uses the goodnode method to fetch a node and instantiate the Steem class .'''
if self . s : return self . s for num_of_retries in range ( default . max_retry ) : node = self . util . goodnode ( self . nodes ) try : self . s = Steem ( keys = self . keys , nodes = [ node ] ) except Exception as e : self . util . retry ( "COULD NOT GET STEEM INSTANCE" , e , num_of_re...
def trimmed_split ( s , seps = ( ";" , "," ) ) : """Given a string s , split is by one of one of the seps ."""
for sep in seps : if sep not in s : continue data = [ item . strip ( ) for item in s . strip ( ) . split ( sep ) ] return data return [ s ]
def scalars_impl ( self , run , tag_regex_string ) : """Given a tag regex and single run , return ScalarEvents . Args : run : A run string . tag _ regex _ string : A regular expression that captures portions of tags . Raises : ValueError : if the scalars plugin is not registered . Returns : A dictiona...
if not tag_regex_string : # The user provided no regex . return { _REGEX_VALID_PROPERTY : False , _TAG_TO_EVENTS_PROPERTY : { } , } # Construct the regex . try : regex = re . compile ( tag_regex_string ) except re . error : return { _REGEX_VALID_PROPERTY : False , _TAG_TO_EVENTS_PROPERTY : { } , } # Fetch t...
def fit_isochrone ( orbit , m0 = 2E11 , b0 = 1. , minimize_kwargs = None ) : r"""Fit the toy Isochrone potential to the sum of the energy residuals relative to the mean energy by minimizing the function . . math : : f ( m , b ) = \ sum _ i ( \ frac { 1 } { 2 } v _ i ^ 2 + \ Phi _ { \ rm iso } ( x _ i \ , | \ ...
pot = orbit . hamiltonian . potential if pot is None : raise ValueError ( "The orbit object must have an associated potential" ) w = np . squeeze ( orbit . w ( pot . units ) ) if w . ndim > 2 : raise ValueError ( "Input orbit object must be a single orbit." ) def f ( p , w ) : logm , logb = p potential ...
def get_pre_auth_url_m ( self , redirect_uri ) : """快速获取pre auth url , 可以直接微信中发送该链接 , 直接授权"""
url = "https://mp.weixin.qq.com/safe/bindcomponent?action=bindcomponent&auth_type=3&no_scan=1&" redirect_uri = quote ( redirect_uri , safe = '' ) return "{0}component_appid={1}&pre_auth_code={2}&redirect_uri={3}" . format ( url , self . component_appid , self . create_preauthcode ( ) [ 'pre_auth_code' ] , redirect_uri ...
def do_examine ( self , arg ) : """Opens a unit test case ' s . out . compare file to examine the verbose comparison report across values ."""
# We use their default editor ( if it has been set ) ; otherwise we can ' t do much of # anything and issue a warning . from os import getenv , path , system testcase , output = arg . split ( ) target = path . join ( self . tests [ self . active ] . stagedir , "tests" , testcase , "{}.compare" . format ( output ) ) if ...
def sign ( self , identity , blob ) : """Sign given blob and return the signature ( as bytes ) ."""
curve_name = identity . get_curve_name ( ecdh = False ) log . debug ( '"%s" signing %r (%s) on %s' , identity . to_string ( ) , blob , curve_name , self ) try : result = self . _defs . sign_identity ( self . conn , identity = self . _identity_proto ( identity ) , challenge_hidden = blob , challenge_visual = '' , ec...
def in_flight_request_count ( self , node_id = None ) : """Get the number of in - flight requests for a node or all nodes . Arguments : node _ id ( int , optional ) : a specific node to check . If unspecified , return the total for all nodes Returns : int : pending in - flight requests for the node , or a...
if node_id is not None : conn = self . _conns . get ( node_id ) if conn is None : return 0 return len ( conn . in_flight_requests ) else : return sum ( [ len ( conn . in_flight_requests ) for conn in list ( self . _conns . values ( ) ) ] )
def in_placement_grid ( self , pos : Union [ Point2 , Point3 , Unit ] ) -> bool : """Returns True if you can place something at a position . Remember , buildings usually use 2x2 , 3x3 or 5x5 of these grid points . Caution : some x and y offset might be required , see ramp code : https : / / github . com / Dento...
assert isinstance ( pos , ( Point2 , Point3 , Unit ) ) pos = pos . position . to2 . rounded return self . _game_info . placement_grid [ pos ] != 0
def image_vacuum ( name ) : '''Delete images not in use or installed via image _ present . . warning : : Only image _ present states that are included via the top file will be detected .'''
name = name . lower ( ) ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' } # list of images to keep images = [ ] # retrieve image _ present state data for host for state in __salt__ [ 'state.show_lowstate' ] ( ) : # don ' t throw exceptions when not highstate run if 'state' not in state : ...
def upgradeProcessor1to2 ( oldProcessor ) : """Batch processors stopped polling at version 2 , so they no longer needed the idleInterval attribute . They also gained a scheduled attribute which tracks their interaction with the scheduler . Since they stopped polling , we also set them up as a timed event here...
newProcessor = oldProcessor . upgradeVersion ( oldProcessor . typeName , 1 , 2 , busyInterval = oldProcessor . busyInterval ) newProcessor . scheduled = extime . Time ( ) s = newProcessor . store sch = iaxiom . IScheduler ( s , None ) if sch is None : if s . parent is None : # Only site stores have no parents . ...
def get_create_security_group_commands ( self , sg_id , sg_rules ) : """Commands for creating ACL"""
cmds = [ ] in_rules , eg_rules = self . _format_rules_for_eos ( sg_rules ) cmds . append ( "ip access-list %s dynamic" % self . _acl_name ( sg_id , n_const . INGRESS_DIRECTION ) ) for in_rule in in_rules : cmds . append ( in_rule ) cmds . append ( "exit" ) cmds . append ( "ip access-list %s dynamic" % self . _acl_n...
def _validate_compute_resources ( self , cr ) : """Checks contents of sub dictionary for managed clusters : param cr : computeResources : type cr : dict"""
for param in ( 'instanceRole' , 'maxvCpus' , 'minvCpus' , 'instanceTypes' , 'securityGroupIds' , 'subnets' , 'type' ) : if param not in cr : raise InvalidParameterValueException ( 'computeResources must contain {0}' . format ( param ) ) if self . iam_backend . get_role_by_arn ( cr [ 'instanceRole' ] ) is No...
def continuous_periods ( self ) : """Return a list of continuous data periods by removing the data gaps from the overall record ."""
result = [ ] # For the first period start_date = self . start_date for gap in self . pot_data_gaps : end_date = gap . start_date - timedelta ( days = 1 ) result . append ( PotPeriod ( start_date , end_date ) ) # For the next period start_date = gap . end_date + timedelta ( days = 1 ) # For the last peri...
def clean_pod_template ( pod_template ) : """Normalize pod template and check for type errors"""
if isinstance ( pod_template , str ) : msg = ( 'Expected a kubernetes.client.V1Pod object, got %s' 'If trying to pass a yaml filename then use ' 'KubeCluster.from_yaml' ) raise TypeError ( msg % pod_template ) if isinstance ( pod_template , dict ) : msg = ( 'Expected a kubernetes.client.V1Pod object, got %s...
def add_file_handler_to_root ( log_fn ) : """Adds a file handler to the root logging . : param log _ fn : the name of the log file . : type log _ fn : str"""
file_handler = logging . FileHandler ( log_fn , mode = "w" ) file_handler . setFormatter ( logging . Formatter ( fmt = "[%(asctime)s %(name)s %(levelname)s] %(message)s" , datefmt = "%Y-%m-%d %H:%M:%S" , ) ) logging . root . addHandler ( file_handler )