signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def posterior_inf ( self , X = None , posterior = None ) : """Do the posterior inference on the parameters given this kernels functions and the model posterior , which has to be a GPy posterior , usually found at m . posterior , if m is a GPy model . If not given we search for the the highest parent to be a mod...
if X is None : try : X = self . _highest_parent_ . X except NameError : raise RuntimeError ( "This kernel is not part of a model and cannot be used for posterior inference" ) if posterior is None : try : posterior = self . _highest_parent_ . posterior except NameError : r...
def install_middleware ( self ) : """Attempts to insert the ScoutApm middleware as the first middleware ( first on incoming requests , last on outgoing responses ) ."""
from django . conf import settings # If MIDDLEWARE is set , update that , with handling of tuple vs array forms if getattr ( settings , "MIDDLEWARE" , None ) is not None : if isinstance ( settings . MIDDLEWARE , tuple ) : settings . MIDDLEWARE = ( ( "scout_apm.django.middleware.MiddlewareTimingMiddleware" ,...
def is_cython_function ( fn ) : """Checks if a function is compiled w / Cython ."""
if hasattr ( fn , "__func__" ) : fn = fn . __func__ # Class method , static method name = type ( fn ) . __name__ return ( name == "method_descriptor" or name == "cython_function_or_method" or name == "builtin_function_or_method" )
def request_stop ( self , message = '' , exit_code = 0 ) : """Remove pid and stop daemon : return : None"""
# Log an error message if exit code is not 0 # Force output to stderr if exit_code : if message : logger . error ( message ) try : sys . stderr . write ( message ) except Exception : # pylint : disable = broad - except pass logger . error ( "Sorry, I bail out, exi...
def get ( self , filename ) : """Download a distribution archive from the configured Amazon S3 bucket . : param filename : The filename of the distribution archive ( a string ) . : returns : The pathname of a distribution archive on the local file system or : data : ` None ` . : raises : : exc : ` . CacheBa...
timer = Timer ( ) self . check_prerequisites ( ) with PatchedBotoConfig ( ) : # Check if the distribution archive is available . raw_key = self . get_cache_key ( filename ) logger . info ( "Checking if distribution archive is available in S3 bucket: %s" , raw_key ) key = self . s3_bucket . get_key ( raw_key...
def update ( self , attributes = None ) : """Updates the entry with attributes ."""
if attributes is None : attributes = { } attributes [ 'content_type_id' ] = self . sys [ 'content_type' ] . id return super ( Entry , self ) . update ( attributes )
async def _redirect_async ( self , redirect , auth ) : """Redirect the client endpoint using a Link DETACH redirect response . : param redirect : The Link DETACH redirect details . : type redirect : ~ uamqp . errors . LinkRedirect : param auth : Authentication credentials to the redirected endpoint . : ty...
# pylint : disable = protected - access if not self . _connection . cbs : _logger . info ( "Closing non-CBS session." ) await asyncio . shield ( self . _session . destroy_async ( ) ) self . _session = None self . _auth = auth self . _hostname = self . _remote_address . hostname await self . _connection . redire...
def parseSyslog ( msg ) : """Parses Syslog messages ( RFC 5424) The ` Syslog Message Format ( RFC 5424) < https : / / tools . ietf . org / html / rfc5424 # section - 6 > ` _ can be parsed with simple whitespace tokenization : : SYSLOG - MSG = HEADER SP STRUCTURED - DATA [ SP MSG ] HEADER = PRI VERSION SP ...
tokens = msg . split ( ' ' , 6 ) result = { } if len ( tokens ) > 0 : pri = tokens [ 0 ] start = pri . find ( '<' ) stop = pri . find ( '>' ) if start != - 1 and stop != - 1 : result [ 'pri' ] = pri [ start + 1 : stop ] else : result [ 'pri' ] = '' if stop != - 1 and len ( pri ) ...
def _diff_cache_subnet_group ( current , desired ) : '''If you need to enhance what modify _ cache _ subnet _ group ( ) considers when deciding what is to be ( or can be ) updated , add it to ' modifiable ' below . It ' s a dict mapping the param as used in modify _ cache _ subnet _ group ( ) to that in describ...
modifiable = { 'CacheSubnetGroupDescription' : 'CacheSubnetGroupDescription' , 'SubnetIds' : 'SubnetIds' } need_update = { } for m , o in modifiable . items ( ) : if m in desired : if not o : # Always pass these through - let AWS do the math . . . need_update [ m ] = desired [ m ] else :...
def chisq ( psr , formbats = False ) : """Return the total chisq for the current timing solution , removing noise - averaged mean residual , and ignoring deleted points ."""
if formbats : psr . formbats ( ) res , err = psr . residuals ( removemean = False ) [ psr . deleted == 0 ] , psr . toaerrs [ psr . deleted == 0 ] res -= numpy . sum ( res / err ** 2 ) / numpy . sum ( 1 / err ** 2 ) return numpy . sum ( res * res / ( 1e-12 * err * err ) )
def get_torrent_file ( self , fp , headers = None , cb = None , num_cb = 10 ) : """Get a torrent file ( see to get _ file ) : type fp : file : param fp : The file pointer of where to put the torrent : type headers : dict : param headers : Headers to be passed : type cb : function : param cb : a callback...
return self . get_file ( fp , headers , cb , num_cb , torrent = True )
def write_collection_from_tmpfile ( self , collection_id , tmpfi , parent_sha , auth_info , commit_msg = '' ) : """Given a collection _ id , temporary filename of content , branch and auth _ info"""
return self . write_doc_from_tmpfile ( collection_id , tmpfi , parent_sha , auth_info , commit_msg , doctype_display_name = "collection" )
def convert_to_row_table ( self , add_units = True ) : '''Converts the block into row titled elements . These elements are copied into the return table , which can be much longer than the original block . Args : add _ units : Indicates if units should be appened to each row item . Returns : A row - titled...
rtable = [ ] if add_units : relavent_units = self . get_relavent_units ( ) # Create a row for each data element for row_index in range ( self . start [ 0 ] , self . end [ 0 ] ) : for column_index in range ( self . start [ 1 ] , self . end [ 1 ] ) : cell = self . table [ row_index ] [ column_index ] ...
def load_info ( self ) : '''Get info from logged account'''
headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/login.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://' + self . domain + '/team_news.phtml' , headers = headers ) . content soup = BeautifulSoup ( req ) self ...
def cov_dvrpmllbb_to_vxyz_single ( d , e_d , e_vr , pmll , pmbb , cov_pmllbb , l , b ) : """NAME : cov _ dvrpmllbb _ to _ vxyz PURPOSE : propagate distance , radial velocity , and proper motion uncertainties to Galactic coordinates for scalar inputs INPUT : d - distance [ kpc , as / mas for plx ] e _ ...
M = _K * sc . array ( [ [ pmll , d , 0. ] , [ pmbb , 0. , d ] ] ) cov_dpmllbb = sc . zeros ( ( 3 , 3 ) ) cov_dpmllbb [ 0 , 0 ] = e_d ** 2. cov_dpmllbb [ 1 : 3 , 1 : 3 ] = cov_pmllbb cov_vlvb = sc . dot ( M , sc . dot ( cov_dpmllbb , M . T ) ) cov_vrvlvb = sc . zeros ( ( 3 , 3 ) ) cov_vrvlvb [ 0 , 0 ] = e_vr ** 2. cov_v...
def get_neighbors ( self , site , r , include_index = False , include_image = False ) : """Get all neighbors to a site within a sphere of radius r . Excludes the site itself . Args : site ( Site ) : Which is the center of the sphere . r ( float ) : Radius of sphere . include _ index ( bool ) : Whether the...
nn = self . get_sites_in_sphere ( site . coords , r , include_index = include_index , include_image = include_image ) return [ d for d in nn if site != d [ 0 ] ]
def diff_content ( a , reference , progressbar = None ) : """Return list of tuples where content differ . Tuple structure : ( identifier , hash in a , hash in reference ) Assumes list of identifiers in a and b are identical . Storage broker of reference used to generate hash for files in a . : param a : f...
difference = [ ] for i in a . identifiers : fpath = a . item_content_abspath ( i ) calc_hash = reference . _storage_broker . hasher ( fpath ) ref_hash = reference . item_properties ( i ) [ "hash" ] if calc_hash != ref_hash : info = ( i , calc_hash , ref_hash ) difference . append ( info ...
def init ( size = 250 ) : """Initialize mpv ."""
player = mpv . MPV ( start_event_thread = False ) player [ "force-window" ] = "immediate" player [ "keep-open" ] = "yes" player [ "geometry" ] = f"{size}x{size}" player [ "autofit" ] = f"{size}x{size}" player [ "title" ] = "bum" return player
def save ( arr , filename , hdr = False , force = True , use_compression = False ) : r"""Save the image ` ` arr ` ` as filename using information encoded in ` ` hdr ` ` . The target image format is determined by the ` ` filename ` ` suffix . If the ` ` force ` ` parameter is set to true , an already existing im...
logger = Logger . getInstance ( ) logger . info ( 'Saving image as {}...' . format ( filename ) ) # Check image file existance if not force and os . path . exists ( filename ) : raise ImageSavingError ( 'The target file {} already exists.' . format ( filename ) ) # Roll axes from x , y , z , c to z , y , x , c if a...
def putenv ( key , value ) : """Like ` os . putenv ` but takes unicode under Windows + Python 2 Args : key ( pathlike ) : The env var to get value ( pathlike ) : The value to set Raises : ValueError"""
key = path2fsn ( key ) value = path2fsn ( value ) if is_win and PY2 : try : set_windows_env_var ( key , value ) except WindowsError : # py3 + win fails here raise ValueError else : try : os . putenv ( key , value ) except OSError : # win + py3 raise here for invalid keys which is...
def sync_allocations ( self ) : """Synchronize vxlan _ allocations table with configured tunnel ranges ."""
# determine current configured allocatable vnis vxlan_vnis = set ( ) for tun_min , tun_max in self . tunnel_ranges : vxlan_vnis |= set ( six . moves . range ( tun_min , tun_max + 1 ) ) session = bc . get_writer_session ( ) with session . begin ( subtransactions = True ) : # remove from table unallocated tunnels not...
def reduce ( self , key , values ) : """Select the image with the minimum distance Args : key : ( see mapper ) values : ( see mapper ) Yields : A tuple in the form of ( key , value ) key : Image name value : Image as jpeg byte data"""
dist , key , value = min ( values , key = lambda x : x [ 0 ] ) print ( 'MinDist[%f]' % dist ) yield key , value
def uniq_to_level_ipix ( uniq ) : """Convert a HEALPix cell uniq number to its ( level , ipix ) equivalent . A uniq number is a 64 bits integer equaling to : ipix + 4 * ( 4 * * level ) . Please read this ` paper < http : / / ivoa . net / documents / MOC / 20140602 / REC - MOC - 1.0-20140602 . pdf > ` _ for mo...
uniq = np . asarray ( uniq , dtype = np . int64 ) level = ( np . log2 ( uniq // 4 ) ) // 2 level = level . astype ( np . int64 ) _validate_level ( level ) ipix = uniq - ( 1 << 2 * ( level + 1 ) ) _validate_npix ( level , ipix ) return level , ipix
def write_taxon_info ( taxon , include_anc , output ) : """Writes out data from ` taxon ` to the ` output ` stream to demonstrate the attributes of a taxon object . ( currently some lines are commented out until the web - services call returns more info . See : https : / / github . com / OpenTreeOfLife / taxo...
output . write ( u'Taxon info for OTT ID (ot:ottId) = {}\n' . format ( taxon . ott_id ) ) output . write ( u' name (ot:ottTaxonName) = "{}"\n' . format ( taxon . name ) ) if taxon . synonyms : output . write ( u' known synonyms: "{}"\n' . format ( '", "' . join ( taxon . synonyms ) ) ) else : output . wri...
def get_objective_bank_query_session ( self , proxy ) : """Gets the OsidSession associated with the objective bank query service . : param proxy : a proxy : type proxy : ` ` osid . proxy . Proxy ` ` : return : an ` ` ObjectiveBankQuerySession ` ` : rtype : ` ` osid . learning . ObjectiveBankQuerySession ` `...
if not self . supports_objective_bank_query ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise OperationFailed ( ) proxy = self . _convert_proxy ( proxy ) try : session = sessions . ObjectiveBankQuerySession ( proxy = proxy , runtime = self . _runtime ) except Attribut...
def addLOADDEV ( rh ) : """Sets the LOADDEV statement in the virtual machine ' s directory entry . Input : Request Handle with the following properties : function - ' CHANGEVM ' subfunction - ' ADDLOADDEV ' userid - userid of the virtual machine parms [ ' boot ' ] - Boot program number parms [ ' addr ...
rh . printSysLog ( "Enter changeVM.addLOADDEV" ) # scpDataType and scpData must appear or disappear concurrently if ( 'scpData' in rh . parms and 'scpDataType' not in rh . parms ) : msg = msgs . msg [ '0014' ] [ 1 ] % ( modId , "scpData" , "scpDataType" ) rh . printLn ( "ES" , msg ) rh . updateResults ( msg...
def cublasCgeru ( handle , m , n , alpha , x , incx , y , incy , A , lda ) : """Rank - 1 operation on complex general matrix ."""
status = _libcublas . cublasCgeru_v2 ( handle , m , n , ctypes . byref ( cuda . cuFloatComplex ( alpha . real , alpha . imag ) ) , int ( x ) , incx , int ( y ) , incy , int ( A ) , lda ) cublasCheckStatus ( status )
def inpaint ( self , rescale_factor = 1.0 ) : """Fills in the zero pixels in the image . Parameters rescale _ factor : float amount to rescale the image for inpainting , smaller numbers increase speed Returns : obj : ` DepthImage ` depth image with zero pixels filled in"""
# get original shape orig_shape = ( self . height , self . width ) # form inpaint kernel inpaint_kernel = np . array ( [ [ 1 , 1 , 1 ] , [ 1 , 0 , 1 ] , [ 1 , 1 , 1 ] ] ) # resize the image resized_data = self . resize ( rescale_factor , interp = 'nearest' ) . data # inpaint the smaller image cur_data = resized_data . ...
def validate ( self , value ) : """Validates the inputted value against this columns rules . If the inputted value does not pass , then a validation error will be raised . Override this method in column sub - classes for more specialized validation . : param value | < variant > : return < bool > success"""
# check for the required flag if self . testFlag ( self . Flags . Required ) and not self . testFlag ( self . Flags . AutoAssign ) : if self . isNull ( value ) : msg = '{0} is a required column.' . format ( self . name ( ) ) raise orb . errors . ColumnValidationError ( self , msg ) # otherwise , we ...
def _parse_commit ( self , ref ) : """Parse a commit command ."""
lineno = self . lineno mark = self . _get_mark_if_any ( ) author = self . _get_user_info ( b'commit' , b'author' , False ) more_authors = [ ] while True : another_author = self . _get_user_info ( b'commit' , b'author' , False ) if another_author is not None : more_authors . append ( another_author ) ...
def url_assembler ( query_string , no_redirect = 0 , no_html = 0 , skip_disambig = 0 ) : """Assembler of parameters for building request query . Args : query _ string : Query to be passed to DuckDuckGo API . no _ redirect : Skip HTTP redirects ( for ! bang commands ) . Default - False . no _ html : Remove H...
params = [ ( 'q' , query_string . encode ( "utf-8" ) ) , ( 'format' , 'json' ) ] if no_redirect : params . append ( ( 'no_redirect' , 1 ) ) if no_html : params . append ( ( 'no_html' , 1 ) ) if skip_disambig : params . append ( ( 'skip_disambig' , 1 ) ) return '/?' + urlencode ( params )
def clean_tuple ( t0 , clean_item_fn = None ) : """Return a json - clean tuple . Will log info message for failures ."""
clean_item_fn = clean_item_fn if clean_item_fn else clean_item l = list ( ) for index , item in enumerate ( t0 ) : cleaned_item = clean_item_fn ( item ) l . append ( cleaned_item ) return tuple ( l )
def addContentLen ( self , content , len ) : """Append the extra substring to the node content . NOTE : In contrast to xmlNodeSetContentLen ( ) , @ content is supposed to be raw text , so unescaped XML special chars are allowed , entity references are not supported ."""
libxml2mod . xmlNodeAddContentLen ( self . _o , content , len )
def resource_path ( package_name : str , relative_path : typing . Union [ str , Path ] ) -> Path : """Get absolute path to resource , works for dev and for PyInstaller"""
relative_path = Path ( relative_path ) methods = [ _get_from_dev , _get_from_package , _get_from_sys , ] for method in methods : path = method ( package_name , relative_path ) if path . exists ( ) : return path raise FileNotFoundError ( relative_path )
def _get_types_from_sample ( result_vars , sparql_results_json ) : """Return types if homogenous within sample Compare up to 10 rows of results to determine homogeneity . DESCRIBE and CONSTRUCT queries , for example , : param result _ vars : : param sparql _ results _ json :"""
total_bindings = len ( sparql_results_json [ 'results' ] [ 'bindings' ] ) homogeneous_types = { } for result_var in result_vars : var_types = set ( ) var_datatypes = set ( ) for i in range ( 0 , min ( total_bindings , 10 ) ) : binding = sparql_results_json [ 'results' ] [ 'bindings' ] [ i ] ...
def get_mfd ( self , slip , area , shear_modulus = 30.0 ) : '''Calculates activity rate on the fault : param float slip : Slip rate in mm / yr : param fault _ width : Width of the fault ( km ) : param float disp _ length _ ratio : Displacement to length ratio ( dimensionless ) : param float shear _ mo...
# Working in Nm so convert : shear _ modulus - GPa - > Nm # area - km * * 2 . - > m * * 2. # slip - mm / yr - > m / yr moment_rate = ( shear_modulus * 1.E9 ) * ( area * 1.E6 ) * ( slip / 1000. ) moment_mag = _scale_moment ( self . mmax , in_nm = True ) characteristic_rate = moment_rate / moment_mag if self . sigma and ...
def load_servers_from_env ( self , filter = [ ] , dynamic = None ) : '''Load the name servers environment variable and parse each server in the list . @ param filter Restrict the parsed objects to only those in this path . For example , setting filter to [ [ ' / ' , ' localhost ' , ' host . cxt ' , ' comp1 ...
if dynamic == None : dynamic = self . _dynamic if NAMESERVERS_ENV_VAR in os . environ : servers = [ s for s in os . environ [ NAMESERVERS_ENV_VAR ] . split ( ';' ) if s ] self . _parse_name_servers ( servers , filter , dynamic )
def _gzip_fastq ( in_file , out_dir = None ) : """gzip a fastq file if it is not already gzipped , handling conversion from bzip to gzipped files"""
if fastq . is_fastq ( in_file ) and not objectstore . is_remote ( in_file ) : if utils . is_bzipped ( in_file ) : return _bzip_gzip ( in_file , out_dir ) elif not utils . is_gzipped ( in_file ) : if out_dir : gzipped_file = os . path . join ( out_dir , os . path . basename ( in_file ...
def tem ( fEM , off , freq , time , signal , ft , ftarg , conv = True ) : r"""Return the time - domain response of the frequency - domain response fEM . This function is called from one of the above modelling routines . No input - check is carried out here . See the main description of : mod : ` model ` for i...
# 1 . Scale frequencies if switch - on / off response # Step function for causal times is like a unit fct , therefore an impulse # in frequency domain if signal in [ - 1 , 1 ] : # Divide by signal / ( 2j * pi * f ) to obtain step response fact = signal / ( 2j * np . pi * freq ) else : fact = 1 # 2 . f - > t tra...
def resize ( self , shape ) : """Resize all attached buffers with the given shape Parameters shape : tuple of two integers New buffer shape ( h , w ) , to be applied to all currently attached buffers . For buffers that are a texture , the number of color channels is preserved ."""
# Check if not ( isinstance ( shape , tuple ) and len ( shape ) == 2 ) : raise ValueError ( 'RenderBuffer shape must be a 2-element tuple' ) # Resize our buffers for buf in ( self . color_buffer , self . depth_buffer , self . stencil_buffer ) : if buf is None : continue shape_ = shape if isinsta...
def _apply_dvportgroup_config ( pg_name , pg_spec , pg_conf ) : '''Applies the values in conf to a distributed portgroup spec pg _ name The name of the portgroup pg _ spec The vim . DVPortgroupConfigSpec to apply the config to pg _ conf The portgroup config'''
log . trace ( 'Building portgroup\'s \'%s\' spec' , pg_name ) if 'name' in pg_conf : pg_spec . name = pg_conf [ 'name' ] if 'description' in pg_conf : pg_spec . description = pg_conf [ 'description' ] if 'num_ports' in pg_conf : pg_spec . numPorts = pg_conf [ 'num_ports' ] if 'type' in pg_conf : pg_spec...
def compute_tasks ( self , ** kwargs ) : """perfrom checks and build tasks : return : list of tasks : rtype : list ( kser . sequencing . operation . Operation )"""
params = self . _prebuild ( ** kwargs ) if not params : params = dict ( kwargs ) return self . _build_tasks ( ** params )
async def get_controller ( self ) : """Return a Controller instance for the currently connected model . : return Controller :"""
from juju . controller import Controller controller = Controller ( jujudata = self . _connector . jujudata ) kwargs = self . connection ( ) . connect_params ( ) kwargs . pop ( 'uuid' ) await controller . _connect_direct ( ** kwargs ) return controller
def plot ( parameterized , fignum = None , ax = None , colors = None , figsize = ( 12 , 6 ) ) : """Plot latent space X in 1D : - if fig is given , create input _ dim subplots in fig and plot in these - if ax is given plot input _ dim 1D latent space plots of X into each ` axis ` - if neither fig nor ax is giv...
if ax is None : fig = pb . figure ( num = fignum , figsize = figsize ) if colors is None : from . . Tango import mediumList from itertools import cycle colors = cycle ( mediumList ) pb . clf ( ) else : colors = iter ( colors ) lines = [ ] fills = [ ] bg_lines = [ ] means , variances = parameteri...
def monitor_session_span_command_src_tengigabitethernet_val ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) monitor = ET . SubElement ( config , "monitor" , xmlns = "urn:brocade.com:mgmt:brocade-span" ) session = ET . SubElement ( monitor , "session" ) session_number_key = ET . SubElement ( session , "session-number" ) session_number_key . text = kwargs . pop ( 'session_number' ) span_comma...
def get_precomposed_chars ( ) : """Return the set of IPA characters that are defined in normal form C in the spec . As of 2015 , this is only the voiceless palatal fricative , ç ."""
return set ( [ letter for letter in chart . consonants if unicodedata . normalize ( 'NFD' , letter ) != letter ] )
def as_dataframe ( self , pattern = '*' , max_rows = None ) : """Creates a pandas dataframe from the descriptors that match the filters . Args : pattern : An optional pattern to further filter the descriptors . This can include Unix shell - style wildcards . E . g . ` ` " aws * " ` ` , ` ` " * cluster * " ` `...
data = [ ] for i , resource in enumerate ( self . list ( pattern ) ) : if max_rows is not None and i >= max_rows : break labels = ', ' . join ( [ l . key for l in resource . labels ] ) data . append ( [ resource . type , resource . display_name , labels ] ) return pandas . DataFrame ( data , columns...
def _get_url ( self , obj ) : """Gets object url"""
format_kwargs = { 'app_label' : obj . _meta . app_label , } try : format_kwargs [ 'model_name' ] = getattr ( obj . __class__ , 'get_url_name' ) ( ) except AttributeError : format_kwargs [ 'model_name' ] = obj . _meta . object_name . lower ( ) return self . _default_view_name % format_kwargs
def shadow_calc ( data ) : """计算上下影线 Arguments : data { DataStruct . slice } - - 输入的是一个行情切片 Returns : up _ shadow { float } - - 上影线 down _ shdow { float } - - 下影线 entity { float } - - 实体部分 date { str } - - 时间 code { str } - - 代码"""
up_shadow = abs ( data . high - ( max ( data . open , data . close ) ) ) down_shadow = abs ( data . low - ( min ( data . open , data . close ) ) ) entity = abs ( data . open - data . close ) towards = True if data . open < data . close else False print ( '=' * 15 ) print ( 'up_shadow : {}' . format ( up_shadow ) ) prin...
def group ( self ) : """Returns the periodic table group of the element ."""
z = self . Z if z == 1 : return 1 if z == 2 : return 18 if 3 <= z <= 18 : if ( z - 2 ) % 8 == 0 : return 18 elif ( z - 2 ) % 8 <= 2 : return ( z - 2 ) % 8 else : return 10 + ( z - 2 ) % 8 if 19 <= z <= 54 : if ( z - 18 ) % 18 == 0 : return 18 else : re...
def put ( self ) : """Updates this task type on the saltant server . Returns : : class : ` saltant . models . container _ task _ type . ContainerTaskType ` : A task type model instance representing the task type just updated ."""
return self . manager . put ( id = self . id , name = self . name , description = self . description , command_to_run = self . command_to_run , environment_variables = self . environment_variables , required_arguments = self . required_arguments , required_arguments_default_values = ( self . required_arguments_default_...
def put ( self , source , rel_path , metadata = None ) : """Puts to only the first upstream . This is to be symmetric with put _ stream ."""
return self . upstreams [ 0 ] . put ( source , rel_path , metadata )
def cache_connect ( database = None ) : """Returns a connection object to a sqlite database . Args : database ( str , optional ) : The path to the database the user wishes to connect to . If not specified , a default is chosen using : func : ` . cache _ file ` . If the special database name ' : memory : ' ...
if database is None : database = cache_file ( ) if os . path . isfile ( database ) : # just connect to the database as - is conn = sqlite3 . connect ( database ) else : # we need to populate the database conn = sqlite3 . connect ( database ) conn . executescript ( schema ) with conn as cur : # turn on f...
def _request ( self , ** kwargs ) : '''a helper method for processing all request types'''
response = None error = '' code = 0 # send request from requests import request try : response = request ( ** kwargs ) # handle response if self . handle_response : response , error , code = self . handle_response ( response ) else : code = response . status_code # handle errors except E...
def get_email_context ( self , ** kwargs ) : '''Overrides EmailRecipientMixin'''
includeName = kwargs . pop ( 'includeName' , True ) context = super ( TemporaryEventRegistration , self ) . get_email_context ( ** kwargs ) context . update ( { 'title' : self . event . name , 'start' : self . event . firstOccurrenceTime , 'end' : self . event . lastOccurrenceTime , } ) if includeName : context . u...
def find_record ( self , domain , record_type , name = None , data = None ) : """Returns a single record for this domain that matches the supplied search criteria . If no record matches , a DomainRecordNotFound exception will be raised . If more than one matches , a DomainRecordNotUnique exception will be r...
return domain . find_record ( record_type = record_type , name = name , data = data )
def publish ( self , message_type , client_id , client_storage , * args , ** kwargs ) : """Publishes a message"""
p = self . pack ( message_type , client_id , client_storage , args , kwargs ) self . client . publish ( self . channel , p )
def make_plot ( self ) : """Make the horizon plot ."""
self . get_contour_values ( ) # sets levels of main contour plot colors1 = [ 'blue' , 'green' , 'red' , 'purple' , 'orange' , 'gold' , 'magenta' ] # set contour value . Default is SNR _ CUT . self . snr_contour_value = ( self . SNR_CUT if self . snr_contour_value is None else self . snr_contour_value ) # plot contours ...
def check ( self ) : """Check that this table is complete , that is , every character of this table can be followed by a new character . : return : True if the table is complete , False otherwise ."""
for character , followers in self . items ( ) : for follower in followers : if follower not in self : return False return True
def run ( self , message_cb ) : """Run the event loop to receive messages from Nvim . While the event loop is running , ` message _ cb ` will be called whenever a message has been successfully parsed from the input stream ."""
self . _message_cb = message_cb self . loop . run ( self . _on_data ) self . _message_cb = None
def uses_super ( func ) : """Check if the function / property / classmethod / staticmethod uses the ` super ` builtin"""
if isinstance ( func , property ) : return any ( uses_super ( f ) for f in ( func . fget , func . fset , func . fdel ) if f ) elif isinstance ( func , ( staticmethod , classmethod ) ) : if sys . version_info >= ( 2 , 7 ) : func = func . __func__ elif isinstance ( func , staticmethod ) : func...
def paginate ( self , * , page_size , ** options ) : """Run this query and return a page iterator . Parameters : page _ size ( int ) : The number of entities to fetch per page . \**options(QueryOptions, optional) Returns : Pages : An iterator for this query ' s pages of results ."""
return Pages ( self . _prepare ( ) , page_size , QueryOptions ( self , ** options ) )
def model_loss ( y , model , mean = True ) : """Define loss of TF graph : param y : correct labels : param model : output of the model : param mean : boolean indicating whether should return mean of loss or vector of losses for each input of the batch : return : return mean of loss if True , otherwise ret...
warnings . warn ( "This function is deprecated and will be removed on or after" " 2019-04-05. Switch to cleverhans.train.train." ) op = model . op if op . type == "Softmax" : logits , = op . inputs else : logits = model out = softmax_cross_entropy_with_logits ( logits = logits , labels = y ) if mean : out =...
def canorth ( S ) : "Canonical orthogonalization U / sqrt ( lambda )"
E , U = np . linalg . eigh ( S ) for i in range ( len ( E ) ) : U [ : , i ] = U [ : , i ] / np . sqrt ( E [ i ] ) return U
def configure_logging ( args ) : """Logging to console"""
log_format = logging . Formatter ( '%(levelname)s:%(name)s:line %(lineno)s:%(message)s' ) log_level = logging . INFO if args . verbose else logging . WARN log_level = logging . DEBUG if args . debug else log_level console = logging . StreamHandler ( ) console . setFormatter ( log_format ) console . setLevel ( log_level...
def _make_wrapper ( f ) : """return a wrapped function with a copy of the _ pecan context"""
@ wraps ( f ) def wrapper ( * args , ** kwargs ) : return f ( * args , ** kwargs ) wrapper . _pecan = f . _pecan . copy ( ) return wrapper
def save_data ( self ) : """save _ data"""
state = "" try : state = "create_json_archive" log . info ( "creating json archive" ) self . create_json_archive ( ) state = "building_unique_keys" log . info ( "processing all unique keys" ) self . build_all_keys_dict ( ) state = "flattening" log . info ( "flattening all data" ) sel...
def __get_attr ( what , type_attr , value_attr , ** kwargs ) : """get the value of a parm : param what : string parm : param type _ attr : type of parm : param value _ attr : : param kwargs : : return : value of the parm"""
if what in kwargs : value = int ( kwargs [ what ] ) if type_attr == 'int' else kwargs [ what ] if value in value_attr : return value
def _print_graph ( targets , components , tasks ) : """Print dependency information using a dot directed graph . The graph will contain explicitly requested targets plus any dependencies . If there ' s a circular dependency , those nodes and their dependencies will be colored red . Arguments targets - the...
indentation = " " * 4 _do_dot ( targets , components , tasks , lambda resolved , dep_fn : dep_fn ( indentation , resolved ) , )
def overlay_gateway_sflow_sflow_remote_endpoint ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) overlay_gateway = ET . SubElement ( config , "overlay-gateway" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" ) name_key = ET . SubElement ( overlay_gateway , "name" ) name_key . text = kwargs . pop ( 'name' ) sflow = ET . SubElement ( overlay_gateway , "sflow" ) sflow_profile_name_...
def pposition ( hd , details = False ) : """Parse string into angular position . A string containing 2 or 6 numbers is parsed , and the numbers are converted into decimal numbers . In the former case the numbers are assumed to be floats . In the latter case , the numbers are assumed to be sexagesimal . Pa...
# : TODO : split two angles based on user entered separator and process each part separately . # Split at any character other than a digit , " . " , " - " , and " + " . p = re . split ( r"[^\d\-+.]*" , hd ) if len ( p ) not in [ 2 , 6 ] : raise ValueError ( "Input must contain either 2 or 6 numbers." ) # Two floati...
def start_blocking ( self ) : """Start the advertiser in the background , but wait until it is ready"""
self . _cav_started . clear ( ) self . start ( ) self . _cav_started . wait ( )
def submit_commands ( self , devices , execution ) : """Submit device command executions . Returns : a list of concurrent . futures for scheduled executions ."""
fs = [ ] for device in devices : if device [ key_id_ ] != self . device_id : logging . warning ( 'Ignoring command for unknown device: %s' % device [ key_id_ ] ) continue if not execution : logging . warning ( 'Ignoring noop execution' ) continue for command in execution : ...
def _handle_autologin ( self , event ) : """Automatic logins for client configurations that allow it"""
self . log ( "Verifying automatic login request" ) # TODO : Check for a common secret # noinspection PyBroadException try : client_config = objectmodels [ 'client' ] . find_one ( { 'uuid' : event . requestedclientuuid } ) except Exception : client_config = None if client_config is None or client_config . autolo...
def main ( ) : """NAME k15 _ s . py DESCRIPTION converts . k15 format data to . s format . assumes Jelinek Kappabridge measurement scheme SYNTAX k15 _ s . py [ - h ] [ - i ] [ command line options ] [ < filename ] OPTIONS - h prints help message and quits - i allows interactive entry of options ...
firstline , itilt , igeo , linecnt , key = 1 , 0 , 0 , 0 , "" out = "" data , k15 = [ ] , [ ] dir = './' ofile = "" if '-WD' in sys . argv : ind = sys . argv . index ( '-WD' ) dir = sys . argv [ ind + 1 ] + '/' if '-h' in sys . argv : print ( main . __doc__ ) sys . exit ( ) if '-i' in sys . argv : f...
def clean ( self , value ) : """Cleans and returns the given value , or raises a ParameterNotValidError exception"""
if isinstance ( value , six . string_types ) : return value elif isinstance ( value , numbers . Number ) : return str ( value ) raise ParameterNotValidError
def when ( self ) : """A string describing when the event occurs ( in the local time zone ) ."""
offset = 0 timeFrom = dateFrom = timeTo = dateTo = None fromDt = self . _getFromDt ( ) if fromDt is not None : offset = timezone . localtime ( fromDt ) . toordinal ( ) - fromDt . toordinal ( ) dateFrom , timeFrom = getLocalDateAndTime ( fromDt . date ( ) , self . time_from , self . tz , dt . time . min ) da...
def path_to_str ( path ) : """Convert pathlib . Path objects to str ; return other objects as - is ."""
try : from pathlib import Path as _Path except ImportError : # Python < 3.4 class _Path : pass if isinstance ( path , _Path ) : return str ( path ) return path
def build ( self , builder ) : """Build XML by appending to builder"""
params = { } # Add in the transaction type if self . transaction_type is not None : params [ "TransactionType" ] = self . transaction_type if self . seqnum is None : # SeqNum is not optional ( and defaulted ) raise ValueError ( "SeqNum is not set." ) # pragma : no cover params [ "SeqNum" ] = str ( self . se...
def refresh ( self , scope_list = None ) : """Update the auth data ( tokens ) using the refresh token in auth ."""
request_data = self . get_refresh_token_params ( scope_list ) res = self . _session . post ( ** request_data ) if res . status_code != 200 : raise APIException ( request_data [ 'url' ] , res . status_code , response = res . content , request_param = request_data , response_header = res . headers ) json_res = res . ...
def get_port_channel_detail_input_last_aggregator_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_port_channel_detail = ET . Element ( "get_port_channel_detail" ) config = get_port_channel_detail input = ET . SubElement ( get_port_channel_detail , "input" ) last_aggregator_id = ET . SubElement ( input , "last-aggregator-id" ) last_aggregator_id . text = kwargs . pop ( 'last_ag...
def build_package_data ( self ) : """Copy data files into build directory"""
for package , src_dir , build_dir , filenames in self . data_files : for filename in filenames : target = os . path . join ( build_dir , filename ) self . mkpath ( os . path . dirname ( target ) ) srcfile = os . path . join ( src_dir , filename ) outf , copied = self . copy_file ( sr...
def load_json_file ( i ) : """Input : { json _ file - name of file with json Output : { return - return code = 0 , if successful = 16 , if file not found ( may be warning ) > 0 , if error ( error ) - error text if return > 0 dict - dict from json file"""
fn = i [ 'json_file' ] try : if sys . version_info [ 0 ] > 2 : f = open ( fn , 'r' , encoding = 'utf8' ) else : f = open ( fn , 'r' ) except Exception as e : return { 'return' : 16 , 'error' : 'problem opening json file=' + fn + ' (' + format ( e ) + ')' } try : s = f . read ( ) except E...
def _combine_ranges ( ranges ) : """This function takes a list of row - ranges ( as returned by ` _ parse _ row ` ) ordered by rows , and produces a list of distinct rectangular ranges within this grid . Within this function we define a 2d - range as a rectangular set of cells such that : - there are no e...
ranges2d = [ ] for irow , rowranges in enumerate ( ranges ) : ja = 0 jb = 0 while jb < len ( rowranges ) : bcol0 , bcol1 = rowranges [ jb ] if ja < len ( ranges2d ) : _ , arow1 , acol0 , acol1 = ranges2d [ ja ] if arow1 < irow : ja += 1 ...
def command ( self ) : """Returns a string representing the command you have to type to obtain the same packet"""
f = [ ] for fn , fv in self . fields . items ( ) : fld = self . get_field ( fn ) if isinstance ( fv , Packet ) : fv = fv . command ( ) elif fld . islist and fld . holds_packets and type ( fv ) is list : # fv = " [ % s ] " % " , " . join ( map ( Packet . command , fv ) ) fv = "[%s]" % "," . j...
def _parse_team_data ( self , team_data ) : """Parses a value for every attribute . This function looks through every attribute with the exception of ' _ rank ' and retrieves the value according to the parsing scheme and index of the attribute from the passed HTML data . Once the value is retrieved , the at...
for field in self . __dict__ : # The short field truncates the leading ' _ ' in the attribute name . short_field = str ( field ) [ 1 : ] # The rank attribute is passed directly to the class during # instantiation . if field == '_rank' or field == '_year' : continue elif field == '_name' : ...
def extend_substation ( grid , critical_stations , grid_level ) : """Reinforce MV or LV substation by exchanging the existing trafo and installing a parallel one if necessary . First , all available transformers in a ` critical _ stations ` are extended to maximum power . If this does not solve all present is...
load_factor_lv_trans_lc_normal = cfg_ding0 . get ( 'assumptions' , 'load_factor_lv_trans_lc_normal' ) load_factor_lv_trans_fc_normal = cfg_ding0 . get ( 'assumptions' , 'load_factor_lv_trans_fc_normal' ) trafo_params = grid . network . _static_data [ '{grid_level}_trafos' . format ( grid_level = grid_level ) ] trafo_s_...
def get_binary_dist ( self , requirement ) : """Get or create a cached binary distribution archive . : param requirement : A : class : ` . Requirement ` object . : returns : An iterable of tuples with two values each : A : class : ` tarfile . TarInfo ` object and a file - like object . Gets the cached binar...
cache_file = self . cache . get ( requirement ) if cache_file : if self . needs_invalidation ( requirement , cache_file ) : logger . info ( "Invalidating old %s binary (source has changed) .." , requirement ) cache_file = None else : logger . debug ( "%s hasn't been cached yet, doing so now." , ...
def _get_indices ( self , element , labels = 'all' , mode = 'or' ) : r"""This is the actual method for getting indices , but should not be called directly . Use ` ` pores ` ` or ` ` throats ` ` instead ."""
# Parse and validate all input values . element = self . _parse_element ( element , single = True ) labels = self . _parse_labels ( labels = labels , element = element ) if element + '.all' not in self . keys ( ) : raise Exception ( 'Cannot proceed without {}.all' . format ( element ) ) # Begin computing label arra...
def update_active_breakpoint_flag ( cls ) : """Checks all breakpoints to find wether at least one is active and update ` any _ active _ breakpoint ` accordingly ."""
cls . any_active_breakpoint = any ( [ bp . enabled for bp in cls . breakpoints_by_number if bp ] )
def setCurrentNetwork ( self , body , verbose = None ) : """Sets the current network . : param body : SUID of the Network - - Not required , can be None : param verbose : print more : returns : 200 : successful operation"""
response = api ( url = self . ___url + 'networks/currentNetwork' , method = "PUT" , body = body , verbose = verbose ) return response
def check_inclusions ( item , included = [ ] , excluded = [ ] ) : """Everything passes if both are empty , otherwise , we have to check if empty or is present ."""
if ( len ( included ) == 0 ) : if len ( excluded ) == 0 or item not in excluded : return True else : return False else : if item in included : return True return False
def detect_type ( err , install_rdf = None , xpi_package = None ) : """Determines the type of add - on being validated based on install . rdf , file extension , and other properties ."""
# The types in the install . rdf don ' t pair up 1:1 with the type # system that we ' re using for expectations and the like . This is # to help translate between the two . translated_types = { '2' : PACKAGE_EXTENSION , '4' : PACKAGE_THEME , '8' : PACKAGE_LANGPACK , '32' : PACKAGE_MULTI , '64' : PACKAGE_DICTIONARY , # ...
def starttls ( self , ssl_context = None , post_handshake_callback = None ) : """Start a TLS stream on top of the socket . This is an invalid operation if the stream is not in RAW _ OPEN state . If ` ssl _ context ` is set , it overrides the ` ssl _ context ` passed to the constructor . If ` post _ handshake ...
if self . _state != _State . RAW_OPEN or self . _closing : raise self . _invalid_state ( "starttls() called" ) if ssl_context is not None : self . _ssl_context = ssl_context self . _extra . update ( sslcontext = ssl_context ) else : self . _ssl_context = self . _ssl_context_factory ( self ) if post_hand...
def draw_variables ( self ) : """Draw parameters from the approximating distributions"""
z = self . q [ 0 ] . draw_variable_local ( self . sims ) for i in range ( 1 , len ( self . q ) ) : z = np . vstack ( ( z , self . q [ i ] . draw_variable_local ( self . sims ) ) ) return z
def plot_correlation ( self , on , x_col = None , plot_type = "jointplot" , stat_func = pearsonr , show_stat_func = True , plot_kwargs = { } , ** kwargs ) : """Plot the correlation between two variables . Parameters on : list or dict of functions or strings See ` cohort . load . as _ dataframe ` x _ col : s...
if plot_type not in [ "boxplot" , "barplot" , "jointplot" , "regplot" ] : raise ValueError ( "Invalid plot_type %s" % plot_type ) plot_cols , df = self . as_dataframe ( on , return_cols = True , ** kwargs ) if len ( plot_cols ) != 2 : raise ValueError ( "Must be comparing two columns, but there are %d columns" ...
def create_variable_is_dict ( self ) : """Append code for creating variable with bool if it ' s instance of list with a name ` ` { variable } _ is _ dict ` ` . Similar to ` create _ variable _ with _ length ` ."""
variable_name = '{}_is_dict' . format ( self . _variable ) if variable_name in self . _variables : return self . _variables . add ( variable_name ) self . l ( '{variable}_is_dict = isinstance({variable}, dict)' )
async def install_mediaroom_protocol ( responses_callback , box_ip = None ) : """Install an asyncio protocol to process NOTIFY messages ."""
from . import version _LOGGER . debug ( version ) loop = asyncio . get_event_loop ( ) mediaroom_protocol = MediaroomProtocol ( responses_callback , box_ip ) sock = create_socket ( ) await loop . create_datagram_endpoint ( lambda : mediaroom_protocol , sock = sock ) return mediaroom_protocol
def teleport ( self , location = None , rotation = None ) : """Teleports the agent to a specific location , with a specific rotation . Args : location ( np . ndarray , optional ) : An array with three elements specifying the target world coordinate in meters . If None , keeps the current location . Defaults t...
val = 0 if location is not None : val += 1 np . copyto ( self . _teleport_buffer , location ) if rotation is not None : np . copyto ( self . _rotation_buffer , rotation ) val += 2 self . _teleport_bool_buffer [ 0 ] = val
def power_law_anisotropy ( self , r , kwargs_profile , kwargs_anisotropy , kwargs_light ) : """equation ( 19 ) in Suyu + 2010 : param r : : return :"""
# first term theta_E = kwargs_profile [ 'theta_E' ] gamma = kwargs_profile [ 'gamma' ] r_ani = kwargs_anisotropy [ 'r_ani' ] a = 0.551 * kwargs_light [ 'r_eff' ] rho0_r0_gamma = self . _rho0_r0_gamma ( theta_E , gamma ) prefac1 = 4 * np . pi * const . G * a ** ( - gamma ) * rho0_r0_gamma / ( 3 - gamma ) prefac2 = r * (...