signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def resend_sms_endpoint_verification ( self , endpoint_id ) : """Calls NWS function to resend verification message to endpoint ' s phone number"""
self . _validate_uuid ( endpoint_id ) url = "/notification/v1/endpoint/{}/verification" . format ( endpoint_id ) response = NWS_DAO ( ) . postURL ( url , None , None ) if response . status != 202 : raise DataFailureException ( url , response . status , response . data ) return response . status
def exchange_bind ( self , destination , source = '' , routing_key = '' , nowait = False , arguments = None ) : """This method binds an exchange to an exchange . RULE : A server MUST allow and ignore duplicate bindings - that is , two or more bind methods for a specific exchanges , with identical arguments ...
arguments = { } if arguments is None else arguments args = AMQPWriter ( ) args . write_short ( 0 ) args . write_shortstr ( destination ) args . write_shortstr ( source ) args . write_shortstr ( routing_key ) args . write_bit ( nowait ) args . write_table ( arguments ) self . _send_method ( ( 40 , 30 ) , args ) if not n...
def get_pipeline_boxes ( self , pipeline_key , sort_by = None ) : '''Gets a list of all box objects in a pipeline . Performs a single GET . Args : pipeline _ keykey for pipeline sort _ byin desc order by ' creationTimestamp ' or ' lastUpdatedTimestamp ' Not sure if it is supported returns ( status code fo...
if not pipeline_key : return requests . codes . bad_request , None uri = '/' . join ( [ self . api_uri , self . pipelines_suffix , pipeline_key ] ) if sort_by : if sort_by in [ 'creationTimestamp' , 'lastUpdatedTimestamp' ] : uri += self . sort_by_postfix + sort_by else : return requests . c...
def get_integer_index ( miller_index : bool , round_dp : int = 4 , verbose : bool = True ) -> Tuple [ int , int , int ] : """Attempt to convert a vector of floats to whole numbers . Args : miller _ index ( list of float ) : A list miller indexes . round _ dp ( int , optional ) : The number of decimal places t...
miller_index = np . asarray ( miller_index ) # deal with the case we have small irregular floats # that are all equal or factors of each other miller_index /= min ( [ m for m in miller_index if m != 0 ] ) miller_index /= np . max ( np . abs ( miller_index ) ) # deal with the case we have nice fractions md = [ Fraction ...
def save_config ( self , cmd = "copy running-configuration startup-configuration" , confirm = False , confirm_response = "" , ) : """Saves Config"""
return super ( DellForce10SSH , self ) . save_config ( cmd = cmd , confirm = confirm , confirm_response = confirm_response )
def breathe_lights ( self , color , selector = 'all' , from_color = None , period = 1.0 , cycles = 1.0 , persist = False , power_on = True , peak = 0.5 ) : """Perform breathe effect on lights . selector : String The selector to limit which lights will run the effect . default : all color : required String ...
argument_tuples = [ ( "color" , color ) , ( "from_color" , from_color ) , ( "period" , period ) , ( "cycles" , cycles ) , ( "persist" , persist ) , ( "power_on" , power_on ) , ( "peak" , peak ) , ] return self . client . perform_request ( method = 'post' , endpoint = 'lights/{}/effects/breathe' , endpoint_args = [ sele...
def rollforward ( self , dt ) : """Roll provided date forward to next offset only if not on offset ."""
dt = as_timestamp ( dt ) if not self . onOffset ( dt ) : dt = dt + self . __class__ ( 1 , normalize = self . normalize , ** self . kwds ) return dt
def end_element ( self , tag ) : """search for ending form values ."""
if tag == u'form' : self . forms . append ( self . form ) self . form = None
def describe_keypairs ( self , xml_bytes ) : """Parse the XML returned by the C { DescribeKeyPairs } function . @ param xml _ bytes : XML bytes with a C { DescribeKeyPairsResponse } root element . @ return : a C { list } of L { Keypair } ."""
results = [ ] root = XML ( xml_bytes ) keypairs = root . find ( "keySet" ) if keypairs is None : return results for keypair_data in keypairs : key_name = keypair_data . findtext ( "keyName" ) key_fingerprint = keypair_data . findtext ( "keyFingerprint" ) results . append ( model . Keypair ( key_name , k...
def graft_neuron ( root_section ) : '''Returns a neuron starting at root _ section'''
assert isinstance ( root_section , Section ) return Neuron ( soma = Soma ( root_section . points [ : 1 ] ) , neurites = [ Neurite ( root_section ) ] )
def create_pull_from_issue ( self , issue , base , head ) : """Create a pull request from issue # ` ` issue ` ` . : param int issue : ( required ) , issue number : param str base : ( required ) , e . g . , ' master ' : param str head : ( required ) , e . g . , ' username : branch ' : returns : : class : ` P...
if int ( issue ) > 0 : data = { 'issue' : issue , 'base' : base , 'head' : head } return self . _create_pull ( data ) return None
def tosegwizard ( file , seglist , header = True , coltype = int ) : """Write the segmentlist seglist to the file object file in a segwizard compatible format . If header is True , then the output will begin with a comment line containing column names . The segment boundaries will be coerced to type coltype a...
if header : print >> file , "# seg\tstart \tstop \tduration" for n , seg in enumerate ( seglist ) : print >> file , "%d\t%s\t%s\t%s" % ( n , str ( coltype ( seg [ 0 ] ) ) , str ( coltype ( seg [ 1 ] ) ) , str ( coltype ( abs ( seg ) ) ) )
def build_items ( self ) : """get the items from STATS QUEUE calculate self . stats make new items from self . stats put the new items for ITEM QUEUE"""
while not self . stats_queue . empty ( ) : item = self . stats_queue . get ( ) self . calculate ( item ) for key , value in self . stats . iteritems ( ) : if 'blackbird.queue.length' == key : value = self . queue . qsize ( ) item = BlackbirdStatisticsItem ( key = key , value = value , host = sel...
def galcencyl_to_vxvyvz ( vR , vT , vZ , phi , vsun = [ 0. , 1. , 0. ] , Xsun = 1. , Zsun = 0. , _extra_rot = True ) : """NAME : galcencyl _ to _ vxvyvz PURPOSE : transform cylindrical Galactocentric coordinates to XYZ ( wrt Sun ) coordinates for velocities INPUT : vR - Galactocentric radial velocity vT...
vXg , vYg , vZg = cyl_to_rect_vec ( vR , vT , vZ , phi ) return galcenrect_to_vxvyvz ( vXg , vYg , vZg , vsun = vsun , Xsun = Xsun , Zsun = Zsun , _extra_rot = _extra_rot )
def _run_pass ( self ) : """Read lines from a file and performs a callback against them"""
while True : try : data = self . _file . read ( 4096 ) except IOError , e : if e . errno == errno . ESTALE : self . active = False return False lines = self . _buffer_extract ( data ) if not lines : # Before returning , check if an event ( maybe partial ) is waiti...
def _channel_loop ( tr , parameters , max_trigger_length = 60 , despike = False , debug = 0 ) : """Internal loop for parellel processing . : type tr : obspy . core . trace : param tr : Trace to look for triggers in . : type parameters : list : param parameters : List of TriggerParameter class for trace . ...
for par in parameters : if par [ 'station' ] == tr . stats . station and par [ 'channel' ] == tr . stats . channel : parameter = par break else : msg = 'No parameters set for station ' + str ( tr . stats . station ) warnings . warn ( msg ) return [ ] triggers = [ ] if debug > 0 : pri...
def get_all_clusters_sites ( ) : """Get all the cluster of all the sites . Returns : dict corresponding to the mapping cluster uid to python - grid5000 site"""
result = { } gk = get_api_client ( ) sites = gk . sites . list ( ) for site in sites : clusters = site . clusters . list ( ) result . update ( { c . uid : site . uid for c in clusters } ) return result
def update_membership ( self , group_id , users = [ ] ) : """Update the group ' s membership : type group _ id : int : param group _ id : Group ID Number : type users : list of str : param users : List of emails : rtype : dict : return : dictionary of group information"""
data = { 'groupId' : group_id , 'users' : users , } return _fix_group ( self . post ( 'updateMembership' , data ) )
def set_id ( self , dxid ) : ''': param dxid : New ID to be associated with the handler : type dxid : string Discards the currently stored ID and associates the handler with * dxid *'''
if dxid is not None : verify_string_dxid ( dxid , self . _class ) self . _dxid = dxid
def state_dict ( self ) -> Dict [ str , Any ] : """A ` ` Trainer ` ` can use this to serialize the state of the metric tracker ."""
return { "best_so_far" : self . _best_so_far , "patience" : self . _patience , "epochs_with_no_improvement" : self . _epochs_with_no_improvement , "is_best_so_far" : self . _is_best_so_far , "should_decrease" : self . _should_decrease , "best_epoch_metrics" : self . best_epoch_metrics , "epoch_number" : self . _epoch_n...
def prevId ( self ) : """Previous passage Identifier : rtype : CtsPassage : returns : Previous passage at same level"""
if self . _prev_id is False : # Request the next urn self . _prev_id , self . _next_id = self . getPrevNextUrn ( reference = self . urn . reference ) return self . _prev_id
def getResources ( self , ep , noResp = False , cacheOnly = False ) : """Get list of resources on an endpoint . : param str ep : Endpoint to get the resources of : param bool noResp : Optional - specify no response necessary from endpoint : param bool cacheOnly : Optional - get results from cache on connector...
# load query params if set to other than defaults q = { } result = asyncResult ( ) result . endpoint = ep if noResp or cacheOnly : q [ 'noResp' ] = 'true' if noResp == True else 'false' q [ 'cacheOnly' ] = 'true' if cacheOnly == True else 'false' # make query self . log . debug ( "ep = %s, query=%s" , ep , q ) ...
def solutions_as_2d_trajectories ( self , x_axis , y_axis ) : """Returns the : attr : ` InferenceResult . solutions ` as a plottable 2d trajectory . : param x _ axis : the variable to be on the x axis of projection : param y _ axis : the variable to be on the y axis of preojection : return : a tuple x , y spe...
if not self . solutions : raise Exception ( 'No intermediate solutions returned. ' 'Re-run inference with return_intermediate_solutions=True' ) index_x = self . parameter_index ( x_axis ) index_y = self . parameter_index ( y_axis ) x , y = [ ] , [ ] for parameters , initial_conditions in self . solutions : all_...
def calc_rel_pos_to_parent ( canvas , item , handle ) : """This method calculates the relative position of the given item ' s handle to its parent : param canvas : Canvas to find relative position in : param item : Item to find relative position to parent : param handle : Handle of item to find relative posit...
from gaphas . item import NW if isinstance ( item , ConnectionView ) : return item . canvas . get_matrix_i2i ( item , item . parent ) . transform_point ( * handle . pos ) parent = canvas . get_parent ( item ) if parent : return item . canvas . get_matrix_i2i ( item , parent ) . transform_point ( * handle . pos ...
def set_scm ( scm ) : """Sets the pants Scm ."""
if scm is not None : if not isinstance ( scm , Scm ) : raise ValueError ( 'The scm must be an instance of Scm, given {}' . format ( scm ) ) global _SCM _SCM = scm
def defaults ( ) : """return a dictionary with default option values and description"""
return dict ( ( str ( k ) , str ( v ) ) for k , v in cma_default_options . items ( ) )
def trigger_audited ( self , id , rev , ** kwargs ) : """Triggers a build of a specific Build Configuration in a specific revision This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please define a ` callback ` function to be invoked when receiving the response . ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'callback' ) : return self . trigger_audited_with_http_info ( id , rev , ** kwargs ) else : ( data ) = self . trigger_audited_with_http_info ( id , rev , ** kwargs ) return data
def all_near_zero_mod ( a : Union [ float , complex , Iterable [ float ] , np . ndarray ] , period : float , * , atol : float = 1e-8 ) -> bool : """Checks if the tensor ' s elements are all near multiples of the period . Args : a : Tensor of elements that could all be near multiples of the period . period : T...
b = ( np . asarray ( a ) + period / 2 ) % period - period / 2 return np . all ( np . less_equal ( np . abs ( b ) , atol ) )
def _parse_sentencetree ( self , tree , parent_node_id = None , ignore_traces = True ) : """parse a sentence Tree into this document graph"""
def get_nodelabel ( node ) : if isinstance ( node , nltk . tree . Tree ) : return node . label ( ) elif isinstance ( node , unicode ) : return node . encode ( 'utf-8' ) else : raise ValueError ( "Unexpected node type: {0}, {1}" . format ( type ( node ) , node ) ) root_node_id = self ...
def list_folder ( self , path ) : """Looks up folder contents of ` path . `"""
# Inspired by https : / / github . com / rspivak / sftpserver / blob / 0.3 / src / sftpserver / stub _ sftp . py # L70 try : folder_contents = [ ] for f in os . listdir ( path ) : attr = paramiko . SFTPAttributes . from_stat ( os . stat ( os . path . join ( path , f ) ) ) attr . filename = f ...
def make_proper_simple_record ( record , force_shrink = False ) : """Prepares and ships an individual simplified durable table record over to SNS / SQS for future processing . : param record : : param force _ shrink : : return :"""
# Convert to a simple object item = { 'arn' : record [ 'dynamodb' ] [ 'Keys' ] [ 'arn' ] [ 'S' ] , 'event_time' : record [ 'dynamodb' ] [ 'NewImage' ] [ 'eventTime' ] [ 'S' ] , 'tech' : HISTORICAL_TECHNOLOGY } # We need to de - serialize the raw DynamoDB object into the proper PynamoDB obj : prepped_new_record = _get_d...
def get_lu_from_synset ( self , syn_id , lemma = None ) : """Returns ( lu _ id , synonyms = [ ( word , lu _ id ) ] ) tuple given a synset ID and a lemma"""
if not lemma : return self . get_lus_from_synset ( syn_id ) # alias if not isinstance ( lemma , unicode ) : lemma = unicode ( lemma , 'utf-8' ) root = self . get_synset_xml ( syn_id ) elem_synonyms = root . find ( ".//synonyms" ) lu_id = None synonyms = [ ] for elem_synonym in elem_synonyms : synonym_st...
def _chattrib ( name , key , value , param , root = None ) : '''Change an attribute for a named user'''
pre_info = info ( name , root = root ) if not pre_info : return False if value == pre_info [ key ] : return True cmd = [ 'groupmod' ] if root is not None : cmd . extend ( ( '-R' , root ) ) cmd . extend ( ( param , value , name ) ) __salt__ [ 'cmd.run' ] ( cmd , python_shell = False ) return info ( name , ro...
def z ( self , * args , ** kwargs ) : """NAME : PURPOSE : return vertical height INPUT : t - ( optional ) time at which to get the vertical height ro = ( Object - wide default ) physical scale for distances to use to convert use _ physical = use to override Object - wide default for using a physical sca...
if len ( self . vxvv ) < 5 : raise AttributeError ( "linear and planar orbits do not have z()" ) thiso = self ( * args , ** kwargs ) onet = ( len ( thiso . shape ) == 1 ) if onet : return thiso [ 3 ] else : return thiso [ 3 , : ]
def keysyms_from_strings ( ) : """Yields the tuple ` ` ( character , symbol name ) ` ` for all keysyms ."""
for number , codepoint , status , name in keysym_definitions ( ) : # Ignore keysyms that do not map to unicode characters if all ( c == '0' for c in codepoint ) : continue # Ignore keysyms that are not well established if status != '.' : continue yield ( codepoint , name )
def BGE ( self , params ) : """BGE label Branch to the instruction at label if the N flag is the same as the V flag"""
label = self . get_one_parameter ( self . ONE_PARAMETER , params ) self . check_arguments ( label_exists = ( label , ) ) # BGE label def BGE_func ( ) : if self . is_N_set ( ) == self . is_V_set ( ) : self . register [ 'PC' ] = self . labels [ label ] return BGE_func
def do_rmfilter ( self , arg ) : """Removes the test case filter that limits which results are included in plots / tables ."""
if arg in self . curargs [ "tfilter" ] : if arg == "*" : msg . warn ( "The default filter cannot be removed." ) else : self . curargs [ "tfilter" ] . remove ( arg ) self . do_filter ( "list" )
def csv ( cls , d , order = None , header = None , sort_keys = True ) : """prints a table in csv format : param d : A a dict with dicts of the same type . : type d : dict : param order : The order in which the columns are printed . The order is specified by the key names of the dict . : type order : : p...
first_element = list ( d ) [ 0 ] def _keys ( ) : return list ( d [ first_element ] ) # noinspection PyBroadException def _get ( element , key ) : try : tmp = str ( d [ element ] [ key ] ) except : tmp = ' ' return tmp if d is None or d == { } : return None if order is None : orde...
def ask_yes_no ( question , default = 'no' , answer = None ) : u"""Will ask a question and keeps prompting until answered . Args : question ( str ) : Question to ask end user default ( str ) : Default answer if user just press enter at prompt answer ( str ) : Used for testing Returns : ( bool ) Meanin...
default = default . lower ( ) yes = [ u'yes' , u'ye' , u'y' ] no = [ u'no' , u'n' ] if default in no : help_ = u'[N/y]?' default = False else : default = True help_ = u'[Y/n]?' while 1 : display = question + '\n' + help_ if answer is None : log . debug ( u'Under None' ) answer = ...
def _parse_routes ( iface , opts ) : '''Filters given options and outputs valid settings for the route settings file .'''
# Normalize keys opts = dict ( ( k . lower ( ) , v ) for ( k , v ) in six . iteritems ( opts ) ) result = { } if 'routes' not in opts : _raise_error_routes ( iface , 'routes' , 'List of routes' ) for opt in opts : result [ opt ] = opts [ opt ] return result
def _on_response ( self , action , table , attempt , start , response , future , measurements ) : """Invoked when the HTTP request to the DynamoDB has returned and is responsible for setting the future result or exception based upon the HTTP response provided . : param str action : The action that was taken ...
self . logger . debug ( '%s on %s request #%i = %r' , action , table , attempt , response ) now , exception = time . time ( ) , None try : future . set_result ( self . _process_response ( response ) ) except aws_exceptions . ConfigNotFound as error : exception = exceptions . ConfigNotFound ( str ( error ) ) exc...
def get_disks ( self ) : """Return a list of all the Disks attached to this VM The disks are returned in a sham . storage . volumes . Volume object"""
disks = [ disk for disk in self . xml . iter ( 'disk' ) ] disk_objs = [ ] for disk in disks : source = disk . find ( 'source' ) if source is None : continue path = source . attrib [ 'file' ] diskobj = self . domain . connect ( ) . storageVolLookupByPath ( path ) disk_objs . append ( diskobj ...
def get_bin_hierarchy_design_session ( self ) : """Gets the bin hierarchy design session . return : ( osid . resource . BinHierarchyDesignSession ) - a ` ` BinHierarchyDesignSession ` ` raise : OperationFailed - unable to complete request raise : Unimplemented - ` ` supports _ bin _ hierarchy _ design ( ) `...
if not self . supports_bin_hierarchy_design ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . BinHierarchyDesignSession ( runtime = self . _runtime )
def hdel ( self , * args ) : """This command on the model allow deleting many instancehash fields with only one redis call . You must pass hash names to retrieve as arguments"""
if args and not any ( arg in self . _instancehash_fields for arg in args ) : raise ValueError ( "Only InstanceHashField can be used here." ) # Set indexes for indexable fields . for field_name in args : field = self . get_field ( field_name ) if field . indexable : field . deindex ( ) # Return the n...
def specific_actions ( hazard , exposure ) : """Return actions which are specific for a given hazard and exposure . : param hazard : The hazard definition . : type hazard : safe . definition . hazard : param exposure : The exposure definition . : type hazard : safe . definition . exposure : return : List ...
for item in ITEMS : if item [ 'hazard' ] == hazard and item [ 'exposure' ] == exposure : return item . get ( 'actions' , [ ] ) return [ ]
def fix_auth_url_version_prefix ( auth_url ) : """Fix up the auth url if an invalid or no version prefix was given . People still give a v2 auth _ url even when they specify that they want v3 authentication . Fix the URL to say v3 in this case and add version if it is missing entirely . This should be smarter...
auth_url = _augment_url_with_version ( auth_url ) url_fixed = False if get_keystone_version ( ) >= 3 and has_in_url_path ( auth_url , [ "/v2.0" ] ) : url_fixed = True auth_url = url_path_replace ( auth_url , "/v2.0" , "/v3" , 1 ) return auth_url , url_fixed
def execute_dry_run ( self , dialect = None , billing_tier = None ) : """Dry run a query , to check the validity of the query and return some useful statistics . Args : dialect : { ' legacy ' , ' standard ' } , default ' legacy ' ' legacy ' : Use BigQuery ' s legacy SQL dialect . ' standard ' : Use BigQuery...
try : query_result = self . _api . jobs_insert_query ( self . _sql , self . _code , self . _imports , dry_run = True , table_definitions = self . _external_tables , dialect = dialect , billing_tier = billing_tier ) except Exception as e : raise e return query_result [ 'statistics' ] [ 'query' ]
def mtf_image_transformer_base ( ) : """Set of hyperparameters ."""
hparams = common_hparams . basic_params1 ( ) hparams . no_data_parallelism = True hparams . use_fixed_batch_size = True hparams . batch_size = 1 hparams . max_length = 3072 hparams . hidden_size = 256 hparams . label_smoothing = 0.0 # 8 - way model - parallelism hparams . add_hparam ( "mesh_shape" , "batch:8" ) hparams...
def guided_relu ( ) : """Returns : A context where the gradient of : meth : ` tf . nn . relu ` is replaced by guided back - propagation , as described in the paper : ` Striving for Simplicity : The All Convolutional Net < https : / / arxiv . org / abs / 1412.6806 > ` _"""
from tensorflow . python . ops import gen_nn_ops # noqa @ tf . RegisterGradient ( "GuidedReLU" ) def GuidedReluGrad ( op , grad ) : return tf . where ( 0. < grad , gen_nn_ops . _relu_grad ( grad , op . outputs [ 0 ] ) , tf . zeros ( grad . get_shape ( ) ) ) g = tf . get_default_graph ( ) with g . gradient_override_...
def _callbacks_grouped_by_name ( self ) : """Group callbacks by name and collect names set by the user ."""
callbacks , names_set_by_user = OrderedDict ( ) , set ( ) for name , cb , named_by_user in self . _yield_callbacks ( ) : if named_by_user : names_set_by_user . add ( name ) callbacks [ name ] = callbacks . get ( name , [ ] ) + [ cb ] return callbacks , names_set_by_user
def initialize ( self ) : """Sets up initial ensime - vim editor settings ."""
# TODO : This seems wrong , the user setting value is never used anywhere . if 'EnErrorStyle' not in self . _vim . vars : self . _vim . vars [ 'EnErrorStyle' ] = 'EnError' self . _vim . command ( 'highlight EnErrorStyle ctermbg=red gui=underline' ) # TODO : this SHOULD be a buffer - local setting only , and since i...
def create_settings ( pkg , repo_dest , db_user , db_name , db_password , db_host , db_port ) : """Creates a local settings file out of the distributed template . This also fills in database settings and generates a secret key , etc ."""
vars = { 'pkg' : pkg , 'db_user' : db_user , 'db_name' : db_name , 'db_password' : db_password or '' , 'db_host' : db_host or '' , 'db_port' : db_port or '' , 'hmac_date' : datetime . now ( ) . strftime ( '%Y-%m-%d' ) , 'hmac_key' : generate_key ( 32 ) , 'secret_key' : generate_key ( 32 ) } with dir_path ( repo_dest ) ...
def attended_by ( self , email ) : """Check if user attended the event"""
for attendee in self [ "attendees" ] or [ ] : if ( attendee [ "email" ] == email and attendee [ "responseStatus" ] == "accepted" ) : return True return False
def _k_prototypes_iter ( Xnum , Xcat , centroids , cl_attr_sum , cl_memb_sum , cl_attr_freq , membship , num_dissim , cat_dissim , gamma , random_state ) : """Single iteration of the k - prototypes algorithm"""
moves = 0 for ipoint in range ( Xnum . shape [ 0 ] ) : clust = np . argmin ( num_dissim ( centroids [ 0 ] , Xnum [ ipoint ] ) + gamma * cat_dissim ( centroids [ 1 ] , Xcat [ ipoint ] , X = Xcat , membship = membship ) ) if membship [ clust , ipoint ] : # Point is already in its right place . continue ...
def get_compute_environment ( self , identifier ) : """Get compute environment by name or ARN : param identifier : Name or ARN : type identifier : str : return : Compute Environment or None : rtype : ComputeEnvironment or None"""
env = self . get_compute_environment_by_arn ( identifier ) if env is None : env = self . get_compute_environment_by_name ( identifier ) return env
def copy ( self , * args , ** kwargs ) : """Make a copy of this object . Note : Copies both field data and field values . See Also : For arguments and description of behavior see ` pandas docs ` _ . . . _ pandas docs : http : / / pandas . pydata . org / pandas - docs / stable / generated / pandas . Series...
cls = self . __class__ # Note that type conversion does not perform copy data = pd . DataFrame ( self ) . copy ( * args , ** kwargs ) values = [ field . copy ( ) for field in self . field_values ] return cls ( data , field_values = values )
def get_subarray_sbi_ids ( sub_array_id ) : """Return list of scheduling block Id ' s associated with the given sub _ array _ id"""
ids = [ ] for key in sorted ( DB . keys ( pattern = 'scheduling_block/*' ) ) : config = json . loads ( DB . get ( key ) ) if config [ 'sub_array_id' ] == sub_array_id : ids . append ( config [ 'id' ] ) return ids
def delete_by_hash ( self , file_hash ) : """Remove file / archive by it ' s ` file _ hash ` . Args : file _ hash ( str ) : Hash , which is used to find the file in storage . Raises : IOError : If the file for given ` file _ hash ` was not found in storage ."""
full_path = self . file_path_from_hash ( file_hash ) return self . delete_by_path ( full_path )
def _blobs_page_start ( iterator , page , response ) : """Grab prefixes after a : class : ` ~ google . cloud . iterator . Page ` started . : type iterator : : class : ` ~ google . api _ core . page _ iterator . Iterator ` : param iterator : The iterator that is currently in use . : type page : : class : ` ~ g...
page . prefixes = tuple ( response . get ( "prefixes" , ( ) ) ) iterator . prefixes . update ( page . prefixes )
def verify_jwt ( signed_request , expected_aud , secret , validators = [ ] , required_keys = ( 'request.pricePoint' , 'request.name' , 'request.description' , 'response.transactionID' ) , algorithms = None ) : """Verifies a postback / chargeback JWT . Returns the trusted JSON data from the original request . Wh...
if not algorithms : algorithms = [ 'HS256' ] issuer = _get_issuer ( signed_request = signed_request ) app_req = verify_sig ( signed_request , secret , issuer = issuer , algorithms = algorithms , expected_aud = expected_aud ) # I think this call can be removed after # https : / / github . com / jpadilla / pyjwt / is...
def open ( path_or_url ) : """Wrapper for opening an IO object to a local file or URL : param path _ or _ url : : return :"""
is_url = re . compile ( r'^(?:http|ftp)s?://' # http : / / or https : / / r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain . . . r'localhost|' # localhost . . . r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # . . . or ip r'(?::\d+)?' # optional port r'(?:/?|[/?]\S+)$' , re . IGNORE...
def kaldi_pitch ( wav_dir : str , feat_dir : str ) -> None : """Extract Kaldi pitch features . Assumes 16k mono wav files ."""
logger . debug ( "Make wav.scp and pitch.scp files" ) # Make wav . scp and pitch . scp files prefixes = [ ] for fn in os . listdir ( wav_dir ) : prefix , ext = os . path . splitext ( fn ) if ext == ".wav" : prefixes . append ( prefix ) wav_scp_path = os . path . join ( feat_dir , "wavs.scp" ) with open ...
def nth ( self , n , dropna = None ) : """Take the nth row from each group if n is an int , or a subset of rows if n is a list of ints . If dropna , will take the nth non - null row , dropna is either Truthy ( if a Series ) or ' all ' , ' any ' ( if a DataFrame ) ; this is equivalent to calling dropna ( how...
if isinstance ( n , int ) : nth_values = [ n ] elif isinstance ( n , ( set , list , tuple ) ) : nth_values = list ( set ( n ) ) if dropna is not None : raise ValueError ( "dropna option with a list of nth values is not supported" ) else : raise TypeError ( "n needs to be an int or a list/set/tup...
def read_csv_iter ( path , fieldnames = None , sniff = True , mode = 'rt' , encoding = 'utf-8' , * args , ** kwargs ) : '''Iterate through CSV rows in a file . By default , csv . reader ( ) will be used any output will be a list of lists . If fieldnames is provided , DictReader will be used and output will be l...
with open ( path , mode = mode , encoding = encoding ) as infile : for row in iter_csv_stream ( infile , fieldnames = fieldnames , sniff = sniff , * args , ** kwargs ) : yield row
def transform_sparql_construct ( rdf , construct_query ) : """Perform a SPARQL CONSTRUCT query on the RDF data and return a new graph ."""
logging . debug ( "performing SPARQL CONSTRUCT transformation" ) if construct_query [ 0 ] == '@' : # actual query should be read from file construct_query = file ( construct_query [ 1 : ] ) . read ( ) logging . debug ( "CONSTRUCT query: %s" , construct_query ) newgraph = Graph ( ) for triple in rdf . query ( constr...
def _common ( ret , name , service_name , kwargs ) : '''Returns : tuple whose first element is a bool indicating success or failure and the second element is either a ret dict for salt or an object'''
if 'interface' not in kwargs and 'public_url' not in kwargs : kwargs [ 'interface' ] = name service = __salt__ [ 'keystoneng.service_get' ] ( name_or_id = service_name ) if not service : ret [ 'comment' ] = 'Cannot find service' ret [ 'result' ] = False return ( False , ret ) filters = kwargs . copy ( )...
def _all_same_area ( self , dataset_ids ) : """Return True if all areas for the provided IDs are equal ."""
all_areas = [ ] for ds_id in dataset_ids : for scn in self . scenes : ds = scn . get ( ds_id ) if ds is None : continue all_areas . append ( ds . attrs . get ( 'area' ) ) all_areas = [ area for area in all_areas if area is not None ] return all ( all_areas [ 0 ] == area for area ...
def coupl_model1 ( self ) : """In model 1 , we want enforce the following signs on the couplings . Model 2 has the same couplings but arbitrary signs ."""
self . Coupl [ 0 , 0 ] = np . abs ( self . Coupl [ 0 , 0 ] ) self . Coupl [ 0 , 1 ] = - np . abs ( self . Coupl [ 0 , 1 ] ) self . Coupl [ 1 , 1 ] = np . abs ( self . Coupl [ 1 , 1 ] )
def new_request ( sender , request = None , notify = True , ** kwargs ) : """New request for inclusion ."""
if current_app . config [ 'COMMUNITIES_MAIL_ENABLED' ] and notify : send_community_request_email ( request )
async def set_control_setpoint ( self , setpoint , timeout = OTGW_DEFAULT_TIMEOUT ) : """Manipulate the control setpoint being sent to the boiler . Set to 0 to pass along the value specified by the thermostat . Return the newly accepted value , or None on failure . This method is a coroutine"""
cmd = OTGW_CMD_CONTROL_SETPOINT status = { } ret = await self . _wait_for_cmd ( cmd , setpoint , timeout ) if ret is None : return ret = float ( ret ) status [ DATA_CONTROL_SETPOINT ] = ret self . _update_status ( status ) return ret
def has_commit ( self , client_key = None ) : """Return True if client has new commit . : param client _ key : The client key : type client _ key : str : return : : rtype : boolean"""
if client_key is None and self . current_client is None : raise ClientNotExist ( ) if client_key : if not self . clients . has_client ( client_key ) : raise ClientNotExist ( ) client = self . clients . get_client ( client_key ) return client . has_commit ( ) if self . current_client : client...
def _parseAtCharset ( self , src ) : """[ CHARSET _ SYM S * STRING S * ' ; ' ] ?"""
if isAtRuleIdent ( src , 'charset' ) : src = stripAtRuleIdent ( src ) charset , src = self . _getString ( src ) src = src . lstrip ( ) if src [ : 1 ] != ';' : raise self . ParseError ( '@charset expected a terminating \';\'' , src , self . ctxsrc ) src = src [ 1 : ] . lstrip ( ) self . c...
def comm_sep ( self , plot_locs , criteria , loc_unit = None ) : '''Calculates commonality ( Sorensen and Jaccard ) between pairs of plots . Parameters plot _ locs : dict Dictionary with keys equal to each plot name , which must be represented by a column in the data table , and values equal to a tuple of...
# Set up sad _ dict with key = plot and val = clean sad for that plot sad_dict = { } # Loop through all plot cols , updating criteria , and getting spp _ list for plot in plot_locs . keys ( ) : # Find current count col and remove it from criteria for crit_key in criteria . keys ( ) : if criteria [ crit_key ...
def delete_load_balancer ( access_token , subscription_id , resource_group , lb_name ) : '''Delete a load balancer . Args : access _ token ( str ) : A valid Azure authentication token . subscription _ id ( str ) : Azure subscription id . resource _ group ( str ) : Azure resource group name . lb _ name ( s...
endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourceGroups/' , resource_group , '/providers/Microsoft.Network/loadBalancers/' , lb_name , '?api-version=' , NETWORK_API ] ) return do_delete ( endpoint , access_token )
def lint_file ( file_path ) : """Validate & lint ` file _ path ` and return a LintResult . : param file _ path : YAML filename : type file _ path : str : return : LintResult object"""
with open ( file_path , 'r' ) as yaml : try : return lint ( yaml ) except Exception as e : lr = LintResult ( ) lr . add_error ( 'could not parse YAML: %s' % e , exception = e ) return lr
def length ( self ) : """Gives the length of the queue . Returns ` ` None ` ` if the queue is not connected . If the queue is not connected then it will raise : class : ` retask . ConnectionError ` ."""
if not self . connected : raise ConnectionError ( 'Queue is not connected' ) try : length = self . rdb . llen ( self . _name ) except redis . exceptions . ConnectionError as err : raise ConnectionError ( str ( err ) ) return length
def request ( self , type , command_list ) : '''Send NX - API JSON request to the NX - OS device .'''
req = self . _build_request ( type , command_list ) if self . nxargs [ 'connect_over_uds' ] : self . connection . request ( 'POST' , req [ 'url' ] , req [ 'payload' ] , req [ 'headers' ] ) response = self . connection . getresponse ( ) else : response = self . connection ( req [ 'url' ] , method = 'POST' , ...
def accountSummary ( self , reqId , account , tag , value , curency ) : """accountSummary ( EWrapper self , int reqId , IBString const & account , IBString const & tag , IBString const & value , IBString const & curency )"""
return _swigibpy . EWrapper_accountSummary ( self , reqId , account , tag , value , curency )
def conv2bin ( data ) : """Convert a matrix of probabilities into binary values . If the matrix has values < = 0 or > = 1 , the values are normalized to be in [ 0 , 1 ] . : type data : numpy array : param data : input matrix : return : converted binary matrix"""
if data . min ( ) < 0 or data . max ( ) > 1 : data = normalize ( data ) out_data = data . copy ( ) for i , sample in enumerate ( out_data ) : for j , val in enumerate ( sample ) : if np . random . random ( ) <= val : out_data [ i ] [ j ] = 1 else : out_data [ i ] [ j ] = ...
def dump ( cls ) : """Output all recorded metrics"""
with cls . lock : if not cls . instances : return atexit . unregister ( cls . dump ) for self in cls . instances . values ( ) : self . fh . close ( )
def open_grindstone ( self ) : """Opens a grindstone file and populates the grindstone with it ' s contents . Returns an empty grindstone json object if a file does not exist ."""
try : with open ( self . grindstone_path , 'r' ) as f : # Try opening the file return json . loads ( f . read ( ) ) # If the file is empty except json . decoder . JSONDecodeError : # Default return empty object with empty tasks list return { 'tasks' : [ ] } # The file does not yet exist except FileNotFo...
def draw_visibility_image_internal ( gl , v , f ) : """Assumes camera is set up correctly in gl context ."""
gl . Clear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) ; fc = np . arange ( 1 , len ( f ) + 1 ) fc = np . tile ( col ( fc ) , ( 1 , 3 ) ) fc [ : , 0 ] = fc [ : , 0 ] & 255 fc [ : , 1 ] = ( fc [ : , 1 ] >> 8 ) & 255 fc [ : , 2 ] = ( fc [ : , 2 ] >> 16 ) & 255 fc = np . asarray ( fc , dtype = np . uint8 ) draw_colored_...
def compute_numtab ( self ) : """Recomputes the sets for the static ranges of the trigger time . This method should only be called by the user if the string _ tab member is modified ."""
self . numerical_tab = [ ] for field_str , span in zip ( self . string_tab , FIELD_RANGES ) : split_field_str = field_str . split ( ',' ) if len ( split_field_str ) > 1 and "*" in split_field_str : raise ValueError ( "\"*\" must be alone in a field." ) unified = set ( ) for cron_atom in split_fi...
def _connect ( self ) : """Connect to the EC2 cloud provider . : return : : py : class : ` boto . ec2 . connection . EC2Connection ` : raises : Generic exception on error"""
# check for existing connection if self . _ec2_connection : return self . _ec2_connection try : log . debug ( "Connecting to EC2 endpoint %s" , self . _ec2host ) # connect to webservice ec2_connection = boto . ec2 . connect_to_region ( self . _region_name , aws_access_key_id = self . _access_key , aws_s...
def add_circle ( self , x0 , radius , lcar = None , R = None , compound = False , num_sections = 3 , holes = None , make_surface = True , ) : """Add circle in the : math : ` x ` - : math : ` y ` - plane ."""
if holes is None : holes = [ ] else : assert make_surface # Define points that make the circle ( midpoint and the four cardinal # directions ) . X = numpy . zeros ( ( num_sections + 1 , len ( x0 ) ) ) if num_sections == 4 : # For accuracy , the points are provided explicitly . X [ 1 : , [ 0 , 1 ] ] = numpy ...
def _parse_message_to_mqtt ( self , data ) : """Parse a mysensors command string . Return a MQTT topic , payload and qos - level as a tuple ."""
msg = Message ( data , self ) payload = str ( msg . payload ) msg . payload = '' # prefix / node / child / type / ack / subtype : payload return ( '{}/{}' . format ( self . _out_prefix , msg . encode ( '/' ) ) [ : - 2 ] , payload , msg . ack )
def discharge_coefficient_to_K ( D , Do , C ) : r'''Converts a discharge coefficient to a standard loss coefficient , for use in computation of the actual pressure drop of an orifice or other device . . . math : : K = \ left [ \ frac { \ sqrt { 1 - \ beta ^ 4(1 - C ^ 2 ) } } { C \ beta ^ 2 } - 1 \ right ] ^...
beta = Do / D beta2 = beta * beta beta4 = beta2 * beta2 return ( ( 1.0 - beta4 * ( 1.0 - C * C ) ) ** 0.5 / ( C * beta2 ) - 1.0 ) ** 2
def num_events ( self ) : """Lazy evaluation of the number of events ."""
if not self . _num_events : self . _num_events = self . coll_handle . count ( ) return self . _num_events
def _print_if_needed ( self ) : """Assumes you hold the lock"""
if self . _in_txn or self . print_frequency is None : return elif self . last_export is not None and self . last_export + self . print_frequency > time . time ( ) : return self . export ( )
def sealedbox_encrypt ( data , ** kwargs ) : '''Encrypt data using a public key generated from ` nacl . keygen ` . The encryptd data can be decrypted using ` nacl . sealedbox _ decrypt ` only with the secret key . CLI Examples : . . code - block : : bash salt - run nacl . sealedbox _ encrypt datatoenc sal...
# ensure data is in bytes data = salt . utils . stringutils . to_bytes ( data ) pk = _get_pk ( ** kwargs ) b = libnacl . sealed . SealedBox ( pk ) return base64 . b64encode ( b . encrypt ( data ) )
def _check_argument_units ( args , dimensionality ) : """Yield arguments with improper dimensionality ."""
for arg , val in args . items ( ) : # Get the needed dimensionality ( for printing ) as well as cached , parsed version # for this argument . try : need , parsed = dimensionality [ arg ] except KeyError : # Argument did not have units specified in decorator continue # See if the value passed...
def edge_val_dump ( self ) : """Yield the entire contents of the edge _ val table ."""
self . _flush_edge_val ( ) for ( graph , orig , dest , idx , key , branch , turn , tick , value ) in self . sql ( 'edge_val_dump' ) : yield ( self . unpack ( graph ) , self . unpack ( orig ) , self . unpack ( dest ) , idx , self . unpack ( key ) , branch , turn , tick , self . unpack ( value ) )
def calc_qiga1_v1 ( self ) : """Perform the runoff concentration calculation for the first interflow component . The working equation is the analytical solution of the linear storage equation under the assumption of constant change in inflow during the simulation time step . Required derived parameter : ...
der = self . parameters . derived . fastaccess old = self . sequences . states . fastaccess_old new = self . sequences . states . fastaccess_new if der . ki1 <= 0. : new . qiga1 = new . qigz1 elif der . ki1 > 1e200 : new . qiga1 = old . qiga1 + new . qigz1 - old . qigz1 else : d_temp = ( 1. - modelutils . e...
def change_columns ( self , model , ** fields ) : """Change fields ."""
for name , field in fields . items ( ) : old_field = model . _meta . fields . get ( name , field ) old_column_name = old_field and old_field . column_name model . _meta . add_field ( name , field ) if isinstance ( old_field , pw . ForeignKeyField ) : self . ops . append ( self . migrator . drop_...
def _bnd ( self , xloc , dist , cache ) : """Distribution bounds ."""
return numpy . log ( evaluation . evaluate_bound ( dist , numpy . e ** xloc , cache = cache ) )
def _apply_all ( self , sat ) : """Apply all of the custom functions to the satellite data object ."""
if len ( self . _functions ) > 0 : for func , arg , kwarg , kind in zip ( self . _functions , self . _args , self . _kwargs , self . _kind ) : if len ( sat . data ) > 0 : if kind == 'add' : # apply custom functions that add data to the # instrument object tempd = sat ...
def row ( self ) : """Game Dataset ( Row ) : return : { ' retro _ game _ id ' : Retrosheet Game id ' game _ type ' : Game Type ( S / R / F / D / L / W ) ' game _ type _ des ' : Game Type Description ( Spring Training or Regular Season or Wild - card Game or Divisional Series or LCS or World Series ) ' s...
row = OrderedDict ( ) row [ 'retro_game_id' ] = self . retro_game_id row [ 'game_type' ] = self . game_type row [ 'game_type_des' ] = self . game_type_des row [ 'st_fl' ] = self . st_fl row [ 'regseason_fl' ] = self . regseason_fl row [ 'playoff_fl' ] = self . playoff_fl row [ 'local_game_time' ] = self . local_game_ti...
def get_s3_buckets ( api_client , s3_info , s3_params ) : """List all available buckets : param api _ client : : param s3 _ info : : param s3 _ params : : return :"""
manage_dictionary ( s3_info , 'buckets' , { } ) buckets = api_client [ get_s3_list_region ( s3_params [ 'selected_regions' ] ) ] . list_buckets ( ) [ 'Buckets' ] targets = [ ] for b in buckets : # Abort if bucket is not of interest if ( b [ 'Name' ] in s3_params [ 'skipped_buckets' ] ) or ( len ( s3_params [ 'check...
def broadcast_impl ( self , old_slices , old_shape , new_shape ) : """Implementation of a broadcast operation . Args : old _ slices : LaidOutTensor . old _ shape : Shape . new _ shape : Shape . Returns : LaidOutTensor ."""
new_slice_shape = self . slice_shape ( new_shape ) def tf_fn ( x ) : return ( tf . zeros ( new_slice_shape , dtype = x . dtype ) + _expand_dims ( x , old_shape , new_shape ) ) return self . slicewise ( tf_fn , old_slices )
def handle_new_config ( args ) : """usage : cosmic - ray new - config < config - file > Create a new config file ."""
config = cosmic_ray . commands . new_config ( ) config_str = serialize_config ( config ) with open ( args [ '<config-file>' ] , mode = 'wt' ) as handle : handle . write ( config_str ) return ExitCode . OK