signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def memo ( f ) : "Return a function like f that remembers and reuses results of past calls ."
table = { } def memo_f ( * args ) : try : return table [ args ] except KeyError : table [ args ] = value = f ( * args ) return value return memo_f
def set_dial ( self , json_value , index , timezone = None ) : """: param json _ value : The value to set : param index : The dials index : param timezone : The time zone to use for a time dial : return :"""
values = self . json_state values [ "nonce" ] = str ( random . randint ( 0 , 1000000000 ) ) if timezone is None : json_value [ "channel_configuration" ] = { "channel_id" : "10" } values [ "dials" ] [ index ] = json_value response = self . api_interface . set_device_state ( self , values ) else : json_va...
def step ( self , action ) : """gym api step"""
obs = None reward = None info = None turn = True withturnkey = self . step_options < 2 withinfo = self . step_options == 0 or self . step_options == 2 while not self . done and ( ( obs is None or len ( obs ) == 0 ) or ( withinfo and info is None ) or turn ) : step_message = "<Step" + str ( self . step_options ) + "...
def split ( self ) : """Start parsing the pattern ."""
split_index = [ ] parts = [ ] start = - 1 pattern = self . pattern . decode ( 'latin-1' ) if self . is_bytes else self . pattern i = util . StringIter ( pattern ) iter ( i ) # Detect and store away windows drive as a literal if self . win_drive_detect : m = RE_WIN_PATH . match ( pattern ) if m : drive =...
def cloud_front_origin_access_identity_exists ( Id , region = None , key = None , keyid = None , profile = None ) : '''Return True if a CloudFront origin access identity exists with the given Resource ID or False otherwise . Id Resource ID of the CloudFront origin access identity . region Region to connec...
authargs = { 'region' : region , 'key' : key , 'keyid' : keyid , 'profile' : profile } oais = list_cloud_front_origin_access_identities ( ** authargs ) or [ ] return bool ( [ i [ 'Id' ] for i in oais if i [ 'Id' ] == Id ] )
def search_by_attribute_set ( url : str , profile : Tuple [ str ] , limit : Optional [ int ] = 100 , namespace_filter : Optional [ str ] = None ) -> Dict : """Given a list of phenotypes , returns a ranked list of individuals individuals can be filtered by namespace , eg MONDO , MGI , HGNC : returns Dict with th...
owlsim_url = url + 'searchByAttributeSet' params = { 'a' : profile , 'limit' : limit , 'target' : namespace_filter } return requests . get ( owlsim_url , params = params , timeout = TIMEOUT ) . json ( )
def parse ( cls , content , basedir = None , resolve = True , unresolved_value = DEFAULT_SUBSTITUTION ) : """parse a HOCON content : param content : HOCON content to parse : type content : basestring : param resolve : if true , resolve substitutions : type resolve : boolean : param unresolved _ value : as...
unescape_pattern = re . compile ( r'\\.' ) def replace_escape_sequence ( match ) : value = match . group ( 0 ) return cls . REPLACEMENTS . get ( value , value ) def norm_string ( value ) : return unescape_pattern . sub ( replace_escape_sequence , value ) def unescape_string ( tokens ) : return ConfigUnq...
def mousePressEvent ( self , event ) : """Make sure on a mouse release event that we have a current item . If no item is current , then our edit item will become current . : param event | < QMouseReleaseEvent >"""
item = self . itemAt ( event . pos ( ) ) # set the tag creation item as active if item is None : create_item = self . createItem ( ) if create_item : self . setCurrentItem ( create_item ) self . editItem ( create_item ) # check to see if we ' re removing a tag else : rect = self . visualItem...
def overwriteComponent ( self , comp , row , col ) : """Overwrites the component at the specficied location with a provided one . : param comp : New component to insert : type comp : : class : ` AbstractStimulusComponent < sparkle . stim . abstract _ component . AbstractStimulusComponent > ` : param row : tra...
self . _segments [ row ] [ col ] = comp # in case of samplerate change , just always update self . updateCalibration ( )
def end_script ( self ) : """Indicate that we have finished receiving a script ."""
if self . remote_bridge . status not in ( BRIDGE_STATUS . RECEIVED , BRIDGE_STATUS . WAITING ) : return [ 1 ] # FIXME : State change self . remote_bridge . status = BRIDGE_STATUS . RECEIVED return [ 0 ]
def load_config ( self , config_path = None ) : """Load configuration from the specified path , or self . config _ path"""
if config_path is None : config_path = self . config_path else : self . config_path = config_path config = ConfigParser . SafeConfigParser ( self . DEFAULT_SUBSTITUTIONS , allow_no_value = True ) # Avoid the configparser automatically lowercasing keys config . optionxform = str self . initialize_config ( config...
def check_server_power ( ) : """Check if the server is powered on Skip this check , if the - - noPowerState is set"""
if power_state_flag : power_state = get_data ( sess , oid_power_state , helper ) power_state_summary_output , power_state_long_output = state_summary ( power_state , 'Server power' , server_power_state , helper , server_power_state [ 3 ] ) add_output ( power_state_summary_output , power_state_long_output , ...
def wait_for_workers ( self , min_n_workers = 1 ) : """helper function to hold execution until some workers are active Parameters min _ n _ workers : int minimum number of workers present before the run starts"""
self . logger . debug ( 'wait_for_workers trying to get the condition' ) with self . thread_cond : while ( self . dispatcher . number_of_workers ( ) < min_n_workers ) : self . logger . debug ( 'HBMASTER: only %i worker(s) available, waiting for at least %i.' % ( self . dispatcher . number_of_workers ( ) , m...
def resolveWithMib ( self , mibViewController ) : """Perform MIB variable ID conversion . Parameters mibViewController : : py : class : ` ~ pysnmp . smi . view . MibViewController ` class instance representing MIB browsing functionality . Returns : : py : class : ` ~ pysnmp . smi . rfc1902 . ObjectIdentit...
if self . _mibSourcesToAdd is not None : debug . logger & debug . FLAG_MIB and debug . logger ( 'adding MIB sources %s' % ', ' . join ( self . _mibSourcesToAdd ) ) mibViewController . mibBuilder . addMibSources ( * [ ZipMibSource ( x ) for x in self . _mibSourcesToAdd ] ) self . _mibSourcesToAdd = None if s...
def registrant_monitor ( self , query , exclude = [ ] , days_back = 0 , limit = None , ** kwargs ) : """One or more terms as a Python list or separated by the pipe character ( | ) ."""
return self . _results ( 'registrant-alert' , '/v1/registrant-alert' , query = delimited ( query ) , exclude = delimited ( exclude ) , days_back = days_back , limit = limit , items_path = ( 'alerts' , ) , ** kwargs )
def move_tab_from_another_tabwidget ( self , tabwidget_from , index_from , index_to ) : """Move tab from a tabwidget to another"""
# We pass self object IDs as QString objs , because otherwise it would # depend on the platform : long for 64bit , int for 32bit . Replacing # by long all the time is not working on some 32bit platforms # ( see Issue 1094 , Issue 1098) self . sig_move_tab . emit ( tabwidget_from , to_text_string ( id ( self ) ) , index...
def generic_visit ( self , node ) : """Surround node statement with a try / except block to catch errors . This method is called for every node of the parsed code , and only changes statement lines . Args : node ( ast . AST ) : node statement to surround ."""
if ( isinstance ( node , ast . stmt ) and not isinstance ( node , ast . FunctionDef ) ) : new_node = self . wrap_with_try ( node ) # handling try except statement if isinstance ( node , self . ast_try_except ) : self . try_except_handler ( node ) return new_node # Run recursively on all ...
def _probe_positions ( probe , group ) : """Return the positions of a probe channel group ."""
positions = probe [ 'channel_groups' ] [ group ] [ 'geometry' ] channels = _probe_channels ( probe , group ) return np . array ( [ positions [ channel ] for channel in channels ] )
def set_slimits ( self , min , max ) : """Set limits for the size of points in : meth : ` scatter _ table ` . If both are None , the size will be the given values . : param min : point size for the lowest value . : param max : point size for the highest value ."""
self . limits [ 'smin' ] = sqrt ( min ) self . limits [ 'smax' ] = sqrt ( max )
def intr_write ( self , dev_handle , ep , intf , data , timeout ) : r"""Perform an interrupt write . dev _ handle is the value returned by the open _ device ( ) method . The ep parameter is the bEndpointAddress field whose endpoint the data will be sent to . intf is the bInterfaceNumber field of the interfa...
_not_implemented ( self . intr_write )
def zrevrangebyscore ( self , name , max , min , start = None , num = None , withscores = False , score_cast_func = float ) : """Return a range of values from the sorted set ` ` name ` ` with scores between ` ` min ` ` and ` ` max ` ` in descending order . If ` ` start ` ` and ` ` num ` ` are specified , then r...
if ( start is not None and num is None ) or ( num is not None and start is None ) : raise DataError ( "``start`` and ``num`` must both be specified" ) pieces = [ 'ZREVRANGEBYSCORE' , name , max , min ] if start is not None and num is not None : pieces . extend ( [ Token . get_token ( 'LIMIT' ) , start , num ] )...
def dihedral ( x , dih ) : """Perform any of 8 permutations of 90 - degrees rotations or flips for image x ."""
x = np . rot90 ( x , dih % 4 ) return x if dih < 4 else np . fliplr ( x )
def get_uuid ( obj ) : """Return the uuid for obj , or null uuid if none is set"""
# TODO : deprecate null uuid ret val from uuid import UUID try : uuid = obj . attrs [ 'uuid' ] except KeyError : return UUID ( int = 0 ) # convert to unicode for python 3 try : uuid = uuid . decode ( 'ascii' ) except ( LookupError , AttributeError ) : pass return UUID ( uuid )
def encode ( self , data , content_encoding = "aes128gcm" ) : """Encrypt the data . : param data : A serialized block of byte data ( String , JSON , bit array , etc . ) Make sure that whatever you send , your client knows how to understand it . : type data : str : param content _ encoding : The content _ ...
# Salt is a random 16 byte array . if not data : return if not self . auth_key or not self . receiver_key : raise WebPushException ( "No keys specified in subscription info" ) salt = None if content_encoding not in self . valid_encodings : raise WebPushException ( "Invalid content encoding specified. " "Sel...
def register_plugin ( self ) : """Register plugin in Spyder ' s main window"""
ipyconsole = self . main . ipyconsole treewidget = self . fileexplorer . treewidget self . main . add_dockwidget ( self ) self . fileexplorer . sig_open_file . connect ( self . main . open_file ) self . register_widget_shortcuts ( treewidget ) treewidget . sig_edit . connect ( self . main . editor . load ) treewidget ....
def metrics_api ( self ) : """Helper for log metric - related API calls . See https : / / cloud . google . com / logging / docs / reference / v2 / rest / v2 / projects . metrics"""
if self . _metrics_api is None : if self . _use_grpc : self . _metrics_api = _gapic . make_metrics_api ( self ) else : self . _metrics_api = JSONMetricsAPI ( self ) return self . _metrics_api
def price_dec ( raw_price , default = _not_defined ) : """Price decimal value from raw string . Extract price value from input raw string and present as Decimal number . If raw price does not contain valid price value or contains more than one price value , then return default value . If default value not...
try : price = price_str ( raw_price ) return decimal . Decimal ( price ) except ValueError as err : if default == _not_defined : raise err return default
def set_size ( self , width_in_points , height_in_points ) : """Changes the size of a PostScript surface for the current ( and subsequent ) pages . This method should only be called before any drawing operations have been performed on the current page . The simplest way to do this is to call this method i...
cairo . cairo_ps_surface_set_size ( self . _pointer , width_in_points , height_in_points ) self . _check_status ( )
def devices ( self ) : """Return all devices ."""
service_root = self . webservices [ 'findme' ] [ 'url' ] return FindMyiPhoneServiceManager ( service_root , self . session , self . params )
def send_keysequence_window ( self , window , keysequence , delay = 12000 ) : """Send a keysequence to the specified window . This allows you to send keysequences by symbol name . Any combination of X11 KeySym names separated by ' + ' are valid . Single KeySym names are valid , too . Examples : " semicolo...
_libxdo . xdo_send_keysequence_window ( self . _xdo , window , keysequence , delay )
def restore_db_cluster_from_s3 ( AvailabilityZones = None , BackupRetentionPeriod = None , CharacterSetName = None , DatabaseName = None , DBClusterIdentifier = None , DBClusterParameterGroupName = None , VpcSecurityGroupIds = None , DBSubnetGroupName = None , Engine = None , EngineVersion = None , Port = None , Master...
pass
def invoke ( self , cli , args = None , prog_name = None , input = None , terminate_input = False , env = None , _output_lines = None , ** extra ) : """Like : meth : ` CliRunner . invoke ` but displays what the user would enter in the terminal for env vars , command args , and prompts . : param terminate _ in...
output_lines = _output_lines if _output_lines is not None else [ ] if env : for key , value in sorted ( env . items ( ) ) : value = shlex . quote ( value ) output_lines . append ( "$ export {}={}" . format ( key , value ) ) args = args or [ ] if prog_name is None : prog_name = cli . name . repla...
def MakeRn ( self ) : """This method returns the Rn for a managed object ."""
rnPattern = self . propMoMeta . rn for prop in re . findall ( "\[([^\]]*)\]" , rnPattern ) : if prop in UcsUtils . GetUcsPropertyMetaAttributeList ( self . classId ) : if ( self . getattr ( prop ) != None ) : rnPattern = re . sub ( '\[%s\]' % prop , '%s' % self . getattr ( prop ) , rnPattern ) ...
def create_file ( self , share_name , directory_name , file_name , content_length , content_settings = None , metadata = None , timeout = None ) : '''Creates a new file . See create _ file _ from _ * for high level functions that handle the creation and upload of large files with automatic chunking and progre...
_validate_not_none ( 'share_name' , share_name ) _validate_not_none ( 'file_name' , file_name ) _validate_not_none ( 'content_length' , content_length ) request = HTTPRequest ( ) request . method = 'PUT' request . host = self . _get_host ( ) request . path = _get_path ( share_name , directory_name , file_name ) request...
def cache ( * depends_on ) : """Caches function result in temporary file . Cache will be expired when modification date of files from ` depends _ on ` will be changed . Only functions should be wrapped in ` cache ` , not methods ."""
def cache_decorator ( fn ) : @ memoize @ wraps ( fn ) def wrapper ( * args , ** kwargs ) : if cache . disabled : return fn ( * args , ** kwargs ) else : return _cache . get_value ( fn , depends_on , args , kwargs ) return wrapper return cache_decorator
def notifications ( self ) : """gets the user ' s notifications"""
self . __init ( ) items = [ ] for n in self . _notifications : if "id" in n : url = "%s/%s" % ( self . root , n [ 'id' ] ) items . append ( self . Notification ( url = url , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port ) ) return items
def get_datastream_data ( self , datastream , options ) : """Get input data for the datastream : param datastream : string : param options : dict"""
response_format = None if options and 'format' in options and options [ 'format' ] is not None : response_format = options [ 'format' ] options [ 'format' ] = None url = '/datastream/' + str ( datastream ) + '/data' response = self . http . downstream ( url , response_format ) return response
def p_attr ( self , t ) : """attr : NAME ' . ' NAME | NAME ' . ' ' * '"""
# careful : sqex . infer _ columns relies on AttrX not containing anything but a name t [ 0 ] = AttrX ( NameX ( t [ 1 ] ) , AsterX ( ) if t [ 3 ] == '*' else NameX ( t [ 3 ] ) )
def trapezoidIntegration ( self , x , y ) : """Perform trapezoid integration . Parameters x : array _ like Wavelength set . y : array _ like Integrand . For example , throughput or throughput multiplied by wavelength . Returns sum : float Integrated sum ."""
npoints = x . size if npoints > 0 : indices = N . arange ( npoints ) [ : - 1 ] deltas = x [ indices + 1 ] - x [ indices ] integrand = 0.5 * ( y [ indices + 1 ] + y [ indices ] ) * deltas sum = integrand . sum ( ) if x [ - 1 ] < x [ 0 ] : sum *= - 1.0 return sum else : return 0.0
def init_app ( self , app ) : """Flask application initialization ."""
self . init_config ( app ) app . extensions [ 'invenio-pidrelations' ] = _InvenioPIDRelationsState ( app )
def users_profile_set ( self , ** kwargs ) -> SlackResponse : """Set the profile information for a user ."""
self . _validate_xoxp_token ( ) return self . api_call ( "users.profile.set" , json = kwargs )
def generate_displacements ( self , distance = 0.01 , is_plusminus = 'auto' , is_diagonal = True , is_trigonal = False ) : """Generate displacement dataset"""
displacement_directions = get_least_displacements ( self . _symmetry , is_plusminus = is_plusminus , is_diagonal = is_diagonal , is_trigonal = is_trigonal , log_level = self . _log_level ) displacement_dataset = directions_to_displacement_dataset ( displacement_directions , distance , self . _supercell ) self . set_dis...
def get_label ( self , indices = None ) : """Returns the label pair indices requested by the user @ In , indices , a list of non - negative integers specifying the row indices to return @ Out , a list of integer 2 - tuples specifying the minimum and maximum index of the specified rows ."""
if indices is None : indices = list ( range ( 0 , self . get_sample_size ( ) ) ) elif isinstance ( indices , collections . Iterable ) : indices = sorted ( list ( set ( indices ) ) ) else : indices = [ indices ] if len ( indices ) == 0 : return [ ] partitions = self . get_partitions ( self . persistence ...
def getTraceIdsByServiceName ( self , service_name , end_ts , limit , order ) : """Fetch trace ids by service name . Gets " limit " number of entries from before the " end _ ts " . Timestamps are in microseconds . Parameters : - service _ name - end _ ts - limit - order"""
self . send_getTraceIdsByServiceName ( service_name , end_ts , limit , order ) return self . recv_getTraceIdsByServiceName ( )
def create_api_service ( self , body , ** kwargs ) : # noqa : E501 """create _ api _ service # noqa : E501 create an APIService # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . create _ api _ se...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . create_api_service_with_http_info ( body , ** kwargs ) # noqa : E501 else : ( data ) = self . create_api_service_with_http_info ( body , ** kwargs ) # noqa : E501 return data
def create ( lr , betas = ( 0.9 , 0.999 ) , weight_decay = 0 , epsilon = 1e-8 , layer_groups = False ) : """Vel factory function"""
return AdamFactory ( lr = lr , betas = betas , weight_decay = weight_decay , eps = epsilon , layer_groups = layer_groups )
def sign_transaction ( self , signer : Account ) : """This interface is used to sign the transaction . : param signer : an Account object which will sign the transaction . : return : a Transaction object which has been signed ."""
tx_hash = self . hash256 ( ) sig_data = signer . generate_signature ( tx_hash ) sig = [ Sig ( [ signer . get_public_key_bytes ( ) ] , 1 , [ sig_data ] ) ] self . sig_list = sig
def delete_director_backend ( self , service_id , version_number , director_name , backend_name ) : """Deletes the relationship between a Backend and a Director . The Backend is no longer considered a member of the Director and thus will not have traffic balanced onto it from this Director ."""
content = self . _fetch ( "/service/%s/version/%d/director/%s/backend/%s" % ( service_id , version_number , director_name , backend_name ) , method = "DELETE" ) return self . _status ( content )
def remove_file ( self , file_name , * args , ** kwargs ) : """: meth : ` . WNetworkClientProto . remove _ file ` method implementation"""
client = self . dav_client ( ) remote_path = self . join_path ( self . session_path ( ) , file_name ) if client . is_dir ( remote_path ) is True : raise ValueError ( 'Unable to remove non-file entry' ) client . clean ( remote_path )
def _get_repr ( obj , pretty = False , indent = 1 ) : """Get string representation of an object : param obj : object : type obj : object : param pretty : use pretty formatting : type pretty : bool : param indent : indentation for pretty formatting : type indent : int : return : string representation ...
if pretty : repr_value = pformat ( obj , indent ) else : repr_value = repr ( obj ) if sys . version_info [ 0 ] == 2 : # Try to convert Unicode string to human - readable form try : repr_value = repr_value . decode ( 'raw_unicode_escape' ) except UnicodeError : repr_value = repr_value . d...
def cleanup ( output_root ) : """Remove any reST files which were generated by this extension"""
if os . path . exists ( output_root ) : if os . path . isdir ( output_root ) : rmtree ( output_root ) else : os . remove ( output_root )
def parse_gc_dist ( self , f ) : """Parse the contents of the Qualimap BamQC Mapped Reads GC content distribution file"""
# Get the sample name from the parent parent directory # Typical path : < sample name > / raw _ data _ qualimapReport / mapped _ reads _ gc - content _ distribution . txt s_name = self . get_s_name ( f ) d = dict ( ) reference_species = None reference_d = dict ( ) avg_gc = 0 for l in f [ 'f' ] : if l . startswith (...
def _last_index ( x , default_dim ) : """Returns the last dimension ' s index or default _ dim if x has no shape ."""
if x . get_shape ( ) . ndims is not None : return len ( x . get_shape ( ) ) - 1 else : return default_dim
def eventize ( self , granularity ) : """This splits the JSON information found at self . events into the several events . For this there are three different levels of time consuming actions : 1 - soft , 2 - medium and 3 - hard . Level 1 provides events about emails Level 2 not implemented Level 3 not imp...
email = { } # First level granularity email [ Email . EMAIL_ID ] = [ ] email [ Email . EMAIL_EVENT ] = [ ] email [ Email . EMAIL_DATE ] = [ ] email [ Email . EMAIL_OWNER ] = [ ] email [ Email . EMAIL_SUBJECT ] = [ ] email [ Email . EMAIL_BODY ] = [ ] email [ Email . EMAIL_ORIGIN ] = [ ] events = pandas . DataFrame ( ) ...
def plot ( self , * args , ** kwargs ) : """NAME : plot PURPOSE : plot aspects of an Orbit INPUT : bovy _ plot args and kwargs ro = ( Object - wide default ) physical scale for distances to use to convert vo = ( Object - wide default ) physical scale for velocities to use to convert use _ physical =...
if ( kwargs . get ( 'use_physical' , False ) and kwargs . get ( 'ro' , self . _roSet ) ) or ( not 'use_physical' in kwargs and kwargs . get ( 'ro' , self . _roSet ) ) : labeldict = { 't' : r'$t\ (\mathrm{Gyr})$' , 'R' : r'$R\ (\mathrm{kpc})$' , 'vR' : r'$v_R\ (\mathrm{km\,s}^{-1})$' , 'vT' : r'$v_T\ (\mathrm{km\,s}...
def rmdir ( remote_folder , missing_okay ) : """Forcefully remove a folder and all its children from the board . Remove the specified folder from the board ' s filesystem . Must specify one argument which is the path to the folder to delete . This will delete the directory and ALL of its children recursively ...
# Delete the provided file / directory on the board . board_files = files . Files ( _board ) board_files . rmdir ( remote_folder , missing_okay = missing_okay )
def get_configuration_dict ( self , secret_attrs = False ) : """Overrides superclass method and renames some properties"""
cd = super ( TaxonomicAmendmentsShard , self ) . get_configuration_dict ( secret_attrs = secret_attrs ) # " rename " some keys in the dict provided cd [ 'number of amendments' ] = cd . pop ( 'number of documents' ) cd [ 'amendments' ] = cd . pop ( 'documents' ) # add keys particular to this shard subclass if self . _ne...
def get_profile_name ( org_vm , profile_inst ) : """Get the org , name , and version from the profile instance and return them as a tuple . Returns : tuple of org , name , vers Raises : TypeError : if invalid property type ValueError : If property value outside range"""
try : org = org_vm . tovalues ( profile_inst [ 'RegisteredOrganization' ] ) name = profile_inst [ 'RegisteredName' ] vers = profile_inst [ 'RegisteredVersion' ] return org , name , vers except TypeError as te : print ( 'ORG_VM.TOVALUES FAILED. inst=%s, Exception %s' % ( profile_inst , te ) ) except ...
def writeNSdict ( self , nsdict ) : '''Write a namespace dictionary , taking care to not clobber the standard ( or reserved by us ) prefixes .'''
for k , v in nsdict . items ( ) : if ( k , v ) in _standard_ns : continue rv = _reserved_ns . get ( k ) if rv : if rv != v : raise KeyError ( "Reserved namespace " + str ( ( k , v ) ) + " used" ) continue if k : self . dom . setNamespaceAttribute ( k , v ) ...
def value_to_python ( self , value ) : """Converts the input single value into the expected Python data type , raising django . core . exceptions . ValidationError if the data can ' t be converted . Returns the converted value . Subclasses should override this ."""
if not isinstance ( value , bytes ) : raise tldap . exceptions . ValidationError ( "should be a bytes" ) length = len ( value ) - 8 if length % 4 != 0 : raise tldap . exceptions . ValidationError ( "Invalid sid" ) length = length // 4 array = struct . unpack ( '<bbbbbbbb' + 'I' * length , value ) if array [ 1 ]...
def _str_datetime_now ( self , x = None ) : """Return datetime string for use with time attributes . Handling depends on input : ' now ' - returns datetime for now number - assume datetime values , generate string other - no change , return same value"""
if ( x == 'now' ) : # Now , this is wht datetime _ to _ str ( ) with no arg gives return ( datetime_to_str ( ) ) try : # Test for number junk = x + 0.0 return datetime_to_str ( x ) except TypeError : # Didn ' t look like a number , treat as string return x
def find_bind_module ( name , verbose = False ) : """Find the bind module matching the given name . Args : name ( str ) : Name of package to find bind module for . verbose ( bool ) : If True , print extra output . Returns : str : Filepath to bind module . py file , or None if not found ."""
bindnames = get_bind_modules ( verbose = verbose ) bindfile = bindnames . get ( name ) if bindfile : return bindfile if not verbose : return None # suggest close matches fuzzy_matches = get_close_pkgs ( name , bindnames . keys ( ) ) if fuzzy_matches : rows = [ ( x [ 0 ] , bindnames [ x [ 0 ] ] ) for x in fu...
def expand_variable_dicts ( list_of_variable_dicts : 'List[Union[Dataset, OrderedDict]]' , ) -> 'List[Mapping[Any, Variable]]' : """Given a list of dicts with xarray object values , expand the values . Parameters list _ of _ variable _ dicts : list of dict or Dataset objects Each value for the mappings must b...
from . dataarray import DataArray from . dataset import Dataset var_dicts = [ ] for variables in list_of_variable_dicts : if isinstance ( variables , Dataset ) : var_dicts . append ( variables . variables ) continue # append coords to var _ dicts before appending sanitized _ vars , # because...
def time_label ( intvl , return_val = True ) : """Create time interval label for aospy data I / O ."""
# Monthly labels are 2 digit integers : ' 01 ' for jan , ' 02 ' for feb , etc . if type ( intvl ) in [ list , tuple , np . ndarray ] and len ( intvl ) == 1 : label = '{:02}' . format ( intvl [ 0 ] ) value = np . array ( intvl ) elif type ( intvl ) == int and intvl in range ( 1 , 13 ) : label = '{:02}' . for...
def render ( self , name , value , attrs = None , renderer = None ) : """Include a hidden input to store the serialized upload value ."""
location = getattr ( value , '_seralized_location' , '' ) if location and not hasattr ( value , 'url' ) : value . url = '#' if hasattr ( self , 'get_template_substitution_values' ) : # Django 1.8-1.10 self . template_with_initial = ( '%(initial_text)s: %(initial)s %(clear_template)s' '<br />%(input_text...
def all_coarse_grains_for_blackbox ( blackbox ) : """Generator over all | CoarseGrains | for the given blackbox . If a box has multiple outputs , those outputs are partitioned into the same coarse - grain macro - element ."""
for partition in all_partitions ( blackbox . output_indices ) : for grouping in all_groupings ( partition ) : coarse_grain = CoarseGrain ( partition , grouping ) try : validate . blackbox_and_coarse_grain ( blackbox , coarse_grain ) except ValueError : continue ...
def _validate_type_key ( key , value , types , validated ) : """Validate a key ' s value by type ."""
for key_schema , value_schema in types . items ( ) : if not isinstance ( key , key_schema ) : continue try : validated [ key ] = value_schema ( value ) except NotValid : continue else : return [ ] return [ '%r: %r not matched' % ( key , value ) ]
def wrap_conn ( conn_func ) : """Wrap the mysql conn object with TraceConnection ."""
def call ( * args , ** kwargs ) : try : conn = conn_func ( * args , ** kwargs ) cursor_func = getattr ( conn , CURSOR_WRAP_METHOD ) wrapped = wrap_cursor ( cursor_func ) setattr ( conn , cursor_func . __name__ , wrapped ) return conn except Exception : # pragma : NO COVER...
def get ( self ) : """Returns the Mlag configuration as a resource dict Returns : dict : A dict ojbect containing the Mlag resource attributes ."""
resource = dict ( ) resource . update ( self . _parse_config ( ) ) resource . update ( self . _parse_interfaces ( ) ) return resource
def mutex ( ) : '''Tests the implementation of mutex CLI Examples : . . code - block : : bash salt ' * ' sysbench . mutex'''
# Test options and the values they take # - - mutex - num = [ 50,500,1000] # - - mutex - locks = [ 10000,25000,50000] # - - mutex - loops = [ 2500,5000,10000] # Test data ( Orthogonal test cases ) mutex_num = [ 50 , 50 , 50 , 500 , 500 , 500 , 1000 , 1000 , 1000 ] locks = [ 10000 , 25000 , 50000 , 10000 , 25000 , 50000...
def _get_indices_and_signs ( hasher , terms ) : """For each term from ` ` terms ` ` return its column index and sign , as assigned by FeatureHasher ` ` hasher ` ` ."""
X = _transform_terms ( hasher , terms ) indices = X . nonzero ( ) [ 1 ] signs = X . sum ( axis = 1 ) . A . ravel ( ) return indices , signs
def print_usage ( actions ) : """Print the usage information . ( Help screen )"""
actions = actions . items ( ) actions . sort ( ) print ( 'usage: %s <action> [<options>]' % basename ( sys . argv [ 0 ] ) ) print ( ' %s --help' % basename ( sys . argv [ 0 ] ) ) print ( ) print ( 'actions:' ) for name , ( func , doc , arguments ) in actions : print ( ' %s:' % name ) for line in doc . sp...
def _fbp_filter ( norm_freq , filter_type , frequency_scaling ) : """Create a smoothing filter for FBP . Parameters norm _ freq : ` array - like ` Frequencies normalized to lie in the interval [ 0 , 1 ] . filter _ type : { ' Ram - Lak ' , ' Shepp - Logan ' , ' Cosine ' , ' Hamming ' , ' Hann ' , callable ...
filter_type , filter_type_in = str ( filter_type ) . lower ( ) , filter_type if callable ( filter_type ) : filt = filter_type ( norm_freq ) elif filter_type == 'ram-lak' : filt = np . copy ( norm_freq ) elif filter_type == 'shepp-logan' : filt = norm_freq * np . sinc ( norm_freq / ( 2 * frequency_scaling ) ...
def call_at ( self , when : float , callback : Callable [ ... , None ] , * args : Any , ** kwargs : Any ) -> object : """Runs the ` ` callback ` ` at the absolute time designated by ` ` when ` ` . ` ` when ` ` must be a number using the same reference point as ` IOLoop . time ` . Returns an opaque handle that...
return self . add_timeout ( when , callback , * args , ** kwargs )
def close ( self ) : """Close Impala connection and drop any temporary objects"""
for obj in self . _temp_objects : try : obj . drop ( ) except HS2Error : pass self . con . close ( )
def get_remote_member ( self , member = None ) : """In case of standby cluster this will tel us from which remote master to stream . Config can be both patroni config or cluster . config . data"""
cluster_params = self . get_standby_cluster_config ( ) if cluster_params : name = member . name if member else 'remote_master:{}' . format ( uuid . uuid1 ( ) ) data = { k : v for k , v in cluster_params . items ( ) if k in RemoteMember . allowed_keys ( ) } data [ 'no_replication_slot' ] = 'primary_slot_name...
def _get_stub ( self , table , create ) : """Get the migration stub template : param table : The table name : type table : str : param create : Whether it ' s a create migration or not : type create : bool : rtype : str"""
if table is None : return BLANK_STUB else : if create : stub = CREATE_STUB else : stub = UPDATE_STUB return stub
def update ( self , table , columns , values , where ) : """Update the values of a particular row where a value is met . : param table : table name : param columns : column ( s ) to update : param values : updated values : param where : tuple , ( where _ column , where _ value )"""
# Unpack WHERE clause dictionary into tuple where_col , where_val = where # Create column string from list of values cols = get_col_val_str ( columns , query_type = 'update' ) # Concatenate statement statement = "UPDATE {0} SET {1} WHERE {2}='{3}'" . format ( wrap ( table ) , cols , where_col , where_val ) # Execute st...
def get_ratefactor ( self , base , code ) : """Return the Decimal currency exchange rate factor of ' code ' compared to 1 ' base ' unit , or RuntimeError"""
self . get_latestcurrencyrates ( base ) try : ratefactor = self . rates [ "rates" ] [ code ] except KeyError : raise RuntimeError ( "%s: %s not found" % ( self . name , code ) ) if base == self . base : return ratefactor else : return self . ratechangebase ( ratefactor , self . base , base )
def acquire_read ( self ) : """Acquire a read lock . Several threads can hold this typeof lock . It is exclusive with write locks ."""
self . monitor . acquire ( ) while self . rwlock < 0 or self . writers_waiting : self . readers_ok . wait ( ) self . rwlock += 1 self . monitor . release ( )
def spawn_antigen_predictors ( job , transgened_files , phlat_files , univ_options , mhc_options ) : """Based on the number of alleles obtained from node 14 , this module will spawn callers to predict MHCI : peptide and MHCII : peptide binding on the peptide files from node 17 . Once all MHC : peptide predictio...
job . fileStore . logToMaster ( 'Running spawn_anti on %s' % univ_options [ 'patient' ] ) work_dir = job . fileStore . getLocalTempDir ( ) mhci_options , mhcii_options = mhc_options pept_files = { '9_mer.faa' : transgened_files [ 'transgened_tumor_9_mer_snpeffed.faa' ] , '10_mer.faa' : transgened_files [ 'transgened_tu...
def get_work_unit_status ( self , work_spec_name , work_unit_key ) : '''Get a high - level status for some work unit . The return value is a dictionary . The only required key is ` ` status ` ` , which could be any of : ` ` missing ` ` The work unit does not exist anywhere ` ` available ` ` The work uni...
with self . registry . lock ( identifier = self . worker_id ) as session : # In the available list ? ( unit , priority ) = session . get ( WORK_UNITS_ + work_spec_name , work_unit_key , include_priority = True ) if unit : result = { } if priority < time . time ( ) : result [ 'status'...
def exception_wrapper ( f ) : """Decorator to convert dbus exception to pympris exception ."""
@ wraps ( f ) def wrapper ( * args , ** kwds ) : try : return f ( * args , ** kwds ) except dbus . exceptions . DBusException as err : _args = err . args raise PyMPRISException ( * _args ) return wrapper
def unpack_ip ( fourbytes ) : """Converts an ip address given in a four byte string in network byte order to a string in dotted notation . > > > unpack _ ip ( b " dead " ) '100.101.97.100' > > > unpack _ ip ( b " alive " ) Traceback ( most recent call last ) : ValueError : given buffer is not exactly fo...
if not isinstance ( fourbytes , bytes ) : raise ValueError ( "given buffer is not a string" ) if len ( fourbytes ) != 4 : raise ValueError ( "given buffer is not exactly four bytes long" ) return "." . join ( [ str ( x ) for x in bytes_to_int_seq ( fourbytes ) ] )
def _init_ssh ( opts ) : '''Open a connection to the NX - OS switch over SSH .'''
if opts is None : opts = __opts__ try : this_prompt = None if 'prompt_regex' in opts [ 'proxy' ] : this_prompt = opts [ 'proxy' ] [ 'prompt_regex' ] elif 'prompt_name' in opts [ 'proxy' ] : this_prompt = '{0}.*#' . format ( opts [ 'proxy' ] [ 'prompt_name' ] ) else : log . wa...
def readWindowsFile ( wfile ) : """reading file with windows wfile File containing window info"""
window_file = wfile + '.wnd' assert os . path . exists ( window_file ) , '%s is missing.' % window_file rv = SP . loadtxt ( window_file ) return rv
def lpc ( signal , order , axis = - 1 ) : """Compute the Linear Prediction Coefficients . Return the order + 1 LPC coefficients for the signal . c = lpc ( x , k ) will find the k + 1 coefficients of a k order linear filter : xp [ n ] = - c [ 1 ] * x [ n - 2 ] - . . . - c [ k - 1 ] * x [ n - k - 1] Such as t...
n = signal . shape [ axis ] if order > n : raise ValueError ( "Input signal must have length >= order" ) r = acorr_lpc ( signal , axis ) return levinson_1d ( r , order )
def render ( self , context ) : '''Evaluates the code in the page and returns the result'''
modules = { 'pyjade' : __import__ ( 'pyjade' ) } context [ 'false' ] = False context [ 'true' ] = True try : return six . text_type ( eval ( 'pyjade.runtime.attrs(%s)' % self . code , modules , context ) ) except NameError : return ''
def list_nodes_full ( call = None ) : '''List devices , with all available information . CLI Example : . . code - block : : bash salt - cloud - F salt - cloud - - full - query salt - cloud - f list _ nodes _ full packet - provider'''
if call == 'action' : raise SaltCloudException ( 'The list_nodes_full function must be called with -f or --function.' ) ret = { } for device in get_devices_by_token ( ) : ret [ device . hostname ] = device . __dict__ return ret
def _orientation ( self , edge , point ) : """Returns + 1 if edge [ 0 ] - > point is clockwise from edge [ 0 ] - > edge [ 1 ] , -1 if counterclockwise , and 0 if parallel ."""
v1 = self . pts [ point ] - self . pts [ edge [ 0 ] ] v2 = self . pts [ edge [ 1 ] ] - self . pts [ edge [ 0 ] ] c = np . cross ( v1 , v2 ) # positive if v1 is CW from v2 return 1 if c > 0 else ( - 1 if c < 0 else 0 )
def fetch_todays_schedule ( self , rooms ) : """Fetch the schedules for the given rooms ."""
room_ids = self . fetch_room_ids ( rooms ) inst_id = self . fetch_inst_id ( ) ret = { } now = datetime . datetime . now ( ) day = DAYS [ now . isoweekday ( ) - 1 ] for room_name in room_ids : ret [ room_name ] = [ ] try : events = msgpack . unpack ( urllib2 . urlopen ( "%s/snapshot/head/%s/location/%s?f...
def argval ( key , default = None , type = None , smartcast = True , return_exists = False , argv = None ) : """alias for get _ argval Example : > > > # ENABLE _ DOCTEST > > > import utool as ut > > > import sys > > > argv = [ ' - - aids = [ 1,2,3 ] ' ] > > > value = ut . argval ( ' - - aids ' , default...
defaultable_types = ( tuple , list , int , float ) if type is None and isinstance ( default , defaultable_types ) : type = builtins . type ( default ) return get_argval ( key , type_ = type , default = default , return_was_specified = return_exists , smartcast = smartcast , argv = argv )
def write_branch_data ( self , file ) : """Writes branch data to a ReST table ."""
report = CaseReport ( self . case ) branches = self . case . branches col_width = 8 col_width_2 = col_width * 2 + 1 col1_width = 7 sep = ( "=" * 7 + " " ) * 3 + ( "=" * col_width + " " ) * 6 + "\n" file . write ( sep ) # Line one of column headers file . write ( "Name" . center ( col1_width ) + " " ) file . write ( "Fr...
def find_primitive ( self ) : """Find a primitive version of the unit cell . Returns : A primitive cell in the input cell is searched and returned as an Structure object . If no primitive cell is found , None is returned ."""
lattice , scaled_positions , numbers = spglib . find_primitive ( self . _cell , symprec = self . _symprec ) species = [ self . _unique_species [ i - 1 ] for i in numbers ] return Structure ( lattice , species , scaled_positions , to_unit_cell = True ) . get_reduced_structure ( )
def hmsm_to_days ( hour = 0 , min = 0 , sec = 0 , micro = 0 ) : """Convert hours , minutes , seconds , and microseconds to fractional days . Parameters hour : int , optional Hour number . Defaults to 0. min : int , optional Minute number . Defaults to 0. sec : int , optional Second number . Defaults t...
days = sec + ( micro / 1.e6 ) days = min + ( days / 60. ) days = hour + ( days / 60. ) return days / 24.
def _sanatize_network_params ( self , kwargs ) : '''Sanatize novaclient network parameters'''
params = [ 'label' , 'bridge' , 'bridge_interface' , 'cidr' , 'cidr_v6' , 'dns1' , 'dns2' , 'fixed_cidr' , 'gateway' , 'gateway_v6' , 'multi_host' , 'priority' , 'project_id' , 'vlan_start' , 'vpn_start' ] for variable in six . iterkeys ( kwargs ) : # iterate over a copy , we might delete some if variable not in pa...
def get_issues_by_resource ( resource_id , table ) : """Get all issues for a specific job ."""
v1_utils . verify_existence_and_get ( resource_id , table ) # When retrieving the issues for a job , we actually retrieve # the issues attach to the job itself + the issues attached to # the components the job has been run with . if table . name == 'jobs' : JJI = models . JOIN_JOBS_ISSUES JJC = models . JOIN_JO...
def create_logger ( level = logging . NOTSET ) : """Create a logger for python - gnupg at a specific message level . : type level : : obj : ` int ` or : obj : ` str ` : param level : A string or an integer for the lowest level to include in logs . * * Available levels : * * int str description 0 NOTSET ...
_test = os . path . join ( os . path . join ( os . getcwd ( ) , 'pretty_bad_protocol' ) , 'test' ) _now = datetime . now ( ) . strftime ( "%Y-%m-%d_%H%M%S" ) _fn = os . path . join ( _test , "%s_test_gnupg.log" % _now ) _fmt = "%(relativeCreated)-4d L%(lineno)-4d:%(funcName)-18.18s %(levelname)-7.7s %(message)s" # # Ad...
def init ( self ) : """init ` todo ` file if file exists , then initialization self . todos and record current max index of todos : when add a new todo , the ` idx ` via only ` self . current _ max _ idx + 1 `"""
if os . path . isdir ( self . path ) : raise InvalidTodoFile if os . path . exists ( self . path ) : with open ( self . path , 'r' ) as f : tls = [ tl . strip ( ) for tl in f if tl ] todos = map ( _todo_from_file , tls ) self . todos = todos for todo in todos : if sel...
def read_files ( * filenames ) : """Output the contents of one or more files to a single concatenated string ."""
output = [ ] for filename in filenames : f = codecs . open ( filename , encoding = 'utf-8' ) try : output . append ( f . read ( ) ) finally : f . close ( ) return '\n\n' . join ( output )