signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_item_admin_session_for_bank ( self , bank_id , proxy ) : """Gets the ` ` OsidSession ` ` associated with the item admin service for the given bank . arg : bank _ id ( osid . id . Id ) : the ` ` Id ` ` of the bank arg : proxy ( osid . proxy . Proxy ) : a proxy return : ( osid . assessment . ItemAdminSe...
if not self . supports_item_admin ( ) : raise errors . Unimplemented ( ) # Also include check to see if the catalog Id is found otherwise raise errors . NotFound # pylint : disable = no - member return sessions . ItemAdminSession ( bank_id , proxy , self . _runtime )
def sample ( self , n = None , frac = None , replace = False , weights = None , random_state = None , axis = None , ) : """Returns a random sample of items from an axis of object . Args : n : Number of items from axis to return . Cannot be used with frac . Default = 1 if frac = None . frac : Fraction of axi...
axis = self . _get_axis_number ( axis ) if axis is not None else 0 if axis : axis_labels = self . columns axis_length = len ( axis_labels ) else : # Getting rows requires indices instead of labels . RangeIndex provides this . axis_labels = pandas . RangeIndex ( len ( self . index ) ) axis_length = len (...
def recover_dynamic_model_from_data ( model_class , original_data , modified_data , deleted_data , structure ) : """Function to reconstruct a model from DirtyModel basic information : original data , the modified and deleted fields . Necessary for pickle an object"""
model = model_class ( ) model . __structure__ = { k : d [ 0 ] ( ** d [ 1 ] ) for k , d in structure . items ( ) } return set_model_internal_data ( model , original_data , modified_data , deleted_data )
def get_alert_destination_count ( self , channel = None ) : """Get the number of supported alert destinations : param channel : Channel for alerts to be examined , defaults to current"""
if channel is None : channel = self . get_network_channel ( ) rqdata = ( channel , 0x11 , 0 , 0 ) rsp = self . xraw_command ( netfn = 0xc , command = 2 , data = rqdata ) return ord ( rsp [ 'data' ] [ 1 ] )
def map_size ( self , key ) : """Get the number of items in the map . : param str key : The document ID of the map : return int : The number of items in the map : raise : : cb _ exc : ` NotFoundError ` if the document does not exist . . . seealso : : : meth : ` map _ add `"""
# TODO : This should use get _ count , but we need to check for compat # with server version ( i . e . > = 4.6 ) first ; otherwise it just # disconnects . rv = self . get ( key ) return len ( rv . value )
def _finalize_batch ( self ) : """Method to finalize the batch , this will iterate over the _ batches dict and create a PmtInf node for each batch . The correct information ( from the batch _ key and batch _ totals ) will be inserted and the batch transaction nodes will be folded . Finally , the batches will ...
for batch_meta , batch_nodes in self . _batches . items ( ) : batch_meta_split = batch_meta . split ( "::" ) PmtInf_nodes = self . _create_PmtInf_node ( ) PmtInf_nodes [ 'PmtInfIdNode' ] . text = make_id ( self . _config [ 'name' ] ) PmtInf_nodes [ 'PmtMtdNode' ] . text = "DD" PmtInf_nodes [ 'BtchBo...
def state_likelihood ( self , beta , alpha ) : """Returns likelihood of the states given the variance latent variables Parameters beta : np . array Contains untransformed starting values for latent variables alpha : np . array State matrix Returns State likelihood"""
_ , _ , _ , Q = self . _ss_matrices ( beta ) state_lik = 0 for i in range ( alpha . shape [ 0 ] ) : state_lik += np . sum ( ss . norm . logpdf ( alpha [ i ] [ 1 : ] - alpha [ i ] [ : - 1 ] , loc = 0 , scale = np . power ( Q [ i ] [ i ] , 0.5 ) ) ) return state_lik
def pattern_from_template ( templates , name ) : """Return pattern for name Arguments : templates ( dict ) : Current templates name ( str ) : Name of name"""
if name not in templates : echo ( "No template named \"%s\"" % name ) sys . exit ( 1 ) return templates [ name ]
def naive ( gold_schemes ) : """find naive baseline ( most common scheme of a given length ) ?"""
scheme_path = os . path . join ( os . path . dirname ( os . path . realpath ( __file__ ) ) , 'data' , 'schemes.json' ) with open ( scheme_path , 'r' ) as f : dist = json . loads ( f . read ( ) ) best_schemes = { } for i in dist . keys ( ) : if not dist [ i ] : continue best_schemes [ int ( i ) ] = t...
def resize_image ( image , canvas_size , filter = Filter . NearestNeighbor , does_crop = False , crop_aligment = CropAlignment . center , crop_form = CropForm . rectangle , match_orientation = False ) : """Resize the specified image to the required dimension . @ param image : a Python Image Library ( PIL ) image ...
( source_width , source_height ) = image . size source_aspect = source_width / float ( source_height ) ( canvas_width , canvas_height ) = canvas_size canvas_aspect = canvas_width / float ( canvas_height ) if match_orientation : if ( source_aspect > 1.0 > canvas_aspect ) or ( source_aspect < 1.0 < canvas_aspect ) : ...
def process ( self , ymlfile ) : """Cleans out all document tags from the YAML file to make it JSON - friendly to work with the JSON Schema ."""
output = "" try : # Need a list of line numbers where the documents resides # Used for finding / displaying errors self . doclines = [ ] linenum = None with open ( ymlfile , 'r' ) as txt : for linenum , line in enumerate ( txt ) : # Pattern to match document start lines doc_pattern = re ...
def get_users_subscribed_to_discussion ( recID , check_authorizations = True ) : """Returns the lists of users subscribed to a given discussion . Two lists are returned : the first one is the list of emails for users who can unsubscribe from the discussion , the second list contains the emails of users who ca...
subscribers_emails = { } # Get users that have subscribed to this discussion query = """SELECT id_user FROM "cmtSUBSCRIPTION" WHERE id_bibrec=%s""" params = ( recID , ) res = run_sql ( query , params ) for row in res : uid = row [ 0 ] if check_authorizations : user_info = UserInfo ( uid ) ( auth...
def resume ( self ) : """Resumes the download . : raises SbgError : If download is not in RUNNING state ."""
if self . _status != TransferState . PAUSED : self . _running . set ( ) self . _status = TransferState . RUNNING else : raise SbgError ( 'Can not pause. Download not in PAUSED state.' )
def set_contributor_details ( self , contdetails ) : """Sets ' contributor _ details ' parameter used to enhance the contributors element of the status response to include the screen _ name of the contributor . By default only the user _ id of the contributor is included : param contdetails : Boolean triggering t...
if not isinstance ( contdetails , bool ) : raise TwitterSearchException ( 1008 ) self . arguments . update ( { 'contributor_details' : 'true' if contdetails else 'false' } )
def summary ( self ) : """Creates a text string representing the current query and its children for this item . : return < str >"""
child_text = [ ] for c in range ( self . childCount ( ) ) : child = self . child ( c ) text = [ child . text ( 0 ) , child . text ( 1 ) , child . text ( 2 ) , child . text ( 3 ) ] text = map ( str , text ) while ( '' in text ) : text . remove ( '' ) child_text . append ( ' ' . join ( text ) ...
def fcs ( self , path , features , filtered = True , override = False ) : """Export the data of an RT - DC dataset to an . fcs file Parameters mm : instance of dclab . RTDCBase The dataset that will be exported . path : str Path to a . tsv file . The ending . tsv is added automatically . features : list...
features = [ c . lower ( ) for c in features ] ds = self . rtdc_ds path = pathlib . Path ( path ) # Make sure that path ends with . fcs if path . suffix != ".fcs" : path = path . with_name ( path . name + ".fcs" ) # Check if file already exist if not override and path . exists ( ) : raise OSError ( "File alread...
def compute_md5 ( self ) : """Compute and erturn MD5 hash value ."""
import hashlib with open ( self . path , "rt" ) as fh : text = fh . read ( ) m = hashlib . md5 ( text . encode ( "utf-8" ) ) return m . hexdigest ( )
def _get_default_gateway ( self , ip = 4 ) : """Returns the default gateway for given IP version . The ` ` ip ` ` argument is used to specify the IP version , and can be either 4 or 6."""
net_type = netifaces . AF_INET if ip == 4 else netifaces . AF_INET6 gw = netifaces . gateways ( ) [ 'default' ] . get ( net_type , ( None , None ) ) if gw [ 1 ] == self . name : return gw [ 0 ]
def find_start_point ( self ) : """Find the first location in our array that is not empty"""
for i , row in enumerate ( self . data ) : for j , _ in enumerate ( row ) : if self . data [ i , j ] != 0 : # or not np . isfinite ( self . data [ i , j ] ) : return i , j
async def get_links_from_url ( url ) : """Download the page at ` url ` and parse it for links . Returned links have had the fragment after ` # ` removed , and have been made absolute so , e . g . the URL ' gen . html # tornado . gen . coroutine ' becomes ' http : / / www . tornadoweb . org / en / stable / gen...
response = await httpclient . AsyncHTTPClient ( ) . fetch ( url ) print ( "fetched %s" % url ) html = response . body . decode ( errors = "ignore" ) return [ urljoin ( url , remove_fragment ( new_url ) ) for new_url in get_links ( html ) ]
def cr_login ( self , response ) : """Login using email / username and password , used to get the auth token @ param str account @ param str password @ param str hash _ id ( optional )"""
self . _state_params [ 'auth' ] = response [ 'auth' ] self . _user_data = response [ 'user' ] if not self . logged_in : raise ApiLoginFailure ( response )
def runPlink ( options ) : """Runs Plink with the geno option . : param options : the options . : type options : argparse . Namespace"""
# The plink command plinkCommand = [ "plink" , "--noweb" , "--bfile" , options . bfile , "--geno" , str ( options . geno ) , "--make-bed" , "--out" , options . out ] output = None try : output = subprocess . check_output ( plinkCommand , stderr = subprocess . STDOUT , shell = False ) except subprocess . CalledProce...
def _add_delegate_accessors ( cls , delegate , accessors , typ , overwrite = False ) : """Add accessors to cls from the delegate class . Parameters cls : the class to add the methods / properties to delegate : the class to get methods / properties & doc - strings accessors : string list of accessors to add ...
def _create_delegator_property ( name ) : def _getter ( self ) : return self . _delegate_property_get ( name ) def _setter ( self , new_values ) : return self . _delegate_property_set ( name , new_values ) _getter . __name__ = name _setter . __name__ = name return property ( fget = _...
def get_all ( self ) : """Returns the cache stats as a list of dicts ."""
ret = [ ] for cache_name , stat in self . stats_per_cache . items ( ) : ret . append ( { 'cache_name' : cache_name , 'num_hits' : len ( stat . hit_targets ) , 'num_misses' : len ( stat . miss_targets ) , 'hits' : stat . hit_targets , 'misses' : stat . miss_targets } ) return ret
def interaction_actions ( self ) : """: return : List of strings for allowed interaction / actions combinations : rtype : list [ str ]"""
r = self . session . query ( distinct ( models . ChemGeneIxnInteractionAction . interaction_action ) ) . all ( ) return [ x [ 0 ] for x in r ]
def steepest_descent ( A , b , x0 = None , tol = 1e-5 , maxiter = None , xtype = None , M = None , callback = None , residuals = None ) : """Steepest descent algorithm . Solves the linear system Ax = b . Left preconditioning is supported . Parameters A : array , matrix , sparse matrix , LinearOperator n x n...
A , M , x , b , postprocess = make_system ( A , M , x0 , b ) # Ensure that warnings are always reissued from this function import warnings warnings . filterwarnings ( 'always' , module = 'pyamg\.krylov\._steepest_descent' ) # determine maxiter if maxiter is None : maxiter = int ( len ( b ) ) elif maxiter < 1 : ...
def resetSelection ( self ) : """Reset selection . Nothing will be selected ."""
cursor = self . textCursor ( ) cursor . setPosition ( cursor . position ( ) ) self . setTextCursor ( cursor )
def get_config ( config_file ) : """Get configuration from a file ."""
def load ( fp ) : try : return yaml . safe_load ( fp ) except yaml . YAMLError as e : sys . stderr . write ( text_type ( e ) ) sys . exit ( 1 ) # TODO document exit codes if config_file == '-' : return load ( sys . stdin ) if not os . path . exists ( config_file ) : sys . stderr ...
def read_dalton ( basis_lines , fname ) : '''Reads Dalton - formatted file data and converts it to a dictionary with the usual BSE fields Note that the nwchem format does not store all the fields we have , so some fields are left blank'''
skipchars = '$' basis_lines = [ l for l in basis_lines if l and not l [ 0 ] in skipchars ] bs_data = create_skel ( 'component' ) i = 0 while i < len ( basis_lines ) : line = basis_lines [ i ] if line . lower ( ) . startswith ( 'a ' ) : element_Z = line . split ( ) [ 1 ] i += 1 # Shell am...
def get_public_dsn ( self , scheme = None ) : """Returns a public DSN which is consumable by raven - js > > > # Return scheme - less DSN > > > print client . get _ public _ dsn ( ) > > > # Specify a scheme to use ( http or https ) > > > print client . get _ public _ dsn ( ' https ' )"""
if self . is_enabled ( ) : url = self . remote . get_public_dsn ( ) if scheme : return '%s:%s' % ( scheme , url ) return url
def gc ( self ) : """Garbage collect overflow and / or aged entries ."""
manifest = [ ] overlimit = len ( self . data ) - self . maxsize if self . maxsize is not None else 0 now = self . ttl is not None and self . timer ( ) for key , entry in self . data . items ( ) : if overlimit > 0 or ( now and self . is_expired ( entry , time = now ) ) : overlimit -= 1 manifest . app...
async def finish ( self , * , chat : typing . Union [ str , int , None ] = None , user : typing . Union [ str , int , None ] = None ) : """Finish conversation for user in chat . Chat or user is always required . If one of them is not provided , you have to set missing value based on the provided one . : param...
await self . reset_state ( chat = chat , user = user , with_data = True )
def getServerSSLContext ( self , hostname = None ) : '''Returns an ssl . SSLContext appropriate to listen on a socket Args : hostname : if None , the value from socket . gethostname is used to find the key in the servers directory . This name should match the not - suffixed part of two files ending in . key a...
sslctx = ssl . create_default_context ( ssl . Purpose . CLIENT_AUTH ) if hostname is None : hostname = socket . gethostname ( ) certfile = self . getHostCertPath ( hostname ) if certfile is None : raise s_exc . NoCertKey ( 'Missing .crt for %s' % hostname ) keyfile = self . getHostKeyPath ( hostname ) if keyfil...
def generate_repo_files ( self , release ) : """Dynamically generate our yum repo configuration"""
repo_tmpl = pkg_resources . resource_string ( __name__ , 'templates/repo.mako' ) repo_file = os . path . join ( release [ 'git_dir' ] , '%s.repo' % release [ 'repo' ] ) with file ( repo_file , 'w' ) as repo : repo_out = Template ( repo_tmpl ) . render ( ** release ) self . log . debug ( 'Writing repo file %s:\n...
def integrate_adaptive ( rhs , jac , y0 , x0 , xend , atol , rtol , dx0 = .0 , dx_max = .0 , check_callable = False , check_indexing = False , ** kwargs ) : """Integrates a system of ordinary differential equations . Parameters rhs : callable Function with signature f ( t , y , fout ) which modifies fout * in...
# Sanity checks to reduce risk of having a segfault : jac = _ensure_5args ( jac ) if check_callable : _check_callable ( rhs , jac , x0 , y0 ) if check_indexing : _check_indexing ( rhs , jac , x0 , y0 ) return adaptive ( rhs , jac , np . asarray ( y0 , dtype = np . float64 ) , x0 , xend , atol , rtol , dx0 , dx_...
def _handle_result_line ( self , split_line ) : """Parses the data line and adds the results to the dictionary . : param split _ line : a split data line to parse : returns : the current result id and the dictionary of values obtained from the results"""
values = { } result_id = '' if self . _ar_keyword : # Create a new entry in the values dictionary and store the results values [ self . _ar_keyword ] = { } for idx , val in enumerate ( split_line ) : if self . _columns [ idx ] . lower ( ) == 'sampleid' : result_id = val else : # colu...
def extend_env ( conn , arguments ) : """get the remote environment ' s env so we can explicitly add the path without wiping out everything"""
# retrieve the remote environment variables for the host try : result = conn . gateway . remote_exec ( "import os; channel.send(os.environ.copy())" ) env = result . receive ( ) except Exception : conn . logger . exception ( 'failed to retrieve the remote environment variables' ) env = { } # get the $ PA...
def iter_csv_stream ( input_stream , fieldnames = None , sniff = False , * args , ** kwargs ) : '''Read CSV content as a table ( list of lists ) from an input stream'''
if 'dialect' not in kwargs and sniff : kwargs [ 'dialect' ] = csv . Sniffer ( ) . sniff ( input_stream . read ( 1024 ) ) input_stream . seek ( 0 ) if 'quoting' in kwargs and kwargs [ 'quoting' ] is None : kwargs [ 'quoting' ] = csv . QUOTE_MINIMAL if fieldnames : # read csv using dictreader if isinstanc...
def new_class_from_gtype ( gtype ) : """Create a new class for a gtype not in the gir . The caller is responsible for caching etc ."""
if gtype . is_a ( PGType . from_name ( "GObject" ) ) : parent = gtype . parent . pytype if parent is None or parent == PGType . from_name ( "void" ) : return interfaces = [ i . pytype for i in gtype . interfaces ] bases = tuple ( [ parent ] + interfaces ) cls = type ( gtype . name , bases , ...
def in_use ( self ) : """Check whether this device is in use , i . e . mounted or unlocked ."""
if self . is_mounted or self . is_unlocked : return True if self . is_partition_table : for device in self . _daemon : if device . partition_slave == self and device . in_use : return True return False
def list_resources ( self , device_id ) : """List all resources registered to a connected device . . . code - block : : python > > > for r in api . list _ resources ( device _ id ) : print ( r . name , r . observable , r . uri ) None , True , / 3/0/1 Update , False , / 5/0/3 : param str device _ id : Th...
api = self . _get_api ( mds . EndpointsApi ) return [ Resource ( r ) for r in api . get_endpoint_resources ( device_id ) ]
def make_union ( * transformers , ** kwargs ) : """Construct a FeatureUnion from the given transformers . This is a shorthand for the FeatureUnion constructor ; it does not require , and does not permit , naming the transformers . Instead , they will be given names automatically based on their types . It also...
n_jobs = kwargs . pop ( 'n_jobs' , 1 ) concatenate = kwargs . pop ( 'concatenate' , True ) if kwargs : # We do not currently support ` transformer _ weights ` as we may want to # change its type spec in make _ union raise TypeError ( 'Unknown keyword arguments: "{}"' . format ( list ( kwargs . keys ( ) ) [ 0 ] ) ) ...
def decrement_display_ref_count ( self , amount : int = 1 ) : """Decrement display reference count to indicate this library item is no longer displayed ."""
assert not self . _closed self . __display_ref_count -= amount for display_data_channel in self . display_data_channels : display_data_channel . decrement_display_ref_count ( amount )
def _findOverlap ( self , img_rgb , overlap , overlapDeviation , rotation , rotationDeviation ) : '''return offset ( x , y ) which fit best self . _ base _ img through template matching'''
# get gray images if len ( img_rgb . shape ) != len ( img_rgb . shape ) : raise Exception ( 'number of channels(colors) for both images different' ) if overlapDeviation == 0 and rotationDeviation == 0 : return ( 0 , overlap , rotation ) s = self . base_img_rgb . shape ho = int ( round ( overlap * 0.5 ) ) overla...
def _add_suppl_info ( inp , val ) : """Add supplementary information to inputs from file values ."""
inp [ "type" ] = _get_avro_type ( val ) secondary = _get_secondary_files ( val ) if secondary : inp [ "secondaryFiles" ] = secondary return inp
def set_idle_ttl ( cls , pid , ttl ) : """Set the idle TTL for a pool , after which it will be destroyed . : param str pid : The pool id : param int ttl : The TTL for an idle pool"""
with cls . _lock : cls . _ensure_pool_exists ( pid ) cls . _pools [ pid ] . set_idle_ttl ( ttl )
def ready_argument_list ( self , arguments ) : """ready argument list to be passed to the kernel , allocates gpu mem : param arguments : List of arguments to be passed to the kernel . The order should match the argument list on the CUDA kernel . Allowed values are numpy . ndarray , and / or numpy . int32 , nu...
gpu_args = [ ] for arg in arguments : # if arg i is a numpy array copy to device if isinstance ( arg , numpy . ndarray ) : alloc = drv . mem_alloc ( arg . nbytes ) self . allocations . append ( alloc ) gpu_args . append ( alloc ) drv . memcpy_htod ( gpu_args [ - 1 ] , arg ) else ...
def get_product_info ( self , apps = [ ] , packages = [ ] , timeout = 15 ) : """Get product info for apps and packages : param apps : items in the list should be either just ` ` app _ id ` ` , or ` ` ( app _ id , access _ token ) ` ` : type apps : : class : ` list ` : param packages : items in the list should...
if not apps and not packages : return message = MsgProto ( EMsg . ClientPICSProductInfoRequest ) for app in apps : app_info = message . body . apps . add ( ) app_info . only_public = False if isinstance ( app , tuple ) : app_info . appid , app_info . access_token = app else : app_inf...
def calculate_affinity ( self , username ) : """Get the affinity between the " base user " and ` ` username ` ` . . . note : : The data returned will be a namedtuple , with the affinity and shared rated anime . This can easily be separated as follows ( using the user ` ` Luna ` ` as ` ` username ` ` ) : . ....
scores = self . comparison ( username ) # Handle cases where the shared scores are < = 10 so # affinity can not be accurately calculated . if len ( scores ) <= 10 : raise NoAffinityError ( "Shared rated anime count between " "`{}` and `{}` is less than eleven" . format ( self . _base_user , username ) ) # Sort mult...
def get_texts_box ( texts , fs ) : """Approximation of multiple texts bounds"""
max_len = max ( map ( len , texts ) ) return ( fs , text_len ( max_len , fs ) )
def shard_data ( source_fnames : List [ str ] , target_fname : str , source_vocabs : List [ vocab . Vocab ] , target_vocab : vocab . Vocab , num_shards : int , buckets : List [ Tuple [ int , int ] ] , length_ratio_mean : float , length_ratio_std : float , output_prefix : str ) -> Tuple [ List [ Tuple [ List [ str ] , s...
os . makedirs ( output_prefix , exist_ok = True ) sources_shard_fnames = [ [ os . path . join ( output_prefix , C . SHARD_SOURCE % i ) + ".%d" % f for i in range ( num_shards ) ] for f in range ( len ( source_fnames ) ) ] target_shard_fnames = [ os . path . join ( output_prefix , C . SHARD_TARGET % i ) for i in range (...
def _unsigned_to_signed ( v , bits ) : """Convert an unsigned integer to a signed integer . : param v : The unsigned integer : param bits : How many bits this integer should be : return : The converted signed integer"""
if StridedInterval . _is_msb_zero ( v , bits ) : return v else : return - ( 2 ** bits - v )
def jitter ( x , factor = 1 , amount = None , random_state = None ) : """Add a small amount of noise to values in an array _ like Parameters x : array _ like Values to apply a jitter factor : float Multiplicative value to used in automatically determining the ` amount ` . If the ` amount ` is given then...
if len ( x ) == 0 : return x if random_state is None : random_state = np . random elif isinstance ( random_state , int ) : random_state = np . random . RandomState ( random_state ) x = np . asarray ( x ) try : z = np . ptp ( x [ np . isfinite ( x ) ] ) except IndexError : z = 0 if z == 0 : z = n...
def iter_documents ( self , fileids = None , categories = None , _destroy = False ) : """Return an iterator over corpus documents ."""
doc_ids = self . _filter_ids ( fileids , categories ) for doc in imap ( self . get_document , doc_ids ) : yield doc if _destroy : doc . destroy ( )
def _generate_one_fake ( self , schema ) : """Recursively traverse schema dictionary and for each " leaf node " , evaluate the fake value Implementation : For each key - value pair : 1 ) If value is not an iterable ( i . e . dict or list ) , evaluate the fake data ( base case ) 2 ) If value is a dictionar...
data = { } for k , v in schema . items ( ) : if isinstance ( v , dict ) : data [ k ] = self . _generate_one_fake ( v ) elif isinstance ( v , list ) : data [ k ] = [ self . _generate_one_fake ( item ) for item in v ] else : data [ k ] = getattr ( self . _faker , v ) ( ) return data
def getParameters ( self , notes ) : """Return a C { list } of one L { LiveForm } parameter for editing a L { Notes } . @ type notes : L { Notes } or C { NoneType } @ param notes : If not C { None } , an existing contact item from which to get the parameter ' s default value . @ rtype : C { list }"""
defaultNotes = u'' if notes is not None : defaultNotes = notes . notes return [ liveform . Parameter ( 'notes' , liveform . TEXTAREA_INPUT , unicode , 'Notes' , default = defaultNotes ) ]
def create_indexes ( self , indexes , session = None , ** kwargs ) : """Create one or more indexes on this collection . > > > from pymongo import IndexModel , ASCENDING , DESCENDING > > > index1 = IndexModel ( [ ( " hello " , DESCENDING ) , . . . ( " world " , ASCENDING ) ] , name = " hello _ world " ) > > ...
common . validate_list ( 'indexes' , indexes ) names = [ ] with self . _socket_for_writes ( session ) as sock_info : supports_collations = sock_info . max_wire_version >= 5 def gen_indexes ( ) : for index in indexes : if not isinstance ( index , IndexModel ) : raise TypeError...
def prepare_env ( cls ) : """Prepares current environment and returns Python binary name . This adds some virtualenv friendliness so that we try use uwsgi from it . : rtype : str | unicode"""
os . environ [ 'PATH' ] = cls . get_env_path ( ) return os . path . basename ( Finder . python ( ) )
def vary_name ( name : Text ) : """Validates the name and creates variations"""
snake = re . match ( r'^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$' , name ) if not snake : fail ( 'The project name is not a valid snake-case Python variable name' ) camel = [ x [ 0 ] . upper ( ) + x [ 1 : ] for x in name . split ( '_' ) ] return { 'project_name_snake' : name , 'project_name_camel' : '' . join ( camel ) , 'pr...
def scale_to_vol ( self , vol ) : """Scale ball to encompass a target volume ."""
f = ( vol / self . vol_ball ) ** ( 1.0 / self . n ) # linear factor self . expand *= f self . radius *= f self . vol_ball = vol
def get_first ( self , table = None ) : """Just the first entry ."""
if table is None : table = self . main_table query = 'SELECT * FROM "%s" LIMIT 1;' % table return self . own_cursor . execute ( query ) . fetchone ( )
def get_term_config ( platform , filter_name , term_name , filter_options = None , pillar_key = 'acl' , pillarenv = None , saltenv = None , merge_pillar = True , revision_id = None , revision_no = None , revision_date = True , revision_date_format = '%Y/%m/%d' , source_service = None , destination_service = None , ** t...
terms = [ ] term = { term_name : { } } term [ term_name ] . update ( term_fields ) term [ term_name ] . update ( { 'source_service' : _make_it_list ( { } , 'source_service' , source_service ) , 'destination_service' : _make_it_list ( { } , 'destination_service' , destination_service ) , } ) terms . append ( term ) if n...
def plot_errorbars_trainset ( self , which_data_rows = 'all' , which_data_ycols = 'all' , fixed_inputs = None , plot_raw = False , apply_link = False , label = None , projection = '2d' , predict_kw = None , ** plot_kwargs ) : """Plot the errorbars of the GP likelihood on the training data . These are the errorbar...
canvas , kwargs = pl ( ) . new_canvas ( projection = projection , ** plot_kwargs ) plots = _plot_errorbars_trainset ( self , canvas , which_data_rows , which_data_ycols , fixed_inputs , plot_raw , apply_link , label , projection , predict_kw , ** kwargs ) return pl ( ) . add_to_canvas ( canvas , plots )
def time_series_rdd_from_pandas_series_rdd ( series_rdd ) : """Instantiates a TimeSeriesRDD from an RDD of Pandas Series objects . The series in the RDD are all expected to have the same DatetimeIndex . Parameters series _ rdd : RDD of ( string , pandas . Series ) tuples sc : SparkContext"""
first = series_rdd . first ( ) dt_index = irregular ( first [ 1 ] . index , series_rdd . ctx ) return TimeSeriesRDD ( dt_index , series_rdd . mapValues ( lambda x : x . values ) )
def parse ( self , * args , ** kw ) : """Parse command line , fill ` fuse _ args ` attribute ."""
ev = 'errex' in kw and kw . pop ( 'errex' ) if ev and not isinstance ( ev , int ) : raise TypeError ( "error exit value should be an integer" ) try : self . cmdline = self . parser . parse_args ( * args , ** kw ) except OptParseError : if ev : sys . exit ( ev ) raise return self . fuse_args
def compute ( self , use_cache = True ) : """Call a user defined query and return events with optional help from the cache . : param use _ cache : Specifies whether the cache should be used when possible"""
if use_cache : if not self . _bucket_width : raise ValueError ( 'QueryCompute must be initialized with a bucket_width' ' to use caching features.' ) return list ( self . _query_cache . retrieve_interval ( self . _start_time , self . _end_time , compute_missing = True ) ) else : if self . _metis : ...
def enable_availability_zones ( self , load_balancer_name , zones_to_add ) : """Add availability zones to an existing Load Balancer All zones must be in the same region as the Load Balancer Adding zones that are already registered with the Load Balancer has no effect . : type load _ balancer _ name : string...
params = { 'LoadBalancerName' : load_balancer_name } self . build_list_params ( params , zones_to_add , 'AvailabilityZones.member.%d' ) return self . get_list ( 'EnableAvailabilityZonesForLoadBalancer' , params , None )
def flatten_urlinfo ( urlinfo , shorter_keys = True ) : """Takes a urlinfo object and returns a flat dictionary ."""
def flatten ( value , prefix = "" ) : if is_string ( value ) : _result [ prefix [ 1 : ] ] = value return try : len ( value ) except ( AttributeError , TypeError ) : # a leaf _result [ prefix [ 1 : ] ] = value return try : items = value . items ( ) exce...
def _lock_netmiko_session ( self , start = None ) : """Try to acquire the Netmiko session lock . If not available , wait in the queue until the channel is available again . : param start : Initial start time to measure the session timeout : type start : float ( from time . time ( ) call i . e . epoch time )""...
if not start : start = time . time ( ) # Wait here until the SSH channel lock is acquired or until session _ timeout exceeded while not self . _session_locker . acquire ( False ) and not self . _timeout_exceeded ( start , "The netmiko channel is not available!" ) : time . sleep ( 0.1 ) return True
def get_or_create_candidate_election ( self , row , election , candidate , party ) : """For a given election , this function updates or creates the CandidateElection object using the model method on the election ."""
return election . update_or_create_candidate ( candidate , party . aggregate_candidates , row [ "uncontested" ] )
def _cwl_workflow_template ( inputs , top_level = False ) : """Retrieve CWL inputs shared amongst different workflows ."""
ready_inputs = [ ] for inp in inputs : cur_inp = copy . deepcopy ( inp ) for attr in [ "source" , "valueFrom" , "wf_duplicate" ] : cur_inp . pop ( attr , None ) if top_level : cur_inp = workflow . _flatten_nested_input ( cur_inp ) cur_inp = _clean_record ( cur_inp ) ready_inputs . ap...
def count_indents_length ( self , spacecount , tabs = 0 , offset = 0 ) : """Counts the number of indents that can be tabs or spacecount number of spaces in a row from the current line . Also returns the character length of the indents ."""
if not self . has_space ( offset = offset ) : return 0 spaces = 0 indents = 0 charlen = 0 for char in self . string [ self . pos + offset - self . col : ] : if char == ' ' : spaces += 1 elif tabs and char == '\t' : indents += 1 spaces = 0 else : break charlen += 1 ...
def include_in_layout ( self ) : """| True | if legend should be located inside plot area . Read / write boolean specifying whether legend should be placed inside the plot area . In many cases this will cause it to be superimposed on the chart itself . Assigning | None | to this property causes any ` c : ov...
overlay = self . _element . overlay if overlay is None : return True return overlay . val
def setup_signals ( self , ) : """Connect the signals with the slots to make the ui functional : returns : None : rtype : None : raises : None"""
self . showfilter_tb . toggled . connect ( self . switch_showfilter_icon ) self . addnew_tb . clicked . connect ( self . open_addnew_win ) self . search_le . editingFinished . connect ( self . update_filter ) for cb in ( self . loaded_checkb , self . unloaded_checkb , self . imported_checkb , self . empty_checkb , self...
def delete_volume ( self , volObj , removeMode = 'ONLY_ME' , ** kwargs ) : """removeMode = ' ONLY _ ME ' | ' INCLUDING _ DESCENDANTS ' | ' DESCENDANTS _ ONLY ' | ' WHOLE _ VTREE ' Using kwargs it will be possible to tell delete _ volume ( ) to unmap all SDCs before delting . Not working yet"""
if kwargs : for key , value in kwargs . iteritems ( ) : if key == 'autoUnmap' and value == True : # Find all mapped SDS to this volObj # Call unmap for all of them if self . get_volume_all_sdcs_mapped ( volObj ) : try : self . conn . cluster . unmap_vo...
def extract_iface_name_from_path ( path , name ) : """Extract the ' real ' interface name from the path name . Basically this puts the ' @ ' back in the name in place of the underscore , where the name contains a ' . ' or contains ' macvtap ' or ' macvlan ' . Examples : | real name | path name | | bond0.1...
if name in path : ifname = os . path . basename ( path ) . split ( "_" , 2 ) [ - 1 ] . strip ( ) if "." in ifname or "macvtap" in ifname or "macvlan" in ifname : ifname = ifname . replace ( "_" , "@" ) return ifname
def _items ( mappingorseq ) : """Wrapper for efficient iteration over mappings represented by dicts or sequences : : > > > for k , v in _ items ( ( i , i * i ) for i in xrange ( 5 ) ) : . . . assert k * k = = v > > > for k , v in _ items ( dict ( ( i , i * i ) for i in xrange ( 5 ) ) ) : . . . assert k * ...
if hasattr ( mappingorseq , "iteritems" ) : return mappingorseq . iteritems ( ) elif hasattr ( mappingorseq , "items" ) : return mappingorseq . items ( ) return mappingorseq
def find_all ( connection = None , page_size = 100 , page_number = 0 , sort_by = DEFAULT_SORT_BY , sort_order = DEFAULT_SORT_ORDER ) : """List all playlists ."""
return pybrightcove . connection . ItemResultSet ( "find_all_playlists" , Playlist , connection , page_size , page_number , sort_by , sort_order )
def overview ( index , start , end ) : """Compute metrics in the overview section for enriched git indexes . Returns a dictionary . Each key in the dictionary is the name of a metric , the value is the value of that metric . Value can be a complex object ( eg , a time series ) . : param index : index object...
results = { "activity_metrics" : [ Commits ( index , start , end ) ] , "author_metrics" : [ Authors ( index , start , end ) ] , "bmi_metrics" : [ ] , "time_to_close_metrics" : [ ] , "projects_metrics" : [ ] } return results
def stats ( self , key = None ) : """Return server stats . : param key : Optional if you want status from a key . : type key : six . string _ types : return : A dict with server stats : rtype : dict"""
# TODO : Stats with key is not working . if key is not None : if isinstance ( key , text_type ) : key = str_to_bytes ( key ) keylen = len ( key ) packed = struct . pack ( self . HEADER_STRUCT + '%ds' % keylen , self . MAGIC [ 'request' ] , self . COMMANDS [ 'stat' ] [ 'command' ] , keylen , 0 , 0 , ...
def gauge ( key , gauge = None , default = float ( "nan" ) , ** dims ) : """Adds gauge with dimensions to the global pyformance registry"""
return global_registry ( ) . gauge ( key , gauge = gauge , default = default , ** dims )
def cleanPolyline ( elem , options ) : """Scour the polyline points attribute"""
pts = parseListOfPoints ( elem . getAttribute ( 'points' ) ) elem . setAttribute ( 'points' , scourCoordinates ( pts , options , True ) )
def collection ( name = None ) : """Render the collection page . It renders it either with a collection specific template ( aka collection _ { collection _ name } . html ) or with the default collection template ( collection . html ) ."""
if name is None : collection = Collection . query . get_or_404 ( 1 ) else : collection = Collection . query . filter ( Collection . name == name ) . first_or_404 ( ) # TODO add breadcrumbs # breadcrumbs = current _ breadcrumbs + collection . breadcrumbs ( ln = g . ln ) [ 1 : ] return render_template ( [ 'inveni...
def whois_nameservers ( self , nameservers ) : """Calls WHOIS Nameserver end point Args : emails : An enumerable of nameservers Returns : A dict of { nameserver : domain _ result }"""
api_name = 'opendns-whois-nameservers' fmt_url_path = u'whois/nameservers/{0}' return self . _multi_get ( api_name , fmt_url_path , nameservers )
def get_client_class ( self , client_class_name ) : """Returns a specific client class details from CPNR server ."""
request_url = self . _build_url ( [ 'ClientClass' , client_class_name ] ) return self . _do_request ( 'GET' , request_url )
def _get_proj_enclosing_polygon ( self ) : """See : meth : ` Mesh . _ get _ proj _ enclosing _ polygon ` . : class : ` RectangularMesh ` contains an information about relative positions of points , so it allows to define the minimum polygon , containing the projection of the mesh , which doesn ' t necessarily...
if self . lons . size < 4 : # the mesh doesn ' t contain even a single cell return self . _get_proj_convex_hull ( ) proj = geo_utils . OrthographicProjection ( * geo_utils . get_spherical_bounding_box ( self . lons , self . lats ) ) if len ( self . lons . shape ) == 1 : # 1D mesh lons = self . lons . reshape ( ...
def _GetNormalizedTimestamp ( self ) : """Retrieves the normalized timestamp . Returns : decimal . Decimal : normalized timestamp , which contains the number of seconds since January 1 , 1970 00:00:00 and a fraction of second used for increased precision , or None if the normalized timestamp cannot be det...
if self . _normalized_timestamp is None : if self . _number_of_seconds is not None : self . _normalized_timestamp = ( decimal . Decimal ( self . deciseconds ) / definitions . DECISECONDS_PER_SECOND ) self . _normalized_timestamp += decimal . Decimal ( self . _number_of_seconds ) return self . _norma...
def turn_left ( self , angle_degrees , rate = RATE ) : """Turn to the left , staying on the spot : param angle _ degrees : How far to turn ( degrees ) : param rate : The trurning speed ( degrees / second ) : return :"""
flight_time = angle_degrees / rate self . start_turn_left ( rate ) time . sleep ( flight_time ) self . stop ( )
def powerset ( iterable ) : "powerset ( [ 1,2,3 ] ) - - > ( ) ( 1 , ) ( 2 , ) ( 3 , ) ( 1,2 ) ( 1,3 ) ( 2,3 ) ( 1,2,3)"
s = list ( set ( iterable ) ) combs = chain . from_iterable ( combinations ( s , r ) for r in range ( len ( s ) + 1 ) ) res = set ( frozenset ( x ) for x in combs ) # res = map ( frozenset , combs ) return res
def create_game ( self , map_name ) : """Create a game for the agents to join . Args : map _ name : The map to use ."""
map_inst = maps . get ( map_name ) map_data = map_inst . data ( self . _run_config ) if map_name not in self . _saved_maps : for controller in self . _controllers : controller . save_map ( map_inst . path , map_data ) self . _saved_maps . add ( map_name ) # Form the create game message . create = sc_pb ...
def _get_next_files ( self ) : """Used by the SFTP server code to retrieve a cached directory listing ."""
fnlist = self . __files [ : 16 ] self . __files = self . __files [ 16 : ] return fnlist
def _operate ( self , other , operation , inplace = True ) : """Gives the CustomDistribution operation ( product or divide ) with the other distribution . Parameters other : CustomDistribution The CustomDistribution to be multiplied . operation : str ' product ' for multiplication operation and ' divide...
if not isinstance ( other , CustomDistribution ) : raise TypeError ( "CustomDistribution objects can only be multiplied " "or divided with another CustomDistribution " "object. Got {other_type}, expected: " "CustomDistribution." . format ( other_type = type ( other ) ) ) phi = self if inplace else self . copy ( ) ...
def root2array ( filenames , treename = None , branches = None , selection = None , object_selection = None , start = None , stop = None , step = None , include_weight = False , weight_name = 'weight' , cache_size = - 1 , warn_missing_tree = False ) : """Convert trees in ROOT files into a numpy structured array . ...
filenames = _glob ( filenames ) if not filenames : raise ValueError ( "specify at least one filename" ) if treename is None : trees = list_trees ( filenames [ 0 ] ) if len ( trees ) > 1 : raise ValueError ( "treename must be specified if the file " "contains more than one tree" ) elif not trees ...
def decode_call ( self , call ) : """Replace callable tokens with callable names . : param call : Encoded callable name : type call : string : rtype : string"""
# Callable name is None when callable is part of exclude list if call is None : return None itokens = call . split ( self . _callables_separator ) odict = { } for key , value in self . _clut . items ( ) : if value in itokens : odict [ itokens [ itokens . index ( value ) ] ] = key return self . _callable...
def to_sparse ( self , format = 'csr' , ** kwargs ) : """Convert into a sparse matrix . Parameters format : { ' coo ' , ' csc ' , ' csr ' , ' dia ' , ' dok ' , ' lil ' } Sparse matrix format . kwargs : keyword arguments Passed through to sparse matrix constructor . Returns m : scipy . sparse . spmatri...
h = self . to_haplotypes ( ) m = h . to_sparse ( format = format , ** kwargs ) return m
def plot_station_mapping ( target_latitude , target_longitude , isd_station , distance_meters , target_label = "target" , ) : # pragma : no cover """Plots this mapping on a map ."""
try : import matplotlib . pyplot as plt except ImportError : raise ImportError ( "Plotting requires matplotlib." ) try : import cartopy . crs as ccrs import cartopy . feature as cfeature import cartopy . io . img_tiles as cimgt except ImportError : raise ImportError ( "Plotting requires cartopy....
def _slug_strip ( self , value ) : """Clean up a slug by removing slug separator characters that occur at the beginning or end of a slug . If an alternate separator is used , it will also replace any instances of the default ' - ' separator with the new separator ."""
re_sep = '(?:-|%s)' % re . escape ( self . separator ) value = re . sub ( '%s+' % re_sep , self . separator , value ) return re . sub ( r'^%s+|%s+$' % ( re_sep , re_sep ) , '' , value )
def _infer_shape_impl ( self , partial , * args , ** kwargs ) : """The actual implementation for calling shape inference API ."""
# pylint : disable = too - many - locals if len ( args ) != 0 and len ( kwargs ) != 0 : raise ValueError ( 'Can only specify known argument \ shapes either by positional or kwargs way.' ) sdata = [ ] indptr = [ 0 ] if len ( args ) != 0 : keys = c_array ( ctypes . c_char_p , [ ] ) for i ,...
def parse_params ( self , eps = 2.0 , nb_iter = None , xi = 1e-6 , clip_min = None , clip_max = None , num_iterations = None , ** kwargs ) : """Take in a dictionary of parameters and applies attack - specific checks before saving them as attributes . Attack - specific parameters : : param eps : ( optional flo...
# Save attack - specific parameters self . eps = eps if num_iterations is not None : warnings . warn ( "`num_iterations` is deprecated. Switch to `nb_iter`." " The old name will be removed on or after 2019-04-26." ) # Note : when we remove the deprecated alias , we can put the default # value of 1 for nb _ ...
def _set_service_policy ( self , v , load = False ) : """Setter method for service _ policy , mapped from YANG variable / interface / port _ channel / service _ policy ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ service _ policy is considered as a priv...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = service_policy . service_policy , is_container = 'container' , presence = False , yang_name = "service-policy" , rest_name = "service-policy" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmetho...