signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def update ( custom_sources = False ) : """Update function to be called from cli . py"""
if not shutil . which ( 'git' ) : print ( 'Git executable not found in $PATH.' ) sys . exit ( 1 ) if not custom_sources : print ( 'Creating sources.yaml…' ) write_sources_file ( ) print ( 'Cloning sources…' ) sources_file = rel_to_cwd ( 'sources.yaml' ) jobs = yaml_to_job_list ( sources_file...
def extract_minors_from_setup_py ( filename_setup_py ) : '''Extract supported python minor versions from setup . py and return them as a list of str . Return example : [ ' 2.6 ' , ' 2.7 ' , ' 3.3 ' , ' 3.4 ' , ' 3.5 ' , ' 3.6 ' ]'''
# eg : minors _ str = ' 2.6 \ n2.7 \ n3.3 \ n3.4 \ n3.5 \ n3.6' minors_str = fabric . api . local ( flo ( 'grep --perl-regexp --only-matching ' '"(?<=Programming Language :: Python :: )\\d+\\.\\d+" ' '{filename_setup_py}' ) , capture = True ) # eg : minors = [ ' 2.6 ' , ' 2.7 ' , ' 3.3 ' , ' 3.4 ' , ' 3.5 ' , ' 3.6 ' ]...
def write ( self , symbol , data , metadata = None , prune_previous_version = True , ** kwargs ) : """Write ' data ' under the specified ' symbol ' name to this library . Parameters symbol : ` str ` symbol name for the item data : to be persisted metadata : ` dict ` an optional dictionary of metadata ...
self . _arctic_lib . check_quota ( ) version = { '_id' : bson . ObjectId ( ) } version [ 'arctic_version' ] = ARCTIC_VERSION_NUMERICAL version [ 'symbol' ] = symbol version [ 'version' ] = self . _version_nums . find_one_and_update ( { 'symbol' : symbol } , { '$inc' : { 'version' : 1 } } , upsert = True , new = True ) ...
def to_csv ( df , filepath , sep = ',' , header = True , index = True ) : """Save DataFrame as csv . Note data is expected to be evaluated . Currently delegates to Pandas . Parameters df : DataFrame filepath : str sep : str , optional Separator used between values . header : bool , optional Whethe...
df . to_pandas ( ) . to_csv ( filepath , sep = sep , header = header , index = index )
def get_cloudflare_records ( self , * , account ) : """Return a ` list ` of ` dict ` s containing the zones and their records , obtained from the CloudFlare API Returns : account ( : obj : ` CloudFlareAccount ` ) : A CloudFlare Account object : obj : ` list ` of ` dict `"""
zones = [ ] for zobj in self . __cloudflare_list_zones ( account = account ) : try : self . log . debug ( 'Processing DNS zone CloudFlare/{}' . format ( zobj [ 'name' ] ) ) zone = { 'zone_id' : get_resource_id ( 'cfz' , zobj [ 'name' ] ) , 'name' : zobj [ 'name' ] , 'source' : 'CloudFlare' , 'commen...
def application_state ( context , application ) : """Render current state of application , verbose ."""
new_context = { 'roles' : context [ 'roles' ] , 'org_name' : context [ 'org_name' ] , 'application' : application , } nodelist = template . loader . get_template ( 'kgapplications/%s_common_state.html' % application . type ) output = nodelist . render ( new_context ) return output
def predict_proba ( self , X ) : """Predict class probabilities for X . The predicted class probabilities of an input sample is computed as the mean predicted class probabilities of the base estimators in the ensemble . If base estimators do not implement a ` ` predict _ proba ` ` method , then it resorts t...
# Check data # X = check _ array ( X , accept _ sparse = [ ' csr ' , ' csc ' , ' coo ' ] ) # Dont in version 0.15 if self . n_features_ != X . shape [ 1 ] : raise ValueError ( "Number of features of the model must " "match the input. Model n_features is {0} and " "input n_features is {1}." "" . format ( self . n_fe...
def _get_api_urls ( self , api_urls = None ) : """Completes a dict with the CRUD urls of the API . : param api _ urls : A dict with the urls { ' < FUNCTION > ' : ' < URL > ' , . . . } : return : A dict with the CRUD urls of the base API ."""
view_name = self . __class__ . __name__ api_urls = api_urls or { } api_urls [ "read" ] = url_for ( view_name + ".api_read" ) api_urls [ "delete" ] = url_for ( view_name + ".api_delete" , pk = "" ) api_urls [ "create" ] = url_for ( view_name + ".api_create" ) api_urls [ "update" ] = url_for ( view_name + ".api_update" ,...
def cli ( env , columns , sortby , volume_id ) : """List ACLs ."""
block_manager = SoftLayer . BlockStorageManager ( env . client ) access_list = block_manager . get_block_volume_access_list ( volume_id = volume_id ) table = formatting . Table ( columns . columns ) table . sortby = sortby for key , type_name in [ ( 'allowedVirtualGuests' , 'VIRTUAL' ) , ( 'allowedHardware' , 'HARDWARE...
def reset ( self ) : """Process everything all over again ."""
self . indexCount = 0 indexDir = self . store . newDirectory ( self . indexDirectory ) if indexDir . exists ( ) : indexDir . remove ( ) for src in self . getSources ( ) : src . removeReliableListener ( self ) src . addReliableListener ( self , style = iaxiom . REMOTE )
def as_proj4 ( self ) : """Return the PROJ . 4 string which corresponds to the CRS . For example : : > > > print ( get ( 21781 ) . as _ proj4 ( ) ) + proj = somerc + lat _ 0 = 46.95240555556 + lon _ 0 = 7.4395833333 + k _ 0 = 1 + x _ 0 = 600000 + y _ 0 = 200000 + ellps = bessel + towgs84 = 674.4,15.1,405.3,0,...
url = '{prefix}{code}.proj4?download' . format ( prefix = EPSG_IO_URL , code = self . id ) return requests . get ( url ) . text . strip ( )
def ListFiles ( self , ext_attrs = None ) : """A generator of all keys and values ."""
del ext_attrs # Unused . if not self . IsDirectory ( ) : return if self . hive is None : for name in dir ( winreg ) : if name . startswith ( "HKEY_" ) : response = rdf_client_fs . StatEntry ( st_mode = stat . S_IFDIR ) response_pathspec = self . pathspec . Copy ( ) re...
def _normalize_overlap ( overlap , window , nfft , samp , method = 'welch' ) : """Normalise an overlap in physical units to a number of samples Parameters overlap : ` float ` , ` Quantity ` , ` None ` the overlap in some physical unit ( seconds ) window : ` str ` the name of the window function that will ...
if method == 'bartlett' : return 0 if overlap is None and isinstance ( window , string_types ) : return recommended_overlap ( window , nfft ) if overlap is None : return 0 return seconds_to_samples ( overlap , samp )
def lnprob ( self , theta ) : """Logarithm of the probability"""
global niter params , priors , loglike = self . params , self . priors , self . loglike # Avoid extra likelihood calls with bad priors _lnprior = self . lnprior ( theta ) if np . isfinite ( _lnprior ) : _lnlike = self . lnlike ( theta ) else : _lnprior = - np . inf _lnlike = - np . inf _lnprob = _lnprior + ...
def read_port ( self , port ) : """Read the pin state of a whole port ( 8 pins ) : Example : > > > expander = MCP23017I2C ( gw ) > > > # Read pin A0 - A7 as a int ( A0 and A1 are high ) > > > expander . read _ port ( ' A ' ) > > > # Read pin B0 - B7 as a int ( B2 is high ) > > > expander . read _ port (...
if port == 'A' : raw = self . i2c_read_register ( 0x12 , 1 ) elif port == 'B' : raw = self . i2c_read_register ( 0x13 , 1 ) return struct . unpack ( '>B' , raw ) [ 0 ]
def extract_args_from_signature ( operation , excluded_params = None ) : """Extracts basic argument data from an operation ' s signature and docstring excluded _ params : List of params to ignore and not extract . By default we ignore [ ' self ' , ' kwargs ' ] ."""
args = [ ] try : # only supported in python3 - falling back to argspec if not available sig = inspect . signature ( operation ) args = sig . parameters except AttributeError : sig = inspect . getargspec ( operation ) # pylint : disable = deprecated - method , useless - suppression args = sig . args ...
def get_chain_mutations ( self , pdb_id_1 , chain_1 , pdb_id_2 , chain_2 ) : '''Returns a list of tuples each containing a SEQRES Mutation object and an ATOM Mutation object representing the mutations from pdb _ id _ 1 , chain _ 1 to pdb _ id _ 2 , chain _ 2. SequenceMaps are constructed in this function betwee...
# Set up the objects p1 = self . add_pdb ( pdb_id_1 ) p2 = self . add_pdb ( pdb_id_2 ) sifts_1 , pdb_1 = p1 [ 'sifts' ] , p1 [ 'pdb' ] sifts_2 , pdb_2 = p2 [ 'sifts' ] , p2 [ 'pdb' ] # Set up the sequences # pprint . pprint ( sifts _ 1 . seqres _ to _ atom _ sequence _ maps ) seqres_to_atom_sequence_maps_1 = sifts_1 . ...
def Write ( self , packet ) : """See base class ."""
report_id = 0 out_report_buffer = ( ctypes . c_uint8 * self . internal_max_out_report_len ) ( ) out_report_buffer [ : ] = packet [ : ] result = iokit . IOHIDDeviceSetReport ( self . device_handle , K_IO_HID_REPORT_TYPE_OUTPUT , report_id , out_report_buffer , self . internal_max_out_report_len ) # Non - zero status ind...
def socks_endpoint ( self , reactor , port = None ) : """Returns a TorSocksEndpoint configured to use an already - configured SOCKSPort from the Tor we ' re connected to . By default , this will be the very first SOCKSPort . : param port : a str , the first part of the SOCKSPort line ( that is , a port like...
if len ( self . SocksPort ) == 0 : raise RuntimeError ( "No SOCKS ports configured" ) socks_config = None if port is None : socks_config = self . SocksPort [ 0 ] else : port = str ( port ) # in case e . g . an int passed in if ' ' in port : raise ValueError ( "Can't specify options; use crea...
def config ( env = DEFAULT_ENV , default = 'locmem://' ) : """Returns configured CACHES dictionary from CACHE _ URL"""
config = { } s = os . environ . get ( env , default ) if s : config = parse ( s ) return config
def verify_tls ( self , socket , hostname , context ) : """Verify a TLS connection . Return behaviour is dependent on the as _ callback parameter : - If True , a return value of None means verification succeeded , else it failed . - If False , a return value of True means verification succeeded , an exception o...
cert = socket . getpeercert ( ) try : # Make sure the hostnames for which this certificate is valid include the one we ' re connecting to . ssl . match_hostname ( cert , hostname ) except ssl . CertificateError : return ssl . ALERT_DESCRIPTION_BAD_CERTIFICATE return None
def is_valid_for ( self , entry_point , protocol ) : """Check if the current function can be executed from a request to the given entry point and with the given protocol"""
return self . available_for_entry_point ( entry_point ) and self . available_for_protocol ( protocol )
def rotate_eggs ( self ) : """moves newest . egg to last _ stable . egg this is used by the upload ( ) function upon 2XX return returns ( bool ) : if eggs rotated successfully raises ( IOError ) : if it cant copy the egg from newest to last _ stable"""
# make sure the library directory exists if os . path . isdir ( constants . insights_core_lib_dir ) : # make sure the newest . egg exists if os . path . isfile ( constants . insights_core_newest ) : # try copying newest to latest _ stable try : # copy the core shutil . move ( constants . insight...
def record_event ( self , event : Event ) -> None : """Record the event async ."""
from polyaxon . celery_api import celery_app from polyaxon . settings import EventsCeleryTasks if not event . ref_id : event . ref_id = self . get_ref_id ( ) serialized_event = event . serialize ( dumps = False , include_actor_name = True , include_instance_info = True ) celery_app . send_task ( EventsCeleryTasks ....
def _amp3d_to_2d ( self , amp , sigma_x , sigma_y ) : """converts 3d density into 2d density parameter : param amp : : param sigma _ x : : param sigma _ y : : return :"""
return amp * np . sqrt ( np . pi ) * np . sqrt ( sigma_x * sigma_y * 2 )
def calculateOptionPrice ( self , contract : Contract , volatility : float , underPrice : float , optPrcOptions = None ) -> OptionComputation : """Calculate the option price given the volatility . This method is blocking . https : / / interactivebrokers . github . io / tws - api / option _ computations . html ...
return self . _run ( self . calculateOptionPriceAsync ( contract , volatility , underPrice , optPrcOptions ) )
def setInstrumentParameters ( self , instrpars ) : """This method overrides the superclass to set default values into the parameter dictionary , in case empty entries are provided ."""
pri_header = self . _image [ 0 ] . header self . proc_unit = instrpars [ 'proc_unit' ] instrpars [ 'gnkeyword' ] = 'ATODGAIN' # hard - code for WFPC2 data instrpars [ 'rnkeyword' ] = None if self . _isNotValid ( instrpars [ 'exptime' ] , instrpars [ 'expkeyword' ] ) : instrpars [ 'expkeyword' ] = 'EXPTIME' for chip...
def process_spawn_qty ( self , name ) : """Return the number of processes to spawn for the given consumer name . : param str name : The consumer name : rtype : int"""
return self . consumers [ name ] . qty - self . process_count ( name )
def _initialize ( self , runtime ) : """Common initializer for OsidManager and OsidProxyManager"""
if runtime is None : raise NullArgument ( ) if self . _my_runtime is not None : raise IllegalState ( 'this manager has already been initialized.' ) self . _my_runtime = runtime config = runtime . get_configuration ( ) cf_public_key_param_id = Id ( 'parameter:cloudFrontPublicKey@aws_adapter' ) cf_private_key_par...
def __pre_check ( self , requestedUrl ) : '''Allow the pre - emptive fetching of sites with a full browser if they ' re known to be dick hosters .'''
components = urllib . parse . urlsplit ( requestedUrl ) netloc_l = components . netloc . lower ( ) if netloc_l in Domain_Constants . SUCURI_GARBAGE_SITE_NETLOCS : self . __check_suc_cookie ( components ) elif netloc_l in Domain_Constants . CF_GARBAGE_SITE_NETLOCS : self . __check_cf_cookie ( components ) elif c...
def _normalize_files ( item , fc_dir = None ) : """Ensure the files argument is a list of absolute file names . Handles BAM , single and paired end fastq , as well as split inputs ."""
files = item . get ( "files" ) if files : if isinstance ( files , six . string_types ) : files = [ files ] fastq_dir = flowcell . get_fastq_dir ( fc_dir ) if fc_dir else os . getcwd ( ) files = [ _file_to_abs ( x , [ os . getcwd ( ) , fc_dir , fastq_dir ] ) for x in files ] files = [ x for x in ...
def configure_client ( cls , address : Union [ str , Tuple [ str , int ] , Path ] = 'localhost' , port : int = 6379 , db : int = 0 , password : str = None , ssl : Union [ bool , str , SSLContext ] = False , ** client_args ) -> Dict [ str , Any ] : """Configure a Redis client . : param address : IP address , host ...
assert check_argument_types ( ) if isinstance ( address , str ) and not address . startswith ( '/' ) : address = ( address , port ) elif isinstance ( address , Path ) : address = str ( address ) client_args . update ( { 'address' : address , 'db' : db , 'password' : password , 'ssl' : resolve_reference ( ssl ) ...
def slug ( self ) : """It returns node ' s slug"""
if self . is_root_node ( ) : return "" if self . slugable and self . parent . parent : if not self . page . regex or ( self . page . regex and not self . page . show_regex ) or self . is_leaf_node ( ) : return u"{0}/{1}" . format ( self . parent . slug , self . page . slug ) elif self . page . regex...
def to_triples ( self , short_pred = True , properties = True ) : """Encode the Eds as triples suitable for PENMAN serialization ."""
node_triples , edge_triples = [ ] , [ ] # sort nodeids just so top var is first nodes = sorted ( self . nodes ( ) , key = lambda n : n . nodeid != self . top ) for node in nodes : nid = node . nodeid pred = node . pred . short_form ( ) if short_pred else node . pred . string node_triples . append ( ( nid , ...
def calc_spectrum ( signal , rate ) : """Return the spectrum and frequency indexes for real - valued input signal"""
npts = len ( signal ) padto = 1 << ( npts - 1 ) . bit_length ( ) # print ' length of signal { } , pad to { } ' . format ( npts , padto ) npts = padto sp = np . fft . rfft ( signal , n = padto ) / npts # print ( ' sp len ' , len ( sp ) ) freq = np . arange ( ( npts / 2 ) + 1 ) / ( npts / rate ) # print ( ' freq len ' , ...
def first_prediction ( self , singular_value ) : """get the null space term ( first term ) contribution to prediction error variance at a singular value . used to construct error variance dataframe Parameters singular _ value : int singular value to calc first term at Returns dict : dict dictionary of...
if not self . predictions : raise Exception ( "ErrVar.first(): no predictions are set" ) if singular_value > self . jco . ncol : zero_preds = { } for pred in self . predictions_iter : zero_preds [ ( "first" , pred . col_names [ 0 ] ) ] = 0.0 return zero_preds self . log ( "calc first term parame...
def get_service_methods ( iface ) : """Get a list of methods defined in the interface for a Thrift service . : param iface : The Thrift - generated Iface class defining the interface for the service . : returns : A set containing names of the methods defined for the service ."""
methods = inspect . getmembers ( iface , predicate = inspect . ismethod ) return set ( name for ( name , method ) in methods if not name . startswith ( '__' ) )
def removeSessionWithKey ( self , key ) : """Remove a persistent session , if it exists . @ type key : L { bytes } @ param key : The persistent session identifier ."""
self . store . query ( PersistentSession , PersistentSession . sessionKey == key ) . deleteFromStore ( )
def create_key_file ( service , key ) : """Create a file containing key ."""
keyfile = _keyfile_path ( service ) if os . path . exists ( keyfile ) : log ( 'Keyfile exists at %s.' % keyfile , level = WARNING ) return with open ( keyfile , 'w' ) as fd : fd . write ( key ) log ( 'Created new keyfile at %s.' % keyfile , level = INFO )
def _blas_is_applicable ( * args ) : """Whether BLAS routines can be applied or not . BLAS routines are available for single and double precision float or complex data only . If the arrays are non - contiguous , BLAS methods are usually slower , and array - writing routines do not work at all . Hence , only...
if any ( x . dtype != args [ 0 ] . dtype for x in args [ 1 : ] ) : return False elif any ( x . dtype not in _BLAS_DTYPES for x in args ) : return False elif not ( all ( x . flags . f_contiguous for x in args ) or all ( x . flags . c_contiguous for x in args ) ) : return False elif any ( x . size > np . iinf...
def table_data_client ( self ) : """Getter for the gRPC stub used for the Table Admin API . For example : . . literalinclude : : snippets . py : start - after : [ START bigtable _ table _ data _ client ] : end - before : [ END bigtable _ table _ data _ client ] : rtype : : class : ` . bigtable _ v2 . Bigt...
if self . _table_data_client is None : self . _table_data_client = _create_gapic_client ( bigtable_v2 . BigtableClient ) ( self ) return self . _table_data_client
def timeout_process_add_queue ( self , module , cache_time ) : """Add a module to the timeout _ queue if it is scheduled in the future or if it is due for an update immediately just trigger that . the timeout _ queue is a dict with the scheduled time as the key and the value is a list of module instance names...
# If already set to update do nothing if module in self . timeout_update_due : return # remove if already in the queue key = self . timeout_queue_lookup . get ( module ) if key : queue_item = self . timeout_queue [ key ] queue_item . remove ( module ) if not queue_item : del self . timeout_queue...
def _initialize ( self , ** resource_attributes ) : """Initialize the collection . : param resource _ attributes : API resource parameters"""
super ( APIResourceCollection , self ) . _initialize ( ** resource_attributes ) dict_list = self . data self . data = [ ] for resource in dict_list : self . data . append ( self . _expected_api_resource ( ** resource ) )
def _parse_flowcontrol_send ( self , config ) : """Scans the config block and returns the flowcontrol send value Args : config ( str ) : The interface config block to scan Returns : dict : Returns a dict object with the flowcontrol send value retrieved from the config block . The returned dict object is...
value = 'off' match = re . search ( r'flowcontrol send (\w+)$' , config , re . M ) if match : value = match . group ( 1 ) return dict ( flowcontrol_send = value )
def main ( req_files , verbose = False , outdated = False , latest = False , verbatim = False , repo = None , path = 'requirements.txt' , token = None , branch = 'master' , url = None , delay = None , ) : """Given a list of requirements files reports which requirements are out of date . Everything is rather som...
requirements = [ ] if repo : github_url = build_github_url ( repo , branch , path , token ) req_file = get_requirements_file_from_url ( github_url ) requirements . extend ( parse_req_file ( req_file ) ) elif url : req_file = get_requirements_file_from_url ( url ) requirements . extend ( parse_req_fi...
def connect ( ) : """Connect controller to handle token exchange and query Uber API ."""
# Exchange authorization code for acceess token and create session session = auth_flow . get_session ( request . url ) client = UberRidesClient ( session ) # Fetch profile for driver profile = client . get_driver_profile ( ) . json # Fetch last 50 trips and payments for driver trips = client . get_driver_trips ( 0 , 50...
def validate_subnet ( s ) : """Validate a dotted - quad ip address including a netmask . The string is considered a valid dotted - quad address with netmask if it consists of one to four octets ( 0-255 ) seperated by periods ( . ) followed by a forward slash ( / ) and a subnet bitmask which is expressed in ...
if isinstance ( s , basestring ) : if '/' in s : start , mask = s . split ( '/' , 2 ) return validate_ip ( start ) and validate_netmask ( mask ) else : return False raise TypeError ( "expected string or unicode" )
def parse_uniprot_xml_metadata ( sr ) : """Load relevant attributes and dbxrefs from a parsed UniProt XML file in a SeqRecord . Returns : dict : All parsed information"""
# TODO : What about " reviewed " status ? and EC number xref_dbs_to_keep = [ 'GO' , 'KEGG' , 'PDB' , 'PROSITE' , 'Pfam' , 'RefSeq' ] infodict = { } infodict [ 'alt_uniprots' ] = list ( set ( sr . annotations [ 'accessions' ] ) . difference ( [ sr . id ] ) ) infodict [ 'gene_name' ] = None if 'gene_name_primary' in sr ....
def initialized ( name , ** kwargs ) : r'''Defines a new VM with specified arguments , but does not start it . : param name : the Salt _ id node name you wish your VM to have . Each machine must be initialized individually using this function or the " vagrant . running " function , or the vagrant . init execu...
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : 'The VM is already correctly defined' } # define a machine to start later ret , kwargs = _find_init_change ( name , ret , ** kwargs ) if ret [ 'changes' ] == { } : return ret kwargs [ 'start' ] = False __salt__ [ 'vagrant.init' ] ( name , ** kw...
def _recv_internal ( self , timeout ) : """Read a message from the serial device . : param timeout : . . warning : : This parameter will be ignored . The timeout value of the channel is used . : returns : Received message and False ( because not filtering as taken place ) . . . warning : : Flags like ...
try : # ser . read can return an empty string # or raise a SerialException rx_byte = self . ser . read ( ) except serial . SerialException : return None , False if rx_byte and ord ( rx_byte ) == 0xAA : s = bytearray ( self . ser . read ( 4 ) ) timestamp = ( struct . unpack ( '<I' , s ) ) [ 0 ] dlc =...
def _init_client ( ) : """Initialize connection and create table if needed"""
if client is not None : return global _mysql_kwargs , _table_name _mysql_kwargs = { 'host' : __opts__ . get ( 'mysql.host' , '127.0.0.1' ) , 'user' : __opts__ . get ( 'mysql.user' , None ) , 'passwd' : __opts__ . get ( 'mysql.password' , None ) , 'db' : __opts__ . get ( 'mysql.database' , _DEFAULT_DATABASE_NAME ) ,...
def compare_mean_curves ( calc_ref , calc , nsigma = 3 ) : """Compare the hazard curves coming from two different calculations ."""
dstore_ref = datastore . read ( calc_ref ) dstore = datastore . read ( calc ) imtls = dstore_ref [ 'oqparam' ] . imtls if dstore [ 'oqparam' ] . imtls != imtls : raise RuntimeError ( 'The IMTs and levels are different between ' 'calculation %d and %d' % ( calc_ref , calc ) ) sitecol_ref = dstore_ref [ 'sitecol' ] s...
def support_difference_count ( m , m_hat ) : """Count the number of different elements in the support in one triangle , not including the diagonal ."""
m_nnz , m_hat_nnz , intersection_nnz = _nonzero_intersection ( m , m_hat ) return int ( ( m_nnz + m_hat_nnz - ( 2 * intersection_nnz ) ) / 2.0 )
def _add_logging ( dsk , ignore = None ) : """Add logging to a Dask graph . @ param dsk : The Dask graph . @ return : New Dask graph ."""
ctx = current_action ( ) result = { } # Use topological sort to ensure Eliot actions are in logical order of # execution in Dask : keys = toposort ( dsk ) # Give each key a string name . Some keys are just aliases to other # keys , so make sure we have underlying key available . Later on might # want to shorten them as...
def rmswidth ( self , wavelengths = None , threshold = None ) : """Calculate the : ref : ` bandpass RMS width < synphot - formula - rmswidth > ` . Not to be confused with : func : ` photbw ` . Parameters wavelengths : array - like , ` ~ astropy . units . quantity . Quantity ` , or ` None ` Wavelength values...
x = self . _validate_wavelengths ( wavelengths ) . value y = self ( x ) . value if threshold is None : wave = x thru = y else : if ( isinstance ( threshold , numbers . Real ) or ( isinstance ( threshold , u . Quantity ) and threshold . unit == self . _internal_flux_unit ) ) : mask = y >= threshold ...
def get_default_config ( self ) : """Returns the default collector settings"""
config = super ( S3BucketCollector , self ) . get_default_config ( ) config . update ( { 'path' : 'aws.s3' , 'byte_unit' : 'byte' } ) return config
def create_view ( self , request ) : """Initiates the organization and user account creation process"""
try : if request . user . is_authenticated ( ) : return redirect ( "organization_add" ) except TypeError : if request . user . is_authenticated : return redirect ( "organization_add" ) form = org_registration_form ( self . org_model ) ( request . POST or None ) if form . is_valid ( ) : try :...
def exchange_reference ( root_url , service , version ) : """Generate URL for a Taskcluster exchange reference ."""
root_url = root_url . rstrip ( '/' ) if root_url == OLD_ROOT_URL : return 'https://references.taskcluster.net/{}/{}/exchanges.json' . format ( service , version ) else : return '{}/references/{}/{}/exchanges.json' . format ( root_url , service , version )
def add_data_to_database_table ( self , dictList , createStatement = False ) : """* Import data in the list of dictionaries in the requested database table * Also adds HTMIDs and updates the sherlock - catalogue database helper table with the time - stamp of when the imported catlogue was last updated * * Key A...
self . log . debug ( 'starting the ``add_data_to_database_table`` method' ) if len ( dictList ) == 0 : return myPid = self . myPid dbTableName = self . dbTableName if createStatement : writequery ( log = self . log , sqlQuery = createStatement , dbConn = self . cataloguesDbConn , ) insert_list_of_dictionaries_i...
def removeUserData ( self , users = None ) : """Removes users ' content and data . Args : users ( str ) : A comma delimited list of user names . Defaults to ` ` None ` ` . Warning : When ` ` users ` ` is not provided ( ` ` None ` ` ) , all users in the organization will have their data deleted !"""
admin = None portal = None user = None adminusercontent = None userFolder = None userContent = None userItem = None folderContent = None try : admin = arcrest . manageorg . Administration ( securityHandler = self . _securityHandler ) if users is None : print ( "You have selected to remove all users data...
def augment_send ( self , send_func ) : """: param send _ func : a function that sends messages , such as : meth : ` . Bot . send \ * ` : return : a function that wraps around ` ` send _ func ` ` and examines whether the sent message contains an inline keyboard with callback data . If so , future callback...
def augmented ( * aa , ** kw ) : sent = send_func ( * aa , ** kw ) if self . _enable_chat and self . _contains_callback_data ( kw ) : self . capture_origin ( message_identifier ( sent ) ) return sent return augmented
def load ( self ) : """Load our config , log and raise on error ."""
try : merged_configfile = self . get_merged_config ( ) self . yamldocs = yaml . load ( merged_configfile , Loader = Loader ) # Strip out the top level ' None ' s we get from concatenation . # Functionally not required , but makes dumps cleaner . self . yamldocs = [ x for x in self . yamldocs if x ] ...
def encode_data ( self ) : """Encode this command into a byte array that can be sent The actual command this is encoded into depends on the data that was added ."""
assert self . get_empty ( ) is False self . _data_encoded = True if self . _block_allowed : data = self . _encode_transfer_block_data ( ) else : data = self . _encode_transfer_data ( ) return data
def verify_signature ( public_key , scheme , signature , data ) : """< Purpose > Verify that ' signature ' was produced by the private key associated with ' public _ key ' . > > > scheme = ' ecdsa - sha2 - nistp256' > > > public , private = generate _ public _ and _ private ( scheme ) > > > data = b ' The...
# Are the arguments properly formatted ? # If not , raise ' securesystemslib . exceptions . FormatError ' . securesystemslib . formats . PEMECDSA_SCHEMA . check_match ( public_key ) securesystemslib . formats . ECDSA_SCHEME_SCHEMA . check_match ( scheme ) securesystemslib . formats . ECDSASIGNATURE_SCHEMA . check_match...
def get_model_index ( cls , model , default = True ) : '''Returns the default model index for the given model , or the list of indices if default is False . : param model : model name as a string . : raise KeyError : If the provided model does not have any index associated .'''
try : if default : return cls . _model_name_to_default_index [ model ] return cls . _model_name_to_model_idx [ model ] except KeyError : raise KeyError ( 'Could not find any model index defined for model {}.' . format ( model ) )
def data_log_send ( self , fl_1 , fl_2 , fl_3 , fl_4 , fl_5 , fl_6 , force_mavlink1 = False ) : '''Configurable data log probes to be used inside Simulink fl _ 1 : Log value 1 ( float ) fl _ 2 : Log value 2 ( float ) fl _ 3 : Log value 3 ( float ) fl _ 4 : Log value 4 ( float ) fl _ 5 : Log value 5 ( floa...
return self . send ( self . data_log_encode ( fl_1 , fl_2 , fl_3 , fl_4 , fl_5 , fl_6 ) , force_mavlink1 = force_mavlink1 )
def qos_red_profile_drop_probability ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) qos = ET . SubElement ( config , "qos" , xmlns = "urn:brocade.com:mgmt:brocade-qos" ) red_profile = ET . SubElement ( qos , "red-profile" ) profile_id_key = ET . SubElement ( red_profile , "profile-id" ) profile_id_key . text = kwargs . pop ( 'profile_id' ) drop_probability = ET . Sub...
def structure_attrs_fromtuple ( self , obj , cl ) : # type : ( Tuple , Type [ T ] ) - > T """Load an attrs class from a sequence ( tuple ) ."""
conv_obj = [ ] # A list of converter parameters . for a , value in zip ( cl . __attrs_attrs__ , obj ) : # type : ignore # We detect the type by the metadata . converted = self . _structure_attr_from_tuple ( a , a . name , value ) conv_obj . append ( converted ) return cl ( * conv_obj )
def call_remoteckan ( self , * args , ** kwargs ) : # type : ( Any , Any ) - > Dict """Calls the remote CKAN Args : * args : Arguments to pass to remote CKAN call _ action method * * kwargs : Keyword arguments to pass to remote CKAN call _ action method Returns : Dict : The response from the remote CKAN c...
requests_kwargs = kwargs . get ( 'requests_kwargs' , dict ( ) ) credentials = self . _get_credentials ( ) if credentials : requests_kwargs [ 'auth' ] = credentials kwargs [ 'requests_kwargs' ] = requests_kwargs apikey = kwargs . get ( 'apikey' , self . get_api_key ( ) ) kwargs [ 'apikey' ] = apikey return self . re...
def iter_chunks_class ( self ) : """Yield each readable chunk present in the region . Chunks that can not be read for whatever reason are silently skipped . This function returns a : class : ` nbt . chunk . Chunk ` instance ."""
for m in self . get_metadata ( ) : try : yield self . chunkclass ( self . get_chunk ( m . x , m . z ) ) except RegionFileFormatError : pass
def load_classifiers ( algo_defs , env ) : """Load an algorithm into a module . The algorithm is an instance of ` ` AlgorithmDef ` ` class . : param algo _ defs : algorithm definitions : type algo _ defs : AlgorithmDef | list [ AlgorithmDef ] : param env : environment : Example : > > > import sys > > > ...
if not isinstance ( algo_defs , Iterable ) : algo_defs = [ algo_defs , ] load_algorithms ( algo_defs , 'BaseTrainingAlgorithm' , env )
def parse_fn ( fn ) : """This parses the file name and returns the coordinates of the tile Parameters fn : str Filename of a GEOTIFF Returns coords = [ LLC . lat , LLC . lon , URC . lat , URC . lon ]"""
try : parts = os . path . splitext ( os . path . split ( fn ) [ - 1 ] ) [ 0 ] . replace ( 'o' , '.' ) . split ( '_' ) [ : 2 ] coords = [ float ( crds ) for crds in re . split ( '[NSEW]' , parts [ 0 ] + parts [ 1 ] ) [ 1 : ] ] except : coords = [ np . nan ] * 4 return coords
def RecursiveMultiListChildren ( self , urns , limit = None , age = NEWEST_TIME ) : """Recursively lists bunch of directories . Args : urns : List of urns to list children . limit : Max number of children to list ( NOTE : this is per urn ) . age : The age of the items to retrieve . Should be one of ALL _ TI...
checked_urns = set ( ) urns_to_check = urns while True : found_children = [ ] for subject , values in self . MultiListChildren ( urns_to_check , limit = limit , age = age ) : found_children . extend ( values ) yield subject , values checked_urns . update ( urns_to_check ) urns_to_check =...
def extract_metatile ( io , fmt , offset = None ) : """Extract the tile at the given offset ( defaults to 0/0/0 ) and format from the metatile in the file - like object io ."""
ext = fmt . extension if offset is None : tile_name = '0/0/0.%s' % ext else : tile_name = '%d/%d/%d.%s' % ( offset . zoom , offset . column , offset . row , ext ) with zipfile . ZipFile ( io , mode = 'r' ) as zf : if tile_name in zf . namelist ( ) : return zf . read ( tile_name ) else : ...
def notify_multiple_devices ( self , registration_ids = None , message_body = None , message_title = None , message_icon = None , sound = None , condition = None , collapse_key = None , delay_while_idle = False , time_to_live = None , restricted_package_name = None , low_priority = False , dry_run = False , data_messag...
if not isinstance ( registration_ids , list ) : raise InvalidDataError ( 'Invalid registration IDs (should be list)' ) payloads = [ ] registration_id_chunks = self . registration_id_chunks ( registration_ids ) for registration_ids in registration_id_chunks : # appends a payload with a chunk of registration ids here...
def run ( self ) : """Load all paintings into the database"""
df = PaintingsInputData ( ) . load ( ) # rename columns df . rename ( columns = { 'paintingLabel' : 'name' } , inplace = True ) # get artist IDs , map via artist wiki ID artists = models . Entity . query_with_attributes ( 'artist' , self . client ) df [ 'artist_id' ] = df [ 'creator_wiki_id' ] . map ( artists . set_ind...
def get ( consul_url = None , key = None , token = None , recurse = False , decode = False , raw = False ) : '''Get key from Consul : param consul _ url : The Consul server URL . : param key : The key to use as the starting point for the list . : param recurse : Return values recursively beginning at the valu...
ret = { } if not consul_url : consul_url = _get_config ( ) if not consul_url : log . error ( 'No Consul URL found.' ) ret [ 'message' ] = 'No Consul URL found.' ret [ 'res' ] = False return ret if not key : raise SaltInvocationError ( 'Required argument "key" is missing.' ) q...
def safe_mkdtemp ( cleaner = _mkdtemp_atexit_cleaner , ** kw ) : """Create a temporary directory that is cleaned up on process exit . Arguments are as to tempfile . mkdtemp . : API : public"""
# Proper lock sanitation on fork [ issue 6721 ] would be desirable here . with _MKDTEMP_LOCK : return register_rmtree ( tempfile . mkdtemp ( ** kw ) , cleaner = cleaner )
def get_all_users ( self , path_prefix = '/' , marker = None , max_items = None ) : """List the users that have the specified path prefix . : type path _ prefix : string : param path _ prefix : If provided , only users whose paths match the provided prefix will be returned . : type marker : string : param...
params = { 'PathPrefix' : path_prefix } if marker : params [ 'Marker' ] = marker if max_items : params [ 'MaxItems' ] = max_items return self . get_response ( 'ListUsers' , params , list_marker = 'Users' )
def get_node_selectable ( node , context ) : """Return the Selectable Union [ Table , CTE ] associated with the node ."""
query_path = node . query_path if query_path not in context . query_path_to_selectable : raise AssertionError ( u'Unable to find selectable for query path {} with context {}.' . format ( query_path , context ) ) selectable = context . query_path_to_selectable [ query_path ] return selectable
def normalize ( opts ) : """Performs various normalization functions on opts , the provided namespace . It is assumed that opts has already been validated with anchorhub . validation _ opts . validate ( ) . : param opts : a namespace containing options for AnchorHub : return : a namespace with the attribute...
opts_dict = vars ( opts ) add_is_dir ( opts_dict ) ensure_directories_end_in_separator ( opts_dict ) add_abs_path_directories ( opts_dict ) add_open_close_wrappers ( opts_dict ) add_wrapper_regex ( opts_dict ) return Bunch ( opts_dict )
def eval_objfn ( self ) : r"""Compute components of objective function as well as total contribution to objective function . Data fidelity term is : math : ` ( 1/2 ) \ | H \ mathbf { x } - \ mathbf { s } \ | _ 2 ^ 2 ` and regularisation term is : math : ` \ | W _ { \ mathrm { tv } } \ sqrt { ( G _ r \ mathb...
Ef = self . Af * self . Xf - self . Sf dfd = sl . rfl2norm2 ( Ef , self . S . shape , axis = self . axes ) / 2.0 reg = np . sum ( self . Wtv * np . sqrt ( np . sum ( self . obfn_gvar ( ) ** 2 , axis = self . saxes ) ) ) obj = dfd + self . lmbda * reg return ( obj , dfd , reg )
def parametric_function_api ( scope_name = None , param_desc = None ) : """Decorator for parametric functions . The decorated function is always called under a parameter scope ` ` scope _ name ` ` . Also , the decorator adds an additional argument ` ` name ` ` ( : obj : ` str ` , default is ` ` None ` ` ) a...
if scope_name is None : scope_name = name def parametric_function_api_inside ( func ) : from nnabla . utils . py23_compatible import getargspec import inspect name = func . __name__ doc = func . __doc__ if param_desc : indent = 8 try : desc = map ( lambda d : ' ' * in...
def search ( self , pattern = "*" , mode = "both" ) : """Perform a pattern - based search on keyword names and documentation The pattern matching is insensitive to case . The function returns a list of tuples of the form library _ id , library _ name , keyword _ name , keyword _ synopsis , sorted by library i...
pattern = self . _glob_to_sql ( pattern ) COND = "(keyword.name like ? OR keyword.doc like ?)" args = [ pattern , pattern ] if mode == "name" : COND = "(keyword.name like ?)" args = [ pattern , ] sql = """SELECT collection.collection_id, collection.name, keyword.name, keyword.doc FROM collectio...
def _generate_examples ( self , images_dir_path ) : """Generate flower images and labels given the image directory path . Args : images _ dir _ path : path to the directory where the images are stored . Yields : The image path and its corresponding label ."""
parent_dir = tf . io . gfile . listdir ( images_dir_path ) [ 0 ] walk_dir = os . path . join ( images_dir_path , parent_dir ) dirs = tf . io . gfile . listdir ( walk_dir ) for d in dirs : if tf . io . gfile . isdir ( os . path . join ( walk_dir , d ) ) : for full_path , _ , fname in tf . io . gfile . walk (...
def get_plot ( self , color_set = 'PuBu' , grid_off = True , axis_off = True , show_area = False , alpha = 1 , off_color = 'red' , direction = None , bar_pos = ( 0.75 , 0.15 , 0.05 , 0.65 ) , bar_on = False , units_in_JPERM2 = True , legend_on = True , aspect_ratio = ( 8 , 8 ) , custom_colors = { } ) : """Get the W...
import matplotlib as mpl import matplotlib . pyplot as plt import mpl_toolkits . mplot3d as mpl3 color_list , color_proxy , color_proxy_on_wulff , miller_on_wulff , e_surf_on_wulff = self . _get_colors ( color_set , alpha , off_color , custom_colors = custom_colors ) if not direction : # If direction is not specified ,...
def match_keyword ( token , keywords ) : """Checks if the given token represents one of the given keywords"""
if not token : return False if not token . is_keyword : return False return token . value . upper ( ) in keywords
def to_html ( self , wrap_slash = False ) : """Render a Text MessageElement as html . : param wrap _ slash : Whether to replace slashes with the slash plus the html < wbr > tag which will help to e . g . wrap html in small cells if it contains a long filename . Disabled by default as it may cause side effec...
if self . text is None : return else : text = '' for t in self . text : text += t . to_html ( ) + ' ' text = ' ' . join ( text . split ( ) ) if wrap_slash : # This is a hack to make text wrappable with long filenames TS 3.3 text = text . replace ( '/' , '/<wbr>' ) text = text . replace (...
def get_mapping ( self , index = None , doc_type = None , params = None ) : """Retrieve mapping definition of index or index / type . ` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / indices - get - mapping . html > ` _ : arg index : A comma - separated list of index names ...
return self . transport . perform_request ( "GET" , _make_path ( index , "_mapping" , doc_type ) , params = params )
def clean ( config ) : """Delete a wily cache . : param config : The configuration : type config : : class : ` wily . config . WilyConfig `"""
if not exists ( config ) : logger . debug ( "Wily cache does not exist, skipping" ) return shutil . rmtree ( config . cache_path ) logger . debug ( "Deleted wily cache" )
def create_channel ( self , name , values = None , * , shape = None , units = None , dtype = None , ** kwargs ) -> Channel : """Append a new channel . Parameters name : string Unique name for this channel . values : array ( optional ) Array . If None , an empty array equaling the data shape is created ....
if name in self . channel_names : warnings . warn ( name , wt_exceptions . ObjectExistsWarning ) return self [ name ] elif name in self . variable_names : raise wt_exceptions . NameNotUniqueError ( name ) require_kwargs = { "chunks" : True } if values is None : if shape is None : require_kwargs ...
def get_displayable_field_names ( self ) : """Return all field names , excluding reverse foreign key relationships ."""
return [ f . name for f in self . model . _meta . get_fields ( ) if not f . one_to_many ]
def _parse_ignores ( self ) : """Parse the ignores setting from the pylintrc file if available ."""
error_message = ( colorama . Fore . RED + "{} does not appear to be a valid pylintrc file" . format ( self . rcfile ) + colorama . Fore . RESET ) if not os . path . isfile ( self . rcfile ) : if not self . _is_using_default_rcfile ( ) : print ( error_message ) sys . exit ( 1 ) else : ret...
def skipBytes ( self , nroBytes ) : """Skips the specified number as parameter to the current value of the L { WriteData } stream . @ type nroBytes : int @ param nroBytes : The number of bytes to skip ."""
self . data . seek ( nroBytes + self . data . tell ( ) )
def writeprettyxml ( self , filename_or_file = None , indent = " " , newl = os . linesep , encoding = "UTF-8" ) : """Write the manifest as XML to a file or file object"""
if not filename_or_file : filename_or_file = self . filename if isinstance ( filename_or_file , ( str , unicode ) ) : filename_or_file = open ( filename_or_file , "wb" ) xmlstr = self . toprettyxml ( indent , newl , encoding ) filename_or_file . write ( xmlstr ) filename_or_file . close ( )
def _masquerade ( origin : str , orig : ServiceDefn , new : ServiceDefn , ** map : str ) -> str : """build an origin URL such that the orig has all of the mappings to new defined by map"""
origin : ParseResult = urlparse ( origin ) prev_maps = { } if origin . query : prev_maps = { k : v for k , v in parse_qsl ( origin . query ) } r_args = { } for new_k , orig_k in map . items ( ) : assert new_k in new . rpcs , [ new_k , new . rpcs ] assert orig_k in orig . rpcs , [ orig_k , orig . rpcs ] ...
def batch_get_pay_giftcard ( self , effective = True , offset = 0 , count = 10 ) : """批量查询支付后投放卡券的规则 详情请参见 https : / / mp . weixin . qq . com / wiki ? id = mp1466494654 _ K9rNz : param effective : 是否仅查询生效的规则 : type effective : bool : param offset : 起始偏移量 : type offset : int : param count : 查询的数量 : t...
return self . _post ( 'card/paygiftcard/batchget' , data = { 'type' : 'RULE_TYPE_PAY_MEMBER_CARD' , 'effective' : effective , 'offset' : offset , 'count' : count , } , )
def addImagePath ( new_path ) : """Convenience function . Adds a path to the list of paths to search for images . Can be a URL ( but must be accessible ) ."""
if os . path . exists ( new_path ) : Settings . ImagePaths . append ( new_path ) elif "http://" in new_path or "https://" in new_path : request = requests . get ( new_path ) if request . status_code < 400 : # Path exists Settings . ImagePaths . append ( new_path ) else : raise OSError ( ...
def parse_peddy_sexcheck ( handle : TextIO ) : """Parse Peddy sexcheck output ."""
data = { } samples = csv . DictReader ( handle ) for sample in samples : data [ sample [ 'sample_id' ] ] = { 'predicted_sex' : sample [ 'predicted_sex' ] , 'het_ratio' : float ( sample [ 'het_ratio' ] ) , 'error' : True if sample [ 'error' ] == 'True' else False , } return data
def boolean ( meshes , operation = 'difference' ) : """Run an operation on a set of meshes"""
script = operation + '(){' for i in range ( len ( meshes ) ) : script += 'import(\"$mesh_' + str ( i ) + '\");' script += '}' return interface_scad ( meshes , script )