signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def inspect_edge ( G : AnalysisGraph , source : str , target : str ) :
"""' Drill down ' into an edge in the analysis graph and inspect its
provenance . This function prints the provenance .
Args :
source
target""" | return create_statement_inspection_table ( G [ source ] [ target ] [ "InfluenceStatements" ] ) |
async def cancellable_wait ( self , * awaitables : Awaitable [ _R ] , timeout : float = None ) -> _R :
"""Wait for the first awaitable to complete , unless we timeout or the
token is triggered .
Returns the result of the first awaitable to complete .
Raises TimeoutError if we timeout or
` ~ cancel _ token .... | futures = [ asyncio . ensure_future ( a , loop = self . loop ) for a in awaitables + ( self . wait ( ) , ) ]
try :
done , pending = await asyncio . wait ( futures , timeout = timeout , return_when = asyncio . FIRST_COMPLETED , loop = self . loop , )
except asyncio . futures . CancelledError : # Since we use return ... |
def on_parent_exit ( signame ) :
"""Return a function to be run in a child process which will trigger SIGNAME
to be sent when the parent process dies""" | signum = getattr ( signal , signame )
def set_parent_exit_signal ( ) : # http : / / linux . die . net / man / 2 / prctl
result = cdll [ 'libc.so.6' ] . prctl ( PR_SET_PDEATHSIG , signum )
if result != 0 :
raise PrCtlError ( 'prctl failed with error code %s' % result )
return set_parent_exit_signal |
def run_workload ( database , keys , parameters ) :
"""Runs workload against the database .""" | total_weight = 0.0
weights = [ ]
operations = [ ]
latencies_ms = { }
for operation in OPERATIONS :
weight = float ( parameters [ operation ] )
if weight <= 0.0 :
continue
total_weight += weight
op_code = operation . split ( 'proportion' ) [ 0 ]
operations . append ( op_code )
weights . a... |
def a ( self , ** kwargs ) :
'''Returns the lattice parameter , a , in Angstroms at a given
temperature , ` T ` , in Kelvin ( default : 300 K ) .''' | T = kwargs . get ( 'T' , 300. )
return ( self . a_300K ( ** kwargs ) + self . thermal_expansion ( ** kwargs ) * ( T - 300. ) ) |
def files_info ( self , area_uuid , file_list ) :
"""Get information about files
: param str area _ uuid : A RFC4122 - compliant ID for the upload area
: param list file _ list : The names the files in the Upload Area about which we want information
: return : an array of file information dicts
: rtype : li... | path = "/area/{uuid}/files_info" . format ( uuid = area_uuid )
file_list = [ urlparse . quote ( filename ) for filename in file_list ]
response = self . _make_request ( 'put' , path = path , json = file_list )
return response . json ( ) |
def unlock ( self , session ) :
"""Relinquishes a lock for the specified resource .
Corresponds to viUnlock function of the VISA library .
: param session : Unique logical identifier to a session .
: return : return value of the library call .
: rtype : : class : ` pyvisa . constants . StatusCode `""" | try :
sess = self . sessions [ session ]
except KeyError :
return StatusCode . error_invalid_object
return sess . unlock ( ) |
def haversine ( px , py , r = r_mm ) :
'''Calculate the haversine distance between two points
defined by ( lat , lon ) tuples .
Args :
px ( ( float , float ) ) : lat / long position 1
py ( ( float , float ) ) : lat / long position 2
r ( float ) : Radius of sphere
Returns :
( int ) : Distance in mm .''... | lat1 , lon1 = px
lat2 , lon2 = py
dlat = math . radians ( lat2 - lat1 )
dlon = math . radians ( lon2 - lon1 )
lat1 = math . radians ( lat1 )
lat2 = math . radians ( lat2 )
a = math . sin ( dlat / 2 ) ** 2 + math . cos ( lat1 ) * math . cos ( lat2 ) * math . sin ( dlon / 2 ) ** 2
c = 2 * math . asin ( math . sqrt ( a ) ... |
def get_results ( self , ** kwargs ) :
"""Returns : class : ` NodeResults ` instance .
Subclasses should extend this method ( if needed ) by adding
specialized code that performs some kind of post - processing .""" | # Check whether the process completed .
if self . returncode is None :
raise self . Error ( "return code is None, you should call wait, communicate or poll" )
if self . status is None or self . status < self . S_DONE :
raise self . Error ( "Task is not completed" )
return self . Results . from_node ( self ) |
def get_authorize_url ( self , ** params ) :
'''Returns a formatted authorize URL .
: param \ * \ * params : Additional keyworded arguments to be added to the
request querystring .
: type \ * \ * params : dict''' | params = self . session_obj . sign ( self . authorize_url , self . app_id , self . app_secret , ** params )
return self . authorize_url + '?' + params |
def alterar ( self , id_tipo_acesso , protocolo ) :
"""Edit access type by its identifier .
: param id _ tipo _ acesso : Access type identifier .
: param protocolo : Protocol .
: return : None
: raise ProtocoloTipoAcessoDuplicadoError : Protocol already exists .
: raise InvalidParameterError : Protocol va... | if not is_valid_int_param ( id_tipo_acesso ) :
raise InvalidParameterError ( u'Access type id is invalid or was not informed.' )
tipo_acesso_map = dict ( )
tipo_acesso_map [ 'protocolo' ] = protocolo
url = 'tipoacesso/' + str ( id_tipo_acesso ) + '/'
code , xml = self . submit ( { 'tipo_acesso' : tipo_acesso_map } ... |
def drp_load ( package , resource , confclass = None ) :
"""Load the DRPS from a resource file .""" | data = pkgutil . get_data ( package , resource )
return drp_load_data ( package , data , confclass = confclass ) |
def block_splitter ( self , sources , weight = get_weight , key = lambda src : 1 ) :
""": param sources : a list of sources
: param weight : a weight function ( default . weight )
: param key : None or ' src _ group _ id '
: returns : an iterator over blocks of sources""" | ct = self . oqparam . concurrent_tasks or 1
maxweight = self . csm . get_maxweight ( weight , ct , source . MINWEIGHT )
if not hasattr ( self , 'logged' ) :
if maxweight == source . MINWEIGHT :
logging . info ( 'Using minweight=%d' , source . MINWEIGHT )
else :
logging . info ( 'Using maxweight=... |
def maximum_weighted_independent_set_qubo ( G , weight = None , lagrange = 2.0 ) :
"""Return the QUBO with ground states corresponding to a maximum weighted independent set .
Parameters
G : NetworkX graph
weight : string , optional ( default None )
If None , every node has equal weight . If a string , use t... | # empty QUBO for an empty graph
if not G :
return { }
# We assume that the sampler can handle an unstructured QUBO problem , so let ' s set one up .
# Let us define the largest independent set to be S .
# For each node n in the graph , we assign a boolean variable v _ n , where v _ n = 1 when n
# is in S and v _ n ... |
def _merge_wf_outputs ( new , cur , parallel ) :
"""Merge outputs for a sub - workflow , replacing variables changed in later steps .
ignore _ ids are those used internally in a sub - workflow but not exposed to subsequent steps""" | new_ids = set ( [ ] )
out = [ ]
for v in new :
outv = { }
outv [ "source" ] = v [ "id" ]
outv [ "id" ] = "%s" % get_base_id ( v [ "id" ] )
outv [ "type" ] = v [ "type" ]
if "secondaryFiles" in v :
outv [ "secondaryFiles" ] = v [ "secondaryFiles" ]
if tz . get_in ( [ "outputBinding" , "se... |
def as_svg_data_uri ( matrix , version , scale = 1 , border = None , color = '#000' , background = None , xmldecl = False , svgns = True , title = None , desc = None , svgid = None , svgclass = 'segno' , lineclass = 'qrline' , omitsize = False , unit = '' , encoding = 'utf-8' , svgversion = None , nl = False , encode_m... | encode = partial ( quote , safe = b"" ) if not encode_minimal else partial ( quote , safe = b" :/='" )
buff = io . BytesIO ( )
write_svg ( matrix , version , buff , scale = scale , color = color , background = background , border = border , xmldecl = xmldecl , svgns = svgns , title = title , desc = desc , svgclass = sv... |
def to_text_format ( self ) :
'''Format as detached DNS information as text .''' | return '\n' . join ( itertools . chain ( ( self . fetch_date . strftime ( '%Y%m%d%H%M%S' ) , ) , ( rr . to_text ( ) for rr in self . resource_records ) , ( ) , ) ) |
def load_factory ( name , directory , configuration = None ) :
"""Load a factory and have it initialize in a particular directory
: param name : the name of the plugin to load
: param directory : the directory where the factory will reside
: return :""" | for entry_point in pkg_resources . iter_entry_points ( ENTRY_POINT ) :
if entry_point . name == name :
factory_class = entry_point . load ( require = False )
return factory_class ( directory , configuration )
raise KeyError |
def convert_md_to_rst ( md_path , rst_temp_path ) :
"""Convert the contents of a file from Markdown to reStructuredText .
Returns the converted text as a Unicode string .
Arguments :
md _ path : a path to a UTF - 8 encoded Markdown file to convert .
rst _ temp _ path : a temporary path to which to write the... | # Pandoc uses the UTF - 8 character encoding for both input and output .
command = "pandoc --write=rst --output=%s %s" % ( rst_temp_path , md_path )
print ( "converting with pandoc: %s to %s\n-->%s" % ( md_path , rst_temp_path , command ) )
if os . path . exists ( rst_temp_path ) :
os . remove ( rst_temp_path )
os ... |
def clearcal ( vis , weightonly = False ) :
"""Fill the imaging and calibration columns ( ` ` MODEL _ DATA ` ` ,
` ` CORRECTED _ DATA ` ` , ` ` IMAGING _ WEIGHT ` ` ) of each measurement set with
default values , creating the columns if necessary .
vis ( string )
Path to the input measurement set
weighton... | tb = util . tools . table ( )
cb = util . tools . calibrater ( )
# cb . open ( ) will create the tables if they ' re not present , so
# if that ' s the case , we don ' t actually need to run initcalset ( )
tb . open ( b ( vis ) , nomodify = False )
colnames = tb . colnames ( )
needinit = ( 'MODEL_DATA' in colnames ) or... |
def refresh_frozen_cell ( self , key ) :
"""Refreshes a frozen cell""" | code = self . grid . code_array ( key )
result = self . grid . code_array . _eval_cell ( key , code )
self . grid . code_array . frozen_cache [ repr ( key ) ] = result |
def apply_path ( self , repo ) :
"""Set path to where the repo is and return original path""" | try : # rewrite repo for consistency
if repo . endswith ( '.git' ) :
repo = repo . split ( '.git' ) [ 0 ]
# get org and repo name and path repo will be cloned to
org , name = repo . split ( '/' ) [ - 2 : ]
path = join ( self . plugins_dir , org , name )
# save current path
cwd = getcwd (... |
def drop_constraints ( quiet = True , stdout = None ) :
"""Discover and drop all constraints .
: type : bool
: return : None""" | results , meta = db . cypher_query ( "CALL db.constraints()" )
pattern = re . compile ( ':(.*) \).*\.(\w*)' )
for constraint in results :
db . cypher_query ( 'DROP ' + constraint [ 0 ] )
match = pattern . search ( constraint [ 0 ] )
stdout . write ( ''' - Droping unique constraint and index on label {0} wit... |
def relabeled ( self , label , new_label ) :
"""Return a new table with ` ` label ` ` specifying column label ( s )
replaced by corresponding ` ` new _ label ` ` .
Args :
` ` label ` ` - - ( str or array of str ) The label ( s ) of
columns to be changed .
` ` new _ label ` ` - - ( str or array of str ) : ... | copy = self . copy ( )
copy . relabel ( label , new_label )
return copy |
def replace_vertex_references ( self , mask ) :
"""Replace the vertex index references in every entity .
Parameters
mask : ( len ( self . vertices ) , ) int
Contains new vertex indexes
Alters
entity . points in self . entities
Replaced by mask [ entity . points ]""" | for entity in self . entities :
entity . points = mask [ entity . points ] |
def generate_files ( path = '' , ext = '' , level = None , dirs = False , files = True , verbosity = 0 ) :
"""Recursively generate files ( and thier stats ) in the indicated directory
Filter by the indicated file name extension ( ext )
Args :
path ( str ) : Root / base path to search .
ext ( str ) : File na... | path = path or './'
ext = str ( ext ) . lower ( )
for dir_path , dir_names , filenames in walk_level ( path , level = level ) :
if verbosity > 0 :
print ( 'Checking path "{}"' . format ( dir_path ) )
if files :
for fn in filenames : # itertools . chain ( filenames , dir _ names )
if ... |
def _callable_func ( self , func , axis , * args , ** kwargs ) :
"""Apply callable functions across given axis .
Args :
func : The functions to apply .
axis : Target axis to apply the function along .
Returns :
A new PandasQueryCompiler .""" | def callable_apply_builder ( df , axis = 0 ) :
if not axis :
df . index = index
df . columns = pandas . RangeIndex ( len ( df . columns ) )
else :
df . columns = index
df . index = pandas . RangeIndex ( len ( df . index ) )
result = df . apply ( func , axis = axis , * args , ... |
def vagalume ( song ) :
"""Returns the lyrics found in vagalume . com . br for the specified mp3 file or
an empty string if not found .""" | translate = { '@' : 'a' , URLESCAPE : '' , ' ' : '-' }
artist = song . artist . lower ( )
artist = normalize ( artist , translate )
artist = re . sub ( r'\-{2,}' , '-' , artist )
title = song . title . lower ( )
title = normalize ( title , translate )
title = re . sub ( r'\-{2,}' , '-' , title )
url = 'https://www.vaga... |
def packages ( self ) :
"""Property for accessing : class : ` PackageManager ` instance , which is used to manage packages .
: rtype : yagocd . resources . package . PackageManager""" | if self . _package_manager is None :
self . _package_manager = PackageManager ( session = self . _session )
return self . _package_manager |
def with_extrapolation ( points , noise , n_points ) :
"""Smooths a set of points , but it extrapolates some points at the beginning
Args :
points ( : obj : ` list ` of : obj : ` Point ` )
noise ( float ) : Expected noise , the higher it is the more the path will
be smoothed .
Returns :
: obj : ` list `... | n_points = 10
return kalman_filter ( extrapolate_points ( points , n_points ) + points , noise ) [ n_points : ] |
def load_data ( cr , module_name , filename , idref = None , mode = 'init' ) :
"""Load an xml , csv or yml data file from your post script . The usual case for
this is the
occurrence of newly added essential or useful data in the module that is
marked with " noupdate = ' 1 ' " and without " forcecreate = ' 1 ... | if idref is None :
idref = { }
logger . info ( '%s: loading %s' % ( module_name , filename ) )
_ , ext = os . path . splitext ( filename )
pathname = os . path . join ( module_name , filename )
fp = tools . file_open ( pathname )
try :
if ext == '.csv' :
noupdate = True
tools . convert_csv_impor... |
def get_sticky ( self , subreddit , bottom = False ) :
"""Return a Submission object for the sticky of the subreddit .
: param bottom : Get the top or bottom sticky . If the subreddit has only
a single sticky , it is considered the top one .""" | url = self . config [ 'sticky' ] . format ( subreddit = six . text_type ( subreddit ) )
param = { 'num' : 2 } if bottom else None
return objects . Submission . from_json ( self . request_json ( url , params = param ) ) |
def remove_parenthesis_around_tz ( cls , timestr ) :
"""get rid of parenthesis around timezone : ( GMT ) = > GMT
: return : the new string if parenthesis were found , ` None ` otherwise""" | parenthesis = cls . TIMEZONE_PARENTHESIS . match ( timestr )
if parenthesis is not None :
return parenthesis . group ( 1 ) |
def _dspace ( irez , d2201 , d2211 , d3210 , d3222 , d4410 , d4422 , d5220 , d5232 , d5421 , d5433 , dedt , del1 , del2 , del3 , didt , dmdt , dnodt , domdt , argpo , argpdot , t , tc , gsto , xfact , xlamo , no , atime , em , argpm , inclm , xli , mm , xni , nodem , nm , ) :
fasx2 = 0.13130908 ;
fasx4 = 2.8843... | ft = 0.0 ;
if irez != 0 : # sgp4fix streamline check
if atime == 0.0 or t * atime <= 0.0 or fabs ( t ) < fabs ( atime ) :
atime = 0.0 ;
xni = no ;
xli = xlamo ;
# sgp4fix move check outside loop
if t > 0.0 :
delt = stepp ;
else :
delt = stepn ;
iretn = 381 ;
... |
def zincrby ( self , name , value , amount = 1 ) :
"""Increment the score of the item by ` value `
: param name : str the name of the redis key
: param value :
: param amount :
: return :""" | with self . pipe as pipe :
return pipe . zincrby ( self . redis_key ( name ) , value = self . valueparse . encode ( value ) , amount = amount ) |
def typed_encode ( value , sub_schema , path , net_new_properties , buffer ) :
""": param value : THE DATA STRUCTURE TO ENCODE
: param sub _ schema : dict FROM PATH TO Column DESCRIBING THE TYPE
: param path : list OF CURRENT PATH
: param net _ new _ properties : list FOR ADDING NEW PROPERTIES NOT FOUND IN su... | try : # from jx _ base import Column
if sub_schema . __class__ . __name__ == 'Column' :
value_json_type = python_type_to_json_type [ value . __class__ ]
column_json_type = es_type_to_json_type [ sub_schema . es_type ]
if value_json_type == column_json_type :
pass
# ok... |
def space_events ( lon = None , lat = None , limit = None , date = None ) :
'''lat & lon expect decimal latitude and longitude values . ( Required )
elevation assumes meters . ( Optional )
limit assumes an integer . Default is 5 . ( Optional )
date expects an ISO 8601 formatted date . ( Optional )''' | base_url = 'http://api.predictthesky.org/?'
if not lon or not lat :
raise ValueError ( "space_events endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5" )
else :
try :
validate_float ( lon , lat )
# Floats are entered / displayed as de... |
def work ( ) :
"""Implement a worker for write - math . com .""" | global n
cmd = utils . get_project_configuration ( )
if 'worker_api_key' not in cmd :
return ( "You need to define a 'worker_api_key' in your ~/" )
chunk_size = 1000
logging . info ( "Start working with n=%i" , n )
for _ in range ( chunk_size ) : # contact the write - math server and get something to classify
u... |
def v_unique_name_defintions ( ctx , stmt ) :
"""Make sure that all top - level definitions in a module are unique""" | defs = [ ( 'typedef' , 'TYPE_ALREADY_DEFINED' , stmt . i_typedefs ) , ( 'grouping' , 'GROUPING_ALREADY_DEFINED' , stmt . i_groupings ) ]
def f ( s ) :
for ( keyword , errcode , dict ) in defs :
if s . keyword == keyword and s . arg in dict :
err_add ( ctx . errors , dict [ s . arg ] . pos , errc... |
def clear_caches ( self ) :
"""Clear the mice and repertoire caches .""" | self . _single_node_repertoire_cache . clear ( )
self . _repertoire_cache . clear ( )
self . _mice_cache . clear ( ) |
def inc_convert ( self , value ) :
"""Default converter for the inc : / / protocol .""" | if not os . path . isabs ( value ) :
value = os . path . join ( self . base , value )
with codecs . open ( value , 'r' , encoding = 'utf-8' ) as f :
result = json . load ( f )
return result |
def class_balance ( y_train , y_test = None , ax = None , labels = None , ** kwargs ) :
"""Quick method :
One of the biggest challenges for classification models is an imbalance of
classes in the training data . This function vizualizes the relationship of
the support for each class in both the training and t... | # Instantiate the visualizer
visualizer = ClassBalance ( ax = ax , labels = labels , ** kwargs )
# Fit and transform the visualizer ( calls draw )
visualizer . fit ( y_train , y_test )
visualizer . finalize ( )
# Return the axes object on the visualizer
return visualizer . ax |
def render ( genshi_data , saltenv = 'base' , sls = '' , method = 'xml' , ** kws ) :
'''Render a Genshi template . A method should be passed in as part of the
kwargs . If no method is passed in , xml is assumed . Valid methods are :
. . code - block :
- xml
- xhtml
- html
- text
- newtext
- oldtext ... | if not HAS_LIBS :
return { }
if not isinstance ( genshi_data , six . string_types ) :
genshi_data = genshi_data . read ( )
if genshi_data . startswith ( '#!' ) :
genshi_data = genshi_data [ ( genshi_data . find ( '\n' ) + 1 ) : ]
if not genshi_data . strip ( ) :
return { }
if method == 'text' or method ... |
def _calc_taub ( w , aod700 , p ) :
"""Calculate the taub coefficient""" | p0 = 101325.
tb1 = 1.82 + 0.056 * np . log ( w ) + 0.0071 * np . log ( w ) ** 2
tb0 = 0.33 + 0.045 * np . log ( w ) + 0.0096 * np . log ( w ) ** 2
tbp = 0.0089 * w + 0.13
taub = tb1 * aod700 + tb0 + tbp * np . log ( p / p0 )
return taub |
def checkArgs ( args ) :
"""Checks the arguments and options .
: param args : an object containing the options of the program .
: type args : argparse . Namespace
: returns : ` ` True ` ` if everything was OK .
If there is a problem with an option , an exception is raised using the
: py : class : ` Progra... | # Check the input files
if not args . is_bfile and not args . is_tfile and not args . is_file :
msg = "needs one input file type (--is-bfile, --is-tfile or --is-file)"
raise ProgramError ( msg )
if args . is_bfile and not args . is_tfile and not args . is_file :
for fileName in [ args . ifile + i for i in [... |
def filter_by_moys ( self , moys ) :
"""Filter the Data Collection based on a list of minutes of the year .
Args :
moys : A List of minutes of the year [ 0 . . 8759 * 60]
Return :
A new Data Collection with filtered data""" | t_s = 60 / self . header . analysis_period . timestep
st_ind = self . header . analysis_period . st_time . moy / t_s
if self . header . analysis_period . is_reversed is False :
_filt_indices = [ int ( moy / t_s - st_ind ) for moy in moys ]
else :
if self . header . analysis_period . is_leap_year is False :
... |
def search_data_std ( Channel , RunNos , RepeatNos , directoryPath = '.' ) :
"""Lets you find multiple datasets at once assuming they have a
filename which contains a pattern of the form :
CH < ChannelNo > _ RUN00 . . . < RunNo > _ REPEAT00 . . . < RepeatNo >
Parameters
Channel : int
The channel you want ... | files = glob ( '{}/*' . format ( directoryPath ) )
files_CorrectChannel = [ ]
for file_ in files :
if 'CH{}' . format ( Channel ) in file_ :
files_CorrectChannel . append ( file_ )
files_CorrectRunNo = [ ]
for RunNo in RunNos :
files_match = _fnmatch . filter ( files_CorrectChannel , '*RUN*0{}_*' . form... |
def rsky_lhood ( self , rsky , ** kwargs ) :
"""Evaluates Rsky likelihood at provided position ( s )
: param rsky :
position
: param * * kwargs :
Keyword arguments passed to : func : ` BinaryPopulation . rsky _ distribution `""" | dist = self . rsky_distribution ( ** kwargs )
return dist ( rsky ) |
def block ( self , tofile = "block.dat" ) :
'''获取证券板块信息
: param tofile :
: return : pd . dataFrame or None''' | with self . client . connect ( * self . bestip ) :
data = self . client . get_and_parse_block_info ( tofile )
return self . client . to_df ( data ) |
def get_value ( self , expression ) :
"""Return value of expression .""" | self . _check_valid ( )
return super ( Result , self ) . get_value ( expression ) |
def _get_restore_function ( self ) :
"""Return the binary function for restoring terminal attributes .
: return : function ( signal , frame ) = > None :""" | if os . name == 'nt' or not self . getch_enabled :
return lambda signal , frame : None
try :
fd = self . stdin . fileno ( )
initial = termios . tcgetattr ( fd )
except termios . error :
return lambda signal , frame : None
return lambda signal , frame : termios . tcsetattr ( fd , termios . TCSADRAIN , in... |
def check_password ( cls , instance , raw_password , enable_hash_migration = True ) :
"""checks string with users password hash using password manager
: param instance :
: param raw _ password :
: param enable _ hash _ migration : if legacy hashes should be migrated
: return :""" | verified , replacement_hash = instance . passwordmanager . verify_and_update ( raw_password , instance . user_password )
if enable_hash_migration and replacement_hash :
if six . PY2 :
instance . user_password = replacement_hash . decode ( "utf8" )
else :
instance . user_password = replacement_ha... |
def match ( self , package ) :
"""Match ` ` package ` ` with the requirement .
: param package : Package to test with the requirement .
: type package : package expression string or : class : ` Package `
: returns : ` ` True ` ` if ` ` package ` ` satisfies the requirement .
: rtype : bool""" | if isinstance ( package , basestring ) :
from . packages import Package
package = Package . parse ( package )
if self . name != package . name :
return False
if self . version_constraints and package . version not in self . version_constraints :
return False
if self . build_options :
if package . bu... |
def l2traceroute_input_protocolType_IP_l4protocol ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
l2traceroute = ET . Element ( "l2traceroute" )
config = l2traceroute
input = ET . SubElement ( l2traceroute , "input" )
protocolType = ET . SubElement ( input , "protocolType" )
IP = ET . SubElement ( protocolType , "IP" )
l4protocol = ET . SubElement ( IP , "l4protocol" )
l4protocol ... |
def start ( config , bugnumber = "" ) :
"""Create a new topic branch .""" | repo = config . repo
if bugnumber :
summary , bugnumber , url = get_summary ( config , bugnumber )
else :
url = None
summary = None
if summary :
summary = input ( 'Summary ["{}"]: ' . format ( summary ) ) . strip ( ) or summary
else :
summary = input ( "Summary: " ) . strip ( )
branch_name = ""
if b... |
def parse_resources ( self , resources ) :
"""Parses and sets resources in the model using a factory .""" | self . resources = { }
resource_factory = ResourceFactory ( )
for res_id , res_value in resources . items ( ) :
r = resource_factory . create_resource ( res_id , res_value )
if r :
if r . resource_type in self . resources :
self . resources [ r . resource_type ] . append ( r )
else :... |
def _init_from_dict ( self , model_dict ) :
"""Initiate self from a model _ dict to make sure attributes such as vars , params are available .
Creates lists of alphabetically sorted independent vars , dependent vars , sigma vars , and parameters .
Finally it creates a signature for this model so it can be calle... | sort_func = lambda symbol : symbol . name
self . model_dict = OrderedDict ( sorted ( model_dict . items ( ) , key = lambda i : sort_func ( i [ 0 ] ) ) )
# Everything at the bottom of the toposort is independent , at the top
# dependent , and the rest interdependent .
ordered = list ( toposort ( self . connectivity_mapp... |
def hash_of_signed_transaction ( txn_obj ) :
'''Regenerate the hash of the signed transaction object .
1 . Infer the chain ID from the signature
2 . Strip out signature from transaction
3 . Annotate the transaction with that ID , if available
4 . Take the hash of the serialized , unsigned , chain - aware tr... | ( chain_id , _v ) = extract_chain_id ( txn_obj . v )
unsigned_parts = strip_signature ( txn_obj )
if chain_id is None :
signable_transaction = UnsignedTransaction ( * unsigned_parts )
else :
extended_transaction = unsigned_parts + [ chain_id , 0 , 0 ]
signable_transaction = ChainAwareUnsignedTransaction ( *... |
def get_yield_stress ( self , n ) :
"""Gets the yield stress for a given direction
Args :
n ( 3x1 array - like ) : direction for which to find the
yield stress""" | # TODO : root finding could be more robust
comp = root ( self . get_stability_criteria , - 1 , args = n )
tens = root ( self . get_stability_criteria , 1 , args = n )
return ( comp . x , tens . x ) |
def _recv_guess ( self , value ) :
"""Take the binary spew and try to make it into a float or integer . If
that can ' t be done , return a string .
Note : this is generally a bad idea , as values can be seriously mangled
by going from float - > string - > float . You ' ll generally be better off
using a for... | if self . give_warnings :
w = "Warning: Guessing input format for {}. This can give wildly incorrect values. Consider specifying a format and sending binary data." . format ( value )
warnings . warn ( w , Warning )
tmp_value = value . decode ( )
try :
float ( tmp_value )
if len ( tmp_value . split ( "."... |
def substitute_namespace_into_graph ( self , graph ) :
"""Creates a graph from the local namespace of the code ( to be used after the execution of the code )
: param graph : The graph to use as a recipient of the namespace
: return : the updated graph""" | for key , value in self . namespace . items ( ) :
try :
nodes = graph . vs . select ( name = key )
for node in nodes :
for k , v in value . items ( ) :
node [ k ] = v
except :
pass
try :
nodes = graph . es . select ( name = key )
for node i... |
def enable_audit_device ( self , device_type , description = None , options = None , path = None ) :
"""Enable a new audit device at the supplied path .
The path can be a single word name or a more complex , nested path .
Supported methods :
PUT : / sys / audit / { path } . Produces : 204 ( empty body )
: p... | if path is None :
path = device_type
params = { 'type' : device_type , 'description' : description , 'options' : options , }
api_path = '/v1/sys/audit/{path}' . format ( path = path )
return self . _adapter . post ( url = api_path , json = params ) |
def setimdi ( self , node ) : # OBSOLETE
"""OBSOLETE""" | ns = { 'imdi' : 'http://www.mpi.nl/IMDI/Schema/IMDI' }
self . metadatatype = MetaDataType . IMDI
if LXE :
self . metadata = ElementTree . tostring ( node , xml_declaration = False , pretty_print = True , encoding = 'utf-8' )
else :
self . metadata = ElementTree . tostring ( node , encoding = 'utf-8' )
n = node ... |
def decode_token ( self , token , key , algorithms = None , ** kwargs ) :
"""A JSON Web Key ( JWK ) is a JavaScript Object Notation ( JSON ) data
structure that represents a cryptographic key . This specification
also defines a JWK Set JSON data structure that represents a set of
JWKs . Cryptographic algorith... | return jwt . decode ( token , key , audience = kwargs . pop ( 'audience' , None ) or self . _client_id , algorithms = algorithms or [ 'RS256' ] , ** kwargs ) |
def set_monitor_timeout ( timeout , power = 'ac' , scheme = None ) :
'''Set the monitor timeout in minutes for the given power scheme
Args :
timeout ( int ) :
The amount of time in minutes before the monitor will timeout
power ( str ) :
Set the value for AC or DC power . Default is ` ` ac ` ` . Valid opti... | return _set_powercfg_value ( scheme = scheme , sub_group = 'SUB_VIDEO' , setting_guid = 'VIDEOIDLE' , power = power , value = timeout ) |
def has_parent_group ( self , group ) :
"""Retuns whether the object is a child of the : obj : ` Group ` ` ` group ` `""" | if isinstance ( group , str ) :
return self . _has_parent_group_by_name ( group )
else :
return self . _has_parent_group_by_object ( group ) |
def update ( self , resource , rid , updates ) :
"""Updates the resource with id ' rid ' with the given updates dictionary .""" | if resource [ - 1 ] != '/' :
resource += '/'
resource += str ( rid )
return self . put ( resource , data = updates ) |
def _make_ntgrid ( grid ) :
"""make a named tuple grid
[ [ " " , " a b " , " b c " , " c d " ] ,
[ " x y " , 1 , 2 , 3 ] ,
[ " y z " , 4 , 5 , 6 ] ,
[ " z z " , 7 , 8 , 9 ] , ]
will return
ntcol ( x _ y = ntrow ( a _ b = 1 , b _ c = 2 , c _ d = 3 ) ,
y _ z = ntrow ( a _ b = 4 , b _ c = 5 , c _ d = 6 )... | hnames = [ _nospace ( n ) for n in grid [ 0 ] [ 1 : ] ]
vnames = [ _nospace ( row [ 0 ] ) for row in grid [ 1 : ] ]
vnames_s = " " . join ( vnames )
hnames_s = " " . join ( hnames )
ntcol = collections . namedtuple ( 'ntcol' , vnames_s )
ntrow = collections . namedtuple ( 'ntrow' , hnames_s )
rdict = [ dict ( list ( zi... |
def is_all_field_none ( self ) :
""": rtype : bool""" | if self . _id_ is not None :
return False
if self . _created is not None :
return False
if self . _updated is not None :
return False
if self . _attachment is not None :
return False
return True |
def get_label ( self , lang = None ) :
"""Return label for given lang or any default
: param lang : Language to request
: return : Label value
: rtype : Literal""" | x = None
if lang is None :
for obj in self . graph . objects ( self . asNode ( ) , RDFS . label ) :
return obj
for obj in self . graph . objects ( self . asNode ( ) , RDFS . label ) :
x = obj
if x . language == lang :
return x
return x |
def _confused_state ( self , request : Request ) -> Type [ BaseState ] :
"""If we ' re confused , find which state to call .""" | origin = request . register . get ( Register . STATE )
if origin in self . _allowed_states :
try :
return import_class ( origin )
except ( AttributeError , ImportError ) :
pass
return import_class ( settings . DEFAULT_STATE ) |
def output_file ( filename , title = "Bokeh Plot" , mode = "cdn" , root_dir = None ) :
'''Configure the default output state to generate output saved
to a file when : func : ` show ` is called .
Does not change the current ` ` Document ` ` from ` ` curdoc ( ) ` ` . File and notebook
output may be active at th... | curstate ( ) . output_file ( filename , title = title , mode = mode , root_dir = root_dir ) |
def string_format ( msg , method ) :
"""Format a string ( upper , lower , formal , sentence ) .
: param str msg : The user ' s message .
: param str method : One of ` ` uppercase ` ` , ` ` lowercase ` ` ,
` ` sentence ` ` or ` ` formal ` ` .
: return str : The reformatted string .""" | if method == "uppercase" :
return msg . upper ( )
elif method == "lowercase" :
return msg . lower ( )
elif method == "sentence" :
return msg . capitalize ( )
elif method == "formal" :
return string . capwords ( msg ) |
def _deserialize ( self , value , attr , obj ) :
"""Deserialize value as a Unix timestamp ( in float seconds ) .
Handle both numeric and UTC isoformat strings .""" | if value is None :
return None
try :
return float ( value )
except ValueError :
parsed = parser . parse ( value )
if parsed . tzinfo :
if parsed . utcoffset ( ) . total_seconds ( ) :
raise ValidationError ( "Timestamps must be defined in UTC" )
parsed = parsed . replace ( tzi... |
def Prod ( a , axis , keep_dims ) :
"""Prod reduction op .""" | return np . prod ( a , axis = axis if not isinstance ( axis , np . ndarray ) else tuple ( axis ) , keepdims = keep_dims ) , |
def convert2wavenumber ( self ) :
"""Convert from wavelengths to wavenumber""" | for chname in self . rsr . keys ( ) :
elems = [ k for k in self . rsr [ chname ] . keys ( ) ]
for sat in elems :
if sat == "wavelength" :
LOG . debug ( "Get the wavenumber from the wavelength: sat=%s chname=%s" , sat , chname )
wnum = 1. / ( 1e-4 * self . rsr [ chname ] [ sat ] [... |
def read_xml ( cls , url , markup , game , players ) :
"""read xml object
: param url : contents url
: param markup : markup provider
: param game : MLBAM Game object
: param players : MLBAM Players object
: return : pitchpx . game . game . Game object""" | innings = Inning ( game , players )
base_url = "" . join ( [ url , cls . DIRECTORY ] )
# hit location data
hit_location = cls . _read_hit_chart_data ( MlbamUtil . find_xml ( '/' . join ( [ base_url , cls . FILENAME_INNING_HIT ] ) , markup ) )
# create for atbat & pitch data
for inning in MlbamUtil . find_xml_all ( base... |
def send ( self , url , data , headers ) :
"""Spawn an async request to a remote webserver .""" | eventlet . spawn ( self . _send_payload , ( url , data , headers ) ) |
def _dichFind ( self , needle , currHaystack , offset , lst = None ) :
"""dichotomic search , if lst is None , will return the first position found . If it ' s a list , will return a list of all positions in lst . returns - 1 or [ ] if no match found""" | if len ( currHaystack ) == 1 :
if ( offset <= ( len ( self ) - len ( needle ) ) ) and ( currHaystack [ 0 ] & needle [ 0 ] ) > 0 and ( self [ offset + len ( needle ) - 1 ] & needle [ - 1 ] ) > 0 :
found = True
for i in xrange ( 1 , len ( needle ) - 1 ) :
if self [ offset + i ] & needle [ ... |
def multi_encode ( self , message , masking_key = None , opcode = None , rsv1 = 0 , rsv2 = 0 , rsv3 = 0 , max_payload = 0 ) :
'''Encode a ` ` message ` ` into several frames depending on size .
Returns a generator of bytes to be sent over the wire .''' | max_payload = max ( 2 , max_payload or self . _max_payload )
opcode , masking_key , data = self . _info ( message , opcode , masking_key )
while data :
if len ( data ) >= max_payload :
chunk , data , fin = ( data [ : max_payload ] , data [ max_payload : ] , 0 )
else :
chunk , data , fin = data ,... |
def _get_dicts_from_redis ( self , name , index_name , redis_prefix , item ) :
"""Retrieve the data of an item from redis and put it in an index and data dictionary to match the
common query interface .""" | r = self . _redis
data_dict = { }
data_index_dict = { }
if redis_prefix is None :
raise KeyError ( "redis_prefix is missing" )
if r . scard ( redis_prefix + index_name + str ( item ) ) > 0 :
data_index_dict [ str ( item ) ] = r . smembers ( redis_prefix + index_name + str ( item ) )
for i in data_index_dict... |
def query_keymap ( self ) :
"""Return a bit vector for the logical state of the keyboard ,
where each bit set to 1 indicates that the corresponding key is
currently pressed down . The vector is represented as a list of 32
integers . List item N contains the bits for keys 8N to 8N + 7
with the least signific... | r = request . QueryKeymap ( display = self . display )
return r . map |
def check_row ( state , index , missing_msg = None , expand_msg = None ) :
"""Zoom in on a particular row in the query result , by index .
After zooming in on a row , which is represented as a single - row query result ,
you can use ` ` has _ equal _ value ( ) ` ` to verify whether all columns in the zoomed in ... | if missing_msg is None :
missing_msg = "The system wants to verify row {{index + 1}} of your query result, but couldn't find it. Have another look."
if expand_msg is None :
expand_msg = "Have another look at row {{index + 1}} in your query result. "
msg_kwargs = { "index" : index }
# check that query returned s... |
def set_path ( self , path , val ) :
"""Set the given value at the supplied path where path is either
a tuple of strings or a string in A . B . C format .""" | path = tuple ( path . split ( '.' ) ) if isinstance ( path , str ) else tuple ( path )
disallowed = [ p for p in path if not type ( self ) . _sanitizer . allowable ( p ) ]
if any ( disallowed ) :
raise Exception ( "Attribute strings in path elements cannot be " "correctly escaped : %s" % ',' . join ( repr ( el ) fo... |
def build_git_url ( self ) :
"""get build git url .
: return : build git url or None if not found""" | # pylint : disable = len - as - condition
if len ( self . dutinformation ) > 0 and ( self . dutinformation . get ( 0 ) . build is not None ) :
return self . dutinformation . get ( 0 ) . build . giturl
return None |
def titleize ( word ) :
"""Capitalize all the words and replace some characters in the string to
create a nicer looking title . : func : ` titleize ` is meant for creating pretty
output .
Examples : :
> > > titleize ( " man from the boondocks " )
" Man From The Boondocks "
> > > titleize ( " x - men : t... | return re . sub ( r"\b('?[a-z])" , lambda match : match . group ( 1 ) . capitalize ( ) , humanize ( underscore ( word ) ) ) |
def affine ( self , pixelbuffer = 0 ) :
"""Return an Affine object of tile .
- pixelbuffer : tile buffer in pixels""" | return Affine ( self . pixel_x_size , 0 , self . bounds ( pixelbuffer ) . left , 0 , - self . pixel_y_size , self . bounds ( pixelbuffer ) . top ) |
def register_schema ( self , directory , path ) :
"""Register a json - schema .
: param directory : root directory path .
: param path : schema path , relative to the root directory .""" | self . schemas [ path ] = os . path . abspath ( directory ) |
def description ( self ) :
'''Provide a description for each algorithm available , useful to print in ecc file''' | if 0 < self . algo <= 3 :
return "Reed-Solomon with polynomials in Galois field of characteristic %i (2^%i) with generator=%s, prime poly=%s and first consecutive root=%s." % ( self . field_charac , self . c_exp , self . gen_nb , hex ( self . prim ) , self . fcr )
elif self . algo == 4 :
return "Reed-Solomon wi... |
def delete ( self ) :
"""Delete this table .
For example :
. . literalinclude : : snippets _ table . py
: start - after : [ START bigtable _ delete _ table ]
: end - before : [ END bigtable _ delete _ table ]""" | table_client = self . _instance . _client . table_admin_client
table_client . delete_table ( name = self . name ) |
def pop ( self , key , default = None ) :
"""Get item from the dict and remove it .
Return default if expired or does not exist . Never raise KeyError .""" | with self . lock :
try :
item = OrderedDict . __getitem__ ( self , key )
del self [ key ]
return item [ 0 ]
except KeyError :
return default |
def flush ( self ) :
"""Flush the write buffers of the stream if applicable and
save the object on the cloud .""" | if self . _writable :
with self . _seek_lock :
buffer = self . _get_buffer ( )
# Flush that part of the file
end = self . _seek
start = end - len ( buffer )
# Clear buffer
self . _write_buffer = bytearray ( )
# Flush content
with handle_os_exceptions ( ) :
... |
def occurrence_view ( request , event_pk , pk , template = 'swingtime/occurrence_detail.html' , form_class = forms . SingleOccurrenceForm ) :
'''View a specific occurrence and optionally handle any updates .
Context parameters :
` ` occurrence ` `
the occurrence object keyed by ` ` pk ` `
` ` form ` `
a f... | occurrence = get_object_or_404 ( Occurrence , pk = pk , event__pk = event_pk )
if request . method == 'POST' :
form = form_class ( request . POST , instance = occurrence )
if form . is_valid ( ) :
form . save ( )
return http . HttpResponseRedirect ( request . path )
else :
form = form_class ... |
def get_tree ( cls , session = None , json = False , json_fields = None , query = None ) :
"""This method generate tree of current node table in dict or json
format . You can make custom query with attribute ` ` query ` ` . By default
it return all nodes in table .
Args :
session ( : mod : ` sqlalchemy . or... | # noqa
tree = [ ]
nodes_of_level = { }
# handle custom query
nodes = cls . _base_query ( session )
if query :
nodes = query ( nodes )
nodes = cls . _base_order ( nodes ) . all ( )
# search minimal level of nodes .
min_level = min ( [ node . level for node in nodes ] or [ None ] )
def get_node_id ( node ) :
retu... |
def set ( self , num ) :
"""Sets the current value equal to num""" | self . _value = coord . Angle ( num , unit = u . deg )
self . _variable . set ( self . as_string ( ) ) |
def set_options ( self , ** kwargs ) :
"""Set the options . Existing value will persist
: param kwargs :
: return :""" | options = self . options
options . update ( kwargs )
self . update ( options = options ) |
def _send_http_request ( self , xml_request ) :
"""Send a request via HTTP protocol .
Args :
xml _ request - - A fully formed xml request string for the CPS .
Returns :
The raw xml response string .""" | headers = { "Host" : self . _host , "Content-Type" : "text/xml" , "Recipient" : self . _storage }
try : # Retry once if failed in case the socket has just gone bad .
self . _connection . request ( "POST" , self . _selector_url , xml_request , headers )
response = self . _connection . getresponse ( )
except ( ht... |
def RybToRgb ( hue ) :
'''Maps a hue on Itten ' s RYB color wheel to the standard RGB wheel .
Parameters :
: hue :
The hue on Itten ' s RYB color wheel [ 0 . . . 360]
Returns :
An approximation of the corresponding hue on the standard RGB wheel .
> > > Color . RybToRgb ( 15)
8.0''' | d = hue % 15
i = int ( hue / 15 )
x0 = _RgbWheel [ i ]
x1 = _RgbWheel [ i + 1 ]
return x0 + ( x1 - x0 ) * d / 15 |
def SaveResourceUsage ( self , status ) :
"""Method to tally resources .""" | user_cpu = status . cpu_time_used . user_cpu_time
system_cpu = status . cpu_time_used . system_cpu_time
self . rdf_flow . cpu_time_used . user_cpu_time += user_cpu
self . rdf_flow . cpu_time_used . system_cpu_time += system_cpu
self . rdf_flow . network_bytes_sent += status . network_bytes_sent
if self . rdf_flow . cpu... |
def ToDebugString ( self , indentation_level = 1 ) :
"""Converts the path filter scan tree node into a debug string .
Args :
indentation _ level : an integer containing the text indentation level .
Returns :
A string containing a debug representation of the path filter scan
tree node .""" | indentation = ' ' * indentation_level
text_parts = [ '{0:s}path segment index: {1:d}\n' . format ( indentation , self . path_segment_index ) ]
for path_segment , scan_object in self . _path_segments . items ( ) :
text_parts . append ( '{0:s}path segment: {1:s}\n' . format ( indentation , path_segment ) )
if is... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.