signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def setup ( self , app ) : """Parse and prepare the plugin ' s configuration ."""
super ( ) . setup ( app ) self . enabled = len ( self . cfg . backends ) self . default = self . cfg . default if not self . default and self . enabled : self . default = self . cfg . backends [ 0 ] [ 0 ] self . backends_hash = { name : parse . urlparse ( loc ) for ( name , loc ) in self . cfg . backends } if self ...
def get_size ( self ) : """Get size of this VideoFile in bytes : return : size as integer"""
if self . _size is None : self . _size = self . _filepath . stat ( ) . st_size return self . _size
def get_perturbed_indices ( self , tol = 1e-8 ) : """Gets indices of perturbed elements of the deformation gradient , i . e . those that differ from the identity"""
indices = list ( zip ( * np . where ( abs ( self - np . eye ( 3 ) ) > tol ) ) ) return indices
def distance_to ( self , other_catchment ) : """Returns the distance between the centroids of two catchments in kilometers . : param other _ catchment : Catchment to calculate distance to : type other _ catchment : : class : ` . Catchment ` : return : Distance between the catchments in km . : rtype : float"...
try : if self . country == other_catchment . country : try : return 0.001 * hypot ( self . descriptors . centroid_ngr . x - other_catchment . descriptors . centroid_ngr . x , self . descriptors . centroid_ngr . y - other_catchment . descriptors . centroid_ngr . y ) except TypeError : # I...
def A_cylinder ( D , L ) : r'''Returns the surface area of a cylinder . . . math : : A = \ pi D L + 2 \ cdot \ frac { \ pi D ^ 2 } { 4} Parameters D : float Diameter of the cylinder , [ m ] L : float Length of the cylinder , [ m ] Returns A : float Surface area [ m ] Examples > > > A _ cylin...
cap = pi * D ** 2 / 4 * 2 side = pi * D * L A = cap + side return A
def create_app ( config_name ) : """Factory Function"""
app = Flask ( __name__ ) app . config . from_object ( CONFIG [ config_name ] ) BOOTSTRAP . init_app ( app ) # call controllers from flask_seguro . controllers . main import main as main_blueprint app . register_blueprint ( main_blueprint ) return app
def pivot ( self , columns , rows , values = None , collect = None , zero = None ) : """Generate a table with a column for each unique value in ` ` columns ` ` , with rows for each unique value in ` ` rows ` ` . Each row counts / aggregates the values that match both row and column based on ` ` collect ` ` . ...
if collect is not None and values is None : raise TypeError ( 'collect requires values to be specified' ) if values is not None and collect is None : raise TypeError ( 'values requires collect to be specified' ) columns = self . _as_label ( columns ) rows = self . _as_labels ( rows ) if values is None : sel...
def pad_img ( im , pad ) : """Pad positively with 0 or negatively ( cut ) Parameters im : 2d array The image pad : 4 numbers ( ytop , ybottom , xleft , xright ) or ( imin , imax , jmin , jmax ) Returns im : 2d array The padded ( or cropped ) image offset : 2 numbers The offset related to the inp...
im = np . asarray ( im ) pad = np . asarray ( pad ) # get shape shape = im . shape # extract offset from padding offset = - pad [ : : 2 ] # if the padding is negatif , cut the matrix cut = pad < 0 if cut . any ( ) : # Extract value for pad cut *= pad # the left / top components should be positive cut [ : : ...
def div_safe ( numerator , denominator ) : """Ufunc - extension that returns 0 instead of nan when dividing numpy arrays Parameters numerator : array - like denominator : scalar or array - like that can be validly divided by the numerator returns a numpy array example : div _ safe ( [ - 1 , 0 , 1 ] , 0 ) ...
# First handle scalars if np . isscalar ( numerator ) : raise ValueError ( "div_safe should only be used with an array-like numerator" ) # Then numpy arrays try : with np . errstate ( divide = 'ignore' , invalid = 'ignore' ) : result = np . true_divide ( numerator , denominator ) result [ ~ np ....
def download_manylinux_wheels ( self , abi , packages , directory ) : # type : ( str , List [ str ] , str ) - > None """Download wheel files for manylinux for all the given packages ."""
# If any one of these dependencies fails pip will bail out . Since we # are only interested in all the ones we can download , we need to feed # each package to pip individually . The return code of pip doesn ' t # matter here since we will inspect the working directory to see which # wheels were downloaded . We are onl...
def get_hotp ( secret , intervals_no , as_string = False , casefold = True , digest_method = hashlib . sha1 , token_length = 6 , ) : """Get HMAC - based one - time password on the basis of given secret and interval number . : param secret : the base32 - encoded string acting as secret key : type secret : str ...
if isinstance ( secret , six . string_types ) : # It is unicode , convert it to bytes secret = secret . encode ( 'utf-8' ) # Get rid of all the spacing : secret = secret . replace ( b' ' , b'' ) try : key = base64 . b32decode ( secret , casefold = casefold ) except ( TypeError ) : raise TypeError ( 'Incorre...
def traverse_nodes ( self , qids , up = True , down = False , ** args ) : """Traverse ( optionally ) up and ( optionally ) down from an input set of nodes Arguments qids : list [ str ] list of seed node IDs to start from up : bool if True , include ancestors down : bool if True , include descendants ...
g = self . get_filtered_graph ( ** args ) nodes = set ( ) for id in qids : # reflexive - always add self nodes . add ( id ) if down : nodes . update ( nx . descendants ( g , id ) ) if up : nodes . update ( nx . ancestors ( g , id ) ) return nodes
def _adjust_scrollbar ( self , f ) : """Adjust the scrollbar position to take into account the zooming of the figure ."""
# Adjust horizontal scrollbar : hb = self . horizontalScrollBar ( ) hb . setValue ( int ( f * hb . value ( ) + ( ( f - 1 ) * hb . pageStep ( ) / 2 ) ) ) # Adjust the vertical scrollbar : vb = self . verticalScrollBar ( ) vb . setValue ( int ( f * vb . value ( ) + ( ( f - 1 ) * vb . pageStep ( ) / 2 ) ) )
def _calc_starts ( dims ) : """Calculate starting indexes Parameters dims : list of list of int from ( via cython conversion ) vector [ vector [ uint ] ] dims Examples > > > _ calc _ starts ( [ [ 8 , 2 ] , [ 5 ] , [ 6 , 2 ] ] ) [0 , 16 , 21]"""
# NB : Python uses 0 - indexing ; R uses 1 - indexing . l = len ( dims ) s = [ np . prod ( d ) for d in dims ] starts = np . cumsum ( [ 0 ] + s ) [ 0 : l ] . tolist ( ) # coerce things into ints before returning return [ int ( i ) for i in starts ]
def roleCreated ( self , * args , ** kwargs ) : """Role Created Messages Message that a new role has been created . This exchange outputs : ` ` v1 / role - message . json # ` ` This exchange takes the following keys : * reserved : Space reserved for future routing - key entries , you should always match this ...
ref = { 'exchange' : 'role-created' , 'name' : 'roleCreated' , 'routingKey' : [ { 'multipleWords' : True , 'name' : 'reserved' , } , ] , 'schema' : 'v1/role-message.json#' , } return self . _makeTopicExchange ( ref , * args , ** kwargs )
def read_examples ( input_files , batch_size , shuffle , num_epochs = None ) : """Creates readers and queues for reading example protos ."""
files = [ ] for e in input_files : for path in e . split ( ',' ) : files . extend ( file_io . get_matching_files ( path ) ) thread_count = multiprocessing . cpu_count ( ) # The minimum number of instances in a queue from which examples are drawn # randomly . The larger this number , the more randomness at t...
def _process_state_change_events ( ) : """Process events relating to the overall state of SDP . This function starts and event loop which continually checks for and responds to SDP state change events ."""
sdp_state = SDPState ( ) service_states = get_service_state_list ( ) state_events = sdp_state . get_event_queue ( subscriber = __service_name__ ) state_is_off = sdp_state . current_state == 'off' counter = 0 while True : time . sleep ( 0.1 ) if not state_is_off : # * Hack * to avoid problems with historical eve...
def double_typos ( self ) : """letter combinations two typos away from word"""
return { e2 for e1 in self . typos ( ) for e2 in Word ( e1 ) . typos ( ) }
def x509_name ( name ) : """Parses a subject into a : py : class : ` x509 . Name < cg : cryptography . x509 . Name > ` . If ` ` name ` ` is a string , : py : func : ` parse _ name ` is used to parse it . > > > x509 _ name ( ' / C = AT / CN = example . com ' ) < Name ( C = AT , CN = example . com ) > > > > x...
if isinstance ( name , six . string_types ) : name = parse_name ( name ) return x509 . Name ( [ x509 . NameAttribute ( NAME_OID_MAPPINGS [ typ ] , force_text ( value ) ) for typ , value in name ] )
def _GetStat ( self ) : """Retrieves information about the file entry . Returns : VFSStat : a stat object ."""
stat_object = super ( NTFSFileEntry , self ) . _GetStat ( ) # File data stat information . if self . _fsntfs_file_entry . has_default_data_stream ( ) : stat_object . size = self . _fsntfs_file_entry . get_size ( ) # Ownership and permissions stat information . # TODO : stat _ object . mode # TODO : stat _ object . ...
def _data_augmentation ( self , data , label ) : """perform data augmentations : crop , mirror , resize , sub mean , swap channels . . ."""
if self . is_train and self . _rand_samplers : rand_crops = [ ] for rs in self . _rand_samplers : rand_crops += rs . sample ( label ) num_rand_crops = len ( rand_crops ) # randomly pick up one as input data if num_rand_crops > 0 : index = int ( np . random . uniform ( 0 , 1 ) * num_r...
def create_client ( self , only_db = False ) : """返回连接的客户端"""
# database = parse _ uri ( self . uri ) . get ( " database " ) if self . ioloop : if only_db == False : client = AsyncIOMotorClient ( "/" . join ( self . uri . split ( "/" ) [ : - 1 ] ) , io_loop = self . ioloop ) else : client = AsyncIOMotorClient ( self . uri , io_loop = self . ioloop ) else :...
def calculate_sum_to_n ( n : int ) -> int : """Sums all integers from 1 to n . Parameters : n ( int ) : The range ' s upper limit for the summation . Returns : int : The result of the summation from 1 to n . Examples : > > > calculate _ sum _ to _ n ( 30) 465 > > > calculate _ sum _ to _ n ( 100) ...
return ( 1 + n ) * n // 2
def build_model ( hparams_set , model_name , data_dir , problem_name , beam_size = 1 ) : """Build the graph required to fetch the attention weights . Args : hparams _ set : HParams set to build the model with . model _ name : Name of model . data _ dir : Path to directory containing training data . proble...
hparams = trainer_lib . create_hparams ( hparams_set , data_dir = data_dir , problem_name = problem_name ) translate_model = registry . model ( model_name ) ( hparams , tf . estimator . ModeKeys . EVAL ) inputs = tf . placeholder ( tf . int32 , shape = ( 1 , None , 1 , 1 ) , name = "inputs" ) targets = tf . placeholder...
def decode_conjure_union_type ( cls , obj , conjure_type ) : """Decodes json into a conjure union type . Args : obj : the json object to decode conjure _ type : a class object which is the union type we ' re decoding into Returns : An instance of type conjure _ type ."""
type_of_union = obj [ "type" ] # type : str for attr , conjure_field in conjure_type . _options ( ) . items ( ) : if conjure_field . identifier == type_of_union : attribute = attr conjure_field_definition = conjure_field break else : raise ValueError ( "unknown union type {0} for {1}" . ...
def list_actions ( self ) : """Returns the registered actions . : return : Actions list . : rtype : list"""
actions = [ ] for path , actionName , action in self : actions . append ( self . __namespace_splitter . join ( itertools . chain ( path , ( actionName , ) ) ) ) return sorted ( actions )
def PopAttributeContainer ( self ) : """Pops a serialized attribute container from the list . Returns : bytes : serialized attribute container data ."""
try : serialized_data = self . _list . pop ( 0 ) self . data_size -= len ( serialized_data ) return serialized_data except IndexError : return None
def request_get_next ( request , default_next ) : """get next url form request order : POST . next GET . next HTTP _ REFERER , default _ next"""
next_url = request . POST . get ( 'next' ) or request . GET . get ( 'next' ) or request . META . get ( 'HTTP_REFERER' ) or default_next return next_url
def _process_tz ( self , dt , naive , tz ) : """Process timezone casting and conversion ."""
def _tz ( t ) : if t in ( None , 'naive' ) : return t if t == 'local' : if __debug__ and not localtz : raise ValueError ( "Requested conversion to local timezone, but `localtz` not installed." ) t = localtz if not isinstance ( t , tzinfo ) : if __debug__ and not l...
def rel_humid_from_db_wb ( db_temp , wet_bulb , b_press = 101325 ) : """Relative Humidity ( % ) at db _ temp ( C ) , wet _ bulb ( C ) , and Pressure b _ press ( Pa ) ."""
# Calculate saturation pressure . p_ws = saturated_vapor_pressure ( db_temp + 273.15 ) p_ws_wb = saturated_vapor_pressure ( wet_bulb + 273.15 ) # calculate partial vapor pressure p_w = p_ws_wb - ( b_press * 0.000662 * ( db_temp - wet_bulb ) ) # Calculate the relative humidity . rel_humid = ( p_w / p_ws ) * 100 return r...
def format_sympy_expr ( sympy_expr , functions = None ) : """Convert sympy expression into a string which can be encoded . Args : sympy _ expr : Any sympy expression tree or string . functions : Defines special functions . A dict mapping human readable string names , like " log " , " exp " , " sin " , " cos...
if functions is None : functions = { } str_expr = str ( sympy_expr ) result = str_expr . replace ( " " , "" ) for fn_name , char in six . iteritems ( functions ) : result = result . replace ( fn_name , char ) return result
def format_pair ( input_pair ) : """Formats input to conform with kraken pair format . The API expects one of two formats : XBTXLT or XXBTXLTC Where crypto currencies have an X prepended , and fiat currencies have a Z prepended . Since the API returns the 8 character format , that ' s what we will for...
# There are some exceptions from the general formatting rule # see https : / / api . kraken . com / 0 / public / AssetPairs format_exceptions = [ 'BCHEUR' , 'BCHUSD' , 'BCHXBT' , 'DASHEUR' , 'DASHUSD' , 'DASHXBT' , 'EOSETH' , 'EOSXBT' , 'GNOETH' , 'GNOXBT' , 'USDTZUSD' ] if input_pair . upper ( ) in format_exceptions :...
def getTickTock ( self , vals ) : '''Get a tick , tock time pair . Args : vals ( list ) : A pair of values to norm . Returns : ( int , int ) : A ordered pair of integers .'''
val0 , val1 = vals try : _tick = self . _getLiftValu ( val0 ) except ValueError as e : raise s_exc . BadTypeValu ( name = self . name , valu = val0 , mesg = 'Unable to process the value for val0 in getTickTock.' ) sortval = False if isinstance ( val1 , str ) : if val1 . startswith ( ( '+-' , '-+' ) ) : ...
def port_provisioned ( port_id ) : """Returns true if port still exists ."""
session = db . get_reader_session ( ) with session . begin ( ) : port_model = models_v2 . Port res = bool ( session . query ( port_model ) . filter ( port_model . id == port_id ) . count ( ) ) return res
def display_context ( doc ) : """Create a Jinja context for display"""
from rowgenerators . exceptions import DownloadError context = { s . name . lower ( ) : s . as_dict ( ) for s in doc if s . name . lower ( ) != 'schema' } # import json # print ( json . dumps ( context , indent = 4 ) ) mandatory_sections = [ 'documentation' , 'contacts' ] # Remove section names deletes = [ ] for k , v ...
def evaluateRforces ( Pot , R , z , phi = None , t = 0. , v = None ) : """NAME : evaluateRforce PURPOSE : convenience function to evaluate a possible sum of potentials INPUT : Pot - a potential or list of potentials R - cylindrical Galactocentric distance ( can be Quantity ) z - distance above the pla...
return _evaluateRforces ( Pot , R , z , phi = phi , t = t , v = v )
def _get_scalar_names ( self , limit = None ) : """Only give scalar options that have a varying range"""
names = [ ] if limit == 'point' : inpnames = list ( self . input_dataset . point_arrays . keys ( ) ) elif limit == 'cell' : inpnames = list ( self . input_dataset . cell_arrays . keys ( ) ) else : inpnames = self . input_dataset . scalar_names for name in inpnames : arr = self . input_dataset . get_scal...
def download_data ( request_list , redownload = False , max_threads = None ) : """Download all requested data or read data from disk , if already downloaded and available and redownload is not required . : param request _ list : list of DownloadRequests : type request _ list : list of DownloadRequests : par...
_check_if_must_download ( request_list , redownload ) LOGGER . debug ( "Using max_threads=%s for %s requests" , max_threads , len ( request_list ) ) with concurrent . futures . ThreadPoolExecutor ( max_workers = max_threads ) as executor : return [ executor . submit ( execute_download_request , request ) for reques...
def loadfile ( method = True , writable = False , create = False ) : """A decorator for functions taking a ` filething ` as a first argument . Passes a FileThing instance as the first argument to the wrapped function . Args : method ( bool ) : If the wrapped functions is a method writable ( bool ) : If a fi...
def convert_file_args ( args , kwargs ) : filething = args [ 0 ] if args else None filename = kwargs . pop ( "filename" , None ) fileobj = kwargs . pop ( "fileobj" , None ) return filething , filename , fileobj , args [ 1 : ] , kwargs def wrap ( func ) : @ wraps ( func ) def wrapper ( self , * a...
def loads ( text ) : """Read CCSDS from a string , and provide the beyond class corresponding ; Orbit or list of Orbit if it ' s an OPM , Ephem if it ' s an OEM . Args : text ( str ) : Return : Orbit or Ephem Raise : ValueError : when the text is not a recognizable CCSDS format"""
if text . startswith ( "CCSDS_OEM_VERS" ) : func = _read_oem elif text . startswith ( "CCSDS_OPM_VERS" ) : func = _read_opm else : raise ValueError ( "Unknown CCSDS type" ) return func ( text )
async def runCmdLine ( self , line ) : '''Run a single command line . Args : line ( str ) : Line to execute . Examples : Execute the ' woot ' command with the ' help ' switch : await cli . runCmdLine ( ' woot - - help ' ) Returns : object : Arbitrary data from the cmd class .'''
if self . echoline : self . outp . printf ( f'{self.cmdprompt}{line}' ) ret = None name = line . split ( None , 1 ) [ 0 ] cmdo = self . getCmdByName ( name ) if cmdo is None : self . printf ( 'cmd not found: %s' % ( name , ) ) return try : ret = await cmdo . runCmdLine ( line ) except s_exc . CliFini : ...
def get_doc ( logger = None , plugin = None , reporthook = None ) : """Return URL to documentation . Attempt download if does not exist . Parameters logger : obj or ` None ` Ginga logger . plugin : obj or ` None ` Plugin object . If given , URL points to plugin doc directly . If this function is called ...
from ginga . GingaPlugin import GlobalPlugin , LocalPlugin if isinstance ( plugin , GlobalPlugin ) : plugin_page = 'plugins_global' plugin_name = str ( plugin ) elif isinstance ( plugin , LocalPlugin ) : plugin_page = 'plugins_local' plugin_name = str ( plugin ) else : plugin_page = None plugin_...
def generate_map_from_dataset ( self , l_dataset ) : """creates a map file ( in the standard CSV format ) based on columns of a dataset . 1 . read column names , lookup names in list 2 . read column content , get highest match of distinct values from ontology lists ( eg , Years , countries , cities , ages )...
l_map = [ ] headers = l_dataset . get_header ( ) print ( headers ) for row_num , col in enumerate ( headers ) : if col != '' : l_map . append ( 'column:name:' + str ( row_num ) + '=' + l_dataset . force_to_string ( col ) ) for row_num , col in enumerate ( headers ) : if col != '' : vals = l_data...
async def unban_chat_member ( self , chat_id : typing . Union [ base . Integer , base . String ] , user_id : base . Integer ) -> base . Boolean : """Use this method to unban a previously kicked user in a supergroup or channel . ` The user will not return to the group or channel automatically , but will be able to...
payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . UNBAN_CHAT_MEMBER , payload ) return result
def DisplayAccountTree ( account , accounts , links , depth = 0 ) : """Displays an account tree . Args : account : dict The account to display . accounts : dict Map from customerId to account . links : dict Map from customerId to child links . depth : int Depth of the current account in the tree ."""
prefix = '-' * depth * 2 print '%s%s, %s' % ( prefix , account [ 'customerId' ] , account [ 'name' ] ) if account [ 'customerId' ] in links : for child_link in links [ account [ 'customerId' ] ] : child_account = accounts [ child_link [ 'clientCustomerId' ] ] DisplayAccountTree ( child_account , acc...
def iter_all_volumes ( self ) : '''iterate over all stored volumes'''
for raw_volume in self . _db . iterate_all ( ) : v = self . normalize_volume ( raw_volume ) del v [ 'score' ] yield v
def NotificationsDelete ( self , notification_id ) : """Delete a notification from CommonSense . @ param notification _ id ( int ) - Notification id of the notification to delete . @ return ( bool ) - Boolean indicating whether NotificationsDelete was successful ."""
if self . __SenseApiCall__ ( '/notifications/{0}.json' . format ( notification_id ) , 'DELETE' ) : return True else : self . __error__ = "api call unsuccessful" return False
def info ( name ) : '''Return information about a group CLI Example : . . code - block : : bash salt ' * ' group . info foo'''
if salt . utils . stringutils . contains_whitespace ( name ) : raise SaltInvocationError ( 'Group name cannot contain whitespace' ) try : # getgrnam seems to cache weirdly , so don ' t use it grinfo = next ( iter ( x for x in grp . getgrall ( ) if x . gr_name == name ) ) except StopIteration : return { } el...
def partition_query ( self , sql , params = None , param_types = None , partition_size_bytes = None , max_partitions = None , ) : """Perform a ` ` ParitionQuery ` ` API request . : type sql : str : param sql : SQL query statement : type params : dict , { str - > column value } : param params : values for pa...
if not self . _multi_use : raise ValueError ( "Cannot use single-use snapshot." ) if self . _transaction_id is None : raise ValueError ( "Transaction not started." ) if params is not None : if param_types is None : raise ValueError ( "Specify 'param_types' when passing 'params'." ) params_pb = S...
def store ( self , addr , data , size = None , condition = None , add_constraints = None , endness = None , action = None , inspect = True , priv = None , disable_actions = False ) : """Stores content into memory . : param addr : A claripy expression representing the address to store at . : param data : The dat...
_inspect = inspect and self . state . supports_inspect if priv is not None : self . state . scratch . push_priv ( priv ) addr_e = _raw_ast ( addr ) data_e = _raw_ast ( data ) size_e = _raw_ast ( size ) condition_e = _raw_ast ( condition ) add_constraints = True if add_constraints is None else add_constraints if isi...
def merge ( self , cluster_ids = None , to = None ) : """Merge the selected clusters ."""
if cluster_ids is None : cluster_ids = self . selected if len ( cluster_ids or [ ] ) <= 1 : return self . clustering . merge ( cluster_ids , to = to ) self . _global_history . action ( self . clustering )
def get_box_comments ( self , box_key ) : '''Gets comments in a box with the provided attributes . Args : box _ keykey for box return ( status code , list of comment dicts )'''
uri = '/' . join ( [ self . api_uri , self . boxes_suffix , box_key , self . comments_suffix ] ) return self . _req ( 'get' , uri )
async def try_trigger_before_first_request_functions ( self ) -> None : """Trigger the before first request methods ."""
if self . _got_first_request : return # Reverse the teardown functions , so as to match the expected usage self . teardown_appcontext_funcs = list ( reversed ( self . teardown_appcontext_funcs ) ) for key , value in self . teardown_request_funcs . items ( ) : self . teardown_request_funcs [ key ] = list ( rever...
def roll ( self , count = 0 ) : '''Roll some dice ! : param count : [ 0 ] Return list of sums : return : A single sum or list of ` ` count ` ` sums'''
return super ( FuncRoll , self ) . roll ( count , self . _func )
def parse_soap_enveloped_saml_thingy ( text , expected_tags ) : """Parses a SOAP enveloped SAML thing and returns the thing as a string . : param text : The SOAP object as XML string : param expected _ tags : What the tag of the SAML thingy is expected to be . : return : SAML thingy as a string"""
envelope = defusedxml . ElementTree . fromstring ( text ) # Make sure it ' s a SOAP message assert envelope . tag == '{%s}Envelope' % soapenv . NAMESPACE assert len ( envelope ) >= 1 body = None for part in envelope : if part . tag == '{%s}Body' % soapenv . NAMESPACE : assert len ( part ) == 1 body ...
def getresource ( self , schemacls , name ) : """Get a resource from a builder name . : param type schemacls : waited schema class . : param str name : builder name to use . : return : resource returned by the right builder . getresource ( schema ) ."""
return _SCHEMAFACTORY . getresource ( schemacls = schemacls , name = name )
def cmd_reboot ( self , args ) : '''reboot autopilot'''
if len ( args ) > 0 and args [ 0 ] == 'bootloader' : self . master . reboot_autopilot ( True ) else : self . master . reboot_autopilot ( )
def push ( ** kwargs ) : '''Force synchronization of directory .'''
output , err = cli_syncthing_adapter . refresh ( ** kwargs ) if output : click . echo ( "%s" % output , err = err ) if kwargs [ 'verbose' ] and not err : with click . progressbar ( iterable = None , length = 100 , label = 'Synchronizing' ) as bar : device_num = 0 max_devices = 1 prev_per...
def guard_submit ( obj ) : """Returns if ' submit ' transition can be applied to the worksheet passed in . By default , the target state for the ' submit ' transition for a worksheet is ' to _ be _ verified ' , so this guard returns true if all the analyses assigned to the worksheet have already been submitte...
analyses = obj . getAnalyses ( ) if not analyses : # An empty worksheet cannot be submitted return False can_submit = False for analysis in obj . getAnalyses ( ) : # Dismiss analyses that are not active if not api . is_active ( analysis ) : continue # Dismiss analyses that have been rejected or retr...
def construct_sm_match_dict ( self ) : """Construct the sm _ match _ dict . Reverse the key value structure . The sm _ match _ dict is bigger , but allows for direct matching using a dictionary key access . The sound _ mode _ dict is uses externally to set this dictionary because that has a nicer syntax .""...
mode_dict = list ( self . _sound_mode_dict . items ( ) ) match_mode_dict = { } for matched_mode , sublist in mode_dict : for raw_mode in sublist : match_mode_dict [ raw_mode . upper ( ) ] = matched_mode return match_mode_dict
def load_corpus ( * data_file_paths ) : """Return the data contained within a specified corpus ."""
for file_path in data_file_paths : corpus = [ ] corpus_data = read_corpus ( file_path ) conversations = corpus_data . get ( 'conversations' , [ ] ) corpus . extend ( conversations ) categories = corpus_data . get ( 'categories' , [ ] ) yield corpus , categories , file_path
def p_IfBlock ( p ) : '''IfBlock : IF Expression COLON Terminator Block | IfBlock ELIF Expression COLON Terminator Block'''
if isinstance ( p [ 1 ] , str ) : p [ 0 ] = IfBlock ( None , p [ 2 ] , p [ 4 ] , p [ 5 ] ) else : p [ 0 ] = IfBlock ( p [ 1 ] , p [ 3 ] , p [ 5 ] , p [ 6 ] )
def make_systeminfoitem_hostname ( hostname , condition = 'contains' , negate = False , preserve_case = False ) : """Create a node for SystemInfoItem / hostname : return : A IndicatorItem represented as an Element node"""
document = 'SystemInfoItem' search = 'SystemInfoItem/hostname' content_type = 'string' content = hostname ii_node = ioc_api . make_indicatoritem_node ( condition , document , search , content_type , content , negate = negate , preserve_case = preserve_case ) return ii_node
def get_html_desc ( self , markdown_inst = None ) : """Translates the enum ' s ' desc ' property into HTML . Any RDLFormatCode tags used in the description are converted to HTML . The text is also fed through a Markdown processor . The additional Markdown processing allows designers the choice to use a more...
desc_str = self . _rdl_desc_ if desc_str is None : return None return rdlformatcode . rdlfc_to_html ( desc_str , md = markdown_inst )
def _validate_request_action ( self , action ) : """Validate action from the request json , according to APPLY _ CONNECTIVITY _ CHANGES _ ACTION _ REQUIRED _ ATTRIBUTE _ LIST"""
is_fail = False fail_attribute = "" for class_attribute in self . APPLY_CONNECTIVITY_CHANGES_ACTION_REQUIRED_ATTRIBUTE_LIST : if type ( class_attribute ) is tuple : if not hasattr ( action , class_attribute [ 0 ] ) : is_fail = True fail_attribute = class_attribute [ 0 ] if no...
def assign_comment_to_book ( self , comment_id , book_id ) : """Adds an existing ` ` Comment ` ` to a ` ` Book ` ` . arg : comment _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Comment ` ` arg : book _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Book ` ` raise : AlreadyExists - ` ` comment _ id ` ...
# Implemented from template for # osid . resource . ResourceBinAssignmentSession . assign _ resource _ to _ bin mgr = self . _get_provider_manager ( 'COMMENTING' , local = True ) lookup_session = mgr . get_book_lookup_session ( proxy = self . _proxy ) lookup_session . get_book ( book_id ) # to raise NotFound self . _as...
def validate_request ( self , iface_name , func_name , params ) : """Validates that the given params match the expected length and types for this interface and function . Returns two element tuple : ( bool , string ) - ` bool ` - True if valid , False if not - ` string ` - Description of validation error , ...
self . interface ( iface_name ) . function ( func_name ) . validate_params ( params )
def get_path_str ( self , sep = os . path . sep , type_str = None ) : """Get path from root to this node . Args : sep : str One or more characters to insert between each element in the path . Defaults to " / " on Unix and " \" on Windows . type _ str : SUBJECT _ NODE _ TAG , TYPE _ NODE _ TAG or None . ...
return sep . join ( list ( reversed ( [ v . label_str for v in self . parent_gen if type_str in ( None , v . type_str ) ] ) ) )
def mapkeys ( function , dict_ ) : """Return a new dictionary where the keys come from applying ` ` function ` ` to the keys of given dictionary . . . warning : : If ` ` function ` ` returns the same value for more than one key , it is undefined which key will be chosen for the resulting dictionary . : pa...
ensure_mapping ( dict_ ) function = identity ( ) if function is None else ensure_callable ( function ) return dict_ . __class__ ( ( function ( k ) , v ) for k , v in iteritems ( dict_ ) )
def prep_jid ( nocache = False , passed_jid = None , recurse_count = 0 ) : '''Return a job id and prepare the job id directory . This is the function responsible for making sure jids don ' t collide ( unless it is passed a jid ) . So do what you have to do to make sure that stays the case'''
if recurse_count >= 5 : err = 'prep_jid could not store a jid after {0} tries.' . format ( recurse_count ) log . error ( err ) raise salt . exceptions . SaltCacheError ( err ) if passed_jid is None : # this can be a None or an empty string . jid = salt . utils . jid . gen_jid ( __opts__ ) else : jid...
def close ( self ) : """Closes Serial port , or TCP - Socket connection"""
if ( self . __ser is not None ) : self . __ser . close ( ) if ( self . __tcpClientSocket is not None ) : self . __stoplistening = True self . __tcpClientSocket . shutdown ( socket . SHUT_RDWR ) self . __tcpClientSocket . close ( ) self . __connected = False
def main ( ) : """This example demonstrates how to generate pretty equations from the analytic expressions found in ` ` chempy . kinetics . integrated ` ` ."""
t , kf , t0 , major , minor , prod , beta = sympy . symbols ( 't k_f t0 Y Z X beta' , negative = False ) for f in funcs : args = [ t , kf , prod , major , minor ] if f in ( pseudo_rev , binary_rev ) : args . insert ( 2 , kf / beta ) expr = f ( * args , backend = 'sympy' ) with open ( f . __name_...
def scene ( self , value ) : """Set the reference to the scene that this camera is in . Parameters scene : None , or trimesh . Scene Scene where this camera is attached"""
# save the scene reference self . _scene = value # check if we have local not None transform # an if we can apply it to the scene graph # also check here that scene is a real scene if ( hasattr ( self , '_transform' ) and self . _transform is not None and hasattr ( value , 'graph' ) ) : # set scene transform to locally...
async def load_uint ( reader , width ) : """Constant - width integer serialization : param reader : : param width : : return :"""
buffer = _UINT_BUFFER result = 0 shift = 0 for _ in range ( width ) : await reader . areadinto ( buffer ) result += buffer [ 0 ] << shift shift += 8 return result
def root2hdf5 ( rfile , hfile , rpath = '' , entries = - 1 , userfunc = None , show_progress = False , ignore_exception = False , ** kwargs ) : """Convert all trees in a ROOT file into tables in an HDF5 file . Parameters rfile : string or asrootpy ' d ROOT File A ROOT File handle or string path to an existing...
own_rootfile = False if isinstance ( rfile , string_types ) : rfile = root_open ( rfile ) own_rootfile = True own_h5file = False if isinstance ( hfile , string_types ) : hfile = tables_open ( filename = hfile , mode = "w" , title = "Data" ) own_h5file = True for dirpath , dirnames , treenames in rfile ....
def Artifacts ( self , os_name = None , cpe = None , label = None ) : """Whether the conditions applies , modulo host data . Args : os _ name : An OS string . cpe : A CPE string . label : A label string . Returns : True if os _ name , cpe or labels match . Empty values are ignored ."""
hit = lambda x : x [ 0 ] == x [ 1 ] or not x [ 0 ] seq = [ ( self . os_name , os_name ) , ( self . cpe , cpe ) , ( self . label , label ) ] return all ( map ( hit , seq ) )
def cmd ( parent ) : """Determine subshell command for subprocess . call Arguments : parent ( str ) : Absolute path to parent shell executable"""
shell_name = os . path . basename ( parent ) . rsplit ( "." , 1 ) [ 0 ] dirname = os . path . dirname ( __file__ ) # Support for Bash if shell_name in ( "bash" , "sh" ) : shell = os . path . join ( dirname , "_shell.sh" ) . replace ( "\\" , "/" ) cmd = [ parent . replace ( "\\" , "/" ) , shell ] # Support for C...
def convert_data_array ( arr , filter_func = None , converter_func = None ) : '''Filter and convert any given data array of any dtype . Parameters arr : numpy . array Data array of any dtype . filter _ func : function Function that takes array and returns true or false for each item in array . converter...
# if filter _ func ! = None : # if not hasattr ( filter _ func , ' _ _ call _ _ ' ) : # raise ValueError ( ' Filter is not callable ' ) if filter_func : array = arr [ filter_func ( arr ) ] # Indexing with Boolean Arrays # if converter _ func ! = None : # if not hasattr ( converter _ func , ' _ _ call _ _ ' ) : ...
def get_gaussian_weight ( self , anchor ) : """Args : anchor : coordinate of the center"""
ret = np . zeros ( self . shape , dtype = 'float32' ) y , x = np . mgrid [ : self . shape [ 0 ] , : self . shape [ 1 ] ] y = y . astype ( 'float32' ) / ret . shape [ 0 ] - anchor [ 0 ] x = x . astype ( 'float32' ) / ret . shape [ 1 ] - anchor [ 1 ] g = np . exp ( - ( x ** 2 + y ** 2 ) / self . sigma ) # cv2 . imshow ( ...
def is_transactional ( self , state ) : '''Decide if a request should be wrapped in a transaction , based upon the state of the request . By default , wraps all but ` ` GET ` ` and ` ` HEAD ` ` requests in a transaction , along with respecting the ` ` transactional ` ` decorator from : mod : pecan . decorator...
controller = getattr ( state , 'controller' , None ) if controller : force_transactional = _cfg ( controller ) . get ( 'transactional' , False ) else : force_transactional = False if state . request . method not in ( 'GET' , 'HEAD' ) or force_transactional : return True return False
def readinto ( self , byte_array ) : """Read data into a byte array , upto the size of the byte array . : param byte _ array : A byte array / memory view to pour bytes into . : type byte _ array : ` ` bytearray ` ` or ` ` memoryview ` `"""
max_size = len ( byte_array ) data = self . read ( max_size ) bytes_read = len ( data ) byte_array [ : bytes_read ] = data return bytes_read
def GTax ( x , ax ) : """Compute transpose of gradient of ` x ` along axis ` ax ` . Parameters x : array _ like Input array ax : int Axis on which gradient transpose is to be computed Returns xg : ndarray Output array"""
slc0 = ( slice ( None ) , ) * ax xg = np . roll ( x , 1 , axis = ax ) - x xg [ slc0 + ( slice ( 0 , 1 ) , ) ] = - x [ slc0 + ( slice ( 0 , 1 ) , ) ] xg [ slc0 + ( slice ( - 1 , None ) , ) ] = x [ slc0 + ( slice ( - 2 , - 1 ) , ) ] return xg
def to_one_str ( cls , value , * args , ** kwargs ) : """Convert single record ' s values to str"""
if kwargs . get ( 'wrapper' ) : return cls . _wrapper_to_one_str ( value ) return _es . to_dict_str ( value )
def json ( self ) : """Return a JSON - serializable representation of this result . The output of this function can be converted to a serialized string with : any : ` json . dumps ` ."""
return { "observed_length" : _json_safe_float ( self . observed_length ) , "predicted_length" : _json_safe_float ( self . predicted_length ) , "merged_length" : _json_safe_float ( self . merged_length ) , "num_parameters" : _json_safe_float ( self . num_parameters ) , "observed_mean" : _json_safe_float ( self . observe...
def on_finish ( self ) : """Records the time taken to process the request . This method records the amount of time taken to process the request ( as reported by : meth : ` ~ tornado . httputil . HTTPServerRequest . request _ time ` ) under the path defined by the class ' s module , it ' s name , the request...
super ( ) . on_finish ( ) self . record_timing ( self . request . request_time ( ) , self . __class__ . __name__ , self . request . method , self . get_status ( ) )
def centroid ( coo ) : """Calculates the centroid from a 3D point cloud and returns the coordinates : param coo : Array of coordinate arrays : returns : centroid coordinates as list"""
return list ( map ( np . mean , ( ( [ c [ 0 ] for c in coo ] ) , ( [ c [ 1 ] for c in coo ] ) , ( [ c [ 2 ] for c in coo ] ) ) ) )
def format_help ( self ) : """Override help doc to add cell args ."""
if not self . _cell_args : return super ( CommandParser , self ) . format_help ( ) else : # Print the standard argparse info , the cell arg block , and then the epilog # If we don ' t remove epilog before calling the super , then epilog will # be printed before the ' Cell args ' block . epilog = self . epilog ...
def unique_bincount ( values , minlength , return_inverse = True ) : """For arrays of integers find unique values using bin counting . Roughly 10x faster for correct input than np . unique Parameters values : ( n , ) int Values to find unique members of minlength : int Maximum value that will occur in v...
values = np . asanyarray ( values ) if len ( values . shape ) != 1 or values . dtype . kind != 'i' : raise ValueError ( 'input must be 1D integers!' ) try : # count the number of occurrences of each value counts = np . bincount ( values , minlength = minlength ) except TypeError : # casting failed on 32 bit win...
def set_position_target_local_ned_encode ( self , time_boot_ms , target_system , target_component , coordinate_frame , type_mask , x , y , z , vx , vy , vz , afx , afy , afz , yaw , yaw_rate ) : '''Sets a desired vehicle position in a local north - east - down coordinate frame . Used by an external controller to ...
return MAVLink_set_position_target_local_ned_message ( time_boot_ms , target_system , target_component , coordinate_frame , type_mask , x , y , z , vx , vy , vz , afx , afy , afz , yaw , yaw_rate )
def decompose_covariance ( c ) : """This decomposes a covariance matrix into an error vector and a correlation matrix"""
# make it a kickass copy of the original c = _n . array ( c ) # first get the error vector e = [ ] for n in range ( 0 , len ( c [ 0 ] ) ) : e . append ( _n . sqrt ( c [ n ] [ n ] ) ) # now cycle through the matrix , dividing by e [ 1 ] * e [ 2] for n in range ( 0 , len ( c [ 0 ] ) ) : for m in range ( 0 , len (...
def calc_x_from_L ( L , y ) : """Calculate the industry output x from L and a y vector Parameters L : pandas . DataFrame or numpy . array Symmetric input output Leontief table y : pandas . DataFrame or numpy . array a column vector of the total final demand Returns pandas . DataFrame or numpy . array ...
x = L . dot ( y ) if type ( x ) is pd . Series : x = pd . DataFrame ( x ) if type ( x ) is pd . DataFrame : x . columns = [ 'indout' ] return x
def key ( self , direction , mechanism , purviews = False , _prefix = None ) : """Cache key . This is the call signature of | Subsystem . find _ mice ( ) | ."""
return ( _prefix , direction , mechanism , purviews )
def set_func ( self , func , pnames , args = ( ) ) : """Set the model function to use an efficient but tedious calling convention . The function should obey the following convention : : def func ( param _ vec , * args ) : modeled _ data = { do something using param _ vec } return modeled _ data This funct...
from . lmmin import Problem self . func = func self . _args = args self . pnames = list ( pnames ) self . lm_prob = Problem ( len ( self . pnames ) ) return self
def match_any_learning_objective ( self , match ) : """Matches an item with any objective . arg : match ( boolean ) : ` ` true ` ` to match items with any learning objective , ` ` false ` ` to match items with no learning objectives * compliance : mandatory - - This method must be implemented . *"""
match_key = 'learningObjectiveIds' param = '$exists' if match : flag = 'true' else : flag = 'false' if match_key in self . _my_osid_query . _query_terms : self . _my_osid_query . _query_terms [ match_key ] [ param ] = flag else : self . _my_osid_query . _query_terms [ match_key ] = { param : flag } self...
def _gather_config_parms ( self , is_provider_vlan , vlan_id ) : """Collect auto _ create , auto _ trunk from config ."""
if is_provider_vlan : auto_create = cfg . CONF . ml2_cisco . provider_vlan_auto_create auto_trunk = cfg . CONF . ml2_cisco . provider_vlan_auto_trunk else : auto_create = True auto_trunk = True return auto_create , auto_trunk
def _is_child ( self , parent , child ) : # type : ( str , str ) - > bool """Returns whether a key is strictly a child of another key . AoT siblings are not considered children of one another ."""
parent_parts = tuple ( self . _split_table_name ( parent ) ) child_parts = tuple ( self . _split_table_name ( child ) ) if parent_parts == child_parts : return False return parent_parts == child_parts [ : len ( parent_parts ) ]
def AuthenticatedOrRedirect ( invocation ) : """Middleware class factory that redirects if the user is not logged in . Otherwise , nothing is effected ."""
class AuthenticatedOrRedirect ( GiottoInputMiddleware ) : def http ( self , request ) : if request . user : return request return Redirection ( invocation ) def cmd ( self , request ) : if request . user : return request return Redirection ( invocation ) r...
def kpl_on ( self , address , group ) : """Get the status of a KPL button ."""
addr = Address ( address ) device = self . plm . devices [ addr . id ] device . states [ group ] . on ( )
def contraction_conical ( Di1 , Di2 , fd = None , l = None , angle = None , Re = None , roughness = 0.0 , method = 'Rennels' ) : r'''Returns the loss coefficient for any conical pipe contraction . This calculation has five methods available . The ' Idelchik ' [ 2 ] _ and ' Blevins ' [ 3 ] _ methods use interpol...
beta = Di2 / Di1 if angle is not None : angle_rad = radians ( angle ) l = ( Di1 - Di2 ) / ( 2.0 * tan ( 0.5 * angle_rad ) ) elif l is not None : try : angle_rad = 2.0 * atan ( ( Di1 - Di2 ) / ( 2.0 * l ) ) angle = degrees ( angle_rad ) except ZeroDivisionError : angle_rad = pi ...
def load_inventory_from_cache ( self ) : '''Reads the inventory from the cache file and returns it as a JSON object'''
cache = open ( self . cache_path_cache , 'r' ) json_inventory = cache . read ( ) self . inventory = json . loads ( json_inventory )