signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def mesh_nmasked ( self ) : """A 2D ( masked ) array of the number of masked pixels in each mesh . Only meshes included in the background estimation are included . The array is masked only if meshes were excluded ."""
return self . _make_2d_array ( np . ma . count_masked ( self . _data_sigclip , axis = 1 ) )
def _raise_deferred_exc ( self ) : """Raises deferred exceptions from the daemon ' s synchronous path in the post - fork client ."""
if self . _deferred_exception : try : exc_type , exc_value , exc_traceback = self . _deferred_exception raise_with_traceback ( exc_value , exc_traceback ) except TypeError : # If ` _ deferred _ exception ` isn ' t a 3 - item tuple ( raising a TypeError on the above # destructuring ) , treat ...
def multiple_contacts_get_values ( C ) : """Given an contact representation with repeated contacts , this function removes duplicates and creates a value Parameters C : dict contact representation with multiple repeated contacts . Returns : C _ out : dict Contact representation with duplicate contacts r...
d = collections . OrderedDict ( ) for c in C [ 'contacts' ] : ct = tuple ( c ) if ct in d : d [ ct ] += 1 else : d [ ct ] = 1 new_contacts = [ ] new_values = [ ] for ( key , value ) in d . items ( ) : new_values . append ( value ) new_contacts . append ( key ) C_out = C C_out [ 'cont...
def sg_espcn ( tensor , opt ) : r"""Applies a 2 - D efficient sub pixel convolution . ( see [ Shi et al . 2016 ] ( http : / / www . cv - foundation . org / openaccess / content _ cvpr _ 2016 / papers / Shi _ Real - Time _ Single _ Image _ CVPR _ 2016 _ paper . pdf ) Args : tensor : A 4 - D ` Tensor ` ( automa...
# default options opt += tf . sg_opt ( size = ( 3 , 3 ) , stride = ( 1 , 1 , 1 , 1 ) , pad = 'SAME' , factor = 2 ) opt . size = opt . size if isinstance ( opt . size , ( tuple , list ) ) else [ opt . size , opt . size ] opt . stride = opt . stride if isinstance ( opt . stride , ( tuple , list ) ) else [ 1 , opt . strid...
def getAttributeData ( self , name , channel = None ) : """Returns a attribut"""
return self . _getNodeData ( name , self . _ATTRIBUTENODE , channel )
def _particles ( self , include_ports = False ) : """Return all Particles of the Compound ."""
for child in self . successors ( ) : if not child . children : if include_ports or not child . port_particle : yield child
def add_output ( summary_output , long_output , helper ) : """if the summary output is empty , we don ' t add it as summary , otherwise we would have empty spaces ( e . g . : ' . . . . . ' ) in our summary report"""
if summary_output != '' : helper . add_summary ( summary_output ) helper . add_long_output ( long_output )
def get_default_config ( self ) : """Returns the default collector settings"""
config = super ( CelerymonCollector , self ) . get_default_config ( ) config . update ( { 'host' : 'localhost' , 'port' : '8989' } ) return config
def destroySingleton ( cls ) : """Destroys the singleton instance of this class , if one exists ."""
singleton_key = '_{0}__singleton' . format ( cls . __name__ ) singleton = getattr ( cls , singleton_key , None ) if singleton is not None : setattr ( cls , singleton_key , None ) singleton . close ( ) singleton . deleteLater ( )
def extract_src_loss_table ( dstore , loss_type ) : """Extract the source loss table for a give loss type , ordered in decreasing order . Example : http : / / 127.0.0.1:8800 / v1 / calc / 30 / extract / src _ loss _ table / structural"""
oq = dstore [ 'oqparam' ] li = oq . lti [ loss_type ] source_ids = dstore [ 'source_info' ] [ 'source_id' ] idxs = dstore [ 'ruptures' ] . value [ [ 'srcidx' , 'grp_id' ] ] losses = dstore [ 'rup_loss_table' ] [ : , li ] slt = numpy . zeros ( len ( source_ids ) , [ ( 'grp_id' , U32 ) , ( loss_type , F32 ) ] ) for loss ...
def _save_to_hdx ( self , action , id_field_name , file_to_upload = None ) : # type : ( str , str , Optional [ str ] ) - > None """Creates or updates an HDX object in HDX , saving current data and replacing with returned HDX object data from HDX Args : action ( str ) : Action to perform : ' create ' or ' upda...
result = self . _write_to_hdx ( action , self . data , id_field_name , file_to_upload ) self . old_data = self . data self . data = result
def _get_sz_info ( self ) : """Obtains the current resource allocations , assumes that the guestshell is in an ' Activated ' state"""
if 'None' == self . _state : return None cmd = 'show virtual-service detail name guestshell+' got = self . cli ( cmd ) got = got [ 'TABLE_detail' ] [ 'ROW_detail' ] sz_cpu = int ( got [ 'cpu_reservation' ] ) sz_disk = int ( got [ 'disk_reservation' ] ) sz_memory = int ( got [ 'memory_reservation' ] ) self . sz_has ...
def convert ( self , infile , item = None ) : """Convert an input file to h5features based on its extension . : raise IOError : if ` infile ` is not a valid file . : raise IOError : if ` infile ` extension is not supported ."""
if not os . path . isfile ( infile ) : raise IOError ( '{} is not a valid file' . format ( infile ) ) if item is None : item = os . path . splitext ( infile ) [ 0 ] ext = os . path . splitext ( infile ) [ 1 ] if ext == '.npz' : self . npz_convert ( infile , item ) elif ext == '.mat' : self . mat_convert...
def find ( self , location ) : """Find the specified location in the store . @ param location : The I { location } part of a URL . @ type location : str @ return : An input stream to the document . @ rtype : StringIO"""
try : content = self . store [ location ] return StringIO ( content ) except : reason = 'location "%s" not in document store' % location raise Exception , reason
def history_table ( self ) : '交易历史的table'
if len ( self . history ) > 0 : lens = len ( self . history [ 0 ] ) else : lens = len ( self . _history_headers ) return pd . DataFrame ( data = self . history , columns = self . _history_headers [ : lens ] ) . sort_index ( )
def cmd2 ( command , shell = False , detatch = False , verbose = False , verbout = None ) : """Trying to clean up cmd Args : command ( str ) : string command shell ( bool ) : if True , process is run in shell detatch ( bool ) : if True , process is run in background verbose ( int ) : verbosity mode verb...
import shlex if isinstance ( command , ( list , tuple ) ) : raise ValueError ( 'command tuple not supported yet' ) args = shlex . split ( command , posix = not WIN32 ) if verbose is True : verbose = 2 if verbout is None : verbout = verbose >= 1 if verbose >= 2 : print ( '+=== START CMD2 ===' ) print...
def streaming_bulk ( self , actions , chunk_size = 500 , max_chunk_bytes = 100 * 1024 * 1024 , raise_on_error = True , expand_action_callback = ActionParser . expand_action , raise_on_exception = True , ** kwargs ) : """Streaming bulk consumes actions from the iterable passed in and return the results of all bulk d...
actions = list ( map ( expand_action_callback , actions ) ) for bulk_actions in self . _chunk_actions ( actions , chunk_size , max_chunk_bytes ) : yield self . _process_bulk_chunk ( bulk_actions , raise_on_exception , raise_on_error , ** kwargs )
def _jtag_to_swd ( self ) : """Send the command to switch from SWD to jtag"""
data = [ 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff ] self . _protocol . swj_sequence ( data ) data = [ 0x9e , 0xe7 ] self . _protocol . swj_sequence ( data ) data = [ 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff ] self . _protocol . swj_sequence ( data ) data = [ 0x00 ] self . _protocol . swj_sequence ( data )
def open_shapefile ( shapefile_path , file_geodatabase = None ) : """Opens a shapefile using either a shapefile path or a file geodatabase"""
if file_geodatabase : gdb_driver = ogr . GetDriverByName ( "OpenFileGDB" ) ogr_shapefile = gdb_driver . Open ( file_geodatabase ) ogr_shapefile_lyr = ogr_shapefile . GetLayer ( shapefile_path ) else : ogr_shapefile = ogr . Open ( shapefile_path ) ogr_shapefile_lyr = ogr_shapefile . GetLayer ( ) retu...
def pid ( self , value ) : """Process ID setter ."""
self . bytearray [ self . _get_slicers ( 0 ) ] = bytearray ( c_int32 ( value or 0 ) )
def find_credentials ( ) : '''Cycle through all the possible credentials and return the first one that works .'''
# if the username and password were already found don ' t go through the # connection process again if 'username' in DETAILS and 'password' in DETAILS : return DETAILS [ 'username' ] , DETAILS [ 'password' ] passwords = __pillar__ [ 'proxy' ] [ 'passwords' ] for password in passwords : DETAILS [ 'password' ] = ...
def login ( self , request , extra_context = None ) : """Displays the login form for the given HttpRequest ."""
context = { 'title' : _ ( 'Log in' ) , 'app_path' : request . get_full_path ( ) , } if ( REDIRECT_FIELD_NAME not in request . GET and REDIRECT_FIELD_NAME not in request . POST ) : context [ REDIRECT_FIELD_NAME ] = request . get_full_path ( ) context . update ( extra_context or { } ) defaults = { 'extra_context' : c...
def get_columns ( mixed ) : """Return a collection of all Column objects for given SQLAlchemy object . The type of the collection depends on the type of the object to return the columns from . get _ columns ( User ) get _ columns ( User ( ) ) get _ columns ( User . _ _ table _ _ ) get _ columns ( User...
if isinstance ( mixed , sa . Table ) : return mixed . c if isinstance ( mixed , sa . orm . util . AliasedClass ) : return sa . inspect ( mixed ) . mapper . columns if isinstance ( mixed , sa . sql . selectable . Alias ) : return mixed . c if isinstance ( mixed , sa . orm . Mapper ) : return mixed . colu...
def sequence ( start , stop , step = None ) : """Generate a sequence of integers from ` start ` to ` stop ` , incrementing by ` step ` . If ` step ` is not set , incrementing by 1 if ` start ` is less than or equal to ` stop ` , otherwise - 1. > > > df1 = spark . createDataFrame ( [ ( - 2 , 2 ) ] , ( ' C1 ' ,...
sc = SparkContext . _active_spark_context if step is None : return Column ( sc . _jvm . functions . sequence ( _to_java_column ( start ) , _to_java_column ( stop ) ) ) else : return Column ( sc . _jvm . functions . sequence ( _to_java_column ( start ) , _to_java_column ( stop ) , _to_java_column ( step ) ) )
def derive_resource_name ( name ) : """A stable , human - readable name and identifier for a resource ."""
if name . startswith ( "Anon" ) : name = name [ 4 : ] if name . endswith ( "Handler" ) : name = name [ : - 7 ] if name == "Maas" : name = "MAAS" return name
def _flds_shape ( fieldname , header ) : """Compute shape of flds variable ."""
shp = list ( header [ 'nts' ] ) shp . append ( header [ 'ntb' ] ) # probably a better way to handle this if fieldname == 'Velocity' : shp . insert ( 0 , 3 ) # extra points header [ 'xp' ] = int ( header [ 'nts' ] [ 0 ] != 1 ) shp [ 1 ] += header [ 'xp' ] header [ 'yp' ] = int ( header [ 'nts' ] [ 1 ...
def file_dict ( * packages , ** kwargs ) : '''List the files that belong to a package , grouped by package . Not specifying any packages will return a list of _ every _ file on the system ' s package database ( not generally recommended ) . CLI Examples : . . code - block : : bash salt ' * ' pkg . file _ ...
errors = [ ] files = { } if packages : match_pattern = '\'{0}-[0-9]*\'' cmd = [ 'pkg_info' , '-QL' ] + [ match_pattern . format ( p ) for p in packages ] else : cmd = [ 'pkg_info' , '-QLa' ] ret = __salt__ [ 'cmd.run_all' ] ( cmd , output_loglevel = 'trace' , python_shell = False ) for line in ret [ 'stderr...
def _compute_unnecessary_deps ( self , target , actual_deps ) : """Computes unused deps for the given Target . : returns : A dict of directly declared but unused targets , to sets of suggested replacements ."""
# Flatten the product deps of this target . product_deps = set ( ) for dep_entries in actual_deps . values ( ) : product_deps . update ( dep_entries ) # Determine which of the DEFAULT deps in the declared set of this target were used . used = set ( ) unused = set ( ) for dep , _ in self . _analyzer . resolve_aliase...
def increment_name ( self , name , i ) : """takes something like test . txt and returns test1 . txt"""
if i == 0 : return name if '.' in name : split = name . split ( '.' ) split [ - 2 ] = split [ - 2 ] + str ( i ) return '.' . join ( split ) else : return name + str ( i )
def get_value ( self , eval_width = None ) : """Build a resolved ComponentRef container that describes the relative path"""
resolved_ref_elements = [ ] for name , array_suffixes , name_src_ref in self . ref_elements : idx_list = [ suffix . get_value ( ) for suffix in array_suffixes ] resolved_ref_elements . append ( ( name , idx_list , name_src_ref ) ) # Create container cref = rdltypes . ComponentRef ( self . ref_root , resolved_re...
def label ( self ) : """Convert a module name to a formatted node label . This is a default policy - please override ."""
if len ( self . name ) > 14 and '.' in self . name : return '\\.\\n' . join ( self . name . split ( '.' ) ) # pragma : nocover return self . name
def wait_for_status ( self , status , status_timeout = None ) : """Wait until the status of this partition has a desired value . Parameters : status ( : term : ` string ` or iterable of : term : ` string ` ) : Desired partition status or set of status values to reach ; one or more of the values defined for ...
if status_timeout is None : status_timeout = self . manager . session . retry_timeout_config . status_timeout if status_timeout > 0 : end_time = time . time ( ) + status_timeout if isinstance ( status , ( list , tuple ) ) : statuses = status else : statuses = [ status ] while True : # Fastest way to get...
def verify_keys ( app_req , required_keys , issuer = None ) : """Verify all JWT object keys listed in required _ keys . Each required key is specified as a dot - separated path . The key values are returned as a list ordered by how you specified them . Take this JWT for example : : " iss " : " . . . " , ...
if not issuer : issuer = _get_issuer ( app_req = app_req ) key_vals = [ ] for key_path in required_keys : parent = app_req for kp in key_path . split ( '.' ) : if not isinstance ( parent , dict ) : raise InvalidJWT ( 'JWT is missing %r: %s is not a dict' % ( key_path , kp ) , issuer = is...
def _expectation ( self , prep_prog , operator_programs , random_seed ) -> np . ndarray : """Run a Forest ` ` expectation ` ` job . Users should use : py : func : ` WavefunctionSimulator . expectation ` instead of calling this directly ."""
if isinstance ( operator_programs , Program ) : warnings . warn ( "You have provided a Program rather than a list of Programs. The results " "from expectation will be line-wise expectation values of the " "operator_programs." , SyntaxWarning ) payload = expectation_payload ( prep_prog , operator_programs , random_s...
def from_unit_to_satoshi ( self , value , unit = 'satoshi' ) : """Convert a value to satoshis . units can be any fiat currency . By default the unit is satoshi ."""
if not unit or unit == 'satoshi' : return value if unit == 'bitcoin' or unit == 'btc' : return value * 1e8 # assume fiat currency that we can convert convert = get_current_price ( self . crypto , unit ) return int ( value / convert * 1e8 )
def parse_value ( self , value ) : """Parse value to proper model type ."""
if not isinstance ( value , dict ) : return value embed_type = self . _get_embed_type ( ) return embed_type ( ** value )
def build ( self , builder ) : """Build XML by appending to builder"""
params = dict ( OID = self . oid , Language = self . language ) builder . start ( "mdsol:CustomFunctionDef" , params ) builder . data ( self . code ) builder . end ( "mdsol:CustomFunctionDef" )
def pollNextOverlayEvent ( self , ulOverlayHandle , uncbVREvent ) : """Returns true and fills the event with the next event on the overlay ' s event queue , if there is one . If there are no events this method returns false . uncbVREvent should be the size in bytes of the VREvent _ t struct"""
fn = self . function_table . pollNextOverlayEvent pEvent = VREvent_t ( ) result = fn ( ulOverlayHandle , byref ( pEvent ) , uncbVREvent ) return result , pEvent
def adjacent ( self , node_a , node_b ) : """Determines whether there is an edge from node _ a to node _ b . Returns True if such an edge exists , otherwise returns False ."""
neighbors = self . neighbors ( node_a ) return node_b in neighbors
def _proxy ( self ) : """Generate an instance context for the instance , the context is capable of performing various actions . All instance actions are proxied to the context : returns : TaskChannelContext for this TaskChannelInstance : rtype : twilio . rest . taskrouter . v1 . workspace . task _ channel . T...
if self . _context is None : self . _context = TaskChannelContext ( self . _version , workspace_sid = self . _solution [ 'workspace_sid' ] , sid = self . _solution [ 'sid' ] , ) return self . _context
def hex_to_hsv ( color ) : """Converts from hex to hsv Parameters : color : string Color representation on color Example : hex _ to _ hsv ( ' # ff9933 ' )"""
color = normalize ( color ) color = color [ 1 : ] # color = tuple ( ord ( c ) / 255.0 for c in color . decode ( ' hex ' ) ) color = ( int ( color [ 0 : 2 ] , base = 16 ) / 255.0 , int ( color [ 2 : 4 ] , base = 16 ) / 255.0 , int ( color [ 4 : 6 ] , base = 16 ) / 255.0 ) return colorsys . rgb_to_hsv ( * color )
def clip_lower ( self , threshold ) : """Create new SArray with all values clipped to the given lower bound . This function can operate on numeric arrays , as well as vector arrays , in which case each individual element in each vector is clipped . Throws an exception if the SArray is empty or the types are n...
with cython_context ( ) : return SArray ( _proxy = self . __proxy__ . clip ( threshold , float ( 'nan' ) ) )
def find_default_container ( builder , # type : HasReqsHints default_container = None , # type : Text use_biocontainers = None , # type : bool ) : # type : ( . . . ) - > Optional [ Text ] """Default finder for default containers ."""
if not default_container and use_biocontainers : default_container = get_container_from_software_requirements ( use_biocontainers , builder ) return default_container
def connect ( self ) : """Enumerate and connect to the first USB HID interface ."""
try : return comm . getDongle ( ) except comm . CommException as e : raise interface . NotFoundError ( '{} not connected: "{}"' . format ( self , e ) )
def smp_to_ins ( smp_filename , ins_filename = None , use_generic_names = False , gwutils_compliant = False , datetime_format = None , prefix = '' ) : """create an instruction file for an smp file Parameters smp _ filename : str existing smp file ins _ filename : str instruction file to create . If None ,...
if ins_filename is None : ins_filename = smp_filename + ".ins" df = smp_to_dataframe ( smp_filename , datetime_format = datetime_format ) df . loc [ : , "ins_strings" ] = None df . loc [ : , "observation_names" ] = None name_groups = df . groupby ( "name" ) . groups for name , idxs in name_groups . items ( ) : ...
def __get_value ( self , bundleId , languageId , resourceKey , fallback = False ) : """Returns the value for the key . If fallback is ` ` True ` ` , source language value is used if translated value is not available . If the key is not found , returns ` ` None ` ` ."""
resourceEntryData = self . __get_resource_entry_data ( bundleId = bundleId , languageId = languageId , resourceKey = resourceKey , fallback = fallback ) if not resourceEntryData : return None value = resourceEntryData . get ( self . __RESPONSE_TRANSLATION_KEY ) return value
def get_all_message_ids_in_chat ( self , chat , include_me = False , include_notifications = False ) : """Fetches message ids in chat : param include _ me : Include user ' s messages : type include _ me : bool or None : param include _ notifications : Include events happening on chat : type include _ notifi...
return self . wapi_functions . getAllMessageIdsInChat ( chat . id , include_me , include_notifications )
def translate ( text , target_lang = 'en' , source_lang = None ) : """Use the Google v2 API to translate the text . You had better have set the API key on this function before calling it ."""
url_base = 'https://www.googleapis.com/language/translate/v2' params = dict ( key = translate . API_key , q = text , target = target_lang , ) if source_lang : params [ 'source' ] = source_lang resp = requests . get ( url_base , params = params ) resp . raise_for_status ( ) return resp . json ( ) [ 'data' ] [ 'trans...
def api_url ( self , ** kwargs ) : """The URL for making the given query against the API ."""
query = { 'Operation' : self . Operation , 'Service' : "AWSECommerceService" , 'Timestamp' : time . strftime ( "%Y-%m-%dT%H:%M:%SZ" , time . gmtime ( ) ) , 'Version' : self . Version , } query . update ( kwargs ) query [ 'AWSAccessKeyId' ] = self . AWSAccessKeyId query [ 'Timestamp' ] = time . strftime ( "%Y-%m-%dT%H:%...
def run ( self , tmp = None , task_vars = None ) : """Override run ( ) to notify Connection of task - specific data , so it has a chance to know e . g . the Python interpreter in use ."""
self . _connection . on_action_run ( task_vars = task_vars , delegate_to_hostname = self . _task . delegate_to , loader_basedir = self . _loader . get_basedir ( ) , ) return super ( ActionModuleMixin , self ) . run ( tmp , task_vars )
def create_groups ( iam_client , groups ) : """Create a number of IAM group , silently handling exceptions when entity already exists : param iam _ client : AWS API client for IAM : param groups : Name of IAM groups to be created . : return : None"""
groups_data = [ ] if type ( groups ) != list : groups = [ groups ] for group in groups : errors = [ ] try : printInfo ( 'Creating group %s...' % group ) iam_client . create_group ( GroupName = group ) except Exception as e : if e . response [ 'Error' ] [ 'Code' ] != 'EntityAlread...
def resendFaxRN ( self , CorpNum , OrgRequestNum , SenderNum , SenderName , ReceiverNum , ReceiverName , ReserveDT = None , UserID = None , title = None , RequestNum = None ) : """팩스 단건 전송 args CorpNum : 팝빌회원 사업자번호 OrgRequestNum : 원본 팩스 전송시 할당한 전송요청번호 Rec...
receivers = None if ReceiverNum != "" or ReceiverName != "" : receivers = [ ] receivers . append ( FaxReceiver ( receiveNum = ReceiverNum , receiveName = ReceiverName ) ) return self . resendFaxRN_multi ( CorpNum , OrgRequestNum , SenderNum , SenderName , receivers , ReserveDT , UserID , title , RequestNum )
def base64_b64decode ( instr ) : '''Decode a base64 - encoded string using the " modern " Python interface .'''
decoded = base64 . b64decode ( salt . utils . stringutils . to_bytes ( instr ) ) try : return salt . utils . stringutils . to_unicode ( decoded , encoding = 'utf8' if salt . utils . platform . is_windows ( ) else None ) except UnicodeDecodeError : return decoded
def approvecommittee ( ctx , members , account ) : """Approve committee member ( s )"""
print_tx ( ctx . bitshares . approvecommittee ( members , account = account ) )
def list_tags ( ) : '''Returns a list of tagged images CLI Example : . . code - block : : bash salt myminion docker . list _ tags'''
ret = set ( ) for item in six . itervalues ( images ( ) ) : if not item . get ( 'RepoTags' ) : continue ret . update ( set ( item [ 'RepoTags' ] ) ) return sorted ( ret )
def extract_full ( rec , sites , flank , fw ) : """Full extraction of seq flanking the sites ."""
for s in sites : newid = "{0}:{1}" . format ( rec . name , s ) left = max ( s - flank , 0 ) right = min ( s + flank , len ( rec ) ) frag = rec . seq [ left : right ] . strip ( "Nn" ) newrec = SeqRecord ( frag , id = newid , description = "" ) SeqIO . write ( [ newrec ] , fw , "fasta" )
def create_user ( self , instance , name , password , database_names , host = None ) : """Creates a user with the specified name and password , and gives that user access to the specified database ( s ) ."""
return instance . create_user ( name = name , password = password , database_names = database_names , host = host )
def check_ip_address_availability ( ip_address , virtual_network , resource_group , ** kwargs ) : '''. . versionadded : : 2019.2.0 Check that a private ip address is available within the specified virtual network . : param ip _ address : The ip _ address to query . : param virtual _ network : The virtual ne...
netconn = __utils__ [ 'azurearm.get_client' ] ( 'network' , ** kwargs ) try : check_ip = netconn . virtual_networks . check_ip_address_availability ( resource_group_name = resource_group , virtual_network_name = virtual_network , ip_address = ip_address ) result = check_ip . as_dict ( ) except CloudError as exc...
def sendLocalFiles ( self , file_paths , message = None , thread_id = None , thread_type = ThreadType . USER ) : """Sends local files to a thread : param file _ paths : Paths of files to upload and send : param message : Additional message : param thread _ id : User / Group ID to send to . See : ref : ` intro...
file_paths = require_list ( file_paths ) with get_files_from_paths ( file_paths ) as x : files = self . _upload ( x ) return self . _sendFiles ( files = files , message = message , thread_id = thread_id , thread_type = thread_type )
def _load_embedding ( self , pretrained_file_path , elem_delim , encoding = 'utf8' ) : """Load embedding vectors from a pre - trained token embedding file . Both text files and TokenEmbedding serialization files are supported . elem _ delim and encoding are ignored for non - text files . For every unknown tok...
pretrained_file_path = os . path . expanduser ( pretrained_file_path ) if not os . path . isfile ( pretrained_file_path ) : raise ValueError ( '`pretrained_file_path` must be a valid path ' 'to the pre-trained token embedding file.' ) logging . info ( 'Loading pre-trained token embedding vectors from %s' , pretrain...
def ring_source ( self ) : """The source of the interaction with the ring . If the source is : attr : ` ~ libinput . constant . TabletPadRingAxisSource . FINGER ` , libinput sends a ring position value of - 1 to terminate the current interaction . For events not of type : attr : ` ~ libinput . constant ...
if self . type != EventType . TABLET_PAD_RING : raise AttributeError ( _wrong_prop . format ( self . type ) ) return self . _libinput . libinput_event_tablet_pad_get_ring_source ( self . _handle )
def updateattachmentflags ( self , bugid , attachid , flagname , ** kwargs ) : """Updates a flag for the given attachment ID . Optional keyword args are : status : new status for the flag ( ' - ' , ' + ' , ' ? ' , ' X ' ) requestee : new requestee for the flag"""
# Bug ID was used for the original custom redhat API , no longer # needed though ignore = bugid flags = { "name" : flagname } flags . update ( kwargs ) update = { 'ids' : [ int ( attachid ) ] , 'flags' : [ flags ] } return self . _proxy . Bug . update_attachment ( update )
def monitor ( self , name , handler , request = None , ** kws ) : """Begin subscription to named PV : param str name : PV name string : param callable handler : Completion notification . Called with None ( FIFO not empty ) , RemoteError , Cancelled , or Disconnected : param request : A : py : class : ` p4p . ...
chan = self . _channel ( name ) return Subscription ( context = self , nt = self . _nt , channel = chan , handler = monHandler ( handler ) , pvRequest = wrapRequest ( request ) , ** kws )
def _print_dict ( elem_dict ) : """Print a dict in a readable way"""
for key , value in sorted ( elem_dict . iteritems ( ) ) : if isinstance ( value , collections . Iterable ) : print ( key , len ( value ) ) else : print ( key , value )
def routeevent ( self , path , routinemethod , container = None , host = None , vhost = None , method = [ b'GET' , b'HEAD' ] ) : '''Route specified path to a routine factory : param path : path to match , can be a regular expression : param routinemethod : factory function routinemethod ( event ) , event is the...
regm = re . compile ( path + b'$' ) if vhost is None : vhost = self . vhost if container is None : container = getattr ( routinemethod , '__self__' , None ) def ismatch ( event ) : # Check vhost if vhost is not None and getattr ( event . createby , 'vhost' , '' ) != vhost : return False # First ...
def _string_to_sign ( item , table_name , attribute_actions ) : # type : ( dynamodb _ types . ITEM , Text , AttributeActions ) - > bytes """Generate the string to sign from an encrypted item and configuration . : param dict item : Encrypted DynamoDB item : param str table _ name : Table name to use when generat...
hasher = hashes . Hash ( hashes . SHA256 ( ) , backend = default_backend ( ) ) data_to_sign = bytearray ( ) data_to_sign . extend ( _hash_data ( hasher = hasher , data = "TABLE>{}<TABLE" . format ( table_name ) . encode ( TEXT_ENCODING ) ) ) for key in sorted ( item . keys ( ) ) : action = attribute_actions . actio...
def get_space_system ( self , name ) : """Gets a single space system by its unique name . : param str name : A fully - qualified XTCE name : rtype : . SpaceSystem"""
url = '/mdb/{}/space-systems{}' . format ( self . _instance , name ) response = self . _client . get_proto ( url ) message = mdb_pb2 . SpaceSystemInfo ( ) message . ParseFromString ( response . content ) return SpaceSystem ( message )
def _parse_module_with_import ( self , uri ) : """Look for functions and classes in an importable module . Parameters uri : str The name of the module to be parsed . This module needs to be importable . Returns functions : list of str A list of ( public ) function names in the module . classes : lis...
mod = __import__ ( uri , fromlist = [ uri ] ) # find all public objects in the module . obj_strs = [ obj for obj in dir ( mod ) if not obj . startswith ( '_' ) ] functions = [ ] classes = [ ] for obj_str in obj_strs : # find the actual object from its string representation if obj_str not in mod . __dict__ : ...
def from_file ( cls , fmt , filename = None , structure_file = None , are_coops = False ) : """Creates a CompleteCohp object from an output file of a COHP calculation . Valid formats are either LMTO ( for the Stuttgart LMTO - ASA code ) or LOBSTER ( for the LOBSTER code ) . Args : cohp _ file : Name of the ...
fmt = fmt . upper ( ) if fmt == "LMTO" : # LMTO COOPs and orbital - resolved COHP cannot be handled yet . are_coops = False orb_res_cohp = None if structure_file is None : structure_file = "CTRL" if filename is None : filename = "COPL" cohp_file = LMTOCopl ( filename = filename , to_...
def setCurrentRegItem ( self , regItem ) : """Sets the current registry item ."""
rowIndex = self . model ( ) . indexFromItem ( regItem ) if not rowIndex . isValid ( ) : logger . warn ( "Can't select {!r} in table" . format ( regItem ) ) self . setCurrentIndex ( rowIndex )
def _load ( self , reload = False ) : """Load text of fcatalog file and pass to parse Will do nothing if autoreload is off and reload is not explicitly requested"""
if self . autoreload or reload : # First , we load from YAML , failing if syntax errors are found options = self . storage_options or { } if hasattr ( self . path , 'path' ) or hasattr ( self . path , 'read' ) : file_open = self . path self . path = make_path_posix ( getattr ( self . path , 'pat...
def verify_request_monitoring ( self , partner_address : Address , requesting_address : Address , ) -> bool : """One should only use this method to verify integrity and signatures of a RequestMonitoring message ."""
if not self . non_closing_signature : return False balance_proof_data = pack_balance_proof ( nonce = self . balance_proof . nonce , balance_hash = self . balance_proof . balance_hash , additional_hash = self . balance_proof . additional_hash , canonical_identifier = CanonicalIdentifier ( chain_identifier = self . b...
def export_wif ( self ) -> str : """This interface is used to get export ECDSA private key in the form of WIF which is a way to encoding an ECDSA private key and make it easier to copy . : return : a WIF encode private key ."""
data = b'' . join ( [ b'\x80' , self . __private_key , b'\01' ] ) checksum = Digest . hash256 ( data [ 0 : 34 ] ) wif = base58 . b58encode ( b'' . join ( [ data , checksum [ 0 : 4 ] ] ) ) return wif . decode ( 'ascii' )
def _CreateAllTypes ( self , enumTypes , dataTypes , managedTypes ) : """Create pyVmomi types from pyVmomi type definitions"""
# Create versions for typeInfo in managedTypes : name = typeInfo [ 0 ] version = typeInfo [ 3 ] VmomiSupport . AddVersion ( version , '' , '1.0' , 0 , name ) VmomiSupport . AddVersionParent ( version , 'vmodl.version.version0' ) VmomiSupport . AddVersionParent ( version , 'vmodl.version.version1' ) ...
def ground_motion_fields ( rupture , sites , imts , gsim , truncation_level , realizations , correlation_model = None , seed = None ) : """Given an earthquake rupture , the ground motion field calculator computes ground shaking over a set of sites , by randomly sampling a ground shaking intensity model . A grou...
cmaker = ContextMaker ( rupture . tectonic_region_type , [ gsim ] ) gc = GmfComputer ( rupture , sites , [ str ( imt ) for imt in imts ] , cmaker , truncation_level , correlation_model ) res , _sig , _eps = gc . compute ( gsim , realizations , seed ) return { imt : res [ imti ] for imti , imt in enumerate ( gc . imts )...
def merge_results ( old_results , new_results ) : """Update results in baseline with latest information . : type old _ results : dict : param old _ results : results of status quo : type new _ results : dict : param new _ results : results to replace status quo : rtype : dict"""
for filename , old_secrets in old_results . items ( ) : if filename not in new_results : continue old_secrets_mapping = dict ( ) for old_secret in old_secrets : old_secrets_mapping [ old_secret [ 'hashed_secret' ] ] = old_secret for new_secret in new_results [ filename ] : if new...
def _orderby_sql ( self , quote_char = None , ** kwargs ) : """Produces the ORDER BY part of the query . This is a list of fields and possibly their directionality , ASC or DESC . The clauses are stored in the query under self . _ orderbys as a list of tuples containing the field and directionality ( which can ...
clauses = [ ] selected_aliases = { s . alias for s in self . base_query . _selects } for field , directionality in self . _orderbys : term = "{quote}{alias}{quote}" . format ( alias = field . alias , quote = quote_char or '' ) if field . alias and field . alias in selected_aliases else field . get_sql ( quote_char ...
def named_objs ( objlist , namesdict = None ) : """Given a list of objects , returns a dictionary mapping from string name for the object to the object itself . Accepts an optional name , obj dictionary , which will override any other name if that item is present in the dictionary ."""
objs = OrderedDict ( ) if namesdict is not None : objtoname = { hashable ( v ) : k for k , v in namesdict . items ( ) } for obj in objlist : if namesdict is not None and hashable ( obj ) in objtoname : k = objtoname [ hashable ( obj ) ] elif hasattr ( obj , "name" ) : k = obj . name elif...
def unsubscribe ( self , subscription ) : """Allows endpoint owner to delete subscription . Confirmation message will be delivered . : type subscription : string : param subscription : The ARN of the subscription to be deleted ."""
params = { 'ContentType' : 'JSON' , 'SubscriptionArn' : subscription } response = self . make_request ( 'Unsubscribe' , params , '/' , 'GET' ) body = response . read ( ) if response . status == 200 : return json . loads ( body ) else : boto . log . error ( '%s %s' % ( response . status , response . reason ) ) ...
def set_rd ( self , vrf_name , rd ) : """Configures the VRF rd ( route distinguisher ) Note : A valid RD has the following format admin _ ID : local _ assignment . The admin _ ID can be an AS number or globally assigned IPv4 address . The local _ assignment can be an integer between 0-65,535 if the admin _ ...
cmds = self . command_builder ( 'rd' , value = rd ) return self . configure_vrf ( vrf_name , cmds )
def dot_format ( out , graph , name = "digraph" ) : """Outputs the graph using the graphviz " dot " format ."""
out . write ( "digraph %s {\n" % name ) for step , deps in each_step ( graph ) : for dep in deps : out . write ( " \"%s\" -> \"%s\";\n" % ( step , dep ) ) out . write ( "}\n" )
def put ( self , url_path , data ) : """Update an existing object on the JSS . In general , it is better to use a higher level interface for updating objects , namely , making changes to a JSSObject subclass and then using its save method . Args : url _ path : String API endpoint path to PUT , with ID ( e...
request_url = "%s%s" % ( self . _url , url_path ) data = ElementTree . tostring ( data ) response = self . session . put ( request_url , data ) if response . status_code == 201 and self . verbose : print "PUT %s: Success." % request_url elif response . status_code >= 400 : error_handler ( JSSPutError , response...
def add_inter_group_bonds ( data_api , struct_inflator ) : """Generate inter group bonds . Bond indices are specified within the whole structure and start at 0. : param data _ api the interface to the decoded data : param struct _ inflator the interface to put the data into the client object"""
for i in range ( len ( data_api . bond_order_list ) ) : struct_inflator . set_inter_group_bond ( data_api . bond_atom_list [ i * 2 ] , data_api . bond_atom_list [ i * 2 + 1 ] , data_api . bond_order_list [ i ] )
def view_as_consumer ( wrapped_view : typing . Callable [ [ HttpRequest ] , HttpResponse ] , mapped_actions : typing . Optional [ typing . Dict [ str , str ] ] = None ) -> Type [ AsyncConsumer ] : """Wrap a django View so that it will be triggered by actions over this json websocket consumer ."""
if mapped_actions is None : mapped_actions = { 'create' : 'PUT' , 'update' : 'PATCH' , 'list' : 'GET' , 'retrieve' : 'GET' } class DjangoViewWrapper ( DjangoViewAsConsumer ) : view = wrapped_view actions = mapped_actions return DjangoViewWrapper
def detach_usb_device ( self , id_p , done ) : """Notification that a VM is going to detach ( @ a done = @ c false ) or has already detached ( @ a done = @ c true ) the given USB device . When the @ a done = @ c true request is completed , the VM process will get a : py : func : ` IInternalSessionControl . on...
if not isinstance ( id_p , basestring ) : raise TypeError ( "id_p can only be an instance of type basestring" ) if not isinstance ( done , bool ) : raise TypeError ( "done can only be an instance of type bool" ) self . _call ( "detachUSBDevice" , in_p = [ id_p , done ] )
def delete ( gandi , resource , background , force ) : """Delete one or more IPs ( after detaching them from VMs if necessary ) . resource can be an ip id or ip ."""
resource = sorted ( tuple ( set ( resource ) ) ) possible_resources = gandi . ip . resource_list ( ) # check that each IP can be deleted for item in resource : if item not in possible_resources : gandi . echo ( 'Sorry interface %s does not exist' % item ) gandi . echo ( 'Please use one of the follow...
def parse_args ( self , ctx , args ) : """Check if the first argument is an existing command ."""
if args and args [ 0 ] in self . commands : args . insert ( 0 , '' ) super ( OptionalGroup , self ) . parse_args ( ctx , args )
def setBackgroundBrush ( self , brush ) : """Sets the background brush for this node scene . This will replace the default method as a convenience wrapper around the XNodePalette associated with this scene . : param color | < str > | | < QColor > | | < QBrush >"""
if type ( brush ) == str : brush = QBrush ( QColor ( brush ) ) elif type ( brush ) == QColor : brush = QBrush ( brush ) elif type ( brush ) != QBrush : return # update the palette color palette = self . palette ( ) palette . setColor ( palette . GridBackground , brush . color ( ) ) super ( XNodeScene , self...
def _potential_cross_partial_w ( moment_index : int , op : ops . Operation , state : _OptimizerState ) -> None : """Cross the held W over a partial W gate . [ Where W ( a ) is shorthand for PhasedX ( phase _ exponent = a ) . ] Uses the following identity : ─ ─ ─ W ( a ) ─ ─ ─ W ( b ) ^ t ─ ─ ─ ≡ ─ ─ ─ Z ^ -...
a = state . held_w_phases . get ( op . qubits [ 0 ] ) if a is None : return exponent , phase_exponent = cast ( Tuple [ float , float ] , _try_get_known_phased_pauli ( op ) ) new_op = ops . PhasedXPowGate ( exponent = exponent , phase_exponent = 2 * a - phase_exponent ) . on ( op . qubits [ 0 ] ) state . deletions ....
def clean ( self ) : """check the content of each field : return :"""
cleaned_data = super ( UserServiceForm , self ) . clean ( ) sa = ServicesActivated . objects . get ( name = self . initial [ 'name' ] ) # set the name of the service , related to ServicesActivated model cleaned_data [ 'name' ] = sa if sa . auth_required and sa . self_hosted : if cleaned_data . get ( 'host' ) == '' ...
def is_entailed_by ( self , other ) : """If the other is as or more specific than self"""
other = BoolCell . coerce ( other ) if self . value == U or other . value == self . value : return True return False
def _set_fcoe_map_cee_map ( self , v , load = False ) : """Setter method for fcoe _ map _ cee _ map , mapped from YANG variable / fcoe / fcoe _ map / fcoe _ map _ cee _ map ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ fcoe _ map _ cee _ map is considere...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = fcoe_map_cee_map . fcoe_map_cee_map , is_container = 'container' , presence = False , yang_name = "fcoe-map-cee-map" , rest_name = "cee-map" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethod...
def end_episode ( self ) : """A signal that the Episode has ended . The buffer must be reset . Get only called when the academy resets ."""
self . training_buffer . reset_local_buffers ( ) for agent_id in self . cumulative_rewards : self . cumulative_rewards [ agent_id ] = 0 for agent_id in self . episode_steps : self . episode_steps [ agent_id ] = 0 if self . use_curiosity : for agent_id in self . intrinsic_rewards : self . intrinsic_r...
def resources_of_config ( config ) : """Returns all resources and models from config ."""
return set ( # unique values sum ( [ # join lists to flat list list ( value ) # if value is iter ( ex : list of resources ) if hasattr ( value , '__iter__' ) else [ value , ] # if value is not iter ( ex : model or resource ) for value in config . values ( ) ] , [ ] ) )
def _complete_pot_years ( self , pot_dataset ) : """Return a tuple of a list of : class : ` PotRecord ` s filtering out part - complete years ; and the number of complete years . This method creates complete years by ensuring there is an equal number of each month in the entire record , taking into account da...
# Create a list of 12 sets , one for each month . Each set represents the years for which the POT record includes # a particular month . month_counts = self . _pot_month_counts ( pot_dataset ) # Number of complete years n = min ( [ len ( month ) for month in month_counts ] ) # Use the last available years only such tha...
def remove_api_gateway_logs ( self , project_name ) : """Removed all logs that are assigned to a given rest api id ."""
for rest_api in self . get_rest_apis ( project_name ) : for stage in self . apigateway_client . get_stages ( restApiId = rest_api [ 'id' ] ) [ 'item' ] : self . remove_log_group ( 'API-Gateway-Execution-Logs_{}/{}' . format ( rest_api [ 'id' ] , stage [ 'stageName' ] ) )
def devices ( self ) : """Return all devices on Arlo account ."""
if self . _all_devices : return self . _all_devices self . _all_devices = { } self . _all_devices [ 'cameras' ] = [ ] self . _all_devices [ 'base_station' ] = [ ] url = DEVICES_ENDPOINT data = self . query ( url ) for device in data . get ( 'data' ) : name = device . get ( 'deviceName' ) if ( ( device . get...
def sql_dequote_string ( s : str ) -> str : """Reverses sql _ quote _ string ."""
if len ( s ) < 2 : # Something wrong . return s s = s [ 1 : - 1 ] # strip off the surrounding quotes return s . replace ( "''" , "'" )
def get_default_library_patters ( ) : """Returns library paths depending on the used platform . : return : a list of glob paths"""
python_version = platform . python_version_tuple ( ) python_implementation = platform . python_implementation ( ) system = platform . system ( ) if python_implementation == "PyPy" : if python_version [ 0 ] == "2" : return [ "*/lib-python/%s.%s/*" % python_version [ : 2 ] , "*/site-packages/*" ] else : ...
def validate_account_user_email ( self , account_id , user_id , ** kwargs ) : # noqa : E501 """Validate the user email . # noqa : E501 An endpoint for validating the user email . * * Example usage : * * ` curl - X POST https : / / api . us - east - 1 . mbedcloud . com / v3 / accounts / { accountID } / users / { u...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . validate_account_user_email_with_http_info ( account_id , user_id , ** kwargs ) # noqa : E501 else : ( data ) = self . validate_account_user_email_with_http_info ( account_id , user_id , ** kwargs ) # noqa : E5...