signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def stop ( self ) : """Stops this router ."""
status = yield from self . get_status ( ) if status != "inactive" : try : yield from self . _hypervisor . send ( 'vm stop "{name}"' . format ( name = self . _name ) ) except DynamipsError as e : log . warn ( "Could not stop {}: {}" . format ( self . _name , e ) ) self . status = "stopped" ...
def project_with_metadata ( self , term_doc_mat , x_dim = 0 , y_dim = 1 ) : '''Returns a projection of the : param term _ doc _ mat : a TermDocMatrix : return : CategoryProjection'''
return self . _project_category_corpus ( self . _get_category_metadata_corpus_and_replace_terms ( term_doc_mat ) , x_dim , y_dim )
def with_checklist ( self ) : """Using dialog and checklist option"""
data = [ ] if self . name == "ALL" : data = self . data else : for name in self . data : if self . name in name : data . append ( name ) if data : text = "Press 'spacebar' to choose SlackBuild for view" title = " SlackBuilds.org " backtitle = "{0} {1}" . format ( _meta_ . __all__...
def zadd ( self , name , mapping , nx = False , xx = False , ch = False , incr = False ) : """Set any number of element - name , score pairs to the key ` ` name ` ` . Pairs are specified as a dict of element - names keys to score values . ` ` nx ` ` forces ZADD to only create new elements and not to update sc...
if not mapping : raise DataError ( "ZADD requires at least one element/score pair" ) if nx and xx : raise DataError ( "ZADD allows either 'nx' or 'xx', not both" ) if incr and len ( mapping ) != 1 : raise DataError ( "ZADD option 'incr' only works when passing a " "single element/score pair" ) pieces = [ ] ...
def dec_ptr ( self , ptr ) : """Get previous circular buffer data pointer ."""
result = ptr - self . reading_len [ self . ws_type ] if result < self . data_start : result = 0x10000 - self . reading_len [ self . ws_type ] return result
def add_pull_request_comment ( self , project , repository , pull_request_id , text ) : """Add comment into pull request : param project : : param repository : : param pull _ request _ id : the ID of the pull request within the repository : param text comment text : return :"""
url = 'rest/api/1.0/projects/{project}/repos/{repository}/pull-requests/{pullRequestId}/comments' . format ( project = project , repository = repository , pullRequestId = pull_request_id ) body = { 'text' : text } return self . post ( url , data = body )
def termLons ( TERMS ) : """Returns a list with the absolute longitude of all terms ."""
res = [ ] for i , sign in enumerate ( SIGN_LIST ) : termList = TERMS [ sign ] res . extend ( [ ID , sign , start + 30 * i , ] for ( ID , start , end ) in termList ) return res
def register_presence_callback ( self , type_ , from_ , cb ) : """Register a callback to be called when a presence stanza is received . : param type _ : Presence type to listen for . : type type _ : : class : ` ~ . PresenceType ` : param from _ : Sender JID to listen for , or : data : ` None ` for a wildcard ...
type_ = self . _coerce_enum ( type_ , structs . PresenceType ) warnings . warn ( "register_presence_callback is deprecated; use " "aioxmpp.dispatcher.SimplePresenceDispatcher or " "aioxmpp.PresenceClient instead" , DeprecationWarning , stacklevel = 2 ) self . _xxx_presence_dispatcher . register_callback ( type_ , from_...
def get_spec ( dx , Vin , verbose = False , gain = 1.0 , integration = True ) : """GET _ SPEC : summary : Returns the spectrum of a regularly sampled dataset : parameter dq : sampling interval ( 1D ) : parameter V : data to analyse ( 1D ) . : note : NaN can not be used . : return : * psd : Power Spectra...
V = Vin . copy ( ) N = V . size # part 1 - estimate of the wavenumbers [ k , L , imx ] = get_kx ( N , dx ) # print " dx = % s " % ( dx ) # print " kx = " , k [ 0:3] # print " shape " , k . shape # part 2 - estimate of the spectrum # fast fourier transform fft = ft . fft ( V ) / ( gain ) if verbose : print 'Check pa...
def set_index ( self , index ) : """Display the data of the given index : param index : the index to paint : type index : QtCore . QModelIndex : returns : None : rtype : None : raises : None"""
self . index = index self . reftrack = index . model ( ) . index ( index . row ( ) , 18 , index . parent ( ) ) . data ( REFTRACK_OBJECT_ROLE ) self . set_maintext ( self . index ) self . set_identifiertext ( self . index ) self . set_type_icon ( self . index ) self . disable_restricted ( ) self . hide_restricted ( ) se...
def to_geojson ( self , filename ) : """Save vector as geojson ."""
with open ( filename , 'w' ) as fd : json . dump ( self . to_record ( WGS84_CRS ) , fd )
def put_field ( self , field ) : """Inserts or updates a field in the repository"""
fpath = self . fields_json_path ( field ) # Open fields JSON , locking to prevent other processes # reading or writing with InterProcessLock ( fpath + self . LOCK_SUFFIX , logger = logger ) : try : with open ( fpath , 'r' ) as f : dct = json . load ( f ) except IOError as e : if e . ...
def intersect_3 ( self , second , third ) : """Intersection routine for three inputs . Built out of the intersect , coalesce and play routines"""
self . intersection ( second ) self . intersection ( third ) self . coalesce ( ) return len ( self )
def process_rollout ( self , batch_info , rollout : Rollout ) : """Process rollout for ALGO before any chunking / shuffling"""
assert isinstance ( rollout , Trajectories ) , "A2C requires trajectory rollouts" advantages = discount_bootstrap_gae ( rewards_buffer = rollout . transition_tensors [ 'rewards' ] , dones_buffer = rollout . transition_tensors [ 'dones' ] , values_buffer = rollout . transition_tensors [ 'values' ] , final_values = rollo...
def load_projections_from_path ( p ) : '''load _ projections _ from _ path ( p ) yields a lazy - map of all the map projection files found in the given path specification p . The path specification may be either a directory name , a : - separated list of directory names , or a python list of directory names . ...
p = dirpath_to_list ( p ) return pyr . pmap ( { h : pimms . lazy_map ( { parts [ 1 ] : curry ( lambda flnm , h : load_map_projection ( flnm , chirality = h ) , os . path . join ( pp , fl ) , h ) for pp in p for fl in os . listdir ( pp ) if fl . endswith ( '.json' ) or fl . endswith ( '.json.gz' ) for parts in [ fl . sp...
def Constant ( cls , irsb_c , val , ty ) : """Creates a constant as a VexValue : param irsb _ c : The IRSBCustomizer to use : param val : The value , as an integer : param ty : The type of the resulting VexValue : return : a VexValue"""
assert not ( isinstance ( val , VexValue ) or isinstance ( val , IRExpr ) ) rdt = irsb_c . mkconst ( val , ty ) return cls ( irsb_c , rdt )
def chromedriver_element_center_patch ( ) : """Patch move _ to _ element on ActionChains to work around a bug present in Chromedriver 2.14 to 2.20. Calling this function multiple times in the same process will install the patch once , and just once ."""
patch_name = "_selenic_chromedriver_element_center_patched" if getattr ( ActionChains , patch_name , None ) : return # We ' ve patched ActionChains already ! ! # This is the patched method , which uses getBoundingClientRect # to get the location of the center . def move_to_element ( self , el ) : pos = self . _...
def start ( self , * args , ** kwargs ) : r"""Starts the internal task in the event loop . Parameters \ * args The arguments to to use . \ * \ * kwargs The keyword arguments to use . Raises RuntimeError A task has already been launched . Returns : class : ` asyncio . Task ` The task that has b...
if self . _task is not None : raise RuntimeError ( 'Task is already launched.' ) if self . _injected is not None : args = ( self . _injected , * args ) self . _task = self . loop . create_task ( self . _loop ( * args , ** kwargs ) ) return self . _task
def get ( self ) : """Get a new batch from the internal ring buffer . Returns : buf : Data item saved from inqueue . released : True if the item is now removed from the ring buffer ."""
if self . ttl [ self . idx ] <= 0 : self . buffers [ self . idx ] = self . inqueue . get ( timeout = 300.0 ) self . ttl [ self . idx ] = self . cur_max_ttl if self . cur_max_ttl < self . max_ttl : self . cur_max_ttl += 1 buf = self . buffers [ self . idx ] self . ttl [ self . idx ] -= 1 released = s...
def angledependentairtransmission ( twotheta , mu_air , sampletodetectordistance ) : """Correction for the angle dependent absorption of air in the scattered beam path . Inputs : twotheta : matrix of two - theta values mu _ air : the linear absorption coefficient of air sampletodetectordistance : sample -...
return np . exp ( mu_air * sampletodetectordistance / np . cos ( twotheta ) )
def deploy ( self , job_name , command = '' , blocksize = 1 ) : instances = [ ] """Deploy the template to a resource group ."""
self . client . resource_groups . create_or_update ( self . resource_group , { 'location' : self . location , } ) template_path = os . path . join ( os . path . dirname ( __file__ ) , 'templates' , 'template.json' ) with open ( template_path , 'r' ) as template_file_fd : template = json . load ( template_file_fd ) ...
def can_rewind ( self ) : """check if pg _ rewind executable is there and that pg _ controldata indicates we have either wal _ log _ hints or checksums turned on"""
# low - hanging fruit : check if pg _ rewind configuration is there if not self . config . get ( 'use_pg_rewind' ) : return False cmd = [ self . _pgcommand ( 'pg_rewind' ) , '--help' ] try : ret = subprocess . call ( cmd , stdout = open ( os . devnull , 'w' ) , stderr = subprocess . STDOUT ) if ret != 0 : #...
def select_item ( self , items ) : """Select an items . This adds ` items ` to the set of selected items ."""
if not items : return elif not hasattr ( items , "__iter__" ) : items = ( items , ) selection_changed = False with self . _suppress_selection_events ( ) : for item in items : self . queue_draw_item ( item ) if item is not None and item . model not in self . _selection : self . _s...
def add_argument ( self , parser , path , name = None , schema = None , ** kwargs ) : """Add an argument to the ` parser ` based on a schema definition . Parameters parser : argparse . ArgumentParser parser to add an argument to path : str path in the configuration document to add an argument for name :...
schema = schema or self . SCHEMA name = name or ( '--%s' % os . path . basename ( path ) ) self . arguments [ name . strip ( '-' ) ] = path # Build a path to the help in the schema path = util . split_path ( path ) path = os . path . sep . join ( it . chain ( [ os . path . sep ] , * zip ( it . repeat ( "properties" ) ,...
async def readline ( self ) -> bytes : """Reads body part by line by line ."""
if self . _at_eof : return b'' if self . _unread : line = self . _unread . popleft ( ) else : line = await self . _content . readline ( ) if line . startswith ( self . _boundary ) : # the very last boundary may not come with \ r \ n , # so set single rules for everyone sline = line . rstrip ( b'\r\n' ) ...
def _remove_match ( self , match ) : """Remove a match : param match : : type match : Match"""
if self . __name_dict is not None : if match . name : _BaseMatches . _base_remove ( self . _name_dict [ match . name ] , match ) if self . __tag_dict is not None : for tag in match . tags : _BaseMatches . _base_remove ( self . _tag_dict [ tag ] , match ) if self . __start_dict is not None : ...
def save ( self , path , table_format = 'txt' , sep = '\t' , table_ext = None , float_format = '%.12g' ) : """Saving the system to path Parameters path : pathlib . Path or string path for the saved data ( will be created if necessary , data within will be overwritten ) . table _ format : string Format t...
if type ( path ) is str : path = path . rstrip ( '\\' ) path = Path ( path ) path . mkdir ( parents = True , exist_ok = True ) para_file_path = path / DEFAULT_FILE_NAMES [ 'filepara' ] file_para = dict ( ) file_para [ 'files' ] = dict ( ) if table_format in [ 'text' , 'csv' , 'txt' ] : table_format = 'txt' ...
def to_dict ( self , default = None ) : """Converts sequence of ( Key , Value ) pairs to a dictionary . > > > type ( seq ( [ ( ' a ' , 1 ) ] ) . to _ dict ( ) ) dict > > > seq ( [ ( ' a ' , 1 ) , ( ' b ' , 2 ) ] ) . to _ dict ( ) { ' a ' : 1 , ' b ' : 2} : param default : Can be a callable zero argument f...
dictionary = { } for e in self . sequence : dictionary [ e [ 0 ] ] = e [ 1 ] if default is None : return dictionary else : if hasattr ( default , '__call__' ) : return collections . defaultdict ( default , dictionary ) else : return collections . defaultdict ( lambda : default , dictiona...
def setup_asset_signals ( self , ) : """Setup the signals for the asset page : returns : None : rtype : None : raises : None"""
log . debug ( "Setting up asset signals." ) self . asset_asset_view_pb . clicked . connect ( self . asset_view_asset ) self . asset_asset_create_pb . clicked . connect ( self . asset_create_asset ) self . asset_asset_add_pb . clicked . connect ( self . asset_add_asset ) self . asset_asset_remove_pb . clicked . connect ...
def invalid_kwargs ( invalid_kwargs , raise_exc = True ) : '''Raise a SaltInvocationError if invalid _ kwargs is non - empty'''
if invalid_kwargs : if isinstance ( invalid_kwargs , dict ) : new_invalid = [ '{0}={1}' . format ( x , y ) for x , y in six . iteritems ( invalid_kwargs ) ] invalid_kwargs = new_invalid msg = ( 'The following keyword arguments are not valid: {0}' . format ( ', ' . join ( invalid_kwargs ) ) ) if rais...
def literal ( x ) : """Create a PEG function to consume a literal ."""
xlen = len ( x ) msg = 'Expected: "{}"' . format ( x ) def match_literal ( s , grm = None , pos = 0 ) : if s [ : xlen ] == x : return PegreResult ( s [ xlen : ] , x , ( pos , pos + xlen ) ) raise PegreError ( msg , pos ) return match_literal
def build ( self , requirements , # type : Iterable [ InstallRequirement ] session , # type : PipSession autobuilding = False # type : bool ) : # type : ( . . . ) - > List [ InstallRequirement ] """Build wheels . : param unpack : If True , replace the sdist we built from with the newly built wheel , in preparat...
buildset = [ ] format_control = self . finder . format_control # Whether a cache directory is available for autobuilding = True . cache_available = bool ( self . _wheel_dir or self . wheel_cache . cache_dir ) for req in requirements : ephem_cache = should_use_ephemeral_cache ( req , format_control = format_control ...
def write ( self ) : '''Write signature file with signature of script , input , output and dependent files . Because local input and output files can only be determined after the execution of workflow . They are not part of the construction .'''
if not self . output_files . valid ( ) : raise ValueError ( f'Cannot write signature with undetermined output {self.output_files}' ) else : if 'TARGET' in env . config [ 'SOS_DEBUG' ] or 'ALL' in env . config [ 'SOS_DEBUG' ] : env . log_to_file ( 'TARGET' , f'write signature {self.sig_id} with output {s...
def _get_firmware_update_service_resource ( self ) : """Gets the firmware update service uri . : returns : firmware update service uri : raises : IloError , on an error from iLO . : raises : IloConnectionError , if not able to reach iLO . : raises : IloCommandNotSupportedError , for not finding the uri"""
manager , uri = self . _get_ilo_details ( ) try : fw_uri = manager [ 'Oem' ] [ 'Hp' ] [ 'links' ] [ 'UpdateService' ] [ 'href' ] except KeyError : msg = ( "Firmware Update Service resource not found." ) raise exception . IloCommandNotSupportedError ( msg ) return fw_uri
def textMerge ( self , second ) : """Merge two text nodes into one"""
if second is None : second__o = None else : second__o = second . _o ret = libxml2mod . xmlTextMerge ( self . _o , second__o ) if ret is None : raise treeError ( 'xmlTextMerge() failed' ) __tmp = xmlNode ( _obj = ret ) return __tmp
def createIndex ( self , table , fields , where = '' , whereValues = [ ] ) : """Creates indexes for Raba Class a fields resulting in significantly faster SELECTs but potentially slower UPADTES / INSERTS and a bigger DBs Fields can be a list of fields for Multi - Column Indices , or siply the name of one single fi...
versioTest = sq . sqlite_version_info [ 0 ] >= 3 and sq . sqlite_version_info [ 1 ] >= 8 if len ( where ) > 0 and not versioTest : # raise FutureWarning ( " Partial joints ( with the WHERE clause ) where only implemented in sqlite 3.8.0 + , your version is : % s . Sorry about that . " % sq . sqlite _ version ) sys ...
def toposort ( initialAtoms , initialBonds ) : """initialAtoms , initialBonds - > atoms , bonds Given the list of atoms and bonds in a ring return the topologically sorted atoms and bonds . That is each atom is connected to the following atom and each bond is connected to the following bond in the followi...
atoms = [ ] a_append = atoms . append bonds = [ ] b_append = bonds . append # for the atom and bond hashes # we ignore the first atom since we # would have deleted it from the hash anyway ahash = { } bhash = { } for atom in initialAtoms [ 1 : ] : ahash [ atom . handle ] = 1 for bond in initialBonds : bhash [ bo...
async def workerTypeStats ( self , * args , ** kwargs ) : """Look up the resource stats for a workerType Return an object which has a generic state description . This only contains counts of instances This method gives output : ` ` v1 / worker - type - resources . json # ` ` This method is ` ` experimental ` ...
return await self . _makeApiCall ( self . funcinfo [ "workerTypeStats" ] , * args , ** kwargs )
def check_time ( value ) : """check that it ' s a value like 03:45 or 1:1"""
try : h , m = value . split ( ':' ) h = int ( h ) m = int ( m ) if h >= 24 or h < 0 : raise ValueError if m >= 60 or m < 0 : raise ValueError except ValueError : raise TimeDefinitionError ( "Invalid definition of time %r" % value )
def _generate_combined_log ( self , request , response ) : """Given a request / response pair , generate a logging format similar to the NGINX combined style ."""
current_time = datetime . utcnow ( ) data_len = '-' if response . data is None else len ( response . data ) return '{0} - - [{1}] {2} {3} {4} {5} {6}' . format ( request . remote_addr , current_time , request . method , request . relative_uri , response . status , data_len , request . user_agent )
def unicode_http_header ( value ) : r"""Convert an ASCII HTTP header string into a unicode string with the appropriate encoding applied . Expects headers to be RFC 2047 compliant . > > > unicode _ http _ header ( ' = ? iso - 8859-1 ? q ? p = F6stal ? = ' ) = = u ' p \ xf6stal ' True > > > unicode _ http _ h...
if six . PY3 : # pragma : no cover # email . header . decode _ header expects strings , not bytes . Your input data may be in bytes . # Since these bytes are almost always ASCII , calling ` . decode ( ) ` on it without specifying # a charset should work fine . if isinstance ( value , six . binary_type ) : v...
def updatetext ( self ) : """Recompute textual value based on the text content of the children . Only supported on elements that are a ` ` TEXTCONTAINER ` `"""
if self . TEXTCONTAINER : s = "" for child in self : if isinstance ( child , AbstractElement ) : child . updatetext ( ) s += child . text ( ) elif isstring ( child ) : s += child self . data = [ s ]
def get_info ( self , key = None ) : """Return all posted info about this node"""
node_data = nago . extensions . info . node_data . get ( self . token , { } ) if key is None : return node_data else : return node_data . get ( key , { } )
def expand_link ( self , ** kwargs ) : '''Expands with the given arguments and returns a new untemplated Link object'''
props = self . link . props . copy ( ) del props [ 'templated' ] return Link ( uri = self . expand_uri ( ** kwargs ) , properties = props , )
def python_version_matchers ( ) : """Return set of string representations of current python version"""
version = sys . version_info patterns = [ "{0}" , "{0}{1}" , "{0}.{1}" , ] matchers = [ pattern . format ( * version ) for pattern in patterns ] + [ None ] return set ( matchers )
def save_or_overwrite_slice ( self , args , slc , slice_add_perm , slice_overwrite_perm , slice_download_perm , datasource_id , datasource_type , datasource_name ) : """Save or overwrite a slice"""
slice_name = args . get ( 'slice_name' ) action = args . get ( 'action' ) form_data = get_form_data ( ) [ 0 ] if action in ( 'saveas' ) : if 'slice_id' in form_data : form_data . pop ( 'slice_id' ) # don ' t save old slice _ id slc = models . Slice ( owners = [ g . user ] if g . user else [ ] ) ...
def seek_to_end ( self , * partitions ) : """Seek to the most recent available offset for partitions . Arguments : * partitions : Optionally provide specific TopicPartitions , otherwise default to all assigned partitions . Raises : AssertionError : If any partition is not currently assigned , or if no p...
if not all ( [ isinstance ( p , TopicPartition ) for p in partitions ] ) : raise TypeError ( 'partitions must be TopicPartition namedtuples' ) if not partitions : partitions = self . _subscription . assigned_partitions ( ) assert partitions , 'No partitions are currently assigned' else : for p in partit...
def delete ( self , shape = None , part = None , point = None ) : """Deletes the specified part of any shape by specifying a shape number , part number , or point number ."""
# shape , part , point if shape and part and point : del self . _shapes [ shape ] [ part ] [ point ] # shape , part elif shape and part and not point : del self . _shapes [ shape ] [ part ] # shape elif shape and not part and not point : del self . _shapes [ shape ] # point elif not shape and not part and p...
def _setup_adapter ( self , namespace , route_prefix ) : """Initialize the serializer and loop through the views to generate them . : param namespace : Prefix for generated endpoints : param route _ prefix : Prefix for route patterns"""
self . serializer = JSONAPI ( self . sqla . Model , prefix = '{}://{}{}' . format ( self . app . config [ 'PREFERRED_URL_SCHEME' ] , self . app . config [ 'SERVER_NAME' ] , route_prefix ) ) for view in views : method , endpoint = view pattern = route_prefix + endpoint . value name = '{}_{}_{}' . format ( na...
def r12_serial_port ( port ) : '''Create a serial connect to the arm .'''
return serial . Serial ( port , baudrate = BAUD_RATE , parity = PARITY , stopbits = STOP_BITS , bytesize = BYTE_SIZE )
def remove_genelist ( self , list_id , case_obj = None ) : """Remove a gene list and links to cases ."""
gene_list = self . gene_list ( list_id ) if case_obj : # remove a single link between case and gene list case_ids = [ case_obj . id ] else : # remove all links and the list itself case_ids = [ case . id for case in gene_list . cases ] self . session . delete ( gene_list ) case_links = self . query ( CaseGen...
def standardize_strings ( arg , strtype = settings . MODERNRPC_PY2_STR_TYPE , encoding = settings . MODERNRPC_PY2_STR_ENCODING ) : """Python 2 only . Lookup given * arg * and convert its str or unicode value according to MODERNRPC _ PY2 _ STR _ TYPE and MODERNRPC _ PY2 _ STR _ ENCODING settings ."""
assert six . PY2 , "This function should be used with Python 2 only" if not strtype : return arg if strtype == six . binary_type or strtype == 'str' : # We want to convert from unicode to str return _generic_convert_string ( arg , six . text_type , six . binary_type , encoding ) elif strtype == six . text_type ...
def get_wind_components ( speed , wdir ) : r"""Calculate the U , V wind vector components from the speed and direction . Parameters speed : array _ like The wind speed ( magnitude ) wdir : array _ like The wind direction , specified as the direction from which the wind is blowing , with 0 being North . ...
u = - speed * np . sin ( wdir ) v = - speed * np . cos ( wdir ) return u , v
def kick_user ( self , jid ) : """Kicks a member from the chatroom . Kicked user will receive no more messages ."""
for member in filter ( lambda m : m [ 'JID' ] == jid , self . params [ 'MEMBERS' ] ) : member [ 'STATUS' ] = 'KICKED' self . send_message ( 'You have been kicked from %s' % ( self . name , ) , member ) self . client . sendPresence ( jid = member [ 'JID' ] , typ = 'unsubscribed' ) self . client . sendPre...
def loadmetadata ( self ) : """Load metadata for this file . This is usually called automatically upon instantiation , except if explicitly disabled . Works both locally as well as for clients connecting to a CLAM service ."""
if not self . remote : metafile = self . projectpath + self . basedir + '/' + self . metafilename ( ) if os . path . exists ( metafile ) : f = io . open ( metafile , 'r' , encoding = 'utf-8' ) xml = "" . join ( f . readlines ( ) ) f . close ( ) else : raise IOError ( 2 , "No ...
async def setup_watchdog ( self , cb , timeout ) : """Trigger a reconnect after @ timeout seconds of inactivity ."""
self . _watchdog_timeout = timeout self . _watchdog_cb = cb self . _watchdog_task = self . loop . create_task ( self . _watchdog ( timeout ) )
def _init_metadata ( self ) : """stub"""
self . _file_metadata = { 'element_id' : Id ( self . my_osid_object_form . _authority , self . my_osid_object_form . _namespace , 'file' ) , 'element_label' : 'File' , 'instructions' : 'accepts an asset id and optional asset_content type' , 'required' : False , 'read_only' : False , 'linked' : False , 'array' : False ,...
def ReadTrigger ( self , trigger_link , options = None ) : """Reads a trigger . : param str trigger _ link : The link to the trigger . : param dict options : The request options for the request . : return : The read Trigger . : rtype : dict"""
if options is None : options = { } path = base . GetPathFromLink ( trigger_link ) trigger_id = base . GetResourceIdOrFullNameFromLink ( trigger_link ) return self . Read ( path , 'triggers' , trigger_id , None , options )
def _extract_yaml_docstring ( stream ) : '''Extract the comments at the top of the YAML file , from the stream handler . Return the extracted comment as string .'''
comment_lines = [ ] lines = stream . read ( ) . splitlines ( ) for line in lines : line_strip = line . strip ( ) if not line_strip : continue if line_strip . startswith ( '#' ) : comment_lines . append ( line_strip . replace ( '#' , '' , 1 ) . strip ( ) ) else : break return ' ' ...
def authenticate ( self , request , url_auth_token = None ) : """Check the token and return the corresponding user ."""
try : return self . parse_token ( url_auth_token ) except TypeError : backend = "%s.%s" % ( self . __module__ , self . __class__ . __name__ ) logger . exception ( "TypeError in %s, here's the traceback before " "Django swallows it:" , backend ) raise
def tofile ( self , f ) : """Write the bloom filter to file object ` f ' . Underlying bits are written as machine values . This is much more space efficient than pickling the object ."""
f . write ( pack ( self . FILE_FMT , self . error_rate , self . num_slices , self . bits_per_slice , self . capacity , self . count ) ) ( f . write ( self . bitarray . tobytes ( ) ) if is_string_io ( f ) else self . bitarray . tofile ( f ) )
def MergeAttributeContainers ( self , callback = None , maximum_number_of_containers = 0 ) : """Reads attribute containers from a task storage file into the writer . Args : callback ( function [ StorageWriter , AttributeContainer ] ) : function to call after each attribute container is deserialized . maximu...
if maximum_number_of_containers < 0 : raise ValueError ( 'Invalid maximum number of containers' ) if not self . _cursor : self . _Open ( ) self . _ReadStorageMetadata ( ) self . _container_types = self . _GetContainerTypes ( ) number_of_containers = 0 while self . _active_cursor or self . _container_typ...
def mode ( series ) : """pandas mode is " empty if nothing has 2 + occurrences . " this method always returns something : nan if the series is empty / nan ) , breaking ties arbitrarily"""
if series . notnull ( ) . sum ( ) == 0 : return np . nan else : return series . value_counts ( ) . idxmax ( )
def WideResnetBlock ( channels , strides = ( 1 , 1 ) , channel_mismatch = False ) : """WideResnet convolutational block ."""
main = layers . Serial ( layers . BatchNorm ( ) , layers . Relu ( ) , layers . Conv ( channels , ( 3 , 3 ) , strides , padding = 'SAME' ) , layers . BatchNorm ( ) , layers . Relu ( ) , layers . Conv ( channels , ( 3 , 3 ) , padding = 'SAME' ) ) shortcut = layers . Identity ( ) if not channel_mismatch else layers . Conv...
def pretty_print_probabilities ( self , decimal_digits = 2 ) : """Prints outcome probabilities , ignoring all outcomes with approximately zero probabilities ( up to a certain number of decimal digits ) and rounding the probabilities to decimal _ digits . : param int decimal _ digits : The number of digits to tr...
outcome_dict = { } qubit_num = len ( self ) for index , amplitude in enumerate ( self . amplitudes ) : outcome = get_bitstring_from_index ( index , qubit_num ) prob = round ( abs ( amplitude ) ** 2 , decimal_digits ) if prob != 0. : outcome_dict [ outcome ] = prob return outcome_dict
def filter ( self , * args , ** kwargs ) -> "QuerySet" : """Filters QuerySet by given kwargs . You can filter by related objects like this : . . code - block : : python3 Team . filter ( events _ _ tournament _ _ name = ' Test ' ) You can also pass Q objects to filters as args ."""
return self . _filter_or_exclude ( negate = False , * args , ** kwargs )
def get_canonical_index ( self , alias ) : """RETURN THE INDEX USED BY THIS alias THIS IS ACCORDING TO THE STRICT LIFECYCLE RULES : THERE IS ONLY ONE INDEX WITH AN ALIAS"""
output = jx . sort ( set ( i for ai in self . get_aliases ( ) for a , i in [ ( ai . alias , ai . index ) ] if a == alias or i == alias or ( re . match ( re . escape ( alias ) + "\\d{8}_\\d{6}" , i ) and i != alias ) ) ) if len ( output ) > 1 : Log . error ( "only one index with given alias==\"{{alias}}\" expected" ...
def load ( cls , file_path ) : """Create and return a new Session Token based on the contents of a previously saved JSON - format file . : type file _ path : str : param file _ path : The fully qualified path to the JSON - format file containing the previously saved Session Token information ."""
fp = open ( file_path ) json_doc = fp . read ( ) fp . close ( ) return cls . from_json ( json_doc )
def smart_encode_str ( s ) : """Create a UTF - 16 encoded PDF string literal for ` s ` ."""
try : utf16 = s . encode ( 'utf_16_be' ) except AttributeError : # ints and floats utf16 = str ( s ) . encode ( 'utf_16_be' ) safe = utf16 . replace ( b'\x00)' , b'\x00\\)' ) . replace ( b'\x00(' , b'\x00\\(' ) return b'' . join ( ( codecs . BOM_UTF16_BE , safe ) )
def max_date ( self , symbol ) : """Return the maximum datetime stored for a particular symbol Parameters symbol : ` str ` symbol name for the item"""
res = self . _collection . find_one ( { SYMBOL : symbol } , projection = { ID : 0 , END : 1 } , sort = [ ( START , pymongo . DESCENDING ) ] ) if res is None : raise NoDataFoundException ( "No Data found for {}" . format ( symbol ) ) return utc_dt_to_local_dt ( res [ END ] )
def init_remote ( self ) : '''Initialize / attach to a remote using pygit2 . Return a boolean which will let the calling function know whether or not a new repo was initialized by this function .'''
# https : / / github . com / libgit2 / pygit2 / issues / 339 # https : / / github . com / libgit2 / libgit2 / issues / 2122 home = os . path . expanduser ( '~' ) pygit2 . settings . search_path [ pygit2 . GIT_CONFIG_LEVEL_GLOBAL ] = home new = False if not os . listdir ( self . cachedir ) : # Repo cachedir is empty , i...
def symm_op ( g , ax , theta , do_refl ) : """Perform general point symmetry operation on a geometry . . . todo : : Complete symm _ op docstring"""
# Imports import numpy as np # Depend on lower functions ' geometry vector coercion . Just # do the rotation and , if indicated , the reflection . gx = geom_rotate ( g , ax , theta ) if do_refl : gx = geom_reflect ( gx , ax ) # # end if # Should be good to go return gx
def AddMethod ( self , function , name = None ) : """Adds the specified function as a method of this construction environment with the specified name . If the name is omitted , the default name is the name of the function itself ."""
method = MethodWrapper ( self , function , name ) self . added_methods . append ( method )
def mark_bool_flags_as_mutual_exclusive ( flag_names , required = False , flag_values = _flagvalues . FLAGS ) : """Ensures that only one flag among flag _ names is True . Args : flag _ names : [ str ] , names of the flags . required : bool . If true , exactly one flag must be True . Otherwise , at most one ...
for flag_name in flag_names : if not flag_values [ flag_name ] . boolean : raise _exceptions . ValidationError ( 'Flag --{} is not Boolean, which is required for flags used in ' 'mark_bool_flags_as_mutual_exclusive.' . format ( flag_name ) ) def validate_boolean_mutual_exclusion ( flags_dict ) : flag_co...
def chain_absent ( name , table = 'filter' , family = 'ipv4' ) : '''. . versionadded : : 2014.7.0 Verify the chain is absent . family Networking family , either ipv4 or ipv6'''
ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' } chain_check = __salt__ [ 'nftables.check_chain' ] ( table , name , family ) if not chain_check : ret [ 'result' ] = True ret [ 'comment' ] = ( 'nftables {0} chain is already absent in {1} table for {2}' . format ( name , table , family...
def declare_exchange ( self , name , type , * , durable = True , auto_delete = False , passive = False , internal = False , nowait = False , arguments = None ) : """Declare an : class : ` Exchange ` on the broker . If the exchange does not exist , it will be created . This method is a : ref : ` coroutine < corout...
if name == '' : return exchange . Exchange ( self . reader , self . synchroniser , self . sender , name , 'direct' , True , False , False ) if not VALID_EXCHANGE_NAME_RE . match ( name ) : raise ValueError ( "Invalid exchange name.\n" "Valid names consist of letters, digits, hyphen, underscore, " "period, or co...
def inverse_distance ( xp , yp , variable , grid_x , grid_y , r , gamma = None , kappa = None , min_neighbors = 3 , kind = 'cressman' ) : """Wrap inverse _ distance _ to _ grid for deprecated inverse _ distance function ."""
return inverse_distance_to_grid ( xp , yp , variable , grid_x , grid_y , r , gamma = gamma , kappa = kappa , min_neighbors = min_neighbors , kind = kind )
def validate_units ( self , value ) : """Validate units , assuming that it was called by _ validate _ type _ * ."""
self . validate_quantity ( value ) self . units_type = inspect . stack ( ) [ 1 ] [ 3 ] . split ( '_' ) [ - 1 ] assert self . units_type , ( "`validate_units` should not be called " "directly. It should be called by a " "_validate_type_* methods that sets " "`units_type`" ) units = getattr ( pq , self . units_map [ self...
def clone_repo ( pkg_name , repo_url ) : """Create a new cloned repo with the given parameters ."""
new_repo = ClonedRepo ( name = pkg_name , origin = repo_url ) new_repo . save ( ) return new_repo
def update_warning ( self ) : """Update the warning label , buttons state and sequence text ."""
new_qsequence = self . new_qsequence new_sequence = self . new_sequence self . text_new_sequence . setText ( new_qsequence . toString ( QKeySequence . NativeText ) ) conflicts = self . check_conflicts ( ) if len ( self . _qsequences ) == 0 : warning = SEQUENCE_EMPTY tip = '' icon = QIcon ( ) elif conflicts ...
def _print_head ( self ) : """Generates the table header ."""
self . _print_divide ( ) self . StrTable += "| " for colwidth , attr in zip ( self . AttributesLength , self . Attributes ) : self . StrTable += self . _pad_string ( attr , colwidth * 2 ) self . StrTable += "| " self . StrTable += '\n' self . _print_divide ( )
def get_version ( model_instance , version ) : """try go load from the database one object with specific version : param model _ instance : instance in memory : param version : version number : return :"""
version_field = get_version_fieldname ( model_instance ) kwargs = { 'pk' : model_instance . pk , version_field : version } return model_instance . __class__ . objects . get ( ** kwargs )
def run ( self , request_cb , notification_cb ) : """Run the event loop to receive requests and notifications from Nvim . While the event loop is running , ` request _ cb ` and ` _ notification _ cb ` will be called whenever requests or notifications are respectively available ."""
self . _request_cb = request_cb self . _notification_cb = notification_cb self . _msgpack_stream . run ( self . _on_message ) self . _request_cb = None self . _notification_cb = None
def merge_recursive ( obj_a , obj_b , level = False ) : '''Merge obj _ b into obj _ a .'''
return aggregate ( obj_a , obj_b , level , map_class = AggregatedMap , sequence_class = AggregatedSequence )
def get_by_id ( self , process_name , db_id ) : """method finds a single job record and returns it to the caller"""
collection_name = self . _get_job_collection_name ( process_name ) collection = self . ds . connection ( collection_name ) document = collection . find_one ( { '_id' : ObjectId ( db_id ) } ) if document is None : raise LookupError ( 'MongoDB has no job record in collection {0} for {1}' . format ( collection , db_id...
def _create_column ( values , dtype ) : "Creates a column from values with dtype"
if str ( dtype ) == "tensor(int64)" : return numpy . array ( values , dtype = numpy . int64 ) elif str ( dtype ) == "tensor(float)" : return numpy . array ( values , dtype = numpy . float32 ) else : raise OnnxRuntimeAssertionError ( "Unable to create one column from dtype '{0}'" . format ( dtype ) )
def consolidate ( self , volume , source , dest , * args , ** kwargs ) : """Consolidate will move a volume of liquid from a list of sources to a single target location . See : any : ` Transfer ` for details and a full list of optional arguments . Returns This instance of : class : ` Pipette ` . Examples ...
kwargs [ 'mode' ] = 'consolidate' kwargs [ 'mix_before' ] = ( 0 , 0 ) kwargs [ 'air_gap' ] = 0 kwargs [ 'disposal_vol' ] = 0 args = [ volume , source , dest , * args ] return self . transfer ( * args , ** kwargs )
def resolve_dependencies ( self , to_build , depender ) : """Add any required dependencies ."""
shutit_global . shutit_global_object . yield_to_draw ( ) self . log ( 'In resolve_dependencies' , level = logging . DEBUG ) cfg = self . cfg for dependee_id in depender . depends_on : dependee = self . shutit_map . get ( dependee_id ) # Don ' t care if module doesn ' t exist , we check this later if ( depen...
def _on_disconnect ( self , participant ) : """Trigger the : meth : ` when _ player _ disconnects ` callback ."""
player = None for p in self . get_players ( ) : if p . participant == participant : player = p break self . when_player_disconnects ( player )
def _upload_dists ( self , repo , dists ) : """Upload a given component to pypi The pypi username and password must either be specified in a ~ / . pypirc file or in environment variables PYPI _ USER and PYPI _ PASS"""
from twine . commands . upload import upload if 'PYPI_USER' in os . environ and 'PYPI_PASS' in os . environ : pypi_user = os . environ [ 'PYPI_USER' ] pypi_pass = os . environ [ 'PYPI_PASS' ] else : pypi_user = None pypi_pass = None # Invoke upload this way since subprocess call of twine cli has cross p...
def members ( self ) : """获取小组所有成员的信息列表"""
all_members = [ ] for page in range ( 1 , self . max_page ( ) + 1 ) : all_members . extend ( self . single_page_members ( page ) ) return all_members
def set_root ( self , depth , index ) : """Set the level \' s root of the given depth to index : param depth : the depth level : type depth : int : param index : the new root index : type index : QtCore . QModelIndex : returns : None : rtype : None : raises : None"""
if depth < len ( self . _levels ) : self . _levels [ depth ] . set_root ( index )
def daemonize ( self , log_into , after_app_loading = False ) : """Daemonize uWSGI . : param str | unicode log _ into : Logging destination : * File : / tmp / mylog . log * UPD : 192.168.1.2:1717 . . note : : This will require an UDP server to manage log messages . Use ` ` networking . register _ socket (...
self . _set ( 'daemonize2' if after_app_loading else 'daemonize' , log_into ) return self . _section
def generate ( self , references , buffers ) : '''Create a JSON representation of this event suitable for sending to clients . . . code - block : : python ' kind ' : ' ColumnsStreamed ' ' column _ source ' : < reference to a CDS > ' data ' : < new data to steam to column _ source > ' rollover ' : < roll...
return { 'kind' : 'ColumnsStreamed' , 'column_source' : self . column_source . ref , 'data' : self . data , 'rollover' : self . rollover }
def add_internal_gateway_to_vpn ( internal_gateway_href , vpn_policy , vpn_role = 'central' ) : """Add an internal gateway ( managed engine node ) to a VPN policy based on the internal gateway href . : param str internal _ gateway _ href : href for engine internal gw : param str vpn _ policy : name of vpn pol...
try : vpn = PolicyVPN ( vpn_policy ) vpn . open ( ) if vpn_role == 'central' : vpn . add_central_gateway ( internal_gateway_href ) else : vpn . add_satellite_gateway ( internal_gateway_href ) vpn . save ( ) vpn . close ( ) except ElementNotFound : return False return True
def read_private_key_file ( pkey_file , pkey_password = None , key_type = None , logger = None ) : """Get SSH Public key from a private key file , given an optional password Arguments : pkey _ file ( str ) : File containing a private key ( RSA , DSS or ECDSA ) Keyword Arguments : pkey _ password ( Optiona...
ssh_pkey = None for pkey_class in ( key_type , ) if key_type else ( paramiko . RSAKey , paramiko . DSSKey , paramiko . ECDSAKey , paramiko . Ed25519Key ) : try : ssh_pkey = pkey_class . from_private_key_file ( pkey_file , password = pkey_password ) if logger : logger . debug ( 'Private k...
def get_assign_value ( node ) : """Get the name and value of the assignment of the given node . Assignments to multiple names are ignored , as per PEP 257. : param node : The node to get the assignment value from . : type node : astroid . nodes . Assign or astroid . nodes . AnnAssign : returns : The name th...
try : targets = node . targets except AttributeError : targets = [ node . target ] if len ( targets ) == 1 : target = targets [ 0 ] if isinstance ( target , astroid . nodes . AssignName ) : name = target . name elif isinstance ( target , astroid . nodes . AssignAttr ) : name = target...
def _validate ( self , val ) : """Checks that the value is numeric and that it is within the hard bounds ; if not , an exception is raised ."""
if callable ( val ) : return val if self . allow_None and val is None : return if not _is_number ( val ) : raise ValueError ( "Parameter '%s' only takes numeric values" % ( self . name ) ) if self . step is not None and not _is_number ( self . step ) : raise ValueError ( "Step parameter can only be None...
def plotMDS ( inputFileName , outPrefix , populationFileName , options ) : """Plots the MDS value . : param inputFileName : the name of the ` ` mds ` ` file . : param outPrefix : the prefix of the output files . : param populationFileName : the name of the population file . : param options : the options :...
# The options plotMDS_options = Dummy ( ) plotMDS_options . file = inputFileName plotMDS_options . out = outPrefix plotMDS_options . format = options . format plotMDS_options . title = options . title plotMDS_options . xlabel = options . xlabel plotMDS_options . ylabel = options . ylabel plotMDS_options . population_fi...
def search_hash ( self , searchterm ) : """Search for hashes : type searchterm : str : rtype : list"""
return self . __search ( type_attribute = self . __misphashtypes ( ) , value = searchterm )