signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def value ( self ) : """Get the summation of all non - expired points"""
now = time . time ( ) cutoff = now - self . window while self . points and self . points [ 0 ] [ 0 ] < cutoff : self . points . pop ( 0 ) return sum ( [ p [ 1 ] for p in self . points ] )
def cum_serial ( self , raw , rev = 0 ) : """Cumulate serial data and return times ( int ) 計算數據重複 ( 持續 ) 次數"""
org = raw [ 1 : ] diff = raw [ : - 1 ] result = [ ] for i in xrange ( len ( org ) ) : result . append ( self . high_or_low ( org [ i ] , diff [ i ] , rev ) ) times = 0 try : if result [ - 1 ] == result [ - 2 ] : signal = result [ - 1 ] re_signal = result [ : ] try : while sig...
def render_node ( node , context = None , edit = True ) : """Render node as html for templates , with edit tagging ."""
output = node . render ( ** context or { } ) or u'' if edit : return u'<span data-i18n="{0}">{1}</span>' . format ( node . uri . clone ( scheme = None , ext = None , version = None ) , output ) else : return output
def shared_databases ( self ) : """Retrieves a list containing the names of databases shared with this account . : returns : List of database names"""
endpoint = '/' . join ( ( self . server_url , '_api' , 'v2' , 'user' , 'shared_databases' ) ) resp = self . r_session . get ( endpoint ) resp . raise_for_status ( ) data = response_to_json_dict ( resp ) return data . get ( 'shared_databases' , [ ] )
def markdown ( value , extensions = MARKDOWN_EXTENSIONS ) : """Markdown processing with optionally using various extensions that python - markdown supports . ` extensions ` is an iterable of either markdown . Extension instances or extension paths ."""
try : import markdown except ImportError : warnings . warn ( "The Python markdown library isn't installed." , RuntimeWarning ) return value return markdown . markdown ( force_text ( value ) , extensions = extensions )
def get_issues_event ( self , id ) : """: calls : ` GET / repos / : owner / : repo / issues / events / : id < http : / / developer . github . com / v3 / issues / events > ` _ : param id : integer : rtype : : class : ` github . IssueEvent . IssueEvent `"""
assert isinstance ( id , ( int , long ) ) , id headers , data = self . _requester . requestJsonAndCheck ( "GET" , self . url + "/issues/events/" + str ( id ) , headers = { 'Accept' : Consts . mediaTypeLockReasonPreview } ) return github . IssueEvent . IssueEvent ( self . _requester , headers , data , completed = True )
def node_sub ( self , node_self , node_other ) : '''node _ sub Low - level api : Compute the delta of two configs . This method is recursive . Assume two configs are different . Parameters node _ self : ` Element ` A config node in a config tree that is being processed . node _ self cannot be a leaf nod...
def same_leaf_list ( tag ) : list_self = [ c for c in list ( node_self ) if c . tag == tag ] list_other = [ c for c in list ( node_other ) if c . tag == tag ] s_node = self . device . get_schema_node ( ( list_self + list_other ) [ 0 ] ) if s_node . get ( 'ordered-by' ) == 'user' : if [ i . text ...
def add_group_grant ( self , permission , group_id ) : """Convenience method that provides a quick way to add a canonical group grant to a key . This method retrieves the current ACL , creates a new grant based on the parameters passed in , adds that grant to the ACL and then PUT ' s the new ACL back to GS . ...
acl = self . get_acl ( ) acl . add_group_grant ( permission , group_id ) self . set_acl ( acl )
def new ( self , sources_by_grp ) : """Generate a new CompositeSourceModel from the given dictionary . : param sources _ by _ group : a dictionary grp _ id - > sources : returns : a new CompositeSourceModel instance"""
source_models = [ ] for sm in self . source_models : src_groups = [ ] for src_group in sm . src_groups : sg = copy . copy ( src_group ) sg . sources = sorted ( sources_by_grp . get ( sg . id , [ ] ) , key = operator . attrgetter ( 'id' ) ) src_groups . append ( sg ) newsm = logictree...
def get_image ( self , filename : str = None ) -> None : """Download the photo associated with a Savings Goal ."""
if filename is None : filename = "{0}.png" . format ( self . name ) endpoint = "/account/{0}/savings-goals/{1}/photo" . format ( self . _account_uid , self . uid ) response = get ( _url ( endpoint , self . _sandbox ) , headers = self . _auth_headers ) response . raise_for_status ( ) base64_image = response . json (...
def BeginEdit ( self , row , col , grid ) : """Fetch the value from the table and prepare the edit control to begin editing . Set the focus to the edit control . * Must Override *"""
# Disable if cell is locked , enable if cell is not locked grid = self . main_window . grid key = grid . actions . cursor locked = grid . code_array . cell_attributes [ key ] [ "locked" ] or grid . code_array . cell_attributes [ key ] [ "button_cell" ] self . _tc . Enable ( not locked ) self . _tc . Show ( not locked )...
def _count_counters ( self , counter ) : """Return all elements count from Counter"""
if getattr ( self , 'as_set' , False ) : return len ( set ( counter ) ) else : return sum ( counter . values ( ) )
def notification_filters ( self ) : """Property for accessing : class : ` NotificationFilterManager ` instance , which is used to manage notification filters . : rtype : yagocd . resources . notification _ filter . NotificationFilterManager"""
if self . _notification_filter_manager is None : self . _notification_filter_manager = NotificationFilterManager ( session = self . _session ) return self . _notification_filter_manager
def rolling_restart ( self , slave_batch_size = None , slave_fail_count_threshold = None , sleep_seconds = None , stale_configs_only = None , unupgraded_only = None , restart_role_types = None , restart_role_names = None ) : """Rolling restart the roles of a service . The sequence is : 1 . Restart all the non - s...
args = dict ( ) if slave_batch_size : args [ 'slaveBatchSize' ] = slave_batch_size if slave_fail_count_threshold : args [ 'slaveFailCountThreshold' ] = slave_fail_count_threshold if sleep_seconds : args [ 'sleepSeconds' ] = sleep_seconds if stale_configs_only : args [ 'staleConfigsOnly' ] = stale_config...
def intersect ( self , other , strategy = _STRATEGY . GEOMETRIC , _verify = True ) : """Find the common intersection with another surface . Args : other ( Surface ) : Other surface to intersect with . strategy ( Optional [ ~ bezier . curve . IntersectionStrategy ] ) : The intersection algorithm to use . Def...
if _verify : if not isinstance ( other , Surface ) : raise TypeError ( "Can only intersect with another surface" , "Received" , other , ) if self . _dimension != 2 or other . _dimension != 2 : raise NotImplementedError ( "Intersection only implemented in 2D" ) if strategy == _STRATEGY . GEOMETRI...
def _kpatch ( url , data ) : '''patch any object in kubernetes based on URL'''
# Prepare headers headers = { "Content-Type" : "application/json-patch+json" } # Make request ret = http . query ( url , method = 'PATCH' , header_dict = headers , data = salt . utils . json . dumps ( data ) ) # Check requests status if ret . get ( 'error' ) : log . error ( "Got an error: %s" , ret . get ( "error" ...
def filespecs ( self ) : """Return a filespecs dict representing both globs and excludes ."""
filespecs = { 'globs' : self . _file_globs } exclude_filespecs = self . _exclude_filespecs if exclude_filespecs : filespecs [ 'exclude' ] = exclude_filespecs return filespecs
def globals ( self ) : """Find the globals of ` self ` by importing ` self . module `"""
try : return vars ( __import__ ( self . module , fromlist = self . module . split ( '.' ) ) ) except ImportError : if self . warn_import : warnings . warn ( ImportWarning ( 'Cannot import module {} for SerializableFunction. Restricting to builtins.' . format ( self . module ) ) ) return { '__builtin...
def add_support ( self , date , on = 'low' , mode = 'starttoend' , text = None , ** kwargs ) : """Adds a support line to the QuantFigure Parameters : date0 : string The support line will be drawn at the ' y ' level value that corresponds to this date . on : string Indicate the data series in which the ...
d = { 'kind' : 'support' , 'date' : date , 'mode' : mode , 'on' : on , 'text' : text } d . update ( ** kwargs ) self . trendlines . append ( d )
def vm_attach ( name , kwargs = None , call = None ) : '''Attaches a new disk to the given virtual machine . . . versionadded : : 2016.3.0 name The name of the VM for which to attach the new disk . path The path to a file containing a single disk vector attribute . Syntax within the file can be the usua...
if call != 'action' : raise SaltCloudSystemExit ( 'The vm_attach action must be called with -a or --action.' ) if kwargs is None : kwargs = { } path = kwargs . get ( 'path' , None ) data = kwargs . get ( 'data' , None ) if data : if path : log . warning ( 'Both the \'data\' and \'path\' arguments we...
def _set_character_restriction ( self , v , load = False ) : """Setter method for character _ restriction , mapped from YANG variable / password _ attributes / character _ restriction ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ character _ restriction ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = character_restriction . character_restriction , is_container = 'container' , presence = False , yang_name = "character-restriction" , rest_name = "character-restriction" , parent = self , path_helper = self . _path_helper , e...
def add ( self , val ) : """Add the element * val * to the list ."""
_maxes , _lists = self . _maxes , self . _lists if _maxes : pos = bisect_right ( _maxes , val ) if pos == len ( _maxes ) : pos -= 1 _maxes [ pos ] = val _lists [ pos ] . append ( val ) else : insort ( _lists [ pos ] , val ) self . _expand ( pos ) else : _maxes . appen...
def unregister ( matcher ) : """Unregister a matcher ( or alias ) from the registry"""
# If it ' s a string handle it like an alias if isinstance ( matcher , text_types ) and matcher in matchers : matcher = matchers [ matcher ] # Find all aliases associated to the matcher aliases = [ k for k , v in matchers . iteritems ( ) if v == matcher ] for alias in aliases : del matchers [ alias ] # Clea...
def factory ( cls , object_source ) : """Return a proper object"""
if object_source . type is ObjectRaw . Types . object : return ObjectObject ( object_source ) elif object_source . type not in ObjectRaw . Types or object_source . type is ObjectRaw . Types . type : return ObjectType ( object_source ) elif object_source . type is ObjectRaw . Types . array : return ObjectArr...
def load_global_config ( config_path ) : """Load a global configuration object , and query for any required variables along the way"""
config = configparser . RawConfigParser ( ) if os . path . exists ( config_path ) : logger . debug ( "Checking and setting global parameters..." ) config . read ( config_path ) else : _initial_run ( ) logger . info ( "Unable to find a global sprinter configuration!" ) logger . info ( "Creating one n...
def auth_aws_iam ( self , access_key , secret_key , session_token = None , header_value = None , mount_point = 'aws' , role = '' , use_token = True , region = 'us-east-1' ) : """POST / auth / < mount point > / login : param access _ key : AWS IAM access key ID : type access _ key : str : param secret _ key : ...
request = aws_utils . generate_sigv4_auth_request ( header_value = header_value ) auth = aws_utils . SigV4Auth ( access_key , secret_key , session_token , region ) auth . add_auth ( request ) # https : / / github . com / hashicorp / vault / blob / master / builtin / credential / aws / cli . go headers = json . dumps ( ...
async def delete_messages ( self , entity , message_ids , * , revoke = True ) : """Deletes a message from a chat , optionally " for everyone " . Args : entity ( ` entity ` ) : From who the message will be deleted . This can actually be ` ` None ` ` for normal chats , but * * must * * be present for channe...
if not utils . is_list_like ( message_ids ) : message_ids = ( message_ids , ) message_ids = ( m . id if isinstance ( m , ( types . Message , types . MessageService , types . MessageEmpty ) ) else int ( m ) for m in message_ids ) entity = await self . get_input_entity ( entity ) if entity else None if isinstance ( e...
def trim_tree ( self , node ) : """trims the tree for any empty data nodes"""
data_len = len ( node [ - 1 ] ) if node [ 1 ] == - 1 and node [ 2 ] == - 1 : if data_len == 0 : return 1 else : return 0 else : if self . trim_tree ( node [ 1 ] ) == 1 : node [ 1 ] = - 1 if self . trim_tree ( node [ 2 ] ) == 1 : node [ 2 ] = - 1 if node [ 1 ] == - 1 a...
def instantiate_single ( self , seed = 0 , preset = 'default' ) : """Create a new Env instance - single"""
env = self . env . instantiate ( seed = seed , serial_id = 0 , preset = preset ) if self . frame_history is not None : env = FrameStack ( env , self . frame_history ) return env
def process_post_tag ( self , bulk_mode , api_tag ) : """Create or update a Tag related to a post . : param bulk _ mode : If True , minimize db operations by bulk creating post objects : param api _ tag : the API data for the Tag : return : the Tag object"""
tag = None # try to get from the ref data map if in bulk mode if bulk_mode : tag = self . ref_data_map [ "tags" ] . get ( api_tag [ "ID" ] ) # double check the db before giving up , we may have sync ' d it in a previous run if not tag : tag , created = Tag . objects . get_or_create ( site_id = self . site_id , ...
def process_options ( arglist = None , parse_argv = False , config_file = None , parser = None ) : """Process options passed either via arglist or via command line args . Passing in the ` ` config _ file ` ` parameter allows other tools , such as flake8 to specify their own options to be processed in pycodestyl...
if not parser : parser = get_parser ( ) if not parser . has_option ( '--config' ) : group = parser . add_option_group ( "Configuration" , description = ( "The project options are read from the [%s] section of the " "tox.ini file or the setup.cfg file located in any parent folder " "of the path(s) being processe...
def list_keyvaults ( access_token , subscription_id , rgname ) : '''Lists key vaults in the named resource group . Args : access _ token ( str ) : A valid Azure authentication token . subscription _ id ( str ) : Azure subscription id . rgname ( str ) : Azure resource group name . Returns : HTTP response...
endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourcegroups/' , rgname , '/providers/Microsoft.KeyVault/vaults' , '?api-version=' , KEYVAULT_API ] ) return do_get_next ( endpoint , access_token )
def getApplicationProcessId ( self , pchAppKey ) : """Returns the process ID for an application . Return 0 if the application was not found or is not running ."""
fn = self . function_table . getApplicationProcessId result = fn ( pchAppKey ) return result
def cpower ( a , b ) : '''cpower ( a , b ) is equivalent to a * * b except that it also operates over sparse arrays ; though it must reify them to do so .'''
if sps . issparse ( a ) : a = a . toarray ( ) if sps . issparse ( b ) : b = b . toarray ( ) return a ** b
def unregister ( self , name , func ) : """Remove a previously registered callback : param str name : Hook name : param callable func : A function reference that was registered previously"""
try : templatehook = self . _registry [ name ] except KeyError : return templatehook . unregister ( func )
def get_default_base_name ( self , viewset ) : """Attempt to automatically determine base name using ` get _ url _ name ` ."""
queryset = getattr ( viewset , 'queryset' , None ) if queryset is not None : get_url_name = getattr ( queryset . model , 'get_url_name' , None ) if get_url_name is not None : return get_url_name ( ) return super ( SortedDefaultRouter , self ) . get_default_base_name ( viewset )
def get_actor ( self , name ) : """Get an actor by name : param name : str : return :"""
return next ( ( x for x in self . actors if x . name == name ) , None )
def from_filenames ( poscar_filenames , transformations = None , extend_collection = False ) : """Convenient constructor to generates a POSCAR transmuter from a list of POSCAR filenames . Args : poscar _ filenames : List of POSCAR filenames transformations : New transformations to be applied to all struct...
tstructs = [ ] for filename in poscar_filenames : with open ( filename , "r" ) as f : tstructs . append ( TransformedStructure . from_poscar_string ( f . read ( ) , [ ] ) ) return StandardTransmuter ( tstructs , transformations , extend_collection = extend_collection )
def add_wikipage ( self , slug , content , ** attrs ) : """Add a Wiki page to the project and returns a : class : ` WikiPage ` object . : param name : name of the : class : ` WikiPage ` : param attrs : optional attributes for : class : ` WikiPage `"""
return WikiPages ( self . requester ) . create ( self . id , slug , content , ** attrs )
def proto_to_dict ( message ) : """Converts protobuf message instance to dict : param message : protobuf message instance : return : parameters and their values : rtype : dict : raises : : class : ` . TypeError ` if ` ` message ` ` is not a proto message"""
if not isinstance ( message , _ProtoMessageType ) : raise TypeError ( "Expected `message` to be a instance of protobuf message" ) data = { } for desc , field in message . ListFields ( ) : if desc . type == desc . TYPE_MESSAGE : if desc . label == desc . LABEL_REPEATED : data [ desc . name ] ...
def reduce ( cls , requirements : Iterable [ 'FetchRequirement' ] ) -> 'FetchRequirement' : """Reduce a set of fetch requirements into a single requirement . Args : requirements : The set of fetch requirements ."""
return reduce ( lambda x , y : x | y , requirements , cls . NONE )
def to_tree ( instance , * children ) : """Generate tree structure of an instance , and its children . This method yields its results , instead of returning them ."""
# Yield representation of self yield unicode ( instance ) # Iterate trough each instance child collection for i , child in enumerate ( children ) : lines = 0 yield "|" yield "+---" + unicode ( child ) if i != len ( children ) - 1 : a = "|" else : a = " " # Iterate trough all valu...
def retinotopy_data ( m , source = 'any' ) : '''retinotopy _ data ( m ) yields a dict containing a retinotopy dataset with the keys ' polar _ angle ' , ' eccentricity ' , and any other related fields for the given retinotopy type ; for example , ' pRF _ size ' and ' variance _ explained ' may be included for me...
if pimms . is_map ( source ) : if all ( k in source for k in [ 'polar_angle' , 'eccentricity' ] ) : return source if geo . is_vset ( m ) : return retinotopy_data ( m . properties , source = source ) source = source . lower ( ) model_rets = [ 'predicted' , 'model' , 'template' , 'atlas' , 'inferred' ] em...
def fetch ( self , customer_id , data = { } , ** kwargs ) : """Fetch Customer for given Id Args : customer _ id : Id for which customer object has to be retrieved Returns : Order dict for given customer Id"""
return super ( Customer , self ) . fetch ( customer_id , data , ** kwargs )
def init ( self , fle = None ) : """Executes the preprocessing steps at the instantiation stage to read in the tables from hdf5 and hold them in memory ."""
if fle is None : fname = self . kwargs . get ( 'gmpe_table' , self . GMPE_TABLE ) if fname is None : raise ValueError ( 'You forgot to set GMPETable.GMPE_TABLE!' ) elif os . path . isabs ( fname ) : self . GMPE_TABLE = fname else : # NB : ( hackish ) GMPE _ DIR must be set externally ...
def _estimate_count ( self ) : """Update the count number using the estimation of the unset ratio"""
if self . estimate_z == 0 : self . estimate_z = ( 1.0 / self . nbr_bits ) self . estimate_z = min ( self . estimate_z , 0.999999 ) self . count = int ( - ( self . nbr_bits / self . nbr_slices ) * np . log ( 1 - self . estimate_z ) )
def encode ( content , error = None , version = None , mode = None , mask = None , encoding = None , eci = False , micro = None , boost_error = True ) : """Creates a ( Micro ) QR Code . See : py : func : ` segno . make ` for a detailed description of the parameters . Contrary to ` ` make ` ` this function retur...
version = normalize_version ( version ) if not micro and micro is not None and version in consts . MICRO_VERSIONS : raise VersionError ( 'A Micro QR Code version ("{0}") is provided but ' 'parameter "micro" is False' . format ( get_version_name ( version ) ) ) if micro and version is not None and version not in con...
def _find_usage_one_cluster ( self , cluster_name ) : """Find usage for services in each cluster . : param cluster _ name : name of the cluster to find usage for : type cluster _ name : str"""
tps_lim = self . limits [ 'EC2 Tasks per Service (desired count)' ] paginator = self . conn . get_paginator ( 'list_services' ) for page in paginator . paginate ( cluster = cluster_name , launchType = 'EC2' ) : for svc_arn in page [ 'serviceArns' ] : svc = self . conn . describe_services ( cluster = cluster...
def is_text_extractor_available ( extension : str ) -> bool : """Is a text extractor available for the specified extension ?"""
if extension is not None : extension = extension . lower ( ) info = ext_map . get ( extension ) if info is None : return False availability = info [ AVAILABILITY ] if type ( availability ) == bool : return availability elif callable ( availability ) : return availability ( ) else : raise ValueError ...
def structureLink ( lines ) : """Parse STRUCTURE LINK Method"""
# Constants KEYWORDS = ( 'LINK' , 'STRUCTURE' , 'NUMSTRUCTS' , 'STRUCTTYPE' ) WEIR_KEYWORDS = ( 'STRUCTTYPE' , 'CREST_LENGTH' , 'CREST_LOW_ELEV' , 'DISCHARGE_COEFF_FORWARD' , 'DISCHARGE_COEFF_REVERSE' , 'CREST_LOW_LOC' , 'STEEP_SLOPE' , 'SHALLOW_SLOPE' ) CULVERT_KEYWORDS = ( 'STRUCTTYPE' , 'UPINVERT' , 'DOWNINVERT' , '...
def attribute ( self , attr_type , attr_value , displayed = False , source = None , unique = True , formatter = None ) : """Return instance of Attribute unique : * False - Attribute type : value can be duplicated . * Type - Attribute type has to be unique ( e . g . , only 1 Description Attribute ) . * True ...
attr = Attribute ( attr_type , attr_value , displayed , source , formatter ) if unique == 'Type' : for attribute_data in self . _attributes : if attribute_data . type == attr_type : attr = attribute_data break else : self . _attributes . append ( attr ) elif unique is Tru...
def user_disable_throw_rest_endpoint ( self , username , url = 'rest/scriptrunner/latest/custom/disableUser' , param = 'userName' ) : """The disable method throw own rest enpoint"""
url = "{}?{}={}" . format ( url , param , username ) return self . get ( path = url )
def AgregarTambo ( self , nro_tambo_interno , nro_renspa , fecha_venc_cert_tuberculosis , fecha_venc_cert_brucelosis , nro_tambo_provincial = None , ** kwargs ) : "Agrego los datos del productor a la liq ."
tambo = { 'nroTamboInterno' : nro_tambo_interno , 'nroTamboProvincial' : nro_tambo_provincial , 'nroRenspa' : nro_renspa , 'ubicacionTambo' : { } , 'fechaVencCertTuberculosis' : fecha_venc_cert_tuberculosis , 'fechaVencCertBrucelosis' : fecha_venc_cert_brucelosis } self . solicitud [ 'tambo' ] = tambo return True
def read_file ( filename ) : """Reads a TSPLIB file and returns the problem data . Args filename : str Returns type Problem specs ."""
sanitized_filename = sanitize ( filename ) f = open ( sanitized_filename ) specs = None try : specs = _parse_tsplib ( f ) except ParseException : raise finally : # ' finally ' is executed even when we re - raise exceptions f . close ( ) if specs [ 'TYPE' ] != 'CVRP' : raise Exception ( 'Not a CVRP TSPLI...
def mimebundle_to_html ( bundle ) : """Converts a MIME bundle into HTML ."""
if isinstance ( bundle , tuple ) : data , metadata = bundle else : data = bundle html = data . get ( 'text/html' , '' ) if 'application/javascript' in data : js = data [ 'application/javascript' ] html += '\n<script type="application/javascript">{js}</script>' . format ( js = js ) return html
def information ( self , type ) : """Computes the information content of the specified type : - log _ e ( p ( X ) )"""
if not self . base : return - math . log ( self . _dist [ type ] ) else : return - math . log ( self . _dist [ type ] , self . base )
def ending_long_process ( self , message = "" ) : """Clear main window ' s status bar and restore mouse cursor ."""
QApplication . restoreOverrideCursor ( ) self . show_message ( message , timeout = 2000 ) QApplication . processEvents ( )
def cmd ( send , msg , args ) : """Gets a xkcd comic . Syntax : { command } [ num | latest | term ]"""
latest = get_latest ( ) if not msg : msg = randrange ( 1 , latest ) elif msg == 'latest' : msg = latest elif msg . isdigit ( ) : msg = int ( msg ) if msg > latest or msg < 1 : send ( "Number out of range" ) return else : send ( do_search ( msg , args [ 'config' ] [ 'api' ] [ 'googlea...
def split_on_condition ( seq , condition ) : """Split a sequence into two iterables without looping twice"""
l1 , l2 = tee ( ( condition ( item ) , item ) for item in seq ) return ( i for p , i in l1 if p ) , ( i for p , i in l2 if not p )
def get ( self ) : """Fetches the current state of the alarm from the API and updates the object ."""
new_alarm = self . entity . get_alarm ( self ) if new_alarm : self . _add_details ( new_alarm . _info )
def Affine ( self , opset , func ) : """Affine is decomposed as 3 steps : Reshape inputs Gemm Reshape"""
nl = [ ] out_a = fork_name ( func . input [ 0 ] ) base_axis = func . affine_param . base_axis x_shape = list ( self . _var_dict [ func . input [ 0 ] ] . dim [ : ] ) x_shape_dims = [ np . prod ( x_shape [ : base_axis ] ) , np . prod ( x_shape [ base_axis : ] ) ] x_shape_dims_name = fork_name ( 'x_shape_dims' ) x_shape_d...
def records ( self ) : """Return all start records for this the dataset , grouped by the start record"""
return ( self . _session . query ( Process ) . filter ( Process . d_vid == self . _d_vid ) ) . all ( )
def el_is_empty ( el ) : """Return ` ` True ` ` if tuple ` ` el ` ` represents an empty XML element ."""
if len ( el ) == 1 and not isinstance ( el [ 0 ] , ( list , tuple ) ) : return True subels_are_empty = [ ] for subel in el : if isinstance ( subel , ( list , tuple ) ) : subels_are_empty . append ( el_is_empty ( subel ) ) else : subels_are_empty . append ( not bool ( subel ) ) return all ( s...
def get_patient_pharmacies ( self , patient_id , patients_favorite_only = 'N' ) : """invokes TouchWorksMagicConstants . ACTION _ GET _ ENCOUNTER _ LIST _ FOR _ PATIENT action : return : JSON response"""
magic = self . _magic_json ( action = TouchWorksMagicConstants . ACTION_GET_PATIENT_PHARAMCIES , patient_id = patient_id , parameter1 = patients_favorite_only ) response = self . _http_request ( TouchWorksEndPoints . MAGIC_JSON , data = magic ) result = self . _get_results_or_raise_if_magic_invalid ( magic , response ,...
def nl_msg_dump ( msg , ofd = _LOGGER . debug ) : """Dump message in human readable format to callable . https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / msg . c # L970 Positional arguments : msg - - message to print ( nl _ msg class instance ) . Keyword arguments : ofd - - function...
hdr = nlmsg_hdr ( msg ) ofd ( '-------------------------- BEGIN NETLINK MESSAGE ---------------------------' ) ofd ( ' [NETLINK HEADER] %d octets' , hdr . SIZEOF ) print_hdr ( ofd , msg ) if hdr . nlmsg_type == libnl . linux_private . netlink . NLMSG_ERROR : dump_error_msg ( msg , ofd ) elif nlmsg_len ( hdr ) > ...
def add_camera_make_model ( self , make , model ) : '''Add camera make and model .'''
self . _ef [ '0th' ] [ piexif . ImageIFD . Make ] = make self . _ef [ '0th' ] [ piexif . ImageIFD . Model ] = model
def rotatable_count ( mol ) : """Rotatable bond count"""
mol . require ( "Rotatable" ) return sum ( 1 for _ , _ , b in mol . bonds_iter ( ) if b . rotatable )
def parse ( self , data ) : """Converts a OpenVPN JSON to a NetworkX Graph object which is then returned ."""
# initialize graph and list of aggregated nodes graph = self . _init_graph ( ) server = self . _server_common_name # add server ( central node ) to graph graph . add_node ( server ) # data may be empty if data is None : clients = [ ] links = [ ] else : clients = data . client_list . values ( ) links = d...
def assertpath ( path_ , msg = '' , ** kwargs ) : """Asserts that a patha exists"""
if NO_ASSERTS : return if path_ is None : raise AssertionError ( 'path is None! %s' % ( path_ , msg ) ) if path_ == '' : raise AssertionError ( 'path=%r is the empty string! %s' % ( path_ , msg ) ) if not checkpath ( path_ , ** kwargs ) : raise AssertionError ( 'path=%r does not exist! %s' % ( path_ , m...
def integer ( _object ) : """Validates a given input is of type int . . Example usage : : data = { ' a ' : 21} schema = ( ' a ' , integer ) You can also use this as a decorator , as a way to check for the input before it even hits a validator you may be writing . . . note : : If the argument is a call...
if is_callable ( _object ) : _validator = _object @ wraps ( _validator ) def decorated ( value ) : ensure ( isinstance ( value , int ) , "not of type int" ) return _validator ( value ) return decorated ensure ( isinstance ( _object , int ) , "not of type int" )
def wikibase_item_engine_factory ( cls , mediawiki_api_url , sparql_endpoint_url , name = 'LocalItemEngine' ) : """Helper function for creating a WDItemEngine class with arguments set for a different Wikibase instance than Wikidata . : param mediawiki _ api _ url : Mediawiki api url . For wikidata , this is : '...
class SubCls ( cls ) : def __init__ ( self , * args , ** kwargs ) : kwargs [ 'mediawiki_api_url' ] = mediawiki_api_url kwargs [ 'sparql_endpoint_url' ] = sparql_endpoint_url super ( SubCls , self ) . __init__ ( * args , ** kwargs ) SubCls . __name__ = name return SubCls
def func_set_timeout ( timeout , allowOverride = False ) : '''func _ set _ timeout - Decorator to run a function with a given / calculated timeout ( max execution time ) . Optionally ( if # allowOverride is True ) , adds a paramater , " forceTimeout " , to the function which , if provided , will override the de...
# Try to be as efficent as possible . . . don ' t compare the args more than once # Helps closure issue on some versions of python defaultTimeout = copy . copy ( timeout ) isTimeoutAFunction = bool ( issubclass ( timeout . __class__ , ( types . FunctionType , types . MethodType , types . LambdaType , types . BuiltinFun...
def payzen_form ( payment_request , auto_submit = False ) : """TODO docstring ."""
if auto_submit : template_used = "django_payzen/auto_submit_form.html" else : template_used = "django_payzen/form.html" payment_request . update ( ) t = template . loader . get_template ( template_used ) return t . render ( { "form" : forms . PaymentRequestForm ( instance = payment_request ) , "payzen_submit_ur...
def getSessionFromFile ( self , file , verbose = None ) : """Loads a session from a local file and returns the session file name : param file : Session file location as an absolute path : param verbose : print more : returns : 200 : successful operation"""
response = api ( url = self . ___url + 'session' , PARAMS = { 'file' : file } , method = "GET" , verbose = verbose , parse_params = False ) return response
def write_hdf5_segmentlist ( seglist , output , path = None , ** kwargs ) : """Write a ` SegmentList ` to an HDF5 file / group Parameters seglist : : class : ` ~ ligo . segments . segmentlist ` data to write output : ` str ` , ` h5py . File ` , ` h5py . Group ` filename or HDF5 object to write to path :...
if path is None : raise ValueError ( "Please specify the HDF5 path via the " "``path=`` keyword argument" ) # convert segmentlist to Table data = numpy . zeros ( ( len ( seglist ) , 4 ) , dtype = int ) for i , seg in enumerate ( seglist ) : start , end = map ( LIGOTimeGPS , seg ) data [ i , : ] = ( start . ...
def find_by_id ( self , submission_id ) : """Finds submission by ID . Args : submission _ id : ID of the submission Returns : SubmissionDescriptor with information about submission or None if submission is not found ."""
return self . _attacks . get ( submission_id , self . _defenses . get ( submission_id , self . _targeted_attacks . get ( submission_id , None ) ) )
def relative ( self , start : typing . Optional [ typing . Union [ 'Path' , str ] ] = None ) -> str : """: param start : an object of NoneType or Path or str . : return : a string If ` start ` is None : returns the relative path of current Path object from its own directory . Else : returns the relative p...
if start is None : return os . path . split ( str ( self ) ) [ 1 ] if isinstance ( start , Path ) : start = str ( start ) return os . path . relpath ( str ( self ) , start )
def oortC ( self , R , t = 0. , nsigma = None , deg = False , phi = 0. , epsrel = 1.e-02 , epsabs = 1.e-05 , grid = None , gridpoints = 101 , returnGrids = False , derivRGrid = None , derivphiGrid = None , derivGridpoints = 101 , derivHierarchgrid = False , hierarchgrid = False , nlevels = 2 , integrate_method = 'dopr5...
# First calculate the grids if they are not given if isinstance ( grid , bool ) and grid : ( surfacemass , grid ) = self . vmomentsurfacemass ( R , 0 , 0 , deg = deg , t = t , phi = phi , nsigma = nsigma , epsrel = epsrel , epsabs = epsabs , grid = True , gridpoints = gridpoints , returnGrid = True , hierarchgrid =...
async def disconnect ( self ) : """Disconnect from target ."""
if not self . connected : return self . writer . close ( ) self . reader = None self . writer = None
def get ( self , sid ) : """Constructs a TaskChannelContext : param sid : The sid : returns : twilio . rest . taskrouter . v1 . workspace . task _ channel . TaskChannelContext : rtype : twilio . rest . taskrouter . v1 . workspace . task _ channel . TaskChannelContext"""
return TaskChannelContext ( self . _version , workspace_sid = self . _solution [ 'workspace_sid' ] , sid = sid , )
def from_pint ( cls , arr , unit_registry = None ) : """Convert a Pint " Quantity " to a unyt _ array or unyt _ quantity . Parameters arr : Pint Quantity The Quantity to convert from . unit _ registry : yt UnitRegistry , optional A yt unit registry to use in the conversion . If one is not supplied , the...
p_units = [ ] for base , exponent in arr . _units . items ( ) : bs = convert_pint_units ( base ) p_units . append ( "%s**(%s)" % ( bs , Rational ( exponent ) ) ) p_units = "*" . join ( p_units ) if isinstance ( arr . magnitude , np . ndarray ) : return unyt_array ( arr . magnitude , p_units , registry = uni...
def _render ( self , contexts , partials ) : """render variable"""
value = self . _lookup ( self . value , contexts ) # lambda if callable ( value ) : value = inner_render ( str ( value ( ) ) , contexts , partials ) return self . _escape ( value )
def validate ( self , graph = None ) : """Returns ( Boolean , message ) of whether DAG is valid ."""
graph = graph if graph is not None else self . graph if len ( self . ind_nodes ( graph ) ) == 0 : return ( False , 'no independent nodes detected' ) try : self . topological_sort ( graph ) except ValueError : return ( False , 'failed topological sort' ) return ( True , 'valid' )
def wrapwrite ( text ) : """: type text : str : rtype : str"""
try : # Python3 sys . stdout . buffer . write ( text ) except AttributeError : sys . stdout . write ( text . encode ( 'utf-8' ) )
def add ( one , two = 4 , three = False ) : '''This function adds two number . : param one : first number to add : param two : second number to add : rtype : int'''
s = str ( int ( one ) + int ( two ) ) logging . debug ( 'logging sum from hello.py:' + s ) print 'printing sum from hello.py:' , s return s
def main ( ) : """main entry"""
options = parse ( sys . argv [ 1 : ] , CLIRULES , ".splunkrc" ) if options . kwargs [ 'omode' ] not in OUTPUT_MODES : print ( "output mode must be one of %s, found %s" % ( OUTPUT_MODES , options . kwargs [ 'omode' ] ) ) sys . exit ( 1 ) service = connect ( ** options . kwargs ) if path . exists ( options . kwar...
async def prover_create_credential_req ( wallet_handle : int , prover_did : str , cred_offer_json : str , cred_def_json : str , master_secret_id : str ) -> ( str , str ) : """Creates a clam request for the given credential offer . The method creates a blinded master secret for a master secret identified by a prov...
logger = logging . getLogger ( __name__ ) logger . debug ( "prover_create_credential_req: >>> wallet_handle: %r, prover_did: %r, cred_offer_json: %r," " cred_def_json: %r, master_secret_id: %r" , wallet_handle , prover_did , cred_offer_json , cred_def_json , master_secret_id ) if not hasattr ( prover_create_credential_...
def make_json_formatted_for_single_chart ( mutant_features , inference_result_proto , index_to_mutate ) : """Returns JSON formatted for a single mutant chart . Args : mutant _ features : An iterable of ` MutantFeatureValue ` s representing the X - axis . inference _ result _ proto : A ClassificationResponse...
x_label = 'step' y_label = 'scalar' if isinstance ( inference_result_proto , classification_pb2 . ClassificationResponse ) : # classification _ label - > [ { x _ label : y _ label : } ] series = { } # ClassificationResponse has a separate probability for each label for idx , classification in enumerate ( in...
def replace_variable_node ( node , annotation ) : """Replace a node annotated by ` nni . variable ` . node : the AST node to replace annotation : annotation string"""
assert type ( node ) is ast . Assign , 'nni.variable is not annotating assignment expression' assert len ( node . targets ) == 1 , 'Annotated assignment has more than one left-hand value' name , expr = parse_nni_variable ( annotation ) assert test_variable_equal ( node . targets [ 0 ] , name ) , 'Annotated variable has...
def brute_permutation ( A , B ) : """Re - orders the input atom list and xyz coordinates using the brute force method of permuting all rows of the input coordinates Parameters A : array ( N , D ) matrix , where N is points and D is dimension B : array ( N , D ) matrix , where N is points and D is dimens...
rmsd_min = np . inf view_min = None # Sets initial ordering for row indices to [ 0 , 1 , 2 , . . . , len ( A ) ] , used in # brute - force method num_atoms = A . shape [ 0 ] initial_order = list ( range ( num_atoms ) ) for reorder_indices in generate_permutations ( initial_order , num_atoms ) : # Re - order the atom ar...
def send_with_many_media ( self , * args : str , text : str = None , files : List [ str ] = None , captions : List [ str ] = [ ] , ) -> IterationRecord : """Post with several media . Provide filenames so outputs can handle their own uploads . : param args : positional arguments . expected : text to send as ...
if text is None : if len ( args ) < 1 : raise TypeError ( ( "Please provide either required positional argument " "TEXT, or keyword argument text=TEXT" ) ) else : final_text = args [ 0 ] else : final_text = text if files is None : if len ( args ) < 2 : raise TypeError ( ( "Please...
def set_elapsed_time_visible ( self , state ) : """Slot to show / hide elapsed time label ."""
self . show_elapsed_time = state if self . time_label is not None : self . time_label . setVisible ( state )
def push_cluster_configuration ( self , scaleioobj , noUpload = False , noInstall = False , noConfigure = False ) : """Method push cached ScaleIO cluster configuration to IM ( reconfigurations that have been made to cached configuration are committed using IM ) Method : POST Attach JSON cluster configuration as...
self . logger . debug ( "push_cluster_configuration(" + "{},{},{},{})" . format ( scaleioobj , noUpload , noInstall , noConfigure ) ) # print " JSON DUMP OF CLUSTER CONFIG : " # pprint ( json . loads ( scaleioobj ) ) config_params = { 'noUpload' : noUpload , 'noInstall' : noInstall , 'noConfigure' : noConfigure } r1 = ...
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_remote_interface_mac ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_lldp_neighbor_detail = ET . Element ( "get_lldp_neighbor_detail" ) config = get_lldp_neighbor_detail output = ET . SubElement ( get_lldp_neighbor_detail , "output" ) lldp_neighbor_detail = ET . SubElement ( output , "lldp-neighbor-detail" ) local_interface_name_key = ET . SubEleme...
def validate ( args ) : """% prog validate outdir genome . fasta Validate current folder after MAKER run and check for failures . Failed batch will be written to a directory for additional work ."""
from jcvi . utils . counter import Counter p = OptionParser ( validate . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) outdir , genome = args counter = Counter ( ) fsnames , suffix = get_fsnames ( outdir ) dsfile = "{0}{1}/{0}.maker.output/{0}_master_da...
def raster_weights ( raster , rook = False , transform = 'r' , ** kwargs ) : """Construct PySal weights for rasters It drops weights for all cells that have no data or are Inf / NaN Usage : w = raster _ weights ( raster , rook = False , transform = ' r ' , * * kwargs ) where raster : ( Masked ) Numpy arra...
rasterf = raster . flatten ( ) if len ( raster . shape ) == 1 : shape = ( np . sqrt ( raster . shape [ 0 ] ) * np . array ( [ 1 , 1 ] ) ) . astype ( int ) else : shape = raster . shape w = pysal . lat2W ( * shape , rook = rook , ** kwargs ) # Identify missing / no data if isinstance ( rasterf , np . ma . core ....
def show_raslog_output_show_all_raslog_raslog_entries_index ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_raslog = ET . Element ( "show_raslog" ) config = show_raslog output = ET . SubElement ( show_raslog , "output" ) show_all_raslog = ET . SubElement ( output , "show-all-raslog" ) raslog_entries = ET . SubElement ( show_all_raslog , "raslog-entries" ) index = ET . SubElement ( rasl...
def _read_mode_tsopt ( self , size , kind ) : """Read Timestamps option . Positional arguments : * size - int , length of option * kind - int , 8 ( Timestamps ) Returns : * dict - - extracted Timestamps ( TS ) option Structure of TCP TSopt [ RFC 7323 ] : | Kind = 8 | 10 | TS Value ( TSval ) | TS Echo ...
temp = struct . unpack ( '>II' , self . _read_fileng ( size ) ) data = dict ( kind = kind , length = size , val = temp [ 0 ] , ecr = temp [ 1 ] , ) return data
def collect_prs_info ( self ) : """Collect all pending merge PRs info . : returns : mapping of PRs by state"""
REPO_RE = re . compile ( '^(https://github.com/|git@github.com:)' '(?P<owner>.*?)/(?P<repo>.*?)(.git)?$' ) PULL_RE = re . compile ( '^(refs/)?pull/(?P<pr>[0-9]+)/head$' ) remotes = { r [ 'name' ] : r [ 'url' ] for r in self . remotes } all_prs = { } for merge in self . merges : remote = merge [ 'remote' ] ref =...
def get_columns ( self , usage , columns = None ) : """Returns a ` data _ frame . columns ` . : param usage ( str ) : should be a value from [ ALL , INCLUDE , EXCLUDE ] . this value only makes sense if attr ` columns ` is also set . otherwise , should be used with default value ALL . : param columns : * if ...
columns_excluded = pd . Index ( [ ] ) columns_included = self . df . columns if self . has_target ( ) : columns_excluded = pd . Index ( [ self . target_column ] ) if self . has_id ( ) : columns_excluded = columns_excluded . union ( pd . Index ( [ self . id_column ] ) ) if usage == self . INCLUDE : try : ...