signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def asof ( self , label ) :
"""Return the label from the index , or , if not present , the previous one .
Assuming that the index is sorted , return the passed index label if it
is in the index , or return the previous index label if the passed one
is not in the index .
Parameters
label : object
The lab... | try :
loc = self . get_loc ( label , method = 'pad' )
except KeyError :
return self . _na_value
else :
if isinstance ( loc , slice ) :
loc = loc . indices ( len ( self ) ) [ - 1 ]
return self [ loc ] |
def save_load ( jid , load , minions = None ) :
'''Save the load to the specified jid id''' | with _get_serv ( commit = True ) as cur :
sql = '''INSERT INTO `jids` (`jid`, `load`) VALUES (%s, %s)'''
try :
cur . execute ( sql , ( jid , salt . utils . json . dumps ( load ) ) )
except MySQLdb . IntegrityError : # https : / / github . com / saltstack / salt / issues / 22171
# Without this tr... |
def format ( tokens , formatter , outfile = None ) : # pylint : disable = redefined - builtin
"""Format a tokenlist ` ` tokens ` ` with the formatter ` ` formatter ` ` .
If ` ` outfile ` ` is given and a valid file object ( an object
with a ` ` write ` ` method ) , the result will be written to it , otherwise
... | try :
if not outfile :
realoutfile = getattr ( formatter , 'encoding' , None ) and BytesIO ( ) or StringIO ( )
formatter . format ( tokens , realoutfile )
return realoutfile . getvalue ( )
else :
formatter . format ( tokens , outfile )
except TypeError as err :
if ( isinstanc... |
def get_templates ( path : Path ) -> List [ str ] :
'''List all files in ` ` templates ` ` directory , including all subdirectories .
The resulting list contains UNIX - like relative paths starting with ` ` templates ` ` .''' | result = [ ]
for item in path . glob ( '**/*' ) :
if item . is_file ( ) and not item . name . startswith ( '_' ) :
result . append ( item . relative_to ( path . parent ) . as_posix ( ) )
return result |
def get_contributors ( gh , repo_id ) :
"""Get list of contributors to a repository .""" | try : # FIXME : Use ` github3 . Repository . contributors ` to get this information
contrib_url = gh . repository_with_id ( repo_id ) . contributors_url
r = requests . get ( contrib_url )
if r . status_code == 200 :
contributors = r . json ( )
def get_author ( contributor ) :
r =... |
def is_period_alias ( period ) :
"""Check if a given period is possibly an alias .
Parameters
period : float
A period to test if it is a possible alias or not .
Returns
is _ alias : boolean
True if the given period is in a range of period alias .""" | # Based on the period vs periodSN plot of EROS - 2 dataset ( Kim + 2014 ) .
# Period alias occurs mostly at ~ 1 and ~ 30.
# Check each 1 , 2 , 3 , 4 , 5 factors .
for i in range ( 1 , 6 ) : # One - day and one - month alias
if ( .99 / float ( i ) ) < period < ( 1.004 / float ( i ) ) :
return True
if ( 1... |
def get_model ( is_netfree = False , without_reset = False , seeds = None , effective = False ) :
"""Generate a model with parameters in the global scope , ` ` SPECIES _ ATTRIBUTES ` `
and ` ` REACTIONRULES ` ` .
Parameters
is _ netfree : bool , optional
Return ` ` NetfreeModel ` ` if True , and ` ` Network... | try :
if seeds is not None or is_netfree :
m = ecell4_base . core . NetfreeModel ( )
else :
m = ecell4_base . core . NetworkModel ( )
for sp in SPECIES_ATTRIBUTES :
m . add_species_attribute ( sp )
for rr in REACTION_RULES :
m . add_reaction_rule ( rr )
if not without... |
def write_primers ( primer_list , path , names = None , notes = None ) :
'''Write a list of primers out to a csv file . The first three columns are
compatible with the current IDT order form ( name , sequence , notes ) . By
default there are no notes , which is an optional parameter .
: param primer _ list : ... | # Check for notes and names having the right length , apply them to primers
if names is not None :
if len ( names ) != len ( primer_list ) :
names_msg = 'Mismatch in number of notes and primers.'
raise PrimerAnnotationError ( names_msg )
for i , name in enumerate ( names ) :
primer_list ... |
def parse_requires ( __fname : str ) -> List [ str ] :
"""Parse ` ` pip ` ` - style requirements files .
This is a * very * naïve parser , but very few packages make use of the more
advanced features . Support for other features will be added only when
packages in the wild depend on them .
Args :
_ _ fna... | deps = [ ]
with open ( __fname ) as req_file :
entries = [ s . split ( '#' ) [ 0 ] . strip ( ) for s in req_file . readlines ( ) ]
for dep in entries :
if not dep :
continue
elif dep . startswith ( '-r ' ) :
include = dep . split ( ) [ 1 ]
if '/' not in includ... |
def transcribe ( self , text , punctuation = True ) :
"""Accepts a word and returns a string of an approximate pronounciation ( IPA )""" | if not punctuation :
text = re . sub ( r"[\.\";\,\:\[\]\(\)!&?‘]" , "" , text )
text = re . sub ( r'sch' , 'ʃ' , text )
text = re . sub ( r'(?<=[aeiouäëöüâæœêîôû])h' , 'χ' , text )
text = re . sub ( r'h(?=[aeiouäëöüâæœêîôû])' , 'χ' , text )
text = re . sub ( r'(?<=[aeiouäëöüâæœêîôû])s(?=[aeiouäëöüâæœêîôû])' , 'z̥' ... |
def handle_channel_settled ( raiden : 'RaidenService' , event : Event ) :
data = event . event_data
token_network_identifier = event . originating_contract
channel_identifier = data [ 'args' ] [ 'channel_identifier' ]
block_number = data [ 'block_number' ]
block_hash = data [ 'block_hash' ]
tran... | our_locksroot , partner_locksroot = get_onchain_locksroots ( chain = raiden . chain , canonical_identifier = channel_state . canonical_identifier , participant1 = channel_state . our_state . address , participant2 = channel_state . partner_state . address , block_identifier = block_hash , )
channel_settled = ContractRe... |
def pick_flat_z ( data ) :
"""Generate a 2D array of the quasiparticle weight by only selecting the
first particle data""" | zmes = [ ]
for i in data [ 'zeta' ] :
zmes . append ( i [ : , 0 ] )
return np . asarray ( zmes ) |
def _get_photos ( session , user_or_group_id ) :
"""https : / / vk . com / dev / photos . getAll""" | response = session . fetch_items ( "photos.getAll" , Photo . from_json , count = 200 , owner_id = user_or_group_id )
return response |
def get_mate_center ( self , angle = 0 ) :
"""Mate at ring ' s center rotated ` ` angle ` ` degrees .
: param angle : rotation around z - axis ( unit : deg )
: type angle : : class : ` float `
: return : mate in ring ' s center rotated about z - axis
: rtype : : class : ` Mate < cqparts . constraint . Mate ... | return Mate ( self , CoordSystem . from_plane ( cadquery . Plane ( origin = ( 0 , 0 , self . width / 2 ) , xDir = ( 1 , 0 , 0 ) , normal = ( 0 , 0 , 1 ) , ) . rotated ( ( 0 , 0 , angle ) ) # rotate about z - axis
) ) |
def helper_parallel_lines ( start0 , end0 , start1 , end1 , filename ) :
"""Image for : func : ` . parallel _ lines _ parameters ` docstring .""" | if NO_IMAGES :
return
figure = plt . figure ( )
ax = figure . gca ( )
points = stack1d ( start0 , end0 , start1 , end1 )
ax . plot ( points [ 0 , : 2 ] , points [ 1 , : 2 ] , marker = "o" )
ax . plot ( points [ 0 , 2 : ] , points [ 1 , 2 : ] , marker = "o" )
ax . axis ( "scaled" )
_plot_helpers . add_plot_boundary ... |
def ui_main ( fmt_table , node_dict ) :
"""Create the base UI in command mode .""" | cmd_funct = { "quit" : False , "run" : node_cmd , "stop" : node_cmd , "connect" : node_cmd , "details" : node_cmd , "update" : True }
ui_print ( "\033[?25l" )
# cursor off
print ( "{}\n" . format ( fmt_table ) )
sys . stdout . flush ( )
# refresh _ main values :
# None = loop main - cmd , True = refresh - list , False ... |
def chdir ( self , path ) :
"""Changes the current directory to the given path""" | self . cwd = self . _join_chunks ( self . _normalize_path ( path ) ) |
def gp_xfac ( ) :
"""example using QM12 enhancement factors
- uses ` gpcalls ` kwarg to reset xtics
- numpy . loadtxt needs reshaping for input files w / only one datapoint
- according poster presentations see QM12 _ & NSD _ review
. . _ QM12 : http : / / indico . cern . ch / getFile . py / access ? contrib... | # prepare data
inDir , outDir = getWorkDirs ( )
data = OrderedDict ( )
# TODO : " really " reproduce plot using spectral data
for file in os . listdir ( inDir ) :
info = os . path . splitext ( file ) [ 0 ] . split ( '_' )
key = ' ' . join ( info [ : 2 ] + [ ':' , ' - ' . join ( [ str ( float ( s ) / 1e3 ) for s... |
def turn_on ( host , did , token = None ) :
"""Turn on bulb or fixture""" | urllib3 . disable_warnings ( )
if token :
scheme = "https"
if not token :
scheme = "http"
token = "1234567890"
url = ( scheme + '://' + host + '/gwr/gop.php?cmd=DeviceSendCommand&data=<gip><version>1</version><token>' + token + '</token><did>' + did + '</did><value>1</value></gip>&fmt=xml' )
response = requ... |
def find ( self , oid ) :
"""Return list of extensions with given Oid""" | if not isinstance ( oid , Oid ) :
raise TypeError ( "Need crytypescrypto.oid.Oid as argument" )
found = [ ]
index = - 1
end = len ( self )
while True :
index = libcrypto . X509_get_ext_by_NID ( self . cert . cert , oid . nid , index )
if index >= end or index < 0 :
break
found . append ( self [ ... |
def adjust_widths ( self , max_width , colstats ) :
"""Adjust column widths based on the least negative affect it will
have on the viewing experience . We take note of the total character
mass that will be clipped when each column should be narrowed . The
actual score for clipping is based on percentage of to... | adj_colstats = [ ]
for x in colstats :
if not x [ 'preformatted' ] :
adj_colstats . append ( x )
else :
max_width -= x [ 'offt' ]
next_score = lambda x : ( x [ 'counts' ] [ x [ 'offt' ] ] + x [ 'chop_mass' ] + x [ 'chop_count' ] ) / x [ 'total_mass' ]
cur_width = lambda : sum ( x [ 'offt' ] for ... |
def timeout ( seconds = 0 , minutes = 0 , hours = 0 ) :
"""Add a signal - based timeout to any block of code .
If multiple time units are specified , they will be added together to determine time limit .
Usage :
with timeout ( seconds = 5 ) :
my _ slow _ function ( . . . )
Args :
- seconds : The time li... | limit = seconds + 60 * minutes + 3600 * hours
def handler ( signum , frame ) : # pylint : disable = W0613
raise TimeoutError ( 'timed out after {} seconds' . format ( limit ) )
try :
signal . signal ( signal . SIGALRM , handler )
signal . setitimer ( signal . ITIMER_REAL , limit )
yield
finally :
si... |
def add_missing_xml_attributes ( dom , volume_counter = 0 ) :
"""Add ` xmlns ` and ` ID ` attributes to ` ` < mods : mods > ` ` tag .
Args :
dom ( HTMLElement ) : DOM containing whole document .
volume _ counter ( int , default 0 ) : ID of volume .""" | mods_tag = get_mods_tag ( dom )
if mods_tag :
params = mods_tag . params
# add missing attributes
params [ "ID" ] = "MODS_VOLUME_%04d" % ( volume_counter + 1 )
params [ "xmlns:mods" ] = "http://www.loc.gov/mods/v3"
params [ "xmlns:xlink" ] = "http://www.w3.org/1999/xlink"
params [ "xmlns:xsi" ] ... |
def pagerank_weighted ( graph , initial_value = None , damping = 0.85 ) :
"""Calculates PageRank for an undirected graph""" | if initial_value == None :
initial_value = 1.0 / len ( graph . nodes ( ) )
scores = dict . fromkeys ( graph . nodes ( ) , initial_value )
iteration_quantity = 0
for iteration_number in range ( 100 ) :
iteration_quantity += 1
convergence_achieved = 0
for i in graph . nodes ( ) :
rank = 1 - dampin... |
def blueprint ( self , blueprint , ** options ) :
"""Register a blueprint on the application .
: param blueprint : Blueprint object or ( list , tuple ) thereof
: param options : option dictionary with blueprint defaults
: return : Nothing""" | if isinstance ( blueprint , ( list , tuple , BlueprintGroup ) ) :
for item in blueprint :
self . blueprint ( item , ** options )
return
if blueprint . name in self . blueprints :
assert self . blueprints [ blueprint . name ] is blueprint , ( 'A blueprint with the name "%s" is already registered. ' ... |
def user_getinfo ( self , fields , access_token = None ) :
"""Request multiple fields of information about the user .
: param fields : The names of the fields requested .
: type fields : list
: returns : The values of the current user for the fields requested .
The keys are the field names , values are the ... | if g . oidc_id_token is None and access_token is None :
raise Exception ( 'User was not authenticated' )
info = { }
all_info = None
for field in fields :
if access_token is None and field in g . oidc_id_token :
info [ field ] = g . oidc_id_token [ field ]
elif current_app . config [ 'OIDC_USER_INFO_... |
def asarray ( self , key = None , series = None ) :
"""Return image data of multiple TIFF pages as numpy array .
By default the first image series is returned .
Parameters
key : int , slice , or sequence of page indices
Defines which pages to return as array .
series : int
Defines which series of pages ... | if key is None and series is None :
series = 0
if series is not None :
pages = self . series [ series ] . pages
else :
pages = self . pages
if key is None :
pass
elif isinstance ( key , int ) :
pages = [ pages [ key ] ]
elif isinstance ( key , slice ) :
pages = pages [ key ]
elif isinstance ( ke... |
def realpath ( self , filename ) :
"""Return the canonical path of the specified filename , eliminating any
symbolic links encountered in the path .""" | if self . filesystem . is_windows_fs :
return self . abspath ( filename )
filename = make_string_path ( filename )
path , ok = self . _joinrealpath ( filename [ : 0 ] , filename , { } )
return self . abspath ( path ) |
def dispatch ( self , context , consumed , handler , is_endpoint ) :
"""Called as dispatch descends into a tier .
The base extension uses this to maintain the " current url " .""" | request = context . request
if __debug__ :
log . debug ( "Handling dispatch event." , extra = dict ( request = id ( context ) , consumed = consumed , handler = safe_name ( handler ) , endpoint = is_endpoint ) )
# The leading path element ( leading slash ) requires special treatment .
if not consumed and context . r... |
def cleanup_full ( self , trial_runner ) :
"""Cleans up bracket after bracket is completely finished .
Lets the last trial continue to run until termination condition
kicks in .""" | for trial in self . current_trials ( ) :
if ( trial . status == Trial . PAUSED ) :
trial_runner . stop_trial ( trial ) |
async def Check ( self , stream ) :
"""Implements synchronous periodic checks""" | request = await stream . recv_message ( )
checks = self . _checks . get ( request . service )
if checks is None :
await stream . send_trailing_metadata ( status = Status . NOT_FOUND )
elif len ( checks ) == 0 :
await stream . send_message ( HealthCheckResponse ( status = HealthCheckResponse . SERVING , ) )
else... |
def add_unchecked ( self , binsha , mode , name ) :
"""Add the given item to the tree , its correctness is assumed , which
puts the caller into responsibility to assure the input is correct .
For more information on the parameters , see ` ` add ` `
: param binsha : 20 byte binary sha""" | self . _cache . append ( ( binsha , mode , name ) ) |
def _create_at ( self , timestamp = None , id = None , forced_identity = None , ** kwargs ) :
"""WARNING : Only for internal use and testing .
Create a Versionable having a version _ start _ date and
version _ birth _ date set to some pre - defined timestamp
: param timestamp : point in time at which the inst... | id = Versionable . uuid ( id )
if forced_identity :
ident = Versionable . uuid ( forced_identity )
else :
ident = id
if timestamp is None :
timestamp = get_utc_now ( )
kwargs [ 'id' ] = id
kwargs [ 'identity' ] = ident
kwargs [ 'version_start_date' ] = timestamp
kwargs [ 'version_birth_date' ] = timestamp
r... |
def lifecycle_lock ( self ) :
"""An identity - keyed inter - process lock for safeguarding lifecycle and other operations .""" | safe_mkdir ( self . _metadata_base_dir )
return OwnerPrintingInterProcessFileLock ( # N . B . This lock can ' t key into the actual named metadata dir ( e . g . ` . pids / pantsd / lock `
# via ` ProcessMetadataManager . _ get _ metadata _ dir _ by _ name ( ) ` ) because of a need to purge
# the named metadata dir on s... |
def get_schema_version_from_xml ( xml ) :
"""Get schemaVersion attribute from OpenMalaria scenario file
xml - open file or content of xml document to be processed""" | if isinstance ( xml , six . string_types ) :
xml = StringIO ( xml )
try :
tree = ElementTree . parse ( xml )
except ParseError : # Not an XML file
return None
root = tree . getroot ( )
return root . attrib . get ( 'schemaVersion' , None ) |
def operations ( ) :
"""Class decorator stores all calls into list .
Can be used until . invalidate ( ) is called .
: return : decorated class""" | def decorator ( func ) :
@ wraps ( func )
def wrapped_func ( * args , ** kwargs ) :
self = args [ 0 ]
assert self . __can_use , "User operation queue only in 'with' block"
def defaults_dict ( ) :
f_args , varargs , keywords , defaults = inspect . getargspec ( func )
... |
def to_array ( self ) :
"""Serializes this InputVenueMessageContent to a dictionary .
: return : dictionary representation of this object .
: rtype : dict""" | array = super ( InputVenueMessageContent , self ) . to_array ( )
array [ 'latitude' ] = float ( self . latitude )
# type float
array [ 'longitude' ] = float ( self . longitude )
# type float
array [ 'title' ] = u ( self . title )
# py2 : type unicode , py3 : type str
array [ 'address' ] = u ( self . address )
# py2 : t... |
def send_email ( self , source , subject , body , to_addresses , cc_addresses = None , bcc_addresses = None , format = 'text' , reply_addresses = None , return_path = None , text_body = None , html_body = None ) :
"""Composes an email message based on input data , and then immediately
queues the message for sendi... | format = format . lower ( ) . strip ( )
if body is not None :
if format == "text" :
if text_body is not None :
raise Warning ( "You've passed in both a body and a text_body; please choose one or the other." )
text_body = body
else :
if html_body is not None :
rais... |
def findall ( data ) :
"""Worker that finds all occurrences of a given string ( or regex )
in a given text .
: param data : Request data dict : :
' string ' : string to search in text
' sub ' : input text
' regex ' : True to consider string as a regular expression
' whole _ word ' : True to match whole ... | return list ( findalliter ( data [ 'string' ] , data [ 'sub' ] , regex = data [ 'regex' ] , whole_word = data [ 'whole_word' ] , case_sensitive = data [ 'case_sensitive' ] ) ) |
def extentSearch ( self , xmin , ymin , xmax , ymax ) :
"""Filters the data by a geographical bounding box .
The bounding box is given as lower left point coordinates and upper
right point coordinates .
Note :
It ' s necessary that the dataframe has a ` lat ` and ` lng ` column
in order to apply the filte... | if not self . _dataFrame . empty :
try :
questionMin = ( self . _dataFrame . lat >= xmin ) & ( self . _dataFrame . lng >= ymin )
questionMax = ( self . _dataFrame . lat <= xmax ) & ( self . _dataFrame . lng <= ymax )
return np . logical_and ( questionMin , questionMax )
except AttributeE... |
def bisect ( func , a , b , xtol = 1e-12 , maxiter = 100 ) :
"""Finds the root of ` func ` using the bisection method .
Requirements
- func must be continuous function that accepts a single number input
and returns a single number
- ` func ( a ) ` and ` func ( b ) ` must have opposite sign
Parameters
fu... | fa = func ( a )
if fa == 0. :
return a
fb = func ( b )
if fb == 0. :
return b
assert sign ( fa ) != sign ( fb )
for i in xrange ( maxiter ) :
c = ( a + b ) / 2.
fc = func ( c )
if fc == 0. or abs ( b - a ) / 2. < xtol :
return c
if sign ( fc ) == sign ( func ( a ) ) :
a = c
e... |
def verify_log ( opts ) :
'''If an insecre logging configuration is found , show a warning''' | level = LOG_LEVELS . get ( str ( opts . get ( 'log_level' ) ) . lower ( ) , logging . NOTSET )
if level < logging . INFO :
log . warning ( 'Insecure logging configuration detected! Sensitive data may be logged.' ) |
def rm ( * components , ** kwargs ) :
"""Remove a file or directory .
If path is a directory , this recursively removes the directory and
any contents . Non - existent paths are silently ignored .
Supports Unix style globbing by default ( disable using
glob = False ) . For details on globbing pattern expans... | _path = path ( * components )
glob = kwargs . get ( "glob" , True )
paths = iglob ( _path ) if glob else [ _path ]
for file in paths :
if isfile ( file ) :
os . remove ( file )
elif exists ( file ) :
shutil . rmtree ( file , ignore_errors = False ) |
def _divide_and_round ( a , b ) :
"""divide a by b and round result to the nearest integer
When the ratio is exactly half - way between two integers ,
the even integer is returned .""" | # Based on the reference implementation for divmod _ near
# in Objects / longobject . c .
q , r = divmod ( a , b )
# round up if either r / b > 0.5 , or r / b = = 0.5 and q is odd .
# The expression r / b > 0.5 is equivalent to 2 * r > b if b is
# positive , 2 * r < b if b negative .
r *= 2
greater_than_half = r > b if... |
def bezier2polynomial ( p , numpy_ordering = True , return_poly1d = False ) :
"""Converts a tuple of Bezier control points to a tuple of coefficients
of the expanded polynomial .
return _ poly1d : returns a numpy . poly1d object . This makes computations
of derivatives / anti - derivatives and many other oper... | if len ( p ) == 4 :
coeffs = ( - p [ 0 ] + 3 * ( p [ 1 ] - p [ 2 ] ) + p [ 3 ] , 3 * ( p [ 0 ] - 2 * p [ 1 ] + p [ 2 ] ) , 3 * ( p [ 1 ] - p [ 0 ] ) , p [ 0 ] )
elif len ( p ) == 3 :
coeffs = ( p [ 0 ] - 2 * p [ 1 ] + p [ 2 ] , 2 * ( p [ 1 ] - p [ 0 ] ) , p [ 0 ] )
elif len ( p ) == 2 :
coeffs = ( p [ 1 ] -... |
def shelld ( ndim , array ) : # Works ! , use this as example for " I / O " parameters
"""Sort a double precision array using the Shell Sort algorithm .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / shelld _ c . html
: param ndim : Dimension of the array .
: type ndim : int
... | array = stypes . toDoubleVector ( array )
ndim = ctypes . c_int ( ndim )
libspice . shelld_c ( ndim , ctypes . cast ( array , ctypes . POINTER ( ctypes . c_double ) ) )
return stypes . cVectorToPython ( array ) |
def hide_stevedore_logs ( ) :
"""Hides the logs of stevedore , this function was
added in order to support older versions of stevedore
We are using the NullHandler in order to get rid from
' No handlers could be found for logger . . . ' msg
Returns :
None""" | stevedore_logger = logging . getLogger ( 'stevedore.extension' )
stevedore_logger . propagate = False
stevedore_logger . setLevel ( logging . ERROR )
stevedore_logger . addHandler ( logging . NullHandler ( ) ) |
def get_brightness ( self ) :
"""Get current brightness .""" | self . get_status ( )
try :
self . brightness = self . data [ 'color' ] . split ( ';' ) [ - 1 ]
except TypeError :
self . brightness = 0
return self . brightness |
def route_not_found ( * args ) :
"""Constructs a Flask Response for when a API Route ( path + method ) is not found . This is usually
HTTP 404 but with API Gateway this is a HTTP 403 ( https : / / forums . aws . amazon . com / thread . jspa ? threadID = 2166840)
: return : a Flask Response""" | response_data = jsonify ( ServiceErrorResponses . _MISSING_AUTHENTICATION )
return make_response ( response_data , ServiceErrorResponses . HTTP_STATUS_CODE_403 ) |
def load_model ( self , model ) :
'''load _ model
High - level api : Load schema information by compiling the model using
pyang package .
Parameters
model : ` str `
Model name .
Returns
Model
An instance of Model .
YAML Example : :
devices :
asr22:
type : ' ASR '
tacacs :
login _ prompt ... | if os . path . isfile ( model ) :
file_name , file_ext = os . path . splitext ( model )
if file_ext . lower ( ) == '.xml' :
logger . debug ( 'Read model file {}' . format ( model ) )
with open ( model , 'r' ) as f :
xml = f . read ( )
parser = etree . XMLParser ( remove_blank... |
def _transform_snapshot ( raw_snapshot : Dict [ Any , Any ] ) -> str :
"""This migration upgrades the object :
- ` MediatorTransferState ` such that a list of routes is added
to the state to be able to route a waiting transfer in case the
receiving node comes back online .""" | snapshot = json . loads ( raw_snapshot )
secrethash_to_task = snapshot [ 'payment_mapping' ] [ 'secrethashes_to_task' ]
for task in secrethash_to_task . values ( ) :
if task [ '_type' ] != 'raiden.transfer.state.MediatorTask' :
continue
mediator_state = task . get ( 'mediator_state' )
# Make sure th... |
def update_folder_name ( self , name ) :
"""Change this folder name
: param str name : new name to change to
: return : Updated or Not
: rtype : bool""" | if self . root :
return False
if not name :
return False
url = self . build_url ( self . _endpoints . get ( 'get_folder' ) . format ( id = self . folder_id ) )
response = self . con . patch ( url , data = { self . _cc ( 'displayName' ) : name } )
if not response :
return False
folder = response . json ( )
s... |
def cumulative_detections ( dates = None , template_names = None , detections = None , plot_grouped = False , group_name = None , rate = False , plot_legend = True , ax = None , ** kwargs ) :
"""Plot cumulative detections or detection rate in time .
Simple plotting function to take a list of either datetime objec... | import matplotlib . pyplot as plt
from eqcorrscan . core . match_filter import Detection
# Set up a default series of parameters for lines
colors = cycle ( [ 'red' , 'green' , 'blue' , 'cyan' , 'magenta' , 'yellow' , 'black' , 'firebrick' , 'purple' , 'darkgoldenrod' , 'gray' ] )
linestyles = cycle ( [ '-' , '-.' , '--... |
def print_todo ( self , p_todo ) :
"""Given a todo item , pretty print it .""" | todo_str = p_todo . source ( )
for ppf in self . filters :
todo_str = ppf . filter ( todo_str , p_todo )
return TopydoString ( todo_str ) |
def configure_basic_auth_decorator ( graph ) :
"""Configure a basic auth decorator .""" | # use the metadata name if no realm is defined
graph . config . setdefault ( "BASIC_AUTH_REALM" , graph . metadata . name )
return ConfigBasicAuth ( app = graph . flask , # wrap in dict to allow lists of items as well as dictionaries
credentials = dict ( graph . config . basic_auth . credentials ) , ) |
def get_process_curses_data ( self , p , first , args ) :
"""Get curses data to display for a process .
- p is the process to display
- first is a tag = True if the process is the first on the list""" | ret = [ self . curse_new_line ( ) ]
# CPU
if 'cpu_percent' in p and p [ 'cpu_percent' ] is not None and p [ 'cpu_percent' ] != '' :
if args . disable_irix and self . nb_log_core != 0 :
msg = self . layout_stat [ 'cpu' ] . format ( p [ 'cpu_percent' ] / float ( self . nb_log_core ) )
else :
msg =... |
def add_child_gradebook ( self , gradebook_id , child_id ) :
"""Adds a child to a gradebook .
arg : gradebook _ id ( osid . id . Id ) : the ` ` Id ` ` of a gradebook
arg : child _ id ( osid . id . Id ) : the ` ` Id ` ` of the new child
raise : AlreadyExists - ` ` gradebook _ id ` ` is already a parent of
` ... | # Implemented from template for
# osid . resource . BinHierarchyDesignSession . add _ child _ bin _ template
if self . _catalog_session is not None :
return self . _catalog_session . add_child_catalog ( catalog_id = gradebook_id , child_id = child_id )
return self . _hierarchy_session . add_child ( id_ = gradebook_... |
def define_from_values ( cls , xdtu , ydtu , zdtu , xdtu_0 , ydtu_0 , zdtu_0 ) :
"""Define class object from from provided values .
Parameters
xdtu : float
XDTU fits keyword value .
ydtu : float
YDTU fits keyword value .
zdtu : float
ZDTU fits keyword value .
xdtu _ 0 : float
XDTU _ 0 fits keyword... | self = DtuConfiguration ( )
# define DTU variables
self . xdtu = xdtu
self . ydtu = ydtu
self . zdtu = zdtu
self . xdtu_0 = xdtu_0
self . ydtu_0 = ydtu_0
self . zdtu_0 = zdtu_0
return self |
def connect ( self , host : str = '192.168.0.3' , port : Union [ int , str ] = 5555 ) -> None :
'''Connect to a device via TCP / IP directly .''' | self . device_sn = f'{host}:{port}'
if not is_connectable ( host , port ) :
raise ConnectionError ( f'Cannot connect to {self.device_sn}.' )
self . _execute ( 'connect' , self . device_sn ) |
def get ( key , default = - 1 ) :
"""Backport support for original codes .""" | if isinstance ( key , int ) :
return Packet ( key )
if key not in Packet . _member_map_ :
extend_enum ( Packet , key , default )
return Packet [ key ] |
def is_all_field_none ( self ) :
""": rtype : bool""" | if self . _status is not None :
return False
if self . _balance_preferred is not None :
return False
if self . _balance_threshold_high is not None :
return False
if self . _savings_account_alias is not None :
return False
return True |
def build_function ( name , args = None , defaults = None , doc = None ) :
"""create and initialize an astroid FunctionDef node""" | args , defaults = args or [ ] , defaults or [ ]
# first argument is now a list of decorators
func = nodes . FunctionDef ( name , doc )
func . args = argsnode = nodes . Arguments ( )
argsnode . args = [ ]
for arg in args :
argsnode . args . append ( nodes . Name ( ) )
argsnode . args [ - 1 ] . name = arg
arg... |
def set_sync_info ( self , name , mtime , size ) :
"""Store mtime / size when this resource was last synchronized with remote .""" | if not self . is_local ( ) :
return self . peer . set_sync_info ( name , mtime , size )
return self . cur_dir_meta . set_sync_info ( name , mtime , size ) |
def index_objects ( self , objects , index = "default" ) :
"""Bulk index a list of objects .""" | if not objects :
return
index_name = index
index = self . app_state . indexes [ index_name ]
indexed = set ( )
with index . writer ( ) as writer :
for obj in objects :
document = self . get_document ( obj )
if document is None :
continue
object_key = document [ "object_key" ]... |
def upgrade ( ) :
"""Upgrade database .""" | op . create_table ( 'access_actionsroles' , sa . Column ( 'id' , sa . Integer ( ) , nullable = False ) , sa . Column ( 'action' , sa . String ( length = 80 ) , nullable = True ) , sa . Column ( 'exclude' , sa . Boolean ( name = 'exclude' ) , server_default = '0' , nullable = False ) , sa . Column ( 'argument' , sa . St... |
def shuffle ( self ) :
"""Shuffle the deque
Deques themselves do not support this , so this will make all items into
a list , shuffle that list , clear the deque , and then re - init the deque .""" | args = list ( self )
random . shuffle ( args )
self . clear ( )
super ( DogeDeque , self ) . __init__ ( args ) |
def prepare_attached ( self , action , a_name , ** kwargs ) :
"""Prepares an attached volume for a container configuration .
: param action : Action configuration .
: type action : dockermap . map . runner . ActionConfig
: param a _ name : The full name or id of the container sharing the volume .
: type a _... | client = action . client
config_id = action . config_id
policy = self . _policy
if action . container_map . use_attached_parent_name :
v_alias = '{0.config_name}.{0.instance_name}' . format ( config_id )
else :
v_alias = config_id . instance_name
user = policy . volume_users [ config_id . map_name ] [ v_alias ]... |
def _insertFont ( self , fontname , bfname , fontfile , fontbuffer , set_simple , idx , wmode , serif , encoding , ordering ) :
"""_ insertFont ( self , fontname , bfname , fontfile , fontbuffer , set _ simple , idx , wmode , serif , encoding , ordering ) - > PyObject *""" | return _fitz . Page__insertFont ( self , fontname , bfname , fontfile , fontbuffer , set_simple , idx , wmode , serif , encoding , ordering ) |
def readconf ( conffile , section_name = None , log_name = None , defaults = None , raw = False ) :
"""Read config file and return config items as a dict
: param conffile : path to config file , or a file - like object ( hasattr
readline )
: param section _ name : config section to read ( will return all sect... | if defaults is None :
defaults = { }
if raw :
c = RawConfigParser ( defaults )
else :
c = ConfigParser ( defaults )
if hasattr ( conffile , 'readline' ) :
c . readfp ( conffile )
else :
if not c . read ( conffile ) :
print ( "Unable to read config file %s" ) % conffile
sys . exit ( 1... |
def updatePollVote ( self , poll_id , option_ids = [ ] , new_options = [ ] ) :
"""Updates a poll vote
: param poll _ id : ID of the poll to update vote
: param option _ ids : List of the option IDs to vote
: param new _ options : List of the new option names
: param thread _ id : User / Group ID to change s... | data = { "question_id" : poll_id }
for i , option_id in enumerate ( option_ids ) :
data [ "selected_options[{}]" . format ( i ) ] = option_id
for i , option_text in enumerate ( new_options ) :
data [ "new_options[{}]" . format ( i ) ] = option_text
j = self . _post ( self . req_url . UPDATE_VOTE , data , fix_re... |
def flip ( f ) :
"""Calls the function f by flipping the first two positional
arguments""" | def wrapped ( * args , ** kwargs ) :
return f ( * flip_first_two ( args ) , ** kwargs )
f_spec = make_func_curry_spec ( f )
return curry_by_spec ( f_spec , wrapped ) |
def create_json ( self , create_missing = None ) :
"""Create an entity .
Call : meth : ` create _ raw ` . Check the response status code , decode JSON
and return the decoded JSON as a dict .
: return : A dict . The server ' s response , with all JSON decoded .
: raises : ` ` requests . exceptions . HTTPErro... | response = self . create_raw ( create_missing )
response . raise_for_status ( )
return response . json ( ) |
def bind ( self , func : Callable [ [ Any ] , Maybe ] ) -> Maybe :
"""Just x > > = f = f x .""" | value = self . _value
return func ( value ) |
def parse ( self , data , extent , parent , desc_tag ) : # type : ( bytes , int , Optional [ UDFFileEntry ] , UDFTag ) - > None
'''Parse the passed in data into a UDF File Entry .
Parameters :
data - The data to parse .
extent - The extent that this descriptor currently lives at .
parent - The parent File E... | if self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'UDF File Entry already initialized' )
( tag_unused , icb_tag , self . uid , self . gid , self . perms , self . file_link_count , record_format , record_display_attrs , record_len , self . info_len , self . log_block_recorded , access_time , m... |
def load_json_file ( file , decoder = None ) :
"""Load data from json file
: param file : Readable object or path to file
: type file : FileIO | str
: param decoder : Use custom json decoder
: type decoder : T < = DateTimeDecoder
: return : Json data
: rtype : None | int | float | str | list | dict""" | if decoder is None :
decoder = DateTimeDecoder
if not hasattr ( file , "read" ) :
with io . open ( file , "r" , encoding = "utf-8" ) as f :
return json . load ( f , object_hook = decoder . decode )
return json . load ( file , object_hook = decoder . decode ) |
def name ( self ) :
"""Return the name of the sensor .""" | with self . _bt_interface . connect ( self . _mac ) as connection :
name = connection . read_handle ( _HANDLE_READ_NAME )
# pylint : disable = no - member
if not name :
raise BluetoothBackendException ( "Could not read NAME using handle %s" " from Mi Temp sensor %s" % ( hex ( _HANDLE_READ_NAME ) , self . _mac )... |
def write_frame ( self ) :
"""Writes a single frame to the movie file""" | if not hasattr ( self , 'mwriter' ) :
raise AssertionError ( 'This plotter has not opened a movie or GIF file.' )
self . mwriter . append_data ( self . image ) |
def preferred_height ( self , cli , width , max_available_height , wrap_lines ) :
"""Preferred height : as much as needed in order to display all the completions .""" | complete_state = cli . current_buffer . complete_state
column_width = self . _get_column_width ( complete_state )
column_count = max ( 1 , ( width - self . _required_margin ) // column_width )
return int ( math . ceil ( len ( complete_state . current_completions ) / float ( column_count ) ) ) |
def parse_cmdline ( argv = None ) :
"""Parse command line options .
@ param argv : List of command line arguments . If None , get list from system .
@ return : Tuple of Option List and Argument List .""" | parser = optparse . OptionParser ( )
parser . add_option ( '-c' , '--conf' , help = 'Configuration file path.' , dest = 'confpath' , default = None )
parser . add_option ( '-p' , '--bindport' , help = 'Bind to TCP Port. (Default: %d)' % conf [ 'bindport' ] , dest = 'bindport' , type = 'int' , default = None , action = ... |
def get_output_column_widths ( table , spans ) :
"""Gets the widths of the columns of the output table
Parameters
table : list of lists of str
The table of rows of text
spans : list of lists of int
The [ row , column ] pairs of combined cells
Returns
widths : list of int
The widths of each column in... | widths = [ ]
for column in table [ 0 ] :
widths . append ( 3 )
for row in range ( len ( table ) ) :
for column in range ( len ( table [ row ] ) ) :
span = get_span ( spans , row , column )
column_count = get_span_column_count ( span )
if column_count == 1 :
text_row = span [ ... |
def unlock_kinetis_swd ( jlink ) :
"""Unlocks a Kinetis device over SWD .
Steps Involved in Unlocking :
1 . Verify that the device is configured to read / write from the CoreSight
registers ; this is done by reading the Identification Code Register
and checking its validity . This register is always at 0x0 ... | SWDIdentity = Identity ( 0x2 , 0xBA01 )
jlink . power_on ( )
jlink . coresight_configure ( )
# 1 . Verify that the device is configured properly .
flags = registers . IDCodeRegisterFlags ( )
flags . value = jlink . coresight_read ( 0x0 , False )
if not unlock_kinetis_identified ( SWDIdentity , flags ) :
return Fals... |
def _fix_install_dir_for_user_site ( self ) :
"""Fix the install _ dir if " - - user " was used .""" | if not self . user or not site . ENABLE_USER_SITE :
return
self . create_home_path ( )
if self . install_userbase is None :
msg = "User base directory is not specified"
raise DistutilsPlatformError ( msg )
self . install_base = self . install_platbase = self . install_userbase
scheme_name = os . name . repl... |
def Guo_Sun ( dp , voidage , vs , rho , mu , Dt , L = 1 ) :
r'''Calculates pressure drop across a packed bed of spheres using a
correlation developed in [ 1 ] _ . This is valid for highly - packed particles
at particle / tube diameter ratios between 2 and 3 , where a ring packing
structure occurs . If a packi... | # 2 < D / d < 3 , particles in contact with the wall tend to form a highly ordered ring structure .
Rem = dp * rho * vs / mu / ( 1 - voidage )
fv = 180 + ( 9.5374 * dp / Dt - 2.8054 ) * Rem ** 0.97
return fv * ( mu * vs * L / dp ** 2 ) * ( 1 - voidage ) ** 2 / voidage ** 3 |
def setActiveWindow ( self , win ) :
"""Set the given window active ( property _ NET _ ACTIVE _ WINDOW )
: param win : the window object""" | self . _setProperty ( '_NET_ACTIVE_WINDOW' , [ 1 , X . CurrentTime , win . id ] , win ) |
def roundedSpecClass ( self ) :
"""Spectral class with rounded class number ie A8.5V is A9""" | try :
classnumber = str ( int ( np . around ( self . classNumber ) ) )
except TypeError :
classnumber = str ( self . classNumber )
return self . classLetter + classnumber |
def _set_cursor_position ( self , value ) :
"""Set cursor position . Return whether it changed .""" | original_position = self . __cursor_position
self . __cursor_position = max ( 0 , value )
return value != original_position |
def _get_cells_headers_ids ( self , hed , index ) :
"""Returns a list with ids of rows of same column .
: param hed : The list that represents the table header .
: type hed : list ( list ( hatemile . util . html . htmldomelement . HTMLDOMElement ) )
: param index : The index of columns .
: type index : int ... | # pylint : disable = no - self - use
ids = [ ]
for row in hed :
if row [ index ] . get_tag_name ( ) == 'TH' :
ids . append ( row [ index ] . get_attribute ( 'id' ) )
return ids |
def assignOrderNames ( self ) :
"""Assigns the order names for this tree based on the name of the
columns .""" | try :
schema = self . tableType ( ) . schema ( )
except AttributeError :
return
for colname in self . columns ( ) :
column = schema . column ( colname )
if column :
self . setColumnOrderName ( colname , column . name ( ) ) |
def makeGlu ( segID , N , CA , C , O , geo ) :
'''Creates a Glutamic Acid residue''' | # # R - Group
CA_CB_length = geo . CA_CB_length
C_CA_CB_angle = geo . C_CA_CB_angle
N_C_CA_CB_diangle = geo . N_C_CA_CB_diangle
CB_CG_length = geo . CB_CG_length
CA_CB_CG_angle = geo . CA_CB_CG_angle
N_CA_CB_CG_diangle = geo . N_CA_CB_CG_diangle
CG_CD_length = geo . CG_CD_length
CB_CG_CD_angle = geo . CB_CG_CD_angle
CA... |
def _select_batched ( self , table , cols , num_rows , limit , queries_per_batch = 3 , execute = True ) :
"""Run select queries in small batches and return joined resutls .""" | # Execute select queries in small batches to avoid connection timeout
commands , offset = [ ] , 0
while num_rows > 0 : # Use number of rows as limit if num _ rows < limit
_limit = min ( limit , num_rows )
# Execute select _ limit query
commands . append ( self . _select_limit_statement ( table , cols = cols... |
def _build_date_header_string ( self , date_value ) :
"""Gets the date _ value ( may be None , basestring , float or
datetime . datetime instance ) and returns a valid date string as per
RFC 2822.""" | if isinstance ( date_value , datetime ) :
date_value = time . mktime ( date_value . timetuple ( ) )
if not isinstance ( date_value , basestring ) :
date_value = formatdate ( date_value , localtime = True )
# Encode it here to avoid this :
# Date : = ? utf - 8 ? q ? Sat = 2C _ 01 _ Sep _ 2012_13 = 3A08 = 3A29 _ ... |
def _get_step ( self , name , make_copy = True ) :
"""Return step from steps library .
Optionally , the step returned is a deep copy from the step in the steps
library , so additional information ( e . g . , about whether the step was
scattered ) can be stored in the copy .
Args :
name ( str ) : name of t... | self . _closed ( )
s = self . steps_library . get_step ( name )
if s is None :
msg = '"{}" not found in steps library. Please check your ' 'spelling or load additional steps'
raise ValueError ( msg . format ( name ) )
if make_copy :
s = copy . deepcopy ( s )
return s |
def scopeMatch ( assumedScopes , requiredScopeSets ) :
"""Take a list of a assumed scopes , and a list of required scope sets on
disjunctive normal form , and check if any of the required scope sets are
satisfied .
Example :
requiredScopeSets = [
[ " scopeA " , " scopeB " ] ,
[ " scopeC " ]
In this ca... | for scopeSet in requiredScopeSets :
for requiredScope in scopeSet :
for scope in assumedScopes :
if scope == requiredScope : # requiredScope satisifed , no need to check more scopes
break
if scope . endswith ( "*" ) and requiredScope . startswith ( scope [ : - 1 ] ) :... |
def send ( self , request ) :
"""Queue a request to be sent to the RPC .""" | if self . _UNARY_REQUESTS :
try :
self . _send_unary_request ( request )
except exceptions . GoogleAPICallError :
_LOGGER . debug ( "Exception while sending unary RPC. This is typically " "non-fatal as stream requests are best-effort." , exc_info = True , )
else :
self . _rpc . send ( reques... |
def _await_socket ( self , timeout ) :
"""Blocks for the nailgun subprocess to bind and emit a listening port in the nailgun stdout .""" | with safe_open ( self . _ng_stdout , 'r' ) as ng_stdout :
start_time = time . time ( )
accumulated_stdout = ''
while 1 : # TODO : share the decreasing timeout logic here with NailgunProtocol . iter _ chunks ( ) by adding
# a method to pants . util . contextutil !
remaining_time = time . time ( )... |
def job_exists ( self , prov ) :
"""Check if a job exists in the database .""" | with self . lock :
self . cur . execute ( 'select * from "jobs" where "prov" = ?;' , ( prov , ) )
rec = self . cur . fetchone ( )
return rec is not None |
def _greater_warnings_context ( context_lines_string ) :
"""Provide the ` line ` argument to warnings . showwarning ( ) .
warnings . warn _ explicit ( ) doesn ' t use the ` line ` argument to showwarning ( ) , but we want to
make use of the warning filtering provided by warn _ explicit ( ) . This contextmanager... | prev_showwarning = warnings . showwarning
def wrapped ( message , category , filename , lineno , file = None , line = None ) :
return prev_showwarning ( message = message , category = category , filename = filename , lineno = lineno , file = file , line = ( line or context_lines_string ) )
warnings . showwarning = ... |
def patch_dataset ( self , owner , id , body , ** kwargs ) :
"""Update a dataset
Update an existing dataset . Note that only elements or files included in the request will be updated . All omitted elements or files will remain untouched .
This method makes a synchronous HTTP request by default . To make an
as... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . patch_dataset_with_http_info ( owner , id , body , ** kwargs )
else :
( data ) = self . patch_dataset_with_http_info ( owner , id , body , ** kwargs )
return data |
def persist ( name , value , config = None ) :
'''Assign and persist a simple sysctl parameter for this minion . If ` ` config ` `
is not specified , a sensible default will be chosen using
: mod : ` sysctl . default _ config < salt . modules . linux _ sysctl . default _ config > ` .
CLI Example :
. . code ... | if config is None :
config = default_config ( )
edited = False
# If the sysctl . conf is not present , add it
if not os . path . isfile ( config ) :
sysctl_dir = os . path . dirname ( config )
if not os . path . exists ( sysctl_dir ) :
os . makedirs ( sysctl_dir )
try :
with salt . utils... |
async def setup ( self ) :
"""Set up the connection with automatic retry .""" | while True :
fut = self . loop . create_connection ( lambda : SW16Protocol ( self , disconnect_callback = self . handle_disconnect_callback , loop = self . loop , logger = self . logger ) , host = self . host , port = self . port )
try :
self . transport , self . protocol = await asyncio . wait_for ( fu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.