signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def delete ( self , force = False ) : """Volumes cannot be deleted if either a ) they are attached to a device , or b ) they have any snapshots . This method overrides the base delete ( ) method to both better handle these failures , and also to offer a ' force ' option . When ' force ' is True , the volume i...
if force : self . detach ( ) self . delete_all_snapshots ( ) try : super ( CloudBlockStorageVolume , self ) . delete ( ) except exc . VolumeNotAvailable : # Notify the user ? Record it somewhere ? # For now , just re - raise raise
def setup_parser ( ) : """Sets up the argument parser and returns it : returns : the parser : rtype : : class : ` optparse . OptionParser ` : raises : None"""
parser = optparse . OptionParser ( usage = """\ usage: %prog [options] -o <output_path> <module_path> [exclude_path, ...] Look recursively in <module_path> for Python modules and packages and create one reST file with automodule directives per package in the <output_path>. The <exclude_path>s can be files and/or dire...
def query ( options , collection_name , num_to_skip , num_to_return , query , field_selector = None ) : """Get a * * query * * message ."""
data = struct . pack ( "<I" , options ) data += bson . _make_c_string ( collection_name ) data += struct . pack ( "<i" , num_to_skip ) data += struct . pack ( "<i" , num_to_return ) data += bson . BSON . encode ( query ) if field_selector is not None : data += bson . BSON . encode ( field_selector ) return __pack_m...
def AddStop ( self , lat , lng , name , stop_id = None ) : """Add a stop to this schedule . Args : lat : Latitude of the stop as a float or string lng : Longitude of the stop as a float or string name : Name of the stop , which will appear in the feed stop _ id : stop _ id of the stop or None , in which c...
if stop_id is None : stop_id = util . FindUniqueId ( self . stops ) stop = self . _gtfs_factory . Stop ( stop_id = stop_id , lat = lat , lng = lng , name = name ) self . AddStopObject ( stop ) return stop
def mix ( self , cls ) : """Returns a subclass of ` cls ` mixed with ` self . mixins ` . : param cls : The base class to mix into : type cls : ` class `"""
if hasattr ( cls , 'unmixed_class' ) : base_class = cls . unmixed_class old_mixins = cls . __bases__ [ 1 : ] # Skip the original unmixed class mixins = old_mixins + tuple ( mixin for mixin in self . _mixins if mixin not in old_mixins ) else : base_class = cls mixins = self . _mixins mixin_key = ...
def upload_resumable ( self , fd , filesize , filehash , unit_hash , unit_id , unit_size , quick_key = None , action_on_duplicate = None , mtime = None , version_control = None , folder_key = None , filedrop_key = None , path = None , previous_hash = None ) : """upload / resumable http : / / www . mediafire . com...
action = 'upload/resumable' headers = { 'x-filesize' : str ( filesize ) , 'x-filehash' : filehash , 'x-unit-hash' : unit_hash , 'x-unit-id' : str ( unit_id ) , 'x-unit-size' : str ( unit_size ) } params = QueryParams ( { 'quick_key' : quick_key , 'action_on_duplicate' : action_on_duplicate , 'mtime' : mtime , 'version_...
def bool ( self , state ) : """Returns the Boolean evaluation of the clause with respect to a given state Parameters state : dict Key - value mapping describing a Boolean state or assignment Returns boolean The evaluation of the clause with respect to the given state or assignment"""
value = 1 for source , sign in self : value = value and ( state [ source ] if sign == 1 else not state [ source ] ) if not value : break return value
def get_object ( context ) : """Get an object from the context or view ."""
object = None view = context . get ( 'view' ) if view : # View is more reliable then an ' object ' variable in the context . # Works if this is a SingleObjectMixin object = getattr ( view , 'object' , None ) if object is None : object = context . get ( 'object' , None ) return object
def download_static_assets ( doc , destination , base_url , request_fn = make_request , url_blacklist = [ ] , js_middleware = None , css_middleware = None , derive_filename = _derive_filename ) : """Download all static assets referenced from an HTML page . The goal is to easily create HTML5 apps ! Downloads JS , ...
if not isinstance ( doc , BeautifulSoup ) : doc = BeautifulSoup ( doc , "html.parser" ) # Helper function to download all assets for a given CSS selector . def download_assets ( selector , attr , url_middleware = None , content_middleware = None , node_filter = None ) : nodes = doc . select ( selector ) for...
def prepare ( self ) : """Method to check if the impact function can be run . : return : A tuple with the status of the IF and an error message if needed . The status is PREPARE _ SUCCESS if everything was fine . The status is PREPARE _ FAILED _ BAD _ INPUT if the client should fix something . The statu...
self . _provenance_ready = False # save layer reference before preparing . # used to display it in maps original_exposure = self . exposure original_hazard = self . hazard original_aggregation = self . aggregation try : if not self . exposure : message = generate_input_error_message ( tr ( 'The exposure lay...
def _safe_unicode ( o ) : """Returns an equivalent unicode object , trying harder to avoid dependencies on the Python default encoding ."""
def clean ( s ) : return u'' . join ( [ c if c in ASCII_PRINTABLE else '?' for c in s ] ) if USING_PYTHON2 : try : return unicode ( o ) except : try : s = str ( o ) try : return s . decode ( "utf-8" ) except : return clean (...
def _extract_submission ( self , filename ) : """Extracts submission and moves it into self . _ extracted _ submission _ dir ."""
# verify filesize file_size = os . path . getsize ( filename ) if file_size > MAX_SUBMISSION_SIZE_ZIPPED : logging . error ( 'Submission archive size %d is exceeding limit %d' , file_size , MAX_SUBMISSION_SIZE_ZIPPED ) return False # determime archive type exctract_command_tmpl = get_extract_command_template ( ...
def update_reward ( self , new_reward ) : """Updates reward value for policy . : param new _ reward : New reward to save ."""
self . sess . run ( self . model . update_reward , feed_dict = { self . model . new_reward : new_reward } )
def _create ( archive , compression , cmd , format , verbosity , filenames ) : """Create an LZMA or XZ archive with the lzma Python module ."""
if len ( filenames ) > 1 : raise util . PatoolError ( 'multi-file compression not supported in Python lzma' ) try : with lzma . LZMAFile ( archive , mode = 'wb' , ** _get_lzma_options ( format , preset = 9 ) ) as lzmafile : filename = filenames [ 0 ] with open ( filename , 'rb' ) as srcfile : ...
def tk_to_dagcircuit ( circ : Circuit , _qreg_name : str = "q" ) -> DAGCircuit : """Convert a : math : ` \\ mathrm { t | ket } \\ rangle ` : py : class : ` Circuit ` to a : py : class : ` qiskit . DAGCircuit ` . Requires that the circuit only conatins : py : class : ` OpType ` s from the qelib set . : param cir...
dc = DAGCircuit ( ) qreg = QuantumRegister ( circ . n_qubits ( ) , name = _qreg_name ) dc . add_qreg ( qreg ) grid = circ . _int_routing_grid ( ) slices = _grid_to_slices ( grid ) qubits = _grid_to_qubits ( grid , qreg ) in_boundary = circ . _get_boundary ( ) [ 0 ] out_boundary = circ . _get_boundary ( ) [ 1 ] for s in...
def get ( self , columns = None ) : """Execute the query as a " select " statement . : param columns : The columns to get : type columns : list : rtype : orator . Collection"""
models = self . get_models ( columns ) # If we actually found models we will also eager load any relationships that # have been specified as needing to be eager loaded , which will solve the # n + 1 query issue for the developers to avoid running a lot of queries . if len ( models ) > 0 : models = self . eager_load...
def forced_insert ( self ) : """Insert tokens if self . insert _ till hasn ' t been reached yet Will respect self . inserted _ line and make sure token is inserted before it Returns True if it appends anything or if it reached the insert _ till token"""
# If we have any tokens we are waiting for if self . insert_till : # Determine where to append this token append_at = - 1 if self . inserted_line : append_at = - self . inserted_line + 1 # Reset insert _ till if we found it if self . current . tokenum == self . insert_till [ 0 ] and self . curre...
def Debugger_setScriptSource ( self , scriptId , scriptSource , ** kwargs ) : """Function path : Debugger . setScriptSource Domain : Debugger Method name : setScriptSource Parameters : Required arguments : ' scriptId ' ( type : Runtime . ScriptId ) - > Id of the script to edit . ' scriptSource ' ( type ...
assert isinstance ( scriptSource , ( str , ) ) , "Argument 'scriptSource' must be of type '['str']'. Received type: '%s'" % type ( scriptSource ) if 'dryRun' in kwargs : assert isinstance ( kwargs [ 'dryRun' ] , ( bool , ) ) , "Optional argument 'dryRun' must be of type '['bool']'. Received type: '%s'" % type ( kwa...
def explode ( self , hostgroups , contactgroups ) : """Explode hosts with hostgroups , contactgroups : : * Add contact from contactgroups to host contacts * Add host into their hostgroups as hostgroup members : param hostgroups : Hostgroups to explode : type hostgroups : alignak . objects . hostgroup . Host...
for template in list ( self . templates . values ( ) ) : # items : : explode _ contact _ groups _ into _ contacts # take all contacts from our contact _ groups into our contact property self . explode_contact_groups_into_contacts ( template , contactgroups ) # Register host in the hostgroups for host in self : # it...
def val_to_json ( key , val , mode = "summary" , step = None ) : """Converts a wandb datatype to its JSON representation"""
converted = val typename = util . get_full_typename ( val ) if util . is_matplotlib_typename ( typename ) : # This handles plots with images in it because plotly doesn ' t support it # TODO : should we handle a list of plots ? val = util . ensure_matplotlib_figure ( val ) if any ( len ( ax . images ) > 0 for ax...
def create_client ( ) : """Create a new client driver . The driver is automatically created in before _ request function ."""
result = False if g . client_id in drivers : result = True return jsonify ( { 'Success' : result } )
def apply_bios_properties_filter ( settings , filter_to_be_applied ) : """Applies the filter to return the dict of filtered BIOS properties . : param settings : dict of BIOS settings on which filter to be applied . : param filter _ to _ be _ applied : list of keys to be applied as filter . : returns : A dicti...
if not settings or not filter_to_be_applied : return settings return { k : settings [ k ] for k in filter_to_be_applied if k in settings }
def can_aquire_user_lock ( repository_path , session_token ) : """Allow a user to acquire the lock if no other user is currently using it , if the original user is returning , presumably after a network error , or if the lock has expired ."""
# NOTE ALWAYS use within lock access callback user_file_path = cpjoin ( repository_path , 'user_file' ) if not os . path . isfile ( user_file_path ) : return True with open ( user_file_path , 'r' ) as fd2 : content = fd2 . read ( ) if len ( content ) == 0 : return True try : res = json ....
def freeze_encrypt ( dest_dir , zip_filename , config , opt ) : """Encrypts the zip file"""
pgp_keys = grok_keys ( config ) icefile_prefix = "aomi-%s" % os . path . basename ( os . path . dirname ( opt . secretfile ) ) if opt . icefile_prefix : icefile_prefix = opt . icefile_prefix timestamp = time . strftime ( "%H%M%S-%m-%d-%Y" , datetime . datetime . now ( ) . timetuple ( ) ) ice_file = "%s/%s-%s.ice" %...
def add ( self , name , target ) : "target should be a Table or SyntheticTable"
if not isinstance ( target , ( table . Table , SyntheticTable ) ) : raise TypeError ( type ( target ) , target ) if name in self : # note : this is critical for avoiding cycles raise ScopeCollisionError ( 'scope already has' , name ) self . names [ name ] = target
def get_allowed_units ( self , database , username , relation_id = None ) : """Get list of units with access grants for database with username . This is typically used to provide shared - db relations with a list of which units have been granted access to the given database ."""
self . connect ( password = self . get_mysql_root_password ( ) ) allowed_units = set ( ) for unit in related_units ( relation_id ) : settings = relation_get ( rid = relation_id , unit = unit ) # First check for setting with prefix , then without for attr in [ "%s_hostname" % ( database ) , 'hostname' ] : ...
def user_exists_p ( login , connector ) : """Determine if user exists in specified environment ."""
url = '/users/' + login + '/' _r = connector . get ( url ) return ( _r . status_code == Constants . PULP_GET_OK )
def showEvent ( self , event ) : """Override show event to start waiting spinner ."""
QWidget . showEvent ( self , event ) self . spinner . start ( )
def football_data ( season = '1617' , data_set = 'football_data' ) : """Football data from English games since 1993 . This downloads data from football - data . co . uk for the given season ."""
league_dict = { 'E0' : 0 , 'E1' : 1 , 'E2' : 2 , 'E3' : 3 , 'EC' : 4 } def league2num ( string ) : if isinstance ( string , bytes ) : string = string . decode ( 'utf-8' ) return league_dict [ string ] def football2num ( string ) : if isinstance ( string , bytes ) : string = string . decode (...
def _verified_iv_length ( iv_length , algorithm_suite ) : # type : ( int , AlgorithmSuite ) - > int """Verify an IV length for an algorithm suite . : param int iv _ length : IV length to verify : param AlgorithmSuite algorithm _ suite : Algorithm suite to verify against : return : IV length : rtype : int ...
if iv_length != algorithm_suite . iv_len : raise SerializationError ( "Specified IV length ({length}) does not match algorithm IV length ({algorithm})" . format ( length = iv_length , algorithm = algorithm_suite ) ) return iv_length
def equals ( self , other ) : """Ensures : attr : ` subject ` is equal to * other * ."""
self . _run ( unittest_case . assertEqual , ( self . _subject , other ) ) return ChainInspector ( self . _subject )
def GetMessages ( self , formatter_mediator , event ) : """Determines the formatted message strings for an event object . Args : formatter _ mediator ( FormatterMediator ) : mediates the interactions between formatters and other components , such as storage and Windows EventLog resources . event ( EventOb...
if self . DATA_TYPE != event . data_type : raise errors . WrongFormatter ( 'Unsupported data type: {0:s}.' . format ( event . data_type ) ) event_values = event . CopyToDict ( ) page_transition_type = event_values . get ( 'page_transition_type' , None ) if page_transition_type is not None : page_transition , pa...
def destroy ( self ) : '''Tear down the minion'''
if self . _running is False : return self . _running = False if hasattr ( self , 'schedule' ) : del self . schedule if hasattr ( self , 'pub_channel' ) and self . pub_channel is not None : self . pub_channel . on_recv ( None ) if hasattr ( self . pub_channel , 'close' ) : self . pub_channel . cl...
def add_pipeline ( subparsers ) : """Pipeline subcommands ."""
pipeline_parser = subparsers . add_parser ( 'pipeline' , help = add_pipeline . __doc__ , formatter_class = argparse . ArgumentDefaultsHelpFormatter ) pipeline_parser . set_defaults ( func = pipeline_parser . print_help ) pipeline_subparsers = pipeline_parser . add_subparsers ( title = 'Pipelines' ) pipeline_full_parser...
def unlock ( self , request , * args , ** kwargs ) : """Unlocks the considered topic and retirects the user to the success URL ."""
self . object = self . get_object ( ) success_url = self . get_success_url ( ) self . object . status = Topic . TOPIC_UNLOCKED self . object . save ( ) messages . success ( self . request , self . success_message ) return HttpResponseRedirect ( success_url )
def _get_cpu_info_from_sysctl ( ) : '''Returns the CPU info gathered from sysctl . Returns { } if sysctl is not found .'''
try : # Just return { } if there is no sysctl if not DataSource . has_sysctl ( ) : return { } # If sysctl fails return { } returncode , output = DataSource . sysctl_machdep_cpu_hw_cpufrequency ( ) if output == None or returncode != 0 : return { } # Various fields vendor_id = _get...
def wgan ( cls , data : DataBunch , generator : nn . Module , critic : nn . Module , switcher : Callback = None , clip : float = 0.01 , ** learn_kwargs ) : "Create a WGAN from ` data ` , ` generator ` and ` critic ` ."
return cls ( data , generator , critic , NoopLoss ( ) , WassersteinLoss ( ) , switcher = switcher , clip = clip , ** learn_kwargs )
def docs_client ( self ) : """A DocsClient singleton , used to look up spreadsheets by name ."""
if not hasattr ( self , '_docs_client' ) : client = DocsClient ( ) client . ClientLogin ( self . google_user , self . google_password , SOURCE_NAME ) self . _docs_client = client return self . _docs_client
def arcsine_sqrt_transform ( rel_abd ) : """Takes the proportion data from relative _ abundance ( ) and applies the variance stabilizing arcsine square root transformation : X = sin ^ { - 1 } \ sqrt p"""
arcsint = lambda p : math . asin ( math . sqrt ( p ) ) return { col_id : { row_id : arcsint ( rel_abd [ col_id ] [ row_id ] ) for row_id in rel_abd [ col_id ] } for col_id in rel_abd }
def pxe ( hostname , timeout = 20 , username = None , password = None ) : '''Connect to the Dell DRAC and have the boot order set to PXE and power cycle the system to PXE boot CLI Example : . . code - block : : bash salt - run drac . pxe example . com'''
_cmds = [ 'racadm config -g cfgServerInfo -o cfgServerFirstBootDevice pxe' , 'racadm config -g cfgServerInfo -o cfgServerBootOnce 1' , 'racadm serveraction powercycle' , ] client = __connect ( hostname , timeout , username , password ) if isinstance ( client , paramiko . SSHClient ) : for i , cmd in enumerate ( _cm...
def confirm ( text = '' , title = '' , buttons = [ 'OK' , 'Cancel' ] ) : """Displays a message box with OK and Cancel buttons . Number and text of buttons can be customized . Returns the text of the button clicked on ."""
retVal = messageBoxFunc ( 0 , text , title , MB_OKCANCEL | MB_ICONQUESTION | MB_SETFOREGROUND | MB_TOPMOST ) if retVal == 1 or len ( buttons ) == 1 : return buttons [ 0 ] elif retVal == 2 : return buttons [ 1 ] else : assert False , 'Unexpected return value from MessageBox: %s' % ( retVal )
def set ( self , key : bytes , value : bytes ) -> Tuple [ Hash32 ] : """Returns all updated hashes in root - > leaf order"""
validate_is_bytes ( key ) validate_length ( key , self . _key_size ) validate_is_bytes ( value ) path = to_int ( key ) node = value _ , branch = self . _get ( key ) proof_update = [ ] # Keep track of proof updates target_bit = 1 # branch is in root - > leaf order , so flip for sibling_node in reversed ( branch ) : # Se...
def _decode ( self , obj , context ) : """Get the python representation of the obj"""
return b'' . join ( map ( int2byte , [ c + 0x60 for c in bytearray ( obj ) ] ) ) . decode ( "utf8" )
def histogram ( a , bins ) : """Compute the histogram of a set of data . : param a : Input data : param bins : int or sequence of scalars or str , optional : type a : list | tuple : type bins : int | list [ int ] | list [ str ] : return :"""
if any ( map ( lambda x : x < 0 , diff ( bins ) ) ) : raise ValueError ( 'bins must increase monotonically.' ) try : sa = sorted ( a ) except TypeError : # Perhaps just a single value ? Treat as a list and carry on sa = sorted ( [ a ] ) # import numpy as np # nl = np . searchsorted ( sa , bins [ : - 1 ] , '...
async def set_contents ( self , ** params ) : """Writes users content to database Accepts : - public key ( required ) - content ( required ) - description - price - address"""
if params . get ( "message" ) : params = json . loads ( params . get ( "message" , "{}" ) ) if not params : return { "error" : 400 , "reason" : "Missed required fields" } txid = params . get ( "txid" ) public_key = params . get ( "public_key" ) _hash = params . get ( "hash" ) coinid = params . get ( "coinid" ) ...
def _loadConfig ( self ) : """loads configuration from some predictable locations . : return : the config ."""
configPath = path . join ( self . _getConfigPath ( ) , self . _name + ".yml" ) if os . path . exists ( configPath ) : self . logger . warning ( "Loading config from " + configPath ) with open ( configPath , 'r' ) as yml : return yaml . load ( yml , Loader = yaml . FullLoader ) defaultConfig = self . loa...
def compare_contract_versions ( proxy : ContractProxy , expected_version : str , contract_name : str , address : Address , ) -> None : """Compare version strings of a contract . If not matching raise ContractVersionMismatch . Also may raise AddressWrongContract if the contract contains no code ."""
assert isinstance ( expected_version , str ) try : deployed_version = proxy . contract . functions . contract_version ( ) . call ( ) except BadFunctionCallOutput : raise AddressWrongContract ( '' ) deployed_version = deployed_version . replace ( '_' , '0' ) expected_version = expected_version . replace ( '_' , ...
def get_all_prerequisites ( self ) : """Returns all unique ( order - only ) prerequisites for all batches of this Executor ."""
result = SCons . Util . UniqueList ( [ ] ) for target in self . get_all_targets ( ) : if target . prerequisites is not None : result . extend ( target . prerequisites ) return result
def setup ( self ) : """Setup the networks . Setup only does stuff if there are no networks , this is so it only runs once at the start of the experiment . It first calls the same function in the super ( see experiments . py in dallinger ) . Then it adds a source to each network ."""
if not self . networks ( ) : super ( IteratedDrawing , self ) . setup ( ) for net in self . networks ( ) : self . models . DrawingSource ( network = net )
def _vector_coef_op_right ( func ) : """decorator for operator overloading when VectorCoefs is on the right"""
@ wraps ( func ) def verif ( self , vcoef ) : if isinstance ( vcoef , numbers . Number ) : return VectorCoefs ( func ( self , self . scoef1 . _vec , vcoef ) , func ( self , self . scoef2 . _vec , vcoef ) , self . nmax , self . mmax ) else : raise TypeError ( err_msg [ 'no_combi_VC' ] ) return ve...
def full_s ( self ) : """Get the full singular value matrix of self Returns Matrix : Matrix"""
x = np . zeros ( ( self . shape ) , dtype = np . float32 ) x [ : self . s . shape [ 0 ] , : self . s . shape [ 0 ] ] = self . s . as_2d s = Matrix ( x = x , row_names = self . row_names , col_names = self . col_names , isdiagonal = False , autoalign = False ) return s
def gateway ( self ) : """Return the detail of the gateway ."""
url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/gateway' response = requests . get ( url , headers = self . _headers ( ) ) response . raise_for_status ( ) return response . json ( )
def validate ( self , model , checks = [ ] ) : """Use a defined schema to validate the given table ."""
records = self . data . to_dict ( "records" ) self . evaluate_report ( validate ( records , headers = list ( records [ 0 ] ) , preset = 'table' , schema = self . schema , order_fields = True , custom_checks = checks ) )
def cached_query ( qs , timeout = None ) : """Auto cached queryset and generate results ."""
cache_key = generate_cache_key ( qs ) return get_cached ( cache_key , list , args = ( qs , ) , timeout = None )
async def send_script ( self , conn_id , data ) : """Send a a script to this IOTile device Args : conn _ id ( int ) : A unique identifier that will refer to this connection data ( bytes ) : the script to send to the device"""
self . _ensure_connection ( conn_id , True ) connection_string = self . _get_property ( conn_id , "connection_string" ) msg = dict ( connection_string = connection_string , fragment_count = 1 , fragment_index = 0 , script = base64 . b64encode ( data ) ) await self . _send_command ( OPERATIONS . SEND_SCRIPT , msg , COMM...
def _parse_date_columns ( data_frame , parse_dates ) : """Force non - datetime columns to be read as such . Supports both string formatted and integer timestamp columns ."""
parse_dates = _process_parse_dates_argument ( parse_dates ) # we want to coerce datetime64 _ tz dtypes for now to UTC # we could in theory do a ' nice ' conversion from a FixedOffset tz # GH11216 for col_name , df_col in data_frame . iteritems ( ) : if is_datetime64tz_dtype ( df_col ) or col_name in parse_dates : ...
def define_lattice_from_file ( self , filename , cell_lengths ) : """Set up the simulation lattice from a file containing site data . Uses ` init _ lattice . lattice _ from _ sites _ file ` , which defines the site file spec . Args : filename ( Str ) : sites file filename . cell _ lengths ( List ( x , y , z...
self . lattice = init_lattice . lattice_from_sites_file ( filename , cell_lengths = cell_lengths )
def get_meta_value_for ( snapshot , key , default = None ) : """Returns the metadata value for the given key"""
metadata = get_snapshot_metadata ( snapshot ) return metadata . get ( key , default )
def get_attributes ( file , * , attributes = None , mime_type = None , force_document = False , voice_note = False , video_note = False , supports_streaming = False ) : """Get a list of attributes for the given file and the mime type as a tuple ( [ attribute ] , mime _ type ) ."""
# Note : ` ` file . name ` ` works for : tl : ` InputFile ` and some ` IOBase ` streams name = file if isinstance ( file , str ) else getattr ( file , 'name' , 'unnamed' ) if mime_type is None : mime_type = mimetypes . guess_type ( name ) [ 0 ] attr_dict = { types . DocumentAttributeFilename : types . DocumentAttri...
def purge ( name , delete_key = True ) : '''Destroy the named VM'''
ret = { } client = salt . client . get_local_client ( __opts__ [ 'conf_file' ] ) data = vm_info ( name , quiet = True ) if not data : __jid_event__ . fire_event ( { 'error' : 'Failed to find VM {0} to purge' . format ( name ) } , 'progress' ) return 'fail' host = next ( six . iterkeys ( data ) ) try : cmd_r...
def attr ( self , key ) : """Returns the attribute string for corresponding input key from the symbol . This function only works for non - grouped symbols . Example > > > data = mx . sym . Variable ( ' data ' , attr = { ' mood ' : ' angry ' } ) > > > data . attr ( ' mood ' ) ' angry ' Parameters key :...
ret = ctypes . c_char_p ( ) success = ctypes . c_int ( ) check_call ( _LIB . MXSymbolGetAttr ( self . handle , c_str ( key ) , ctypes . byref ( ret ) , ctypes . byref ( success ) ) ) if success . value != 0 : return py_str ( ret . value ) else : return None
def sanitize ( self ) : '''Check if the current settings conform to the LISP specifications and fix them where possible .'''
super ( MapReferralMessage , self ) . sanitize ( ) # WARNING : http : / / tools . ietf . org / html / draft - ietf - lisp - ddt - 00 # does not define this field so the description is taken from # http : / / tools . ietf . org / html / draft - ietf - lisp - 24 # Nonce : An 8 - octet random value created by the sender o...
def newick ( self ) : '''Newick string conversion starting at this ` ` Node ` ` object Returns : ` ` str ` ` : Newick string conversion starting at this ` ` Node ` ` object'''
node_to_str = dict ( ) for node in self . traverse_postorder ( ) : if node . is_leaf ( ) : if node . label is None : node_to_str [ node ] = '' else : node_to_str [ node ] = str ( node . label ) else : out = [ '(' ] for c in node . children : ou...
def lookup_token ( self ) : """Convenience method : look up the vault token"""
url = _url_joiner ( self . _vault_url , 'v1/auth/token/lookup-self' ) resp = requests . get ( url , headers = self . _headers ) resp . raise_for_status ( ) data = resp . json ( ) if data . get ( 'errors' ) : raise VaultException ( u'Error looking up Vault token: {}' . format ( data [ 'errors' ] ) ) return data
def preprocess_x_y ( x , y ) : """Preprocess x , y input data . Returns list of list style . * * 中文文档 * * 预处理输入的x , y数据 。"""
def is_iterable_slicable ( a ) : if hasattr ( a , "__iter__" ) and hasattr ( a , "__getitem__" ) : return True else : return False if is_iterable_slicable ( x ) : if is_iterable_slicable ( x [ 0 ] ) : return x , y else : return ( x , ) , ( y , ) else : raise ValueErro...
def get_default_location ( self ) : """Return the default location ."""
res = [ ] for location in self . distdefault : res . extend ( self . get_location ( location ) ) return res
def check_has ( priority = BaseCheck . HIGH , gname = None ) : """Decorator to wrap a function to check if a dataset has given attributes . : param function func : function to wrap"""
def _inner ( func ) : def _dec ( s , ds ) : attr_process = kvp_convert ( func ( s , ds ) ) ret_val = [ ] # could potentially run tests in parallel if we eliminated side # effects on ` ret _ val ` for kvp in attr_process . items ( ) : # function mutates ret _ val a...
def get_events ( self , ** kwargs ) : """Retrieve events from server ."""
force = kwargs . pop ( 'force' , False ) response = api . request_sync_events ( self . blink , self . network_id , force = force ) try : return response [ 'event' ] except ( TypeError , KeyError ) : _LOGGER . error ( "Could not extract events: %s" , response , exc_info = True ) return False
def auto_scroll ( self , thumbkey ) : """Scroll the window to the thumb ."""
if not self . gui_up : return # force scroll to bottom of thumbs , if checkbox is set scrollp = self . w . auto_scroll . get_state ( ) if not scrollp : return bnch = self . thumb_dict [ thumbkey ] # override X parameter because we only want to scroll vertically pan_x , pan_y = self . c_view . get_pan ( ) self ....
def polygon ( self , vertexes , attr = 0 , row = None ) : 'adds lines for ( x , y ) vertexes of a polygon'
self . polylines . append ( ( vertexes + [ vertexes [ 0 ] ] , attr , row ) )
def pop ( self , n = 1 , raw = False , delete = True ) : """Pop status queue : param int n : number of messages to return as part of peek . : param bool raw : should message content be returned as is ( no parsing ) . : param bool delete : should message be deleted after pop . default is True as this is expect...
def _pop_specific_q ( _q , _n ) : has_messages = False for m in _q . service . get_messages ( _q . name , num_messages = _n ) : if m is not None : has_messages = True result . append ( m if raw else self . _deserialize_message ( m ) ) if delete : _q . ...
def get_anchor_labels ( anchors , gt_boxes , crowd_boxes ) : """Label each anchor as fg / bg / ignore . Args : anchors : Ax4 float gt _ boxes : Bx4 float , non - crowd crowd _ boxes : Cx4 float Returns : anchor _ labels : ( A , ) int . Each element is { - 1 , 0 , 1} anchor _ boxes : Ax4 . Contains the...
# This function will modify labels and return the filtered inds def filter_box_label ( labels , value , max_num ) : curr_inds = np . where ( labels == value ) [ 0 ] if len ( curr_inds ) > max_num : disable_inds = np . random . choice ( curr_inds , size = ( len ( curr_inds ) - max_num ) , replace = False...
def circ_rayleigh ( alpha , w = None , d = None ) : """Rayleigh test for non - uniformity of circular data . Parameters alpha : np . array Sample of angles in radians . w : np . array Number of incidences in case of binned angle data . d : float Spacing ( in radians ) of bin centers for binned data . ...
alpha = np . array ( alpha ) if w is None : r = circ_r ( alpha ) n = len ( alpha ) else : if len ( alpha ) is not len ( w ) : raise ValueError ( "Input dimensions do not match" ) r = circ_r ( alpha , w , d ) n = np . sum ( w ) # Compute Rayleigh ' s statistic R = n * r z = ( R ** 2 ) / n # C...
def increment_all_elements ( input_list : list ) : """Given a list , this function returns a new list where every element is incremented by 1. Example usage : > > > increment _ all _ elements ( [ 1 , 2 , 3 ] ) [2 , 3 , 4] > > > increment _ all _ elements ( [ 5 , 3 , 5 , 2 , 3 , 3 , 9 , 0 , 123 ] ) [6 , 4 ...
return [ element + 1 for element in input_list ]
def get_video_info_for_course_and_profiles ( course_id , profiles ) : """Returns a dict of edx _ video _ ids with a dict of requested profiles . Args : course _ id ( str ) : id of the course profiles ( list ) : list of profile _ names Returns : ( dict ) : Returns all the profiles attached to a specific ...
# In case someone passes in a key ( VAL doesn ' t really understand opaque keys ) course_id = six . text_type ( course_id ) try : encoded_videos = EncodedVideo . objects . filter ( profile__profile_name__in = profiles , video__courses__course_id = course_id ) . select_related ( ) except Exception : error_messag...
def print_intervals ( intervals ) : """Print out the intervals ."""
res = [ ] for i in intervals : res . append ( repr ( i ) ) print ( "" . join ( res ) )
def filter_queryset ( self , request , queryset , view ) : """Filter permissions queryset ."""
user = request . user app_label = queryset . model . _meta . app_label # pylint : disable = protected - access model_name = queryset . model . _meta . model_name # pylint : disable = protected - access kwargs = { } if model_name == 'storage' : model_name = 'data' kwargs [ 'perms_filter' ] = 'data__pk__in' if mo...
def _check_value_mapping ( layer , exposure_key = None ) : """Loop over the exposure type field and check if the value map is correct . : param layer : The layer : type layer : QgsVectorLayer : param exposure _ key : The exposure key . : type exposure _ key : str"""
index = layer . fields ( ) . lookupField ( exposure_type_field [ 'field_name' ] ) unique_exposure = layer . uniqueValues ( index ) if layer . keywords [ 'layer_purpose' ] == layer_purpose_hazard [ 'key' ] : if not exposure_key : message = tr ( 'Hazard value mapping missing exposure key.' ) raise Inv...
def create_config_file ( filename ) : """Create main configuration file if it doesn ' t exist ."""
import textwrap from six . moves . urllib import parse if not os . path . exists ( filename ) : old_default_config_file = os . path . join ( os . path . dirname ( filename ) , '.tksrc' ) if os . path . exists ( old_default_config_file ) : upgrade = click . confirm ( "\n" . join ( textwrap . wrap ( "It l...
def _get_numbers_from_tokens ( tokens : List [ Token ] ) -> List [ Tuple [ str , str ] ] : """Finds numbers in the input tokens and returns them as strings . We do some simple heuristic number recognition , finding ordinals and cardinals expressed as text ( " one " , " first " , etc . ) , as well as numerals ( ...
numbers = [ ] for i , token in enumerate ( tokens ) : number : Union [ int , float ] = None token_text = token . text text = token . text . replace ( ',' , '' ) . lower ( ) if text in NUMBER_WORDS : number = NUMBER_WORDS [ text ] magnitude = 1 if i < len ( tokens ) - 1 : next_tok...
def measure_float_put ( self , measure , value ) : """associates the measure of type Float with the given value"""
if value < 0 : # Should be an error in a later release . logger . warning ( "Cannot record negative values" ) self . _measurement_map [ measure ] = value
def uncomment_line ( line , prefix ) : """Remove prefix ( and space ) from line"""
if not prefix : return line if line . startswith ( prefix + ' ' ) : return line [ len ( prefix ) + 1 : ] if line . startswith ( prefix ) : return line [ len ( prefix ) : ] return line
def _format_api_docs_link_message ( self , task_class ) : """Format a message referring the reader to the full API docs . Parameters task _ class : ` ` lsst . pipe . base . Task ` ` - type The Task class . Returns nodes : ` list ` of docutils nodes Docutils nodes showing a link to the full API docs ."""
fullname = '{0.__module__}.{0.__name__}' . format ( task_class ) p_node = nodes . paragraph ( ) _ = 'See the ' p_node += nodes . Text ( _ , _ ) xref = PyXRefRole ( ) xref_nodes , _ = xref ( 'py:class' , '~' + fullname , '~' + fullname , self . lineno , self . state . inliner ) p_node += xref_nodes _ = ' API reference f...
def from_lt ( rsize , ltm , ltv ) : """Compute the corner location and pixel size in units of unbinned pixels . . . note : : Translated from ` ` calacs / lib / fromlt . c ` ` . Parameters rsize : int Reference pixel size . Usually 1. ltm , ltv : tuple of float See : func : ` get _ lt ` . Returns b...
dbinx = rsize / ltm [ 0 ] dbiny = rsize / ltm [ 1 ] dxcorner = ( dbinx - rsize ) - dbinx * ltv [ 0 ] dycorner = ( dbiny - rsize ) - dbiny * ltv [ 1 ] # Round off to the nearest integer . bin = ( _nint ( dbinx ) , _nint ( dbiny ) ) corner = ( _nint ( dxcorner ) , _nint ( dycorner ) ) return bin , corner
def init_cursor ( self ) : """Position the cursor appropriately . The cursor is set to either the beginning of the oplog , or wherever it was last left off . Returns the cursor and True if the cursor is empty ."""
timestamp = self . read_last_checkpoint ( ) if timestamp is None or self . only_dump : if self . collection_dump : # dump collection and update checkpoint timestamp = self . dump_collection ( ) if self . only_dump : LOG . info ( "Finished dump. Exiting." ) timestamp = None ...
def path_from_structure ( cls , ndivsm , structure ) : """See _ path for the meaning of the variables"""
return cls . _path ( ndivsm , structure = structure , comment = "K-path generated automatically from structure" )
def formatted_str_to_val ( data , format , enum_set = None ) : """Return an unsigned integer representation of the data given format specified . : param data : a string holding the value to convert : param format : a string holding a format which will be used to convert the data string : param enum _ set : an...
type = format [ 0 ] bitwidth = int ( format [ 1 : ] . split ( '/' ) [ 0 ] ) bitmask = ( 1 << bitwidth ) - 1 if type == 's' : rval = int ( data ) & bitmask elif type == 'x' : rval = int ( data , 16 ) elif type == 'b' : rval = int ( data , 2 ) elif type == 'u' : rval = int ( data ) if rval < 0 : ...
def put_annotation ( self , key , value ) : """Annotate segment or subsegment with a key - value pair . Annotations will be indexed for later search query . : param str key : annotation key : param object value : annotation value . Any type other than string / number / bool will be dropped"""
self . _check_ended ( ) if not isinstance ( key , string_types ) : log . warning ( "ignoring non string type annotation key with type %s." , type ( key ) ) return if not isinstance ( value , annotation_value_types ) : log . warning ( "ignoring unsupported annotation value type %s." , type ( value ) ) re...
def p_default_clause ( self , p ) : """default _ clause : DEFAULT COLON source _ elements"""
p [ 0 ] = self . asttypes . Default ( elements = p [ 3 ] ) p [ 0 ] . setpos ( p )
def initialize_snapshot ( self ) : """Copy the DAG and validate"""
logger . debug ( 'Initializing DAG snapshot for job {0}' . format ( self . name ) ) if self . snapshot is not None : logging . warn ( "Attempting to initialize DAG snapshot without " + "first destroying old snapshot." ) snapshot_to_validate = deepcopy ( self . graph ) is_valid , reason = self . validate ( snapshot_...
def set_topic_attributes ( self , topic , attr_name , attr_value ) : """Get attributes of a Topic : type topic : string : param topic : The ARN of the topic . : type attr _ name : string : param attr _ name : The name of the attribute you want to set . Only a subset of the topic ' s attributes are mutable...
params = { 'ContentType' : 'JSON' , 'TopicArn' : topic , 'AttributeName' : attr_name , 'AttributeValue' : attr_value } response = self . make_request ( 'SetTopicAttributes' , params , '/' , 'GET' ) body = response . read ( ) if response . status == 200 : return json . loads ( body ) else : boto . log . error ( ...
def inSignJoy ( self ) : """Returns if the object is in its sign of joy ."""
return props . object . signJoy [ self . obj . id ] == self . obj . sign
def get_original ( mod_name , item_name ) : """Retrieve the original object from a module . If the object has not been patched , then that object will still be retrieved . : param item _ name : A string or sequence of strings naming the attribute ( s ) on the module ` ` mod _ name ` ` to return . : return :...
if isinstance ( item_name , string_types ) : return _get_original ( mod_name , [ item_name ] ) [ 0 ] else : return _get_original ( mod_name , item_name )
def async_aldb_loaded_callback ( self ) : """Unlock the ALDB load lock when loading is complete ."""
if self . aldb_load_lock . locked ( ) : self . aldb_load_lock . release ( ) _LOGGING . info ( 'ALDB Loaded' )
def biopax_process_pc_pathsbetween ( ) : """Process PathwayCommons paths between genes , return INDRA Statements ."""
if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) genes = body . get ( 'genes' ) bp = biopax . process_pc_pathsbetween ( genes ) return _stmts_from_proc ( bp )
def update_image_member ( self , img_id , status ) : """Updates the image whose ID is given with the status specified . This must be called by the user whose project _ id is in the members for the image . If called by the owner of the image , an InvalidImageMember exception will be raised . Valid values for...
if status not in ( "pending" , "accepted" , "rejected" ) : raise exc . InvalidImageMemberStatus ( "The status value must be one " "of 'accepted', 'rejected', or 'pending'. Received: '%s'" % status ) api = self . api project_id = api . identity . tenant_id uri = "/%s/%s/members/%s" % ( self . uri_base , img_id , pro...
def seek ( self , offset ) : """shifts on a given number of record in the original file : param offset : number of record"""
if self . _shifts : if 0 <= offset < len ( self . _shifts ) : current_pos = self . _file . tell ( ) new_pos = self . _shifts [ offset ] if current_pos != new_pos : if current_pos == self . _shifts [ - 1 ] : # reached the end of the file self . _data = self . __rea...
def ipa_substrings ( unicode_string , single_char_parsing = False ) : """Return a list of ( non - empty ) substrings of the given string , where each substring is either : 1 . the longest Unicode string starting at the current index representing a ( known ) valid IPA character , or 2 . a single Unicode char...
return split_using_dictionary ( string = unicode_string , dictionary = UNICODE_TO_IPA , max_key_length = UNICODE_TO_IPA_MAX_KEY_LENGTH , single_char_parsing = single_char_parsing )
def yield_pair_gradients ( self , index1 , index2 ) : """Yields pairs ( ( s ' ( r _ ij ) , grad _ i v ( bar { r } _ ij ) )"""
d_2 = 1 / self . distances [ index1 , index2 ] ** 2 if self . charges is not None : c1 = self . charges [ index1 ] c2 = self . charges [ index2 ] yield - c1 * c2 * d_2 , np . zeros ( 3 ) if self . dipoles is not None : d_4 = d_2 ** 2 d_6 = d_2 ** 3 delta = self . deltas [ index1 , index2 ] p...
def write_row ( dictionary , card , log ) : """Processes a single row from the file ."""
rowhdr = { 'card' : card , 'log' : log } # Do this as a list of 1 - char strings . # Can ' t use a string b / c strings are immutable . row = [ ' ' ] * 80 # Make the row header . for e in [ 'log' , 'card' ] : strt , stop , item = _put_field ( cols ( 0 ) , e , rowhdr [ e ] ) if item is not None : row [ s...