signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
async def get_peer_id ( self , peer , add_mark = True ) : """Gets the ID for the given peer , which may be anything entity - like . This method needs to be ` ` async ` ` because ` peer ` supports usernames , invite - links , phone numbers ( from people in your contact list ) , etc . If ` ` add _ mark is False...
if isinstance ( peer , int ) : return utils . get_peer_id ( peer , add_mark = add_mark ) try : if peer . SUBCLASS_OF_ID not in ( 0x2d45687 , 0xc91c90b6 ) : # 0x2d45687 , 0xc91c90b6 = = crc32 ( b ' Peer ' ) and b ' InputPeer ' peer = await self . get_input_entity ( peer ) except AttributeError : peer...
def _write_config ( config ) : '''writes / usbkey / config'''
try : with salt . utils . atomicfile . atomic_open ( '/usbkey/config' , 'w' ) as config_file : config_file . write ( "#\n# This file was generated by salt\n#\n" ) for prop in salt . utils . odict . OrderedDict ( sorted ( config . items ( ) ) ) : if ' ' in six . text_type ( config [ prop ...
def _create ( cls , repo , path , resolve , reference , force , logmsg = None ) : """internal method used to create a new symbolic reference . If resolve is False , the reference will be taken as is , creating a proper symbolic reference . Otherwise it will be resolved to the corresponding object and a detach...
git_dir = _git_dir ( repo , path ) full_ref_path = cls . to_full_path ( path ) abs_ref_path = osp . join ( git_dir , full_ref_path ) # figure out target data target = reference if resolve : target = repo . rev_parse ( str ( reference ) ) if not force and osp . isfile ( abs_ref_path ) : target_data = str ( targe...
def _get ( self , value , context = None , default = None ) : """Similar to _ get _ list ( ) except that the return value is required to be a str . This calls _ get _ list ( ) to retrieve the value , but raises an exception unless the return is None or a single - valued list when that value will be returned ....
if value is None : return default ret = self . _get_list ( value , context = context ) if ret is None : return default name = getattr ( self , '_name' , None ) if isinstance ( ret , list ) : if len ( ret ) == 0 : raise TaskError ( name , "Value '%s' resolved to an empty list" % ( value , ) ) eli...
def ip_verification_required ( func ) : """Put this decorator before your view to check if the function is coming from an IP on file"""
def wrapper ( request , * args , ** kwargs ) : slug = kwargs . get ( 'slug' , "" ) if not slug : return kickoutt_404 ( "Not found." , content_type = "application/json" ) try : wip = WriteAPIIP . objects . get ( slug = slug ) ip = get_client_ip ( request ) if ip not in wip . a...
def call ( command , silent = False ) : """Runs a bash command safely , with shell = false , catches any non - zero return codes . Raises slightly modified CalledProcessError exceptions on failures . Note : command is a string and cannot include pipes ."""
try : if silent : with open ( os . devnull , 'w' ) as FNULL : return subprocess . check_call ( command_to_array ( command ) , stdout = FNULL ) else : # Using the defaults , shell = False , no i / o redirection . return check_call ( command_to_array ( command ) ) except CalledProcessE...
def start ( self , contract_names , target ) : '''loads the contracts - - starts their event listeners : param contract _ names : : return :'''
if isinstance ( contract_names , str ) : contract_names = [ contract_names ] if not isinstance ( contract_names , list ) : return None , "error: expecting a string, or a list of contract names" contract_listeners = [ ] for name in contract_names : c , err = Contract . get ( name , self ) if err : ...
def most_common_nucleotides ( partitioned_read_sequences ) : """Find the most common nucleotide at each offset to the left and right of a variant . Parameters partitioned _ read _ sequences : list of tuples Each tuple has three elements : - sequence before mutant nucleotides - mutant nucleotides - seq...
counts , variant_column_indices = nucleotide_counts ( partitioned_read_sequences ) max_count_per_column = counts . max ( axis = 0 ) assert len ( max_count_per_column ) == counts . shape [ 1 ] max_nucleotide_index_per_column = np . argmax ( counts , axis = 0 ) assert len ( max_nucleotide_index_per_column ) == counts . s...
def _head ( self , client_kwargs ) : """Returns object or bucket HTTP header . Args : client _ kwargs ( dict ) : Client arguments . Returns : dict : HTTP header ."""
with _handle_client_error ( ) : # Object if 'Key' in client_kwargs : header = self . client . head_object ( ** client_kwargs ) # Bucket else : header = self . client . head_bucket ( ** client_kwargs ) # Clean up HTTP request information for key in ( 'AcceptRanges' , 'ResponseMetadata' ) : ...
def flatten ( self ) : """Flatten the scheme into a dictionary where the keys are compound ' dot ' notation keys , and the values are the corresponding options . Returns : dict : The flattened ` Scheme ` ."""
if self . _flat is None : flat = { } for arg in self . args : if isinstance ( arg , Option ) : flat [ arg . name ] = arg elif isinstance ( arg , ListOption ) : flat [ arg . name ] = arg elif isinstance ( arg , DictOption ) : flat [ arg . name ] = arg ...
def user_entry ( entry_int , num_inst , command ) : """Validate user entry and returns index and validity flag . Processes the user entry and take the appropriate action : abort if ' 0 ' entered , set validity flag and index is valid entry , else return invalid index and the still unset validity flag . Args...
valid_entry = False if not entry_int : print ( "{}aborting{} - {} instance\n" . format ( C_ERR , C_NORM , command ) ) sys . exit ( ) elif entry_int >= 1 and entry_int <= num_inst : entry_idx = entry_int - 1 valid_entry = True else : print ( "{}Invalid entry:{} enter a number between 1" " and {}." . ...
def get_sub_array_sbi_ids ( self , sub_array_id ) : """Get Scheduling Block Instance ID associated with sub array id"""
_ids = [ ] sbi_ids = self . get_sched_block_instance_ids ( ) for details in self . get_block_details ( sbi_ids ) : if details [ 'sub_array_id' ] == sub_array_id : _ids . append ( details [ 'id' ] ) return sorted ( _ids )
def combine_dicts ( * dicts , copy = False , base = None ) : """Combines multiple dicts in one . : param dicts : A sequence of dicts . : type dicts : dict : param copy : If True , it returns a deepcopy of input values . : type copy : bool , optional : param base : Base dict where combine multiple di...
if len ( dicts ) == 1 and base is None : # Only one input dict . cd = dicts [ 0 ] . copy ( ) else : cd = { } if base is None else base # Initialize empty dict . for d in dicts : # Combine dicts . if d : # noinspection PyTypeChecker cd . update ( d ) # Return combined dict . return { ...
def integrate ( self , rate , timestep ) : """Advance a time varying quaternion to its value at a time ` timestep ` in the future . The Quaternion object will be modified to its future value . It is guaranteed to remain a unit quaternion . Params : rate : numpy 3 - array ( or array - like ) describing rotat...
self . _fast_normalise ( ) rate = self . _validate_number_sequence ( rate , 3 ) rotation_vector = rate * timestep rotation_norm = np . linalg . norm ( rotation_vector ) if rotation_norm > 0 : axis = rotation_vector / rotation_norm angle = rotation_norm q2 = Quaternion ( axis = axis , angle = angle ) sel...
def _Matches ( path , pattern_list ) : """Returns true if path matches any patten found in pattern _ list . Args : path : A dot separated path to a package , class , method or variable pattern _ list : A list of wildcard patterns Returns : True if path matches any wildcard found in pattern _ list ."""
# Note : This code does not scale to large pattern _ list sizes . return any ( fnmatch . fnmatchcase ( path , pattern ) for pattern in pattern_list )
def unbuild_month ( self , dt ) : """Deletes the directory at self . get _ build _ path ."""
self . year = str ( dt . year ) self . month = str ( dt . month ) logger . debug ( "Building %s-%s" % ( self . year , self . month ) ) target_path = os . path . split ( self . get_build_path ( ) ) [ 0 ] if self . fs . exists ( target_path ) : logger . debug ( "Removing {}" . format ( target_path ) ) self . fs ....
def read_csv ( csv_file , options , ensemble_list = None ) : """Read csv and return molList , otherwise print error and exit ."""
name , ext = os . path . splitext ( csv_file ) try : if ext == '.gz' : f = gzip . open ( csv_file , 'rb' ) else : f = open ( csv_file , 'rU' ) except IOError : print ( " \n '{f}' could not be opened\n" . format ( f = os . path . basename ( csv_file ) ) ) sys . exit ( 1 ) csv_reader = csv...
def generate_uris ( self ) : """Generate several lambda uris ."""
lambda_arn = "arn:aws:execute-api:{0}:{1}:{2}/*/{3}/{4}" . format ( self . region , self . account_id , self . api_id , self . trigger_settings [ 'method' ] , self . trigger_settings [ 'resource' ] ) lambda_uri = ( "arn:aws:apigateway:{0}:lambda:path/{1}/functions/" "arn:aws:lambda:{0}:{2}:function:{3}/invocations" ) ....
def _is_url_in_cache ( * args , ** kwargs ) : """Return True if request has been cached or False otherwise ."""
# Only include allowed arguments for a PreparedRequest . allowed_args = inspect . getargspec ( requests . models . PreparedRequest . prepare ) . args # self is in there as . prepare ( ) is a method . allowed_args . remove ( 'self' ) kwargs_cleaned = { } for key , value in dict ( kwargs ) . items ( ) : if key in all...
def identifier ( self ) : """Get the identifier for this node . Extended keys can be identified by the Hash160 ( RIPEMD160 after SHA256) of the public key ' s ` key ` . This corresponds exactly to the data used in traditional Bitcoin addresses . It is not advised to represent this data in base58 format thou...
key = self . get_public_key_hex ( ) return ensure_bytes ( hexlify ( hash160 ( unhexlify ( ensure_bytes ( key ) ) ) ) )
def expect_request ( self , schema , merge = False ) : """* Sets the schema to validate the request properties * Expectations are effective for following requests in the test suite , or until they are reset or updated by using expectation keywords again . On the test suite level ( suite setup ) , they are bes...
schema = self . _input_object ( schema ) if "properties" not in schema : schema = { "properties" : schema } if self . _input_boolean ( merge ) : new_schema = SchemaBuilder ( schema_uri = False ) new_schema . add_schema ( self . schema [ "properties" ] [ "request" ] ) new_schema . add_schema ( schema ) ...
def _get_asset_content ( self , asset_id , asset_content_type_str = None , asset_content_id = None ) : """stub"""
rm = self . my_osid_object . _get_provider_manager ( 'REPOSITORY' ) if 'assignedBankIds' in self . my_osid_object . _my_map : if self . my_osid_object . _proxy is not None : als = rm . get_asset_lookup_session_for_repository ( Id ( self . my_osid_object . _my_map [ 'assignedBankIds' ] [ 0 ] ) , self . my_os...
def get_description ( self ) : """Gets a description of this service implementation . return : ( osid . locale . DisplayText ) - a description compliance : mandatory - This method must be implemented ."""
return DisplayText ( { 'text' : profile . DESCRIPTION , 'languageTypeId' : profile . LANGUAGETYPEID , 'scriptTypeId' : profile . SCRIPTTYPEID , 'formatTypeId' : profile . FORMATTYPEID } )
async def click ( self , entity , reply_to = None , silent = False , clear_draft = False , hide_via = False ) : """Clicks this result and sends the associated ` message ` . Args : entity ( ` entity ` ) : The entity to which the message of this result should be sent . reply _ to ( ` int ` | ` Message < telet...
entity = await self . _client . get_input_entity ( entity ) reply_id = None if reply_to is None else utils . get_message_id ( reply_to ) req = functions . messages . SendInlineBotResultRequest ( peer = entity , query_id = self . _query_id , id = self . result . id , silent = silent , clear_draft = clear_draft , hide_vi...
def close ( self , kill_restart = True ) : '''Use when you would like to close everything down @ param kill _ restart = Prevent kazoo restarting from occurring'''
self . do_not_restart = kill_restart self . zoo_client . stop ( ) self . zoo_client . close ( )
def _build_action_bound_constraints_table ( self ) : '''Builds the lower and upper action bound constraint expressions .'''
self . action_lower_bound_constraints = { } self . action_upper_bound_constraints = { } for name , preconds in self . local_action_preconditions . items ( ) : for precond in preconds : expr_type = precond . etype expr_args = precond . args bounds_expr = None if expr_type == ( 'aggreg...
def prepare_on_all_hosts ( self , query , excluded_host , keyspace = None ) : """Prepare the given query on all hosts , excluding ` ` excluded _ host ` ` . Intended for internal use only ."""
futures = [ ] for host in tuple ( self . _pools . keys ( ) ) : if host != excluded_host and host . is_up : future = ResponseFuture ( self , PrepareMessage ( query = query , keyspace = keyspace ) , None , self . default_timeout ) # we don ' t care about errors preparing against specific hosts , ...
def read_from ( self , provider , null_allowed = False , ** options ) : """Reads from the data : class : ` Provider ` the necessary number of bytes for the : attr : ` data ` object referenced by the ` Pointer ` field . A ` Pointer ` field stores the binary data read from the data : class : ` Provider ` in its...
if self . _data is None : pass elif is_provider ( provider ) : if self . _value < 0 : pass elif null_allowed or self . _value > 0 : while True : self . bytestream = provider . read ( self . address , self . data_size ) index = self . deserialize_data ( ) #...
def copycol ( self , origin_col : str , dest_col : str ) : """Copy a columns values in another column : param origin _ col : name of the column to copy : type origin _ col : str : param dest _ col : name of the new column : type dest _ col : str : example : ` ` ds . copy ( " col 1 " , " New col " ) ` `"""
try : self . df [ dest_col ] = self . df [ [ origin_col ] ] except Exception as e : self . err ( e , self . copy_col , "Can not copy column" )
def _read_para_notification ( self , code , cbit , clen , * , desc , length , version ) : """Read HIP NOTIFICATION parameter . Structure of HIP NOTIFICATION parameter [ RFC 7401 ] : 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 | Type | Length | | Reserved | Notify Message Type |...
_resv = self . _read_fileng ( 2 ) _code = self . _read_unpack ( 2 ) _data = self . _read_fileng ( 2 ) _type = _NOTIFICATION_TYPE . get ( _code ) if _type is None : if 1 <= _code <= 50 : _type = 'Unassigned (IETF Review)' elif 51 <= _code <= 8191 : _type = 'Unassigned (Specification Required; Err...
def clusterMetrics ( timeValues , massValues , massScalingFactor = 1 ) : """# TODO : docstring"""
metrics = dict ( ) metrics [ 'meanTime' ] = numpy . mean ( timeValues ) metrics [ 'meanMass' ] = numpy . mean ( massValues ) metrics [ 'devTime' ] = timeValues - metrics [ 'meanTime' ] metrics [ 'devMass' ] = massValues - metrics [ 'meanMass' ] # metrics [ ' devMass ' ] = ( 1 - metrics [ ' meanMass ' ] / massValues ) m...
def db_exists ( cls , impl , working_dir ) : """Does the chainstate db exist ?"""
path = config . get_snapshots_filename ( impl , working_dir ) return os . path . exists ( path )
def scaled_imu2_send ( self , time_boot_ms , xacc , yacc , zacc , xgyro , ygyro , zgyro , xmag , ymag , zmag , force_mavlink1 = False ) : '''The RAW IMU readings for secondary 9DOF sensor setup . This message should contain the scaled values to the described units time _ boot _ ms : Timestamp ( milliseconds s...
return self . send ( self . scaled_imu2_encode ( time_boot_ms , xacc , yacc , zacc , xgyro , ygyro , zgyro , xmag , ymag , zmag ) , force_mavlink1 = force_mavlink1 )
def set_deployment_run_name ( self ) : """Sets the deployment run name from deployment properties : return : None"""
log = logging . getLogger ( self . cls_logger + '.set_deployment_run_name' ) self . deployment_run_name = self . get_value ( 'cons3rt.deploymentRun.name' ) log . info ( 'Found deployment run name: {n}' . format ( n = self . deployment_run_name ) )
def remove_elaborated ( type_ ) : """removes type - declaration class - binder : class : ` elaborated _ t ` from the ` type _ ` If ` type _ ` is not : class : ` elaborated _ t ` , it will be returned as is"""
nake_type = remove_alias ( type_ ) if not is_elaborated ( nake_type ) : return type_ else : if isinstance ( type_ , cpptypes . elaborated_t ) : type_ = type_ . base return type_
def clean ( ctx ) : """clean generated project files"""
os . chdir ( PROJECT_DIR ) patterns = [ '.cache' , '.coverage' , '.eggs' , 'build' , 'dist' ] ctx . run ( 'rm -vrf {0}' . format ( ' ' . join ( patterns ) ) ) ctx . run ( '''find . \( -name '*,cover' -o -name '__pycache__' -o -name '*.py[co]' -o -name '_work' \) ''' '''-exec rm -vrf '{}' \; || true''' )
def init_client ( client_id ) : """Initialse a driver for client and store for future reference @ param client _ id : ID of client user @ return whebwhatsapi object"""
if client_id not in drivers : drivers [ client_id ] = init_driver ( client_id ) return drivers [ client_id ]
def retry_until_not_none_or_limit_reached ( method , limit , sleep_s = 1 , catch_exceptions = ( ) ) : """Executes a method until the retry limit is hit or not None is returned ."""
return retry_until_valid_or_limit_reached ( method , limit , lambda x : x is not None , sleep_s , catch_exceptions )
def get_info ( self , url = None , thing_id = None , * args , ** kwargs ) : """Look up existing items by thing _ id ( fullname ) or url . : param url : A url to lookup . : param thing _ id : A single thing _ id , or a list of thing _ ids . A thing _ id can be any one of Comment ( ` ` t1 _ ` ` ) , Link ( ` ` t...
if bool ( url ) == bool ( thing_id ) : raise TypeError ( 'Only one of url or thing_id is required!' ) # In these cases , we will have a list of things to return . # Otherwise , it will just be one item . if isinstance ( thing_id , six . string_types ) and ',' in thing_id : thing_id = thing_id . split ( ',' ) re...
def from_bytes ( cls , bitstream , decode_payload = True ) : r'''Parse the given packet and update properties accordingly > > > data _ hex = ( ' c033d3c100000745c0005835400000' . . . ' ff06094a254d38204d45d1a30016f597' . . . ' a1c3c7406718bf1b50180ff0793f0000' . . . ' b555e59ff5ba6aad33d875c600fd8c1f ' . ...
packet = cls ( ) # Convert to ConstBitStream ( if not already provided ) if not isinstance ( bitstream , ConstBitStream ) : if isinstance ( bitstream , Bits ) : bitstream = ConstBitStream ( auto = bitstream ) else : bitstream = ConstBitStream ( bytes = bitstream ) # Read the flags ( nonce_presen...
def man ( self , ** kwargs ) : """Print some man for each understood command"""
str_man = 'commands' str_amount = 'full' for k , v in kwargs . items ( ) : if k == 'on' : str_man = v if k == 'amount' : str_amount = v if str_man == 'commands' : str_commands = """ This script/module provides CURL-based GET/PUT/POST communication over http to a remot...
def extract_tar ( fileobj ) : """Yields 3 - tuples of ( name , modified , bytes ) ."""
import time archive = tarfile . open ( fileobj = fileobj ) filenames = [ info . name for info in archive . getmembers ( ) if info . isfile ( ) ] for src_name , dst_name in filter_tzfiles ( filenames ) : mtime = archive . getmember ( src_name ) . mtime modified = tuple ( time . gmtime ( mtime ) [ : 6 ] ) byt...
def notConnectedNodes ( self ) -> Set [ str ] : """Returns the names of nodes in the registry this node is NOT connected to ."""
return set ( self . registry . keys ( ) ) - self . conns
def cdx_clamp ( cdx_iter , from_ts , to_ts ) : """Clamp by start and end ts"""
if from_ts and len ( from_ts ) < 14 : from_ts = pad_timestamp ( from_ts , PAD_14_DOWN ) if to_ts and len ( to_ts ) < 14 : to_ts = pad_timestamp ( to_ts , PAD_14_UP ) for cdx in cdx_iter : if from_ts and cdx [ TIMESTAMP ] < from_ts : continue if to_ts and cdx [ TIMESTAMP ] > to_ts : conti...
def get_logger ( name = None , filename = None , filemode = None , level = WARNING ) : """Gets a customized logger . Parameters name : str , optional Name of the logger . filename : str , optional The filename to which the logger ' s output will be sent . filemode : str , optional The file mode to ope...
logger = logging . getLogger ( name ) if name is not None and not getattr ( logger , '_init_done' , None ) : logger . _init_done = True if filename : mode = filemode if filemode else 'a' hdlr = logging . FileHandler ( filename , mode ) else : hdlr = logging . StreamHandler ( ) ...
def endofcell_marker ( source , comment ) : """Issues # 31 # 38 : does the cell contain a blank line ? In that case we add an end - of - cell marker"""
endofcell = '-' while True : endofcell_re = re . compile ( r'^{}( )' . format ( comment ) + endofcell + r'\s*$' ) if list ( filter ( endofcell_re . match , source ) ) : endofcell = endofcell + '-' else : return endofcell
def get_unique_repositories ( repo_list ) : """Method to create unique list of repositories from the list of repositories given . : param repo _ list : List of repositories which might contain duplicates . : return : List of repositories with no duplicate in them ."""
unique_list = list ( ) included = defaultdict ( lambda : False ) for repo in repo_list : if not included [ repo . full_name ] : unique_list . append ( repo ) included [ repo . full_name ] = True return unique_list
def render_pep440_branch_based ( pieces ) : """Build up version string , with post - release " local version identifier " . Our goal : TAG [ + DISTANCE . BRANCH _ gHEX [ . dirty ] ] . Note that if you get a tagged build and then dirty it , you ' ll get TAG + 0 . BRANCH _ gHEX . dirty Exceptions : 1 : no tag...
replacements = ( [ ' ' , '.' ] , [ '(' , '' ] , [ ')' , '' ] , [ '\\' , '.' ] , [ '/' , '.' ] ) branch_name = pieces . get ( 'branch' ) or '' if branch_name : for old , new in replacements : branch_name = branch_name . replace ( old , new ) else : branch_name = 'unknown_branch' if pieces [ "closest-tag"...
def resample_time_series ( self ) : """OHLC time series resampler . Resamples time series data to create Open - Hi - Lo - Close ( OHLC ) data , which can be useful for statistical tests , or simply for charting . Frequency abbreviations are taken from the pandas library . By default , this method does daily...
with cursor ( ) as cur : cur . execute ( "SELECT max(starttime) FROM resampled_ledger" ) if cur . rowcount : last_resample = str ( cur . fetchone ( ) [ 0 ] ) else : last_resample = 0 if not self . quiet : print ( "Resampling time series..." ) for market in self . markets : ...
def set_python ( self , value ) : """Expect list of record instances , convert to a SortedDict for internal representation"""
if not self . multiselect : if value and not isinstance ( value , list ) : value = [ value ] value = value or [ ] records = SortedDict ( ) for record in value : self . validate_value ( record ) records [ record . id ] = record return_value = self . _set ( records ) self . record . _raw [ 'values' ] ...
def is_valid_scalar ( self , node : ValueNode ) -> None : """Check whether this is a valid scalar . Any value literal may be a valid representation of a Scalar , depending on that scalar type ."""
# Report any error at the full type expected by the location . location_type = self . context . get_input_type ( ) if not location_type : return type_ = get_named_type ( location_type ) if not is_scalar_type ( type_ ) : self . report_error ( GraphQLError ( bad_value_message ( location_type , print_ast ( node ) ...
def str_strip ( arr , to_strip = None , side = 'both' ) : """Strip whitespace ( including newlines ) from each string in the Series / Index . Parameters to _ strip : str or unicode side : { ' left ' , ' right ' , ' both ' } , default ' both ' Returns Series or Index"""
if side == 'both' : f = lambda x : x . strip ( to_strip ) elif side == 'left' : f = lambda x : x . lstrip ( to_strip ) elif side == 'right' : f = lambda x : x . rstrip ( to_strip ) else : # pragma : no cover raise ValueError ( 'Invalid side' ) return _na_map ( f , arr )
def handle_submodules ( repo , ** kwargs ) : """: return : repo . submodules ( )"""
log . info ( 'submodules: %s %s' % ( repo , kwargs ) ) return [ serialize ( s , type = 'submodule' , url = s . url ) for s in repo . submodules ( ** kwargs ) ]
def _get_device_by_label ( devices , label ) : '''Returns the device with the given label , raises error if the device is not found . devices list of vim . vm . device . VirtualDevice objects key Unique key of device'''
device_labels = [ d for d in devices if d . deviceInfo . label == label ] if device_labels : return device_labels [ 0 ] else : raise salt . exceptions . VMwareObjectNotFoundError ( 'Virtual machine device with ' 'label {0} does not exist' . format ( label ) )
def post_venue ( self , id , ** data ) : """POST / venues / : id / Updates a : format : ` venue ` and returns it as an object ."""
return self . post ( "/venues/{0}/" . format ( id ) , data = data )
def bsrchi ( value , ndim , array ) : """Do a binary search for a key value within an integer array , assumed to be in increasing order . Return the index of the matching array entry , or - 1 if the key value is not found . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / bsrchi...
value = ctypes . c_int ( value ) ndim = ctypes . c_int ( ndim ) array = stypes . toIntVector ( array ) return libspice . bsrchi_c ( value , ndim , array )
def make_vcard ( name , displayname , email = None , phone = None , fax = None , videophone = None , memo = None , nickname = None , birthday = None , url = None , pobox = None , street = None , city = None , region = None , zipcode = None , country = None , org = None , lat = None , lng = None , source = None , rev = ...
return segno . make_qr ( make_vcard_data ( name , displayname , email = email , phone = phone , fax = fax , videophone = videophone , memo = memo , nickname = nickname , birthday = birthday , url = url , pobox = pobox , street = street , city = city , region = region , zipcode = zipcode , country = country , org = org ...
def assignrepr ( self , prefix : str ) -> str : """Return a | repr | string with a prefixed assignment ."""
with objecttools . repr_ . preserve_strings ( True ) : with objecttools . assignrepr_tuple . always_bracketed ( False ) : blanks = ' ' * ( len ( prefix ) + 8 ) lines = [ '%sElement("%s",' % ( prefix , self . name ) ] for groupname in ( 'inlets' , 'outlets' , 'receivers' , 'senders' ) : ...
def slow_augmenting_row_reduction ( n , ii , jj , idx , count , x , y , u , v , c ) : '''Perform the augmenting row reduction step from the Jonker - Volgenaut algorithm n - the number of i and j in the linear assignment problem ii - the unassigned i jj - the j - index of every entry in c idx - the index of ...
# From Jonker : # procedure AUGMENTING ROW REDUCTION ; # begin # LIST : = { all unassigned rows } ; # for all i in LIST do # repeat # ul : = min { c [ i , j ] - v [ j ] for j = l . . . n } ; # select j1 with c [ i , j 1 ] - v [ j 1 ] = u1; # u2 : = min { c [ i , j ] - v [ j ] for j = l . . . n , j < > jl } ; # select j...
def validate_mutations ( self , mutations ) : '''This function has been refactored to use the SimpleMutation class . The parameter is a list of Mutation objects . The function has no return value but raises a PDBValidationException if the wildtype in the Mutation m does not match the residue type corresponding ...
# Chain , ResidueID , WildTypeAA , MutantAA resID2AA = self . get_residue_id_to_type_map ( ) badmutations = [ ] for m in mutations : wildtype = resID2AA . get ( PDB . ChainResidueID2String ( m . Chain , m . ResidueID ) , "" ) if m . WildTypeAA != wildtype : badmutations . append ( m ) if badmutations : ...
def cli ( ctx , feature_id , description , organism = "" , sequence = "" ) : """Set a feature ' s description Output : A standard apollo feature dictionary ( { " features " : [ { . . . } ] } )"""
return ctx . gi . annotations . set_description ( feature_id , description , organism = organism , sequence = sequence )
def print_devices_change_callback ( devices , key , new ) : """Print the reply from & devices ( ) and highlight errors ."""
dev = devices [ key ] print ( '- ' , new , ' ' , dev ) if dev [ 'type' ] == QSType . unknown : print ( " ERR decoding" ) elif dev [ 'value' ] == - 1 : dev ( " ERR decoding: -1?" ) qcord = pyqwikswitch . decode_qwikcord ( dev [ 'data' ] [ pyqwikswitch . QS_VALUE ] ) if qcord is not None : print ( ' qwikcord ...
def request ( self , method : str , path : str , content : Optional [ Union [ dict , bytes , str ] ] = None , timestamp : Optional [ int ] = None , external_url : Optional [ str ] = None , headers : Optional [ Dict [ str , str ] ] = None , query_params : Optional [ Dict [ str , Any ] ] = None , api_path : str = "/_matr...
content = content or { } headers = headers or { } query_params = query_params or { } query_params [ "access_token" ] = self . token if timestamp is not None : if isinstance ( timestamp , datetime ) : timestamp = int ( timestamp . replace ( tzinfo = timezone . utc ) . timestamp ( ) * 1000 ) query_params ...
def aggregator ( name , func , * args , type = None ) : 'Define simple aggregator ` name ` that calls func ( values )'
def _func ( col , rows ) : # wrap builtins so they can have a . type vals = list ( col . getValues ( rows ) ) try : return func ( vals , * args ) except Exception as e : if len ( vals ) == 0 : return None return e aggregators [ name ] = _defaggr ( name , type , _func )
def set_exclude_filters ( self , exclude_filters ) : ''': param list ( ExcludeFilter ) exclude _ filters :'''
self . _exclude_filters = exclude_filters self . require_module = False for exclude_filter in exclude_filters : if not exclude_filter . is_path : self . require_module = True break
def mixing_phases ( U ) : """Return the angles and CP phases of the CKM or PMNS matrix in standard parametrization , starting from a matrix with arbitrary phase convention ."""
f = { } # angles f [ 't13' ] = asin ( abs ( U [ 0 , 2 ] ) ) if U [ 0 , 0 ] == 0 : f [ 't12' ] = pi / 2 else : f [ 't12' ] = atan ( abs ( U [ 0 , 1 ] ) / abs ( U [ 0 , 0 ] ) ) if U [ 2 , 2 ] == 0 : f [ 't23' ] = pi / 2 else : f [ 't23' ] = atan ( abs ( U [ 1 , 2 ] ) / abs ( U [ 2 , 2 ] ) ) s12 = sin ( f ...
def translate_y ( self , d ) : """Translate mesh for y - direction : param float d : Amount to translate"""
mat = numpy . array ( [ [ 1 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 0 ] , [ 0 , 0 , 1 , 0 ] , [ 0 , d , 0 , 1 ] ] ) self . vectors = self . vectors . dot ( mat ) return self
def filename ( self ) -> str : """Return the filename . Given a path - like - string ( e . g . " / Users / dspadini / pydriller / myfile . py " ) returns only the filename ( e . g . " myfile . py " ) : return : str filename"""
if self . _new_path is not None and str ( self . _new_path ) != "/dev/null" : path = self . _new_path else : path = self . _old_path return path . name
def binary ( self ) : """return encoded representation"""
if isinstance ( self . value , list ) : length = len ( self . value ) if length == 0 : return b_chr ( _TAG_NIL_EXT ) elif length > 4294967295 : raise OutputException ( 'uint32 overflow' ) elif self . improper : return ( b_chr ( _TAG_LIST_EXT ) + struct . pack ( b'>I' , length - 1...
def clear ( self , scope = 'screen' ) : """see doc in Term class According to http : / / support . microsoft . com / kb / 99261 the best way to clear the console is to write out empty spaces"""
# TODO : clear attributes too if scope == 'screen' : bos = ( 0 , self . _get_console_info ( ) [ 'window' ] [ 'top' ] ) cols , lines = self . get_size ( ) length = cols * lines self . _clear_console ( length , bos ) self . move ( 'beginning of screen' ) elif scope == ' beginning of line' : pass e...
def train_batch ( self , batch_info : BatchInfo ) -> None : """Batch - the most atomic unit of learning . For this reinforforcer , that involves : 1 . Roll out environment and store out experience in the buffer 2 . Sample the buffer and train the algo on sample batch"""
# For each reinforcer batch : # 1 . Roll out environment and store out experience in the buffer self . roll_out_and_store ( batch_info ) # 2 . Sample the buffer and train the algo on sample batch self . train_on_replay_memory ( batch_info )
def interpolate_cosine_single ( start , end , coefficient ) : """Cosine interpolation"""
cos_out = ( np . cos ( np . pi * coefficient ) + 1 ) / 2.0 return end + ( start - end ) * cos_out
def stop ( self ) : """Stops the bundle . Does nothing if the bundle is already stopped . : raise BundleException : The bundle activator failed ."""
if self . _state != Bundle . ACTIVE : # Invalid state return exception = None with self . _lock : # Store the bundle current state previous_state = self . _state # Stopping . . . self . _state = Bundle . STOPPING self . _fire_bundle_event ( BundleEvent . STOPPING ) # Call the activator , if any ...
def walk ( self ) : """Walk proposal kernel"""
if self . verbose > 1 : print_ ( '\t' + self . _id + ' Running Walk proposal kernel' ) # Mask for values to move phi = self . phi theta = self . walk_theta u = random ( len ( phi ) ) z = ( theta / ( 1 + theta ) ) * ( theta * u ** 2 + 2 * u - 1 ) if self . _prime : xp , x = self . values else : x , xp = self...
def run_dependent_peptides_from_parameters ( paramfile , outfile ) : """transform a allPeptides . txt and experimentalDesign . txt table into the dependentPeptides . txt table written in outfile . : param paramfile : Perseus parameters . xml including at least two FileParam entries names ' allPeptides . txt '...
parameters = parse_parameters ( paramfile ) allPeptides_file = fileParam ( parameters , 'allPeptides.txt' ) rawFilesTable_file = fileParam ( parameters , 'Raw files table' ) run_dependent_peptides ( allPeptides_file , rawFilesTable_file , outfile )
def columns ( self , dimensions = None ) : """Convert dimension values to a dictionary . Returns a dictionary of column arrays along each dimension of the element . Args : dimensions : Dimensions to return as columns Returns : Dictionary of arrays for each dimension"""
if dimensions is None : dimensions = self . kdims else : dimensions = [ self . get_dimension ( d , strict = True ) for d in dimensions ] vdims = [ d for d in dimensions if d in self . vdims ] if vdims : raise ValueError ( '%s element does not hold data for value ' 'dimensions. Could not return data for %s '...
def discard_config ( self ) : """Discard changes ( rollback 0 ) ."""
self . device . cu . rollback ( rb_id = 0 ) if not self . config_lock : self . _unlock ( )
def _create_gcloud_zone ( self , dns_name ) : """Creates a google cloud ManagedZone with dns _ name , and zone named derived from it . calls . create ( ) method and returns it . : param dns _ name : fqdn of zone to create : type dns _ name : str : type return : new google . cloud . dns . ManagedZone"""
# Zone name must begin with a letter , end with a letter or digit , # and only contain lowercase letters , digits or dashes , # and be 63 characters or less zone_name = 'zone-{}-{}' . format ( dns_name . replace ( '.' , '-' ) , uuid4 ( ) . hex ) [ : 63 ] gcloud_zone = self . gcloud_client . zone ( name = zone_name , dn...
def p_field_void ( self , p ) : """field : ID NL | ID NL INDENT annotation _ ref _ list docsection DEDENT"""
p [ 0 ] = AstVoidField ( self . path , p . lineno ( 1 ) , p . lexpos ( 1 ) , p [ 1 ] ) if len ( p ) > 3 : if p [ 4 ] is not None : p [ 0 ] . set_annotations ( p [ 4 ] ) if p [ 5 ] is not None : p [ 0 ] . set_doc ( p [ 5 ] )
def marshall ( values ) : """Marshall a ` dict ` into something DynamoDB likes . : param dict values : The values to marshall : rtype : dict : raises ValueError : if an unsupported type is encountered Return the values in a nested dict structure that is required for writing the values to DynamoDB ."""
serialized = { } for key in values : serialized [ key ] = _marshall_value ( values [ key ] ) return serialized
def _is_out_of_order ( segmentation ) : """Check if a given segmentation is out of order . Examples > > > _ is _ out _ of _ order ( [ [ 0 , 1 , 2 , 3 ] ] ) False > > > _ is _ out _ of _ order ( [ [ 0 , 1 ] , [ 2 , 3 ] ] ) False > > > _ is _ out _ of _ order ( [ [ 0 , 1 , 3 ] , [ 2 ] ] ) True"""
last_stroke = - 1 for symbol in segmentation : for stroke in symbol : if last_stroke > stroke : return True last_stroke = stroke return False
def get ( obj , glob , separator = "/" ) : """Given an object which contains only one possible match for the given glob , return the value for the leaf matching the given glob . If more than one leaf matches the glob , ValueError is raised . If the glob is not found , KeyError is raised ."""
ret = None found = False for item in search ( obj , glob , yielded = True , separator = separator ) : if ret is not None : raise ValueError ( "dpath.util.get() globs must match only one leaf : %s" % glob ) ret = item [ 1 ] found = True if found is False : raise KeyError ( glob ) return ret
def get_baserate ( self ) : """Helper function to populate the base rate"""
rateslist = self . rates [ 'list' ] [ 'resources' ] for rate in rateslist : rateobj = rate [ 'resource' ] [ 'fields' ] if rateobj [ 'symbol' ] . partition ( '=' ) [ 0 ] == rateobj [ 'name' ] : return rateobj [ 'name' ] raise RuntimeError ( "%s: baserate not found" % self . name )
def plot_events_distribution ( events , num_bars = 50 , ax = None ) : """Plots the distribution of events in time . Parameters events : pd . Series A pd . Series whose index contains at least ' date ' level . num _ bars : integer , optional Number of bars to plot ax : matplotlib . Axes , optional Axes...
if ax is None : f , ax = plt . subplots ( 1 , 1 , figsize = ( 18 , 6 ) ) start = events . index . get_level_values ( 'date' ) . min ( ) end = events . index . get_level_values ( 'date' ) . max ( ) group_interval = ( end - start ) / num_bars grouper = pd . Grouper ( level = 'date' , freq = group_interval ) events . ...
def get_bibtex ( isbn_identifier ) : """Get a BibTeX string for the given ISBN . : param isbn _ identifier : ISBN to fetch BibTeX entry for . : returns : A BibTeX string or ` ` None ` ` if could not fetch it . > > > get _ bibtex ( ' 9783161484100 ' ) ' @ book { 9783161484100, \\ n title = { Berkeley , Oakla...
# Try to find the BibTeX using associated DOIs bibtex = doi . get_bibtex ( to_doi ( isbn_identifier ) ) if bibtex is None : # In some cases , there are no DOIs for a given ISBN . In this case , try # to fetch bibtex directly from the ISBN , using a combination of # Google Books and worldcat . org results . bibtex =...
def lastNode ( class_ , hot_map ) : '''Return the very last node ( recursively ) in the hot map .'''
children = hot_map [ - 1 ] [ 2 ] if children : return class_ . lastNode ( children ) else : return hot_map [ - 1 ] [ 1 ]
def get_filename ( self , year ) : """returns the filename"""
res = self . fldr + os . sep + self . type + year + '.' + self . user return res
def flush_read_tuple ( self ) : """Flush the internal buffer of reads ."""
if not self . is_empty ( ) : suffix_comment_buffer = [ ] if self . _info_simulator is not None : suffix_comment_buffer . append ( self . _info_simulator ) if self . _info_reads_in_tuple : # todo : orientation ( FF , FR , etc . ) # orientation = " " . join ( [ ] ) suffix_comment_buffer . ...
def entry_point ( context , block_name ) : """include an snippet at the bottom of a block , if it exists For example , if the plugin with slug ' attachments ' is registered waliki / attachments _ edit _ content . html will be included with { % entry _ point ' edit _ content ' % } which is declared at the bo...
from waliki . plugins import get_plugins includes = [ ] for plugin in get_plugins ( ) : template_name = 'waliki/%s_%s.html' % ( plugin . slug , block_name ) try : # template exists template . loader . get_template ( template_name ) includes . append ( template_name ) except template . Templa...
def support_index_min ( self , tags = None ) : # type : ( Optional [ List [ Pep425Tag ] ] ) - > Optional [ int ] """Return the lowest index that one of the wheel ' s file _ tag combinations achieves in the supported _ tags list e . g . if there are 8 supported tags , and one of the file tags is first in the lis...
if tags is None : # for mock tags = pep425tags . get_supported ( ) indexes = [ tags . index ( c ) for c in self . file_tags if c in tags ] return min ( indexes ) if indexes else None
def StaticServe ( base_path = '/views/static/' ) : """Meta program for serving any file based on the path"""
def get_file ( path = RAW_INVOCATION_ARGS ) : fullpath = get_config ( 'project_path' ) + os . path . join ( base_path , path ) try : mime , encoding = mimetypes . guess_type ( fullpath ) return open ( fullpath , 'rb' ) , mime or 'application/octet-stream' except IOError : raise DataN...
def _get_altair_html_ ( self , chart_obj , slug ) : """Get html for an Altair chart"""
try : json_data = chart_obj . to_json ( indent = 0 ) except Exception as e : self . err ( e ) html = '<div id="' + slug + '"></div>\n' html += '<script type="text/javascript">' html += 'var spec = ' + json_data . replace ( "\n" , "" ) + ";" html += """ var embed_opt = {"mode": "vega-lite"}; func...
def status ( self , status_code = None ) : """Set status or Get Status"""
if status_code is not None : self . response_model . status = status_code # return string for response support return str ( self . response_model . status )
def coinbase_tx ( cls , public_key_sec , coin_value , coinbase_bytes = b'' , version = 1 , lock_time = 0 ) : """Create the special " first in block " transaction that includes the mining fees ."""
tx_in = cls . TxIn . coinbase_tx_in ( script = coinbase_bytes ) COINBASE_SCRIPT_OUT = "%s OP_CHECKSIG" script_text = COINBASE_SCRIPT_OUT % b2h ( public_key_sec ) script_bin = BitcoinScriptTools . compile ( script_text ) tx_out = cls . TxOut ( coin_value , script_bin ) return cls ( version , [ tx_in ] , [ tx_out ] , loc...
def remove_search_paths ( self , path_type , paths , target_name = None , configuration_name = None ) : """Removes the given search paths from the path _ type section of the target on the configurations : param path _ type : name of the path type to be removed the values from : param paths : A string or array o...
for configuration in self . objects . get_configurations_on_targets ( target_name , configuration_name ) : configuration . remove_search_paths ( path_type , paths )
def filter ( value ) : """Modifier decorator to force the inclusion or exclusion of an attribute . This only modifies the behaviour of the : func : ` create _ patches ` function and the : func : ` patches ` decorator , given that their parameter ` ` use _ decorators ` ` is set to ` ` True ` ` . Parameters ...
def decorator ( wrapped ) : data = get_decorator_data ( _get_base ( wrapped ) , set_default = True ) data . filter = value return wrapped return decorator
def _copy_calibration ( self , calibration ) : """Copy another ` ` StereoCalibration ` ` object ' s values ."""
for key , item in calibration . __dict__ . items ( ) : self . __dict__ [ key ] = item
def search ( format , string , pos = 0 , endpos = None , extra_types = None , evaluate_result = True , case_sensitive = False ) : '''Search " string " for the first occurrence of " format " . The format may occur anywhere within the string . If instead you wish for the format to exactly match the string use p...
p = Parser ( format , extra_types = extra_types , case_sensitive = case_sensitive ) return p . search ( string , pos , endpos , evaluate_result = evaluate_result )
def lock ( self , key , ttl = - 1 ) : """Acquires the lock for the specified key infinitely or for the specified lease time if provided . If the lock is not available , the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired . You get a lock whether...
check_not_none ( key , "key can't be None" ) key_data = self . _to_data ( key ) return self . _encode_invoke_on_key ( map_lock_codec , key_data , invocation_timeout = MAX_SIZE , key = key_data , thread_id = thread_id ( ) , ttl = to_millis ( ttl ) , reference_id = self . reference_id_generator . get_and_increment ( ) )
def _get_margin_width ( self , cli , margin ) : """Return the width for this margin . ( Calculate only once per render time . )"""
# Margin . get _ width , needs to have a UIContent instance . def get_ui_content ( ) : return self . _get_ui_content ( cli , width = 0 , height = 0 ) def get_width ( ) : return margin . get_width ( cli , get_ui_content ) key = ( margin , cli . render_counter ) return self . _margin_width_cache . get ( key , get...