signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def add_text ( self , text , x , y , ** kws ) : """add text to plot"""
self . panel . add_text ( text , x , y , ** kws )
def add_circle ( self , center_lat = None , center_lng = None , radius = None , ** kwargs ) : """Adds a circle dict to the Map . circles attribute The circle in a sphere is called " spherical cap " and is defined in the Google Maps API by at least the center coordinates and its radius , in meters . A circle h...
kwargs . setdefault ( 'center' , { } ) if center_lat : kwargs [ 'center' ] [ 'lat' ] = center_lat if center_lng : kwargs [ 'center' ] [ 'lng' ] = center_lng if radius : kwargs [ 'radius' ] = radius if set ( ( 'lat' , 'lng' ) ) != set ( kwargs [ 'center' ] . keys ( ) ) : raise AttributeError ( 'circle ce...
def discover ( glob_pattern ) : """Find all files matching given glob _ pattern , parse them , and return list of environments : > > > envs = discover ( " requirements / * . in " ) > > > # print ( envs ) > > > envs = = [ . . . { ' name ' : ' base ' , ' refs ' : set ( ) } , . . . { ' name ' : ' py27 ' , ...
in_paths = glob . glob ( glob_pattern ) names = { extract_env_name ( path ) : path for path in in_paths } return order_by_refs ( [ { 'name' : name , 'refs' : Environment . parse_references ( in_path ) } for name , in_path in names . items ( ) ] )
def delete_role ( resource_root , service_name , name , cluster_name = "default" ) : """Delete a role by name @ param resource _ root : The root Resource object . @ param service _ name : Service name @ param name : Role name @ param cluster _ name : Cluster name @ return : The deleted ApiRole object"""
return call ( resource_root . delete , _get_role_path ( cluster_name , service_name , name ) , ApiRole )
def getunicode ( self , name , default = None , encoding = None ) : '''Return the value as a unicode string , or the default .'''
try : return self . _fix ( self [ name ] , encoding ) except ( UnicodeError , KeyError ) : return default
def basemz ( df ) : """The mz of the most abundant ion ."""
# returns the d = np . array ( df . columns ) [ df . values . argmax ( axis = 1 ) ] return Trace ( d , df . index , name = 'basemz' )
def summarize_address_range ( first , last ) : """Summarize a network range given the first and last IP addresses . Example : > > > summarize _ address _ range ( IPv4Address ( ' 1.1.1.0 ' ) , IPv4Address ( ' 1.1.1.130 ' ) ) [ IPv4Network ( ' 1.1.1.0/25 ' ) , IPv4Network ( ' 1.1.1.128/31 ' ) , IPv4Network ...
if not ( isinstance ( first , _BaseIP ) and isinstance ( last , _BaseIP ) ) : raise TypeError ( 'first and last must be IP addresses, not networks' ) if first . version != last . version : raise TypeError ( "%s and %s are not of the same version" % ( str ( first ) , str ( last ) ) ) if first > last : raise ...
def register ( self , es , append = None , modulo = None ) : """register a ` CMAEvolutionStrategy ` instance for logging , ` ` append = True ` ` appends to previous data logged under the same name , by default previous data are overwritten ."""
if not isinstance ( es , CMAEvolutionStrategy ) : raise TypeError ( "only class CMAEvolutionStrategy can be " + "registered for logging" ) self . es = es if append is not None : self . append = append if modulo is not None : self . modulo = modulo self . registered = True return self
def arc ( pRA , pDecl , sRA , sDecl , mcRA , lat ) : """Returns the arc of direction between a Promissor and Significator . It uses the generic proportional semi - arc method ."""
pDArc , pNArc = utils . dnarcs ( pDecl , lat ) sDArc , sNArc = utils . dnarcs ( sDecl , lat ) # Select meridian and arcs to be used # Default is MC and Diurnal arcs mdRA = mcRA sArc = sDArc pArc = pDArc if not utils . isAboveHorizon ( sRA , sDecl , mcRA , lat ) : # Use IC and Nocturnal arcs mdRA = angle . norm ( mc...
def create_local_arrays ( reified_arrays , array_factory = None ) : """Function that creates arrays , given the definitions in the reified _ arrays dictionary and the array _ factory keyword argument . Arguments reified _ arrays : dictionary Dictionary keyed on array name and array definitions . Can be ...
# By default , create numpy arrays if array_factory is None : array_factory = np . empty # Construct the array dictionary by calling the # array _ factory for each array return { n : array_factory ( ra . shape , ra . dtype ) for n , ra in reified_arrays . iteritems ( ) }
def assigned_add_ons ( self ) : """Access the assigned _ add _ ons : returns : twilio . rest . api . v2010 . account . incoming _ phone _ number . assigned _ add _ on . AssignedAddOnList : rtype : twilio . rest . api . v2010 . account . incoming _ phone _ number . assigned _ add _ on . AssignedAddOnList"""
if self . _assigned_add_ons is None : self . _assigned_add_ons = AssignedAddOnList ( self . _version , account_sid = self . _solution [ 'account_sid' ] , resource_sid = self . _solution [ 'sid' ] , ) return self . _assigned_add_ons
def _set_mct_l2ys_state ( self , v , load = False ) : """Setter method for mct _ l2ys _ state , mapped from YANG variable / mct _ l2ys _ state ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ mct _ l2ys _ state is considered as a private method . Backends...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = mct_l2ys_state . mct_l2ys_state , is_container = 'container' , presence = False , yang_name = "mct-l2ys-state" , rest_name = "mct-l2ys-state" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmetho...
def parse_content_type_header ( value ) : """maintype " / " subtype * ( " ; " parameter ) The maintype and substype are tokens . Theoretically they could be checked against the official IANA list + x - token , but we don ' t do that ."""
ctype = ContentType ( ) recover = False if not value : ctype . defects . append ( errors . HeaderMissingRequiredValue ( "Missing content type specification" ) ) return ctype try : token , value = get_token ( value ) except errors . HeaderParseError : ctype . defects . append ( errors . InvalidHeaderDefe...
def autocorrelation ( self , x , lag ) : """As in tsfresh ` autocorrelation < https : / / github . com / blue - yonder / tsfresh / blob / master / tsfresh / feature _ extraction / feature _ calculators . py # L1457 > ` _ Calculates the autocorrelation of the specified lag , according to the ` formula < https : / ...
# This is important : If a series is passed , the product below is calculated # based on the index , which corresponds to squaring the series . if lag is None : lag = 0 _autoc = feature_calculators . autocorrelation ( x , lag ) logging . debug ( "autocorrelation by tsfresh calculated" ) return _autoc
def get_config_var_data ( self , index , offset ) : """Get a chunk of data for a config variable ."""
if index == 0 or index > len ( self . config_database . entries ) : return [ Error . INVALID_ARRAY_KEY , b'' ] entry = self . config_database . entries [ index - 1 ] if not entry . valid : return [ ConfigDatabaseError . OBSOLETE_ENTRY , b'' ] if offset >= len ( entry . data ) : return [ Error . INVALID_ARRA...
def decode_from_bytes ( cls , data ) : """Decode an AMQP message from a bytearray . The returned message will not have a delivery context and therefore will be considered to be in an " already settled " state . : param data : The AMQP wire - encoded bytes to decode . : type data : bytes or bytearray"""
decoded_message = c_uamqp . decode_message ( len ( data ) , data ) return cls ( message = decoded_message )
def blame ( self , committer = True , by = 'repository' , ignore_globs = None , include_globs = None ) : """Returns the blame from the current HEAD of the repositories as a DataFrame . The DataFrame is grouped by committer name , so it will be the sum of all contributions to all repositories by each committer . A...
df = None for repo in self . repos : try : if df is None : df = repo . blame ( committer = committer , by = by , ignore_globs = ignore_globs , include_globs = include_globs ) else : df = df . append ( repo . blame ( committer = committer , by = by , ignore_globs = ignore_glob...
async def connect ( self , url , headers = { } , transports = None , engineio_path = 'engine.io' ) : """Connect to an Engine . IO server . : param url : The URL of the Engine . IO server . It can include custom query string parameters if required by the server . : param headers : A dictionary with custom head...
if self . state != 'disconnected' : raise ValueError ( 'Client is not in a disconnected state' ) valid_transports = [ 'polling' , 'websocket' ] if transports is not None : if isinstance ( transports , six . text_type ) : transports = [ transports ] transports = [ transport for transport in transport...
def _expand ( self , pos ) : """Splits sublists that are more than double the load level . Updates the index when the sublist length is less than double the load level . This requires incrementing the nodes in a traversal from the leaf node to the root . For an example traversal see self . _ loc ."""
_lists = self . _lists _keys = self . _keys _index = self . _index if len ( _keys [ pos ] ) > self . _dual : _maxes = self . _maxes _load = self . _load _lists_pos = _lists [ pos ] _keys_pos = _keys [ pos ] half = _lists_pos [ _load : ] half_keys = _keys_pos [ _load : ] del _lists_pos [ _loa...
def import_family ( self , rfa_file ) : """Append a import family entry to the journal . This instructs Revit to import a family into the opened model . Args : rfa _ file ( str ) : full path of the family file"""
self . _add_entry ( templates . IMPORT_FAMILY . format ( family_file = rfa_file ) )
def compute_path ( self ) : """Compute the min cost path between the two waves , and return it . Return the computed path as a tuple with two elements , each being a : class : ` numpy . ndarray ` ( 1D ) of ` ` int ` ` indices : : : ( [ r _ 1 , r _ 2 , . . . , r _ k ] , [ s _ 1 , s _ 2 , . . . , s _ k ] ) wh...
self . _setup_dtw ( ) if self . dtw is None : self . log ( u"Inner self.dtw is None => returning None" ) return None self . log ( u"Computing path..." ) wave_path = self . dtw . compute_path ( ) self . log ( u"Computing path... done" ) self . log ( u"Translating path to full wave indices..." ) real_indices = nu...
def do_tap ( self , x , y ) : """Simulate click operation Args : x , y ( int ) : position"""
rx , ry = x / self . scale , y / self . scale self . session . tap ( rx , ry )
def create_heroku_connect_schema ( using = DEFAULT_DB_ALIAS ) : """Create Heroku Connect schema . Note : This function is only meant to be used for local development . In a production environment the schema will be created by Heroku Connect . Args : using ( str ) : Alias for database connection . Retu...
connection = connections [ using ] with connection . cursor ( ) as cursor : cursor . execute ( _SCHEMA_EXISTS_QUERY , [ settings . HEROKU_CONNECT_SCHEMA ] ) schema_exists = cursor . fetchone ( ) [ 0 ] if schema_exists : return False cursor . execute ( "CREATE SCHEMA %s;" , [ AsIs ( settings . HE...
def prune_by_ngram_count ( self , minimum = None , maximum = None , label = None ) : """Removes results rows whose total n - gram count ( across all works bearing this n - gram ) is outside the range specified by ` minimum ` and ` maximum ` . For each text , the count used as part of the sum across all work...
self . _logger . info ( 'Pruning results by n-gram count' ) def calculate_total ( group ) : work_grouped = group . groupby ( constants . WORK_FIELDNAME , sort = False ) total_count = work_grouped [ constants . COUNT_FIELDNAME ] . max ( ) . sum ( ) group [ 'total_count' ] = pd . Series ( [ total_count ] * le...
def setup_logger ( debug , color ) : """Configure the logger ."""
if debug : log_level = logging . DEBUG else : log_level = logging . INFO logger = logging . getLogger ( 'exifread' ) stream = Handler ( log_level , debug , color ) logger . addHandler ( stream ) logger . setLevel ( log_level )
def text_to_data ( self , text , elt , ps ) : '''convert text into typecode specific data .'''
if text is None : return None m = Duration . lex_pattern . match ( text ) if m is None : raise EvaluateException ( 'Illegal duration' , ps . Backtrace ( elt ) ) d = m . groupdict ( ) if d [ 'T' ] and ( d [ 'h' ] is None and d [ 'm' ] is None and d [ 's' ] is None ) : raise EvaluateException ( 'Duration has ...
def read ( self , size ) : """Read bytes from the stream and block until sample rate is achieved . Args : size : number of bytes to read from the stream ."""
now = time . time ( ) missing_dt = self . _sleep_until - now if missing_dt > 0 : time . sleep ( missing_dt ) self . _sleep_until = time . time ( ) + self . _sleep_time ( size ) data = ( self . _wavep . readframes ( size ) if self . _wavep else self . _fp . read ( size ) ) # When reach end of audio stream , pad rema...
def get_thread_block_dimensions ( params , block_size_names = None ) : """thread block size from tuning params , currently using convention"""
if not block_size_names : block_size_names = default_block_size_names block_size_x = params . get ( block_size_names [ 0 ] , 256 ) block_size_y = params . get ( block_size_names [ 1 ] , 1 ) block_size_z = params . get ( block_size_names [ 2 ] , 1 ) return ( int ( block_size_x ) , int ( block_size_y ) , int ( block_...
def metadata ( self , filename ) : '''Get some metadata for a given file . Can vary from a backend to another but some are always present : - ` filename ` : the base filename ( without the path / prefix ) - ` url ` : the file public URL - ` checksum ` : a checksum expressed in the form ` algo : hash ` - '...
metadata = self . backend . metadata ( filename ) metadata [ 'filename' ] = os . path . basename ( filename ) metadata [ 'url' ] = self . url ( filename , external = True ) return metadata
def result ( self , timeout = None ) : """Return the last result of the callback chain or raise the last exception thrown and not caught by an errback . This will block until the result is available . If a timeout is given and the call times out raise a TimeoutError If SIGINT is caught while waiting raises ...
self . _do_wait ( timeout ) if self . _exception : self . _last_exception . exception = None self . _last_exception . tb_info = None raise self . _result else : return self . _result
def host ( self , hostname = None ) : """Get or set host ( IPv4 / IPv6 or hostname like ' plc . domain . net ' ) : param hostname : hostname or IPv4 / IPv6 address or None for get value : type hostname : str or None : returns : hostname or None if set fail : rtype : str or None"""
if ( hostname is None ) or ( hostname == self . __hostname ) : return self . __hostname # when hostname change ensure old socket is close self . close ( ) # IPv4 ? try : socket . inet_pton ( socket . AF_INET , hostname ) self . __hostname = hostname return self . __hostname except socket . error : p...
def resolve ( self ) : """Resolves references in this model ."""
model = self . copy ( ) for ct in model . component_types : model . resolve_component_type ( ct ) for c in model . components : if c . id not in model . fat_components : model . add ( model . fatten_component ( c ) ) for c in ct . constants : c2 = c . copy ( ) c2 . numeric_value = model . get_nu...
def add ( self , key , value , expire = 0 , noreply = None ) : """The memcached " add " command . Args : key : str , see class docs for details . value : str , see class docs for details . expire : optional int , number of seconds until the item is expired from the cache , or zero for no expiry ( the defa...
if noreply is None : noreply = self . default_noreply return self . _store_cmd ( b'add' , { key : value } , expire , noreply ) [ key ]
def __at_om_to_im ( self , om ) : """Convert an " outer " access mode to an " inner " access mode . Returns a tuple of : ( < system access mode > , < is append > , < is universal newlines > ) ."""
original_om = om if om [ 0 ] == 'U' : om = om [ 1 : ] is_um = True else : is_um = False if om == 'r' : return ( original_om , O_RDONLY , False , is_um ) elif om == 'w' : return ( original_om , O_WRONLY | O_CREAT | O_TRUNC , False , is_um ) elif om == 'a' : return ( original_om , O_WRONLY | O_CRE...
def repr_tree ( self ) : """reconstruct represented tree as a DiGraph to preserve the current rootedness"""
import utool as ut import networkx as nx repr_tree = nx . DiGraph ( ) for u , v in ut . itertwo ( self . values ( ) ) : if not repr_tree . has_edge ( v , u ) : repr_tree . add_edge ( u , v ) return repr_tree
def _loadData ( self , data ) : """Load attribute values from Plex XML response ."""
self . _data = data self . listType = 'video' self . addedAt = utils . toDatetime ( data . attrib . get ( 'addedAt' ) ) self . key = data . attrib . get ( 'key' , '' ) self . lastViewedAt = utils . toDatetime ( data . attrib . get ( 'lastViewedAt' ) ) self . librarySectionID = data . attrib . get ( 'librarySectionID' )...
def compose_headers ( self , req , headers = None , opt = None , as_dict = False ) : """a utility to compose headers from pyswagger . io . Request and customized headers : return : list of tuple ( key , value ) when as _ dict is False , else dict"""
if headers is None : return list ( req . header . items ( ) ) if not as_dict else req . header opt = opt or { } join_headers = opt . pop ( BaseClient . join_headers , None ) if as_dict and not join_headers : # pick the most efficient way for special case headers = dict ( headers ) if isinstance ( headers , list...
def toggle_shade ( self , shade ) : """This method will overlay a semi - transparent shade on top of the tile ' s image . Inputs : shade - This will designate which shade you wish to turn on or off . Blue and red shades are available by default . ( doc string updated ver 0.1)"""
# First toggle the user specified shade if self . shades [ shade ] [ 0 ] : self . shades [ shade ] [ 0 ] = 0 else : self . shades [ shade ] [ 0 ] = 1 # Now draw the image with the active shades self . image . blit ( self . pic , ( 0 , 0 ) ) for key in self . shades : if self . shades [ key ] [ 0 ] : ...
def key ( seq : Sequence , tooth : Callable [ [ Sequence ] , str ] = ( lambda seq : str ( random . SystemRandom ( ) . choice ( seq ) ) . strip ( ) ) , nteeth : int = 6 , delimiter : str = ' ' , ) -> str : """Concatenate strings generated by the tooth function ."""
return delimiter . join ( tooth ( seq ) for _ in range ( nteeth ) )
def find_bad_footnote_urls ( tagged_lines , include_tags = None ) : """Find lines in the list of 2 - tuples of adoc - tagged lines that contain bad footnotes ( only urls ) > > > sections = get _ tagged _ sections ( BOOK _ PATH ) > > > tagged _ lines = list ( sections [ 0 ] [ 1 ] ) > > > find _ bad _ footnote ...
section_baddies = [ ] logger . debug ( tagged_lines [ : 2 ] ) for lineno , ( tag , line ) in enumerate ( tagged_lines ) : line_baddies = None if tag is None or include_tags is None or tag in include_tags or any ( ( tag . startswith ( t ) for t in include_tags ) ) : line_baddies = get_line_bad_footnotes ...
def is_uid ( str ) : """Input : string to check Output : True if UID , otherwise False"""
import re if len ( str ) != 16 : return False pattern = r'[^\.a-f0-9]' if re . search ( pattern , str . lower ( ) ) : return False return True
def count ( start = 0 , step = 1 , * , interval = 0 ) : """Generate consecutive numbers indefinitely . Optional starting point and increment can be defined , respectively defaulting to ` ` 0 ` ` and ` ` 1 ` ` . An optional interval can be given to space the values out ."""
agen = from_iterable . raw ( itertools . count ( start , step ) ) return time . spaceout . raw ( agen , interval ) if interval else agen
def sample ( self , start_state = None , size = 1 , return_type = "dataframe" ) : """Sample from the Markov Chain . Parameters : start _ state : dict or array - like iterable Representing the starting states of the variables . If None is passed , a random start _ state is chosen . size : int Number of sam...
if start_state is None and self . state is None : self . state = self . random_state ( ) elif start_state is not None : self . set_start_state ( start_state ) types = [ ( var_name , 'int' ) for var_name in self . variables ] sampled = np . zeros ( size , dtype = types ) . view ( np . recarray ) sampled [ 0 ] = ...
def _on_cluster_discovery ( self , future ) : """Invoked when the Redis server has responded to the ` ` CLUSTER _ NODES ` ` command . : param future : The future containing the response from Redis : type future : tornado . concurrent . Future"""
LOGGER . debug ( '_on_cluster_discovery(%r)' , future ) common . maybe_raise_exception ( future ) nodes = future . result ( ) for node in nodes : name = '{}:{}' . format ( node . ip , node . port ) if name in self . _cluster : LOGGER . debug ( 'Updating cluster connection info for %s:%s' , node . ip , n...
def create_ver_browser ( self , layout ) : """Create a version browser and insert it into the given layout : param layout : the layout to insert the browser into : type layout : QLayout : returns : the created browser : rtype : : class : ` jukeboxcore . gui . widgets . browser . ComboBoxBrowser ` : raises...
brws = ComboBoxBrowser ( 1 , headers = [ 'Version:' ] ) layout . insertWidget ( 1 , brws ) return brws
def selective_download ( name , oldest , newest ) : """Note : RSS feeds are counted backwards , default newest is 0 , the most recent ."""
if six . PY3 : name = name . encode ( "utf-8" ) feed = resolve_name ( name ) if six . PY3 : feed = feed . decode ( ) d = feedparser . parse ( feed ) logger . debug ( d ) try : d . entries [ int ( oldest ) ] except IndexError : print ( "Error feed does not contain this many items." ) print ( "Hitman ...
def random_string ( ** kwargs ) : """By default generates a random string of 10 chars composed of digits and ascii lowercase letters . String length and pool can be override by using kwargs . Pool must be a list of strings"""
n = kwargs . get ( 'length' , 10 ) pool = kwargs . get ( 'pool' ) or string . digits + string . ascii_lowercase return '' . join ( random . SystemRandom ( ) . choice ( pool ) for _ in range ( n ) )
def save ( self , data ) : """Save a document or list of documents"""
if not self . is_connected : raise Exception ( "No database selected" ) if not data : return False if isinstance ( data , dict ) : doc = couchdb . Document ( ) doc . update ( data ) self . db . create ( doc ) elif isinstance ( data , couchdb . Document ) : self . db . update ( data ) elif isinst...
def parse_changelog ( args : Any ) -> Tuple [ str , str ] : """Return an updated changelog and and the list of changes ."""
with open ( "CHANGELOG.rst" , "r" ) as file : match = re . match ( pattern = r"(.*?Unreleased\n---+\n)(.+?)(\n*[^\n]+\n---+\n.*)" , string = file . read ( ) , flags = re . DOTALL , ) assert match header , changes , tail = match . groups ( ) tag = "%s - %s" % ( args . tag , datetime . date . today ( ) . isoformat ( ...
def create ( self , phone_number , sms_capability , account_sid = values . unset , friendly_name = values . unset , unique_name = values . unset , cc_emails = values . unset , sms_url = values . unset , sms_method = values . unset , sms_fallback_url = values . unset , sms_fallback_method = values . unset , status_callb...
data = values . of ( { 'PhoneNumber' : phone_number , 'SmsCapability' : sms_capability , 'AccountSid' : account_sid , 'FriendlyName' : friendly_name , 'UniqueName' : unique_name , 'CcEmails' : serialize . map ( cc_emails , lambda e : e ) , 'SmsUrl' : sms_url , 'SmsMethod' : sms_method , 'SmsFallbackUrl' : sms_fallback_...
def _FlowProcessingRequestHandlerLoop ( self , handler ) : """The main loop for the flow processing request queue ."""
while not self . flow_processing_request_handler_stop : try : msgs = self . _LeaseFlowProcessingReqests ( ) if msgs : for m in msgs : self . flow_processing_request_handler_pool . AddTask ( target = handler , args = ( m , ) ) else : time . sleep ( self...
def density_2d ( self , x , y , Rs , rho0 , r_core , center_x = 0 , center_y = 0 ) : """projected two dimenstional NFW profile ( kappa * Sigma _ crit ) : param R : radius of interest : type R : float / numpy array : param Rs : scale radius : type Rs : float : param rho0 : density normalization ( character...
x_ = x - center_x y_ = y - center_y R = np . sqrt ( x_ ** 2 + y_ ** 2 ) b = r_core * Rs ** - 1 x = R * Rs ** - 1 Fx = self . _F ( x , b ) return 2 * rho0 * Rs * Fx
def prepare_bucket ( self ) : """Resets and creates the destination bucket ( only called if - - create is true ) . : return :"""
self . logger . info ( 'Deleting old bucket first' ) del_url = '{0}/buckets/{1}' . format ( self . cluster_prefix , self . bucket ) r = self . _htsess . delete ( del_url ) try : r . raise_for_status ( ) except : self . logger . exception ( "Couldn't delete bucket" ) cr_url = '{0}/buckets' . format ( self . clus...
def dump ( self , config , instance , file_object , prefer = None , ** kwargs ) : """An abstract method that dumps to a given file object . : param class config : The config class of the instance : param object instance : The instance to dump : param file file _ object : The file object to dump to : param s...
file_object . write ( self . dumps ( config , instance , prefer = prefer , ** kwargs ) )
def buildcss ( app , buildpath , imagefile ) : """Create CSS file ."""
# set default values div = 'body' repeat = 'repeat-y' position = 'center' attachment = 'scroll' if app . config . sphinxmark_div != 'default' : div = app . config . sphinxmark_div if app . config . sphinxmark_repeat is False : repeat = 'no-repeat' if app . config . sphinxmark_fixed is True : attachment = 'f...
def metric_detail ( slug , with_data_table = False ) : """Template Tag to display a metric ' s * current * detail . * ` ` slug ` ` - - the metric ' s unique slug * ` ` with _ data _ table ` ` - - if True , prints the raw data in a table ."""
r = get_r ( ) granularities = list ( r . _granularities ( ) ) metrics = r . get_metric ( slug ) metrics_data = [ ] for g in granularities : metrics_data . append ( ( g , metrics [ g ] ) ) return { 'granularities' : [ g . title ( ) for g in granularities ] , 'slug' : slug , 'metrics' : metrics_data , 'with_data_tabl...
def updateIDs ( self , ginfo , tag = None , debug = False ) : """ensure all player ' s playerIDs are correct given game ' s info"""
# SC2APIProtocol . ResponseGameInfo attributes : # map _ name # mod _ names # local _ map _ path # player _ info # start _ raw # options thisPlayer = self . whoAmI ( ) for pInfo in ginfo . player_info : # parse ResponseGameInfo . player _ info to validate player information ( SC2APIProtocol . PlayerInfo ) against the s...
def get_docker_memory ( self , container_id , all_stats ) : """Return the container MEMORY . Input : id is the full container id all _ stats is the output of the stats method of the Docker API Output : a dict { ' rss ' : 1015808 , ' cache ' : 356352 , ' usage ' : . . . , ' max _ usage ' : . . . }"""
ret = { } # Read the stats try : # Do not exist anymore with Docker 1.11 ( issue # 848) # ret [ ' rss ' ] = all _ stats [ ' memory _ stats ' ] [ ' stats ' ] [ ' rss ' ] # ret [ ' cache ' ] = all _ stats [ ' memory _ stats ' ] [ ' stats ' ] [ ' cache ' ] ret [ 'usage' ] = all_stats [ 'memory_stats' ] [ 'usage' ] ...
def handle_client_stream ( self , stream , is_unix = False ) : """Handles stream of data received from client ."""
assert stream data = [ ] stream . settimeout ( 2 ) while True : try : if is_unix : buf = stream . recv ( 1024 ) else : buf = stream . read ( 1024 ) if not buf : break data . append ( buf ) except ( AttributeError , ValueError ) as message : ...
def marshal_value ( datatype , value ) : """Marshal a given string into a relevant Python type given the uPnP datatype . Assumes that the value has been pre - validated , so performs no checks . Returns a tuple pair of a boolean to say whether the value was marshalled and the ( un ) marshalled value ."""
for types , func in MARSHAL_FUNCTIONS : if datatype in types : return True , func ( value ) return False , value
def unwatch ( connection , volume_id ) : """Remove watching of a volume : type connection : boto . ec2 . connection . EC2Connection : param connection : EC2 connection object : type volume _ id : str : param volume _ id : VolumeID to add to the watchlist : returns : bool - True if the watch was successful...
try : volume = connection . get_all_volumes ( volume_ids = [ volume_id ] ) [ 0 ] volume . remove_tag ( 'AutomatedEBSSnapshots' ) except EC2ResponseError : pass logger . info ( 'Removed {} from the watchlist' . format ( volume_id ) ) return True
def _select_designated_port ( self , root_port ) : """DESIGNATED _ PORT is a port of the side near the root bridge of each link . It is determined by the cost of each path , etc same as ROOT _ PORT ."""
d_ports = [ ] root_msg = root_port . designated_priority for port in self . ports . values ( ) : port_msg = port . designated_priority if ( port . state is PORT_STATE_DISABLE or port . ofport . port_no == root_port . ofport . port_no ) : continue if ( port_msg is None or ( port_msg . root_id . value...
def page_slice ( self ) : """Return the query from : size tuple ( 0 - based ) ."""
return ( None if self . query is None else ( self . query . get ( "from" , 0 ) , self . query . get ( "size" , 10 ) ) )
def toFile ( self , filename ) : """Save the suffix array instance including all features attached in filename . Accept any filename following the _ open conventions , for example if it ends with . gz the file created will be a compressed GZip file ."""
start = _time ( ) fd = _open ( filename , "w" ) savedData = [ self . string , self . unit , self . voc , self . vocSize , self . SA , self . features ] for featureName in self . features : featureValues = getattr ( self , "_%s_values" % featureName ) featureDefault = getattr ( self , "%s_default" % featureName ...
def all_table_names_in_database ( self , cache = False , cache_timeout = None , force = False ) : """Parameters need to be passed as keyword arguments ."""
if not self . allow_multi_schema_metadata_fetch : return [ ] return self . db_engine_spec . fetch_result_sets ( self , 'table' )
def search_videohub ( cls , query , filters = None , status = None , sort = None , size = None , page = None ) : """searches the videohub given a query and applies given filters and other bits : see : https : / / github . com / theonion / videohub / blob / master / docs / search / post . md : see : https : / / ...
# construct url url = getattr ( settings , "VIDEOHUB_API_SEARCH_URL" , cls . DEFAULT_VIDEOHUB_API_SEARCH_URL ) # construct auth headers headers = { "Content-Type" : "application/json" , "Authorization" : settings . VIDEOHUB_API_TOKEN , } # construct payload payload = { "query" : query , } if filters : assert isinst...
def remove_storage ( self , storage ) : """Remove Storage from a Server . The Storage must be a reference to an object in Server . storage _ devices or the method will throw and Exception . A Storage from get _ storage ( uuid ) will not work as it is missing the ' address ' property ."""
if not hasattr ( storage , 'address' ) : raise Exception ( ( 'Storage does not have an address. ' 'Access the Storage via Server.storage_devices ' 'so they include an address. ' '(This is due how the API handles Storages)' ) ) self . cloud_manager . detach_storage ( server = self . uuid , address = storage . addres...
def _validate_scales ( self , proposal ) : """Validates the ` scales ` based on the mark ' s scaled attributes metadata . First checks for missing scale and then for ' rtype ' compatibility ."""
# Validate scales ' ' rtype ' versus data attribute ' rtype ' decoration # At this stage it is already validated that all values in self . scales # are instances of Scale . scales = proposal . value for name in self . trait_names ( scaled = True ) : trait = self . traits ( ) [ name ] if name not in scales : # C...
def detach_lb_from_subnets ( self , name , subnets ) : """Detaches load balancer from one or more subnets . : type name : string : param name : The name of the Load Balancer : type subnets : List of strings : param subnets : The name of the subnet ( s ) to detach . : rtype : List of strings : return : A...
params = { 'LoadBalancerName' : name } self . build_list_params ( params , subnets , 'Subnets.member.%d' ) return self . get_list ( 'DettachLoadBalancerFromSubnets' , params , None )
def ensure_dtraj_list ( dtrajs ) : r"""Makes sure that dtrajs is a list of discrete trajectories ( array of int )"""
if isinstance ( dtrajs , list ) : # elements are ints ? then wrap into a list if is_list_of_int ( dtrajs ) : return [ np . array ( dtrajs , dtype = int ) ] else : for i , dtraj in enumerate ( dtrajs ) : dtrajs [ i ] = ensure_dtraj ( dtraj ) return dtrajs else : return [ e...
def put ( self , entity ) : """Remember an entity ' s state to be saved during : meth : ` commit ` . . . note : : Any existing properties for the entity will be replaced by those currently set on this instance . Already - stored properties which do not correspond to keys set on this instance will be removed...
if self . _status != self . _IN_PROGRESS : raise ValueError ( "Batch must be in progress to put()" ) if entity . key is None : raise ValueError ( "Entity must have a key" ) if self . project != entity . key . project : raise ValueError ( "Key must be from same project as batch" ) if entity . key . is_partia...
def run ( self ) : has_npm = npm_installation_check ( ) if has_npm : run_npm_install ( ) else : print ( "Warning: npm not installed using prebuilded js files!" , file = sys . stderr ) """Download npm packages required by package . json and extract required files from them"""
for js in JS_FILES : downloaded_js_name = os . path . join ( TOP_DIR , js ) installed_js_name = os . path . join ( TOP_DIR , "sphinx_hwt" , "html" , js ) if has_npm : assert os . path . exists ( downloaded_js_name ) , downloaded_js_name os . makedirs ( os . path . dirname ( installed_js_name...
def write ( notebook , file_or_stream , fmt , version = nbformat . NO_CONVERT , ** kwargs ) : """Write a notebook to a file"""
# Python 2 compatibility text = u'' + writes ( notebook , fmt , version , ** kwargs ) file_or_stream . write ( text ) # Add final newline # 165 if not text . endswith ( u'\n' ) : file_or_stream . write ( u'\n' )
def _trim_value ( self , value ) : """Trim double quotes off the ends of a value , un - escaping inner double quotes and literal backslashes . Also convert escapes to unicode . If the string is not quoted , return it unmodified ."""
if value [ 0 ] == '"' : assert value [ - 1 ] == '"' value = value [ 1 : - 1 ] . replace ( '\\"' , '"' ) . replace ( "\\\\" , "\\" ) return Parser . _unescape_re . sub ( Parser . _unescape_fn , value ) return value
def _bytes_to_uint_48 ( self , bytes_ ) : """Converts an array of 6 bytes to a 48bit integer . : param data : bytearray to be converted to a 48bit integer : type data : bytearray : return : the integer : rtype : int"""
return ( ( bytes_ [ 0 ] * pow ( 2 , 40 ) ) + ( bytes_ [ 1 ] * pow ( 2 , 32 ) ) + ( bytes_ [ 2 ] * pow ( 2 , 24 ) ) + ( bytes_ [ 3 ] << 16 ) + ( bytes_ [ 4 ] << 8 ) + bytes_ [ 4 ] )
def projection ( radius = 5e-6 , sphere_index = 1.339 , medium_index = 1.333 , wavelength = 550e-9 , pixel_size = 1e-7 , grid_size = ( 80 , 80 ) , center = ( 39.5 , 39.5 ) ) : """Optical path difference projection of a dielectric sphere Parameters radius : float Radius of the sphere [ m ] sphere _ index : f...
# grid x = np . arange ( grid_size [ 0 ] ) . reshape ( - 1 , 1 ) y = np . arange ( grid_size [ 1 ] ) . reshape ( 1 , - 1 ) cx , cy = center # sphere location rpx = radius / pixel_size r = rpx ** 2 - ( x - cx ) ** 2 - ( y - cy ) ** 2 # distance z = np . zeros_like ( r ) rvalid = r > 0 z [ rvalid ] = 2 * np . sqrt ( r [ ...
def start_sync ( self ) : """Starts all the synchonization loop ( sensor / effector controllers ) ."""
if self . _syncing : return [ c . start ( ) for c in self . _controllers ] [ c . wait_to_start ( ) for c in self . _controllers ] self . _primitive_manager . start ( ) self . _primitive_manager . _running . wait ( ) self . _syncing = True logger . info ( 'Starting robot synchronization.' )
def show_code ( self , x , file = None ) : """Print details of methods , functions , or code to * file * . If * file * is not provided , the output is printed on stdout ."""
return _show_code ( x , self . opc . version , file )
def auth_refresh ( self , apikey = None , secret = None , email = None , password = None ) : """Renew authentication token manually . Uses POST to / auth interface : param apikey : Unique identifier for authorized use of the API : type apikey : str or None : param secret : The secret password corresponding to...
jwt = self . auth_token ( apikey = apikey , secret = secret , email = email , password = password ) self . _headers [ "Authorization" ] = "Bearer %s" % jwt self . _auth_token = jwt self . _last_auth = datetime . utcnow ( )
def linsert ( self , key , pivot , value , before = False ) : """Inserts value in the list stored at key either before or after the reference value pivot ."""
where = b'AFTER' if not before else b'BEFORE' return self . execute ( b'LINSERT' , key , where , pivot , value )
def process_git_configs ( git_short = '' ) : """Retrieve _ application . json _ files from GitLab . Args : git _ short ( str ) : Short Git representation of repository , e . g . forrest / core . Returns : collections . defaultdict : Configurations stored for each environment found ."""
LOG . info ( 'Processing application.json files from GitLab "%s".' , git_short ) file_lookup = FileLookup ( git_short = git_short ) app_configs = process_configs ( file_lookup , RUNWAY_BASE_PATH + '/application-master-{env}.json' , RUNWAY_BASE_PATH + '/pipeline.json' ) commit_obj = file_lookup . project . commits . get...
def webhook ( ) : """When the Flask server gets a request at the ` / webhook ` URL , it will run this function . Most of the time , that request will be a genuine webhook notification from Nylas . However , it ' s possible that the request could be a fake notification from someone else , trying to fool our ap...
# When you first tell Nylas about your webhook , it will test that webhook # URL with a GET request to make sure that it responds correctly . # We just need to return the ` challenge ` parameter to indicate that this # is a valid webhook URL . if request . method == "GET" and "challenge" in request . args : print (...
def init_app ( self , app ) : """绑定app"""
if app . config . GRIDFS_SETTINGS and isinstance ( app . config . GRIDFS_SETTINGS , dict ) : self . GRIDFS_SETTINGS = app . config . GRIDFS_SETTINGS self . app = app else : raise ValueError ( "nonstandard sanic config GRIDFS_URIS,GRIDFS_URIS must be a Dict[Bucket_name,Tuple[dburl,collection]]" ) @ app . lis...
def get_api_keys_of_account_group ( self , account_id , group_id , ** kwargs ) : # noqa : E501 """Get API keys of a group . # noqa : E501 An endpoint for listing the API keys of the group with details . * * Example usage : * * ` curl https : / / api . us - east - 1 . mbedcloud . com / v3 / accounts / { accountID ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . get_api_keys_of_account_group_with_http_info ( account_id , group_id , ** kwargs ) # noqa : E501 else : ( data ) = self . get_api_keys_of_account_group_with_http_info ( account_id , group_id , ** kwargs ) # noq...
def set_actor ( user , sender , instance , signal_duid , ** kwargs ) : """Signal receiver with an extra , required ' user ' kwarg . This method becomes a real ( valid ) signal receiver when it is curried with the actor ."""
if hasattr ( threadlocal , 'auditlog' ) : if signal_duid != threadlocal . auditlog [ 'signal_duid' ] : return try : app_label , model_name = settings . AUTH_USER_MODEL . split ( '.' ) auth_user_model = apps . get_model ( app_label , model_name ) except ValueError : auth_user_...
def record_markdown ( text , cellid ) : """Records the specified markdown text to the acorn database . Args : text ( str ) : the * raw * markdown text entered into the cell in the ipython notebook ."""
from acorn . logging . database import record from time import time ekey = "nb-{}" . format ( cellid ) global _cellid_map if cellid not in _cellid_map : from acorn . logging . database import active_db from difflib import SequenceMatcher from acorn . logging . diff import cascade taskdb = active_db ( ) ...
def CUnescape ( text ) : """Unescape a text string with C - style escape sequences to UTF - 8 bytes ."""
def ReplaceHex ( m ) : # Only replace the match if the number of leading back slashes is odd . i . e . # the slash itself is not escaped . if len ( m . group ( 1 ) ) & 1 : return m . group ( 1 ) + 'x0' + m . group ( 2 ) return m . group ( 0 ) # This is required because the ' string _ escape ' encoding d...
def rotate ( self , l , u ) : """rotate l radians around axis u"""
cl = math . cos ( l ) sl = math . sin ( l ) x = ( cl + u . x * u . x * ( 1 - cl ) ) * self . x + ( u . x * u . y * ( 1 - cl ) - u . z * sl ) * self . y + ( u . x * u . z * ( 1 - cl ) + u . y * sl ) * self . z y = ( u . y * u . x * ( 1 - cl ) + u . z * sl ) * self . x + ( cl + u . y * u . y * ( 1 - cl ) ) * self . y + (...
def optimize_structure_handler ( rule , handler ) : """Produce an " optimized " version of handler for the dispatcher to limit reference lookups ."""
def runner ( walk , dispatcher , node ) : handler ( dispatcher , node ) return yield # pragma : no cover return runner
def cli ( ctx , list , dir , files , project_dir , sayno ) : """Manage verilog examples . \n Install with ` apio install examples `"""
exit_code = 0 if list : exit_code = Examples ( ) . list_examples ( ) elif dir : exit_code = Examples ( ) . copy_example_dir ( dir , project_dir , sayno ) elif files : exit_code = Examples ( ) . copy_example_files ( files , project_dir , sayno ) else : click . secho ( ctx . get_help ( ) ) click . sec...
def change_dcv ( gandi , resource , dcv_method ) : """Change the DCV for a running certificate operation . Resource can be a CN or an ID"""
ids = gandi . certificate . usable_ids ( resource ) if len ( ids ) > 1 : gandi . echo ( 'Will not update, %s is not precise enough.' % resource ) gandi . echo ( ' * cert : ' + '\n * cert : ' . join ( [ str ( id_ ) for id_ in ids ] ) ) return id_ = ids [ 0 ] opers = gandi . oper . list ( { 'cert_id' : id_ ...
def check_sender_and_entity_handle_match ( sender_handle , entity_handle ) : """Ensure that sender and entity handles match . Basically we ' ve already verified the sender is who they say when receiving the payload . However , the sender might be trying to set another author in the payload itself , since Diaspo...
if sender_handle != entity_handle : logger . warning ( "sender_handle and entity_handle don't match, aborting! sender_handle: %s, entity_handle: %s" , sender_handle , entity_handle ) return False return True
def appendPath ( self , path ) : """Appends the inputted path to the end of the sys . path variable , provided the path does not already exist in it . : param path : type str : return bool : success"""
# normalize the path path = os . path . normcase ( nstr ( path ) ) . strip ( ) if path and path != '.' and path not in sys . path : sys . path . append ( path ) self . _addedpaths . append ( path ) return True return False
def continuous_binary_search ( f , lo , hi , gap = 1e-4 ) : """Binary search for a function : param f : boolean monotone function with f ( hi ) = True : param int lo : : param int hi : with hi > = lo : param float gap : : returns : first value x in [ lo , hi ] such that f ( x ) , x is computed up to som...
while hi - lo > gap : # in other languages you can force floating division by using 2.0 mid = ( lo + hi ) / 2. if f ( mid ) : hi = mid else : lo = mid return lo
def _get_course_descriptor_path ( self , courseid ) : """: param courseid : the course id of the course : raise InvalidNameException , CourseNotFoundException : return : the path to the descriptor of the course"""
if not id_checker ( courseid ) : raise InvalidNameException ( "Course with invalid name: " + courseid ) course_fs = self . get_course_fs ( courseid ) if course_fs . exists ( "course.yaml" ) : return courseid + "/course.yaml" if course_fs . exists ( "course.json" ) : return courseid + "/course.json" raise Co...
def _fetch_remote_json ( service_url , params = None , use_http_post = False ) : """Retrieves a JSON object from a URL ."""
if not params : params = { } request_url , response = _fetch_remote ( service_url , params , use_http_post ) if six . PY3 : str_response = response . read ( ) . decode ( 'utf-8' ) return ( request_url , json . loads ( str_response , parse_float = Decimal ) ) return ( request_url , json . load ( response , p...
def find_by_hash ( self , hash = None , book = - 1 ) : '''Search notes for a given ( possibly abbreviated ) hash'''
if hash : self . fyi ( "nota.find_by_hash() with abbreviated hash %s; book=%s" % ( hash , book ) ) try : if book < 0 : rows = self . cur . execute ( "SELECT noteId, hash FROM note WHERE book > 0;" ) . fetchall ( ) else : rows = self . cur . execute ( "SELECT noteId, hash FROM note WHERE book...
def cycle_data ( self , verbose = False , result_cycle = None , result_size = None , result_edges = None , changelog = True ) : """Get data from JIRA for cycle / flow times and story points size change . Build a numerically indexed data frame with the following ' fixed ' columns : ` key ` , ' url ' , ' issue _ ...
cycle_names = [ s [ 'name' ] for s in self . settings [ 'cycle' ] ] accepted_steps = set ( s [ 'name' ] for s in self . settings [ 'cycle' ] if s [ 'type' ] == StatusTypes . accepted ) completed_steps = set ( s [ 'name' ] for s in self . settings [ 'cycle' ] if s [ 'type' ] == StatusTypes . complete ) series = { 'key' ...
def _parse_planar_geometry_surface ( self , node ) : """Parses a planar geometry surface"""
nodes = [ ] for key in [ "topLeft" , "topRight" , "bottomRight" , "bottomLeft" ] : nodes . append ( geo . Point ( getattr ( node , key ) [ "lon" ] , getattr ( node , key ) [ "lat" ] , getattr ( node , key ) [ "depth" ] ) ) top_left , top_right , bottom_right , bottom_left = tuple ( nodes ) return geo . PlanarSurfac...
def emitSortingChanged ( self , index ) : """Emits the sorting changed signal if the user clicks on a sorting column . : param index | < int >"""
if not self . signalsBlocked ( ) and self . isSortingEnabled ( ) : self . sortingChanged . emit ( index , self . header ( ) . sortIndicatorOrder ( ) )