signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _dD_dR ( self , R ) :
"""Return numpy array of dD / dR from D1 up to and including Dn .""" | HNn_R_sina = self . _HNn / R / self . _sin_alpha
return HNn_R_sina * ( 0.3 * ( HNn_R_sina + 0.3 * HNn_R_sina ** 2. + 1 ) / R / ( 0.3 * HNn_R_sina + 1 ) ** 2 - ( 1 / R * ( 1 + 0.6 * HNn_R_sina ) / ( 0.3 * HNn_R_sina + 1 ) ) ) |
def linalg_gemm ( attrs , inputs , proto_obj ) :
"""Performs general matrix multiplication and accumulation""" | trans_a = 0
trans_b = 0
alpha = 1
beta = 1
if 'transA' in attrs :
trans_a = attrs [ 'transA' ]
if 'transB' in attrs :
trans_b = attrs [ 'transB' ]
if 'alpha' in attrs :
alpha = attrs [ 'alpha' ]
if 'beta' in attrs :
beta = attrs [ 'beta' ]
flatten_a = symbol . flatten ( inputs [ 0 ] )
matmul_op = symbol... |
def preparse_iter ( self ) :
"""Comments can be anywhere . So break apart the Dockerfile into significant
lines and any comments that precede them . And if a line is a carryover
from the previous via an escaped - newline , bring the directive with it .""" | to_yield = { }
last_directive = None
lines_processed = 0
for line in self . lines_iter ( ) :
if not line :
continue
if line . startswith ( u'#' ) :
comment = line . lstrip ( '#' ) . strip ( )
# Directives have to precede any instructions
if lines_processed == 1 :
if c... |
def reset ( self , ** kwargs ) :
"""Reset all of the motor parameter attributes to their default value .
This will also have the effect of stopping the motor .""" | for key in kwargs :
setattr ( self , key , kwargs [ key ] )
self . command = self . COMMAND_RESET |
def get_all_recurrings ( self , params = None ) :
"""Get all recurrings
This will iterate over all pages until it gets all elements .
So if the rate limit exceeded it will throw an Exception and you will get nothing
: param params : search params
: return : list""" | if not params :
params = { }
return self . _iterate_through_pages ( self . get_recurrings_per_page , resource = RECURRINGS , ** { 'params' : params } ) |
def _process_maybe_work ( self , yes_work , maybe_work , work_dir , yn_results_path , stats ) :
"""Returns statistics of how ` yes _ work ` compares with ` maybe _ work ` .
: param yes _ work : name of work for which stats are collected
: type yes _ work : ` str `
: param maybe _ work : name of work being com... | if maybe_work == yes_work :
return stats
self . _logger . info ( 'Processing "maybe" work {} against "yes" work {}.' . format ( maybe_work , yes_work ) )
# Set base values for each statistic of interest , for each
# witness .
for siglum in self . _corpus . get_sigla ( maybe_work ) :
witness = ( maybe_work , sig... |
def parse_file ( file_or_path , encoding = 'utf-8' , validate = False ) :
"""Tries to parse a given filepath or fileobj into a Bibliography instance . If
` ` validate ` ` is passed as keyword argument and set to ` ` True ` ` , the
Bibliography will be validated using the standard rules .""" | try :
is_string = isinstance ( file_or_path , basestring )
except NameError :
is_string = isinstance ( file_or_path , str )
if is_string :
with codecs . open ( file_or_path , 'r' , encoding ) as file_ :
result = pattern . parseFile ( file_ ) [ 0 ]
else :
result = pattern . parseFile ( file_or_pa... |
def moments_match_ep ( self , Y_i , tau_i , v_i , Y_metadata_i = None ) :
"""Moments match of the marginal approximation in EP algorithm
: param i : number of observation ( int )
: param tau _ i : precision of the cavity distribution ( float )
: param v _ i : mean / variance of the cavity distribution ( float... | if Y_i == 1 :
sign = 1.
elif Y_i == 0 or Y_i == - 1 :
sign = - 1
else :
raise ValueError ( "bad value for Bernoulli observation (0, 1)" )
if isinstance ( self . gp_link , link_functions . Probit ) :
z = sign * v_i / np . sqrt ( tau_i ** 2 + tau_i )
phi_div_Phi = derivLogCdfNormal ( z )
log_Z_hat... |
def _extract_player_stats ( self , table , player_dict , home_or_away ) :
"""Combine all player stats into a single object .
Since each player generally has a couple of rows worth of stats ( one
for basic stats and another for advanced stats ) on the boxscore page ,
both rows should be combined into a single ... | for row in table ( 'tbody tr' ) . items ( ) :
player_id = self . _find_player_id ( row )
# Occurs when a header row is identified instead of a player .
if not player_id :
continue
name = self . _find_player_name ( row )
try :
player_dict [ player_id ] [ 'data' ] += str ( row ) . stri... |
def GlorotUniformInitializer ( out_dim = 0 , in_dim = 1 ) :
"""An initializer function for random uniform Glorot - scaled coefficients .""" | def init ( shape , rng ) :
fan_in , fan_out = shape [ in_dim ] , shape [ out_dim ]
std = np . sqrt ( 2.0 / ( fan_in + fan_out ) )
a = np . sqrt ( 3.0 ) * std
return backend . random . uniform ( rng , shape , minval = - a , maxval = a )
return init |
def EnumValueName ( self , enum , value ) :
"""Returns the string name of an enum value .
This is just a small helper method to simplify a common operation .
Args :
enum : string name of the Enum .
value : int , value of the enum .
Returns :
string name of the enum value .
Raises :
KeyError if eithe... | return self . enum_types_by_name [ enum ] . values_by_number [ value ] . name |
def to_julian_date ( self ) :
"""Convert Datetime Array to float64 ndarray of Julian Dates .
0 Julian date is noon January 1 , 4713 BC .
http : / / en . wikipedia . org / wiki / Julian _ day""" | # http : / / mysite . verizon . net / aesir _ research / date / jdalg2 . htm
year = np . asarray ( self . year )
month = np . asarray ( self . month )
day = np . asarray ( self . day )
testarr = month < 3
year [ testarr ] -= 1
month [ testarr ] += 12
return ( day + np . fix ( ( 153 * month - 457 ) / 5 ) + 365 * year + ... |
def from_cone ( cls , center , radius = 3 * u . arcmin , magnitudelimit = None , ** kw ) :
'''Create a Constellation from a cone search of the sky ,
characterized by a positional center and a radius from it .
Parameters
center : SkyCoord object
The center around which the query will be made .
radius : flo... | # make sure the center is a SkyCoord
center = parse_center ( center )
criteria = { }
if magnitudelimit is not None :
criteria [ cls . defaultfilter + 'mag' ] = '<{}' . format ( magnitudelimit )
v = Vizier ( columns = cls . columns , column_filters = criteria )
v . ROW_LIMIT = - 1
# run the query
print ( 'querying V... |
def add_user ( self , username , password ) :
"""Add an user to the dictionary .""" | self . server . user_dict [ username ] = password
self . server . isAuth = True |
def all_timescales_ ( self ) :
"""Implied relaxation timescales each sample in the ensemble
Returns
timescales : array - like , shape = ( n _ samples , n _ timescales , )
The longest implied relaxation timescales of the each sample in
the ensemble of transition matrices , expressed in units of
time - step... | us , lvs , rvs = self . _get_eigensystem ( )
# make sure to leave off equilibrium distribution
timescales = - self . lag_time / np . log ( us [ : , 1 : ] )
return timescales |
def front_and_backfill ( self , cols , inplace = True ) :
"""Groups dataframe by index name then replaces null values in selected
columns with front / backfilled values if available .
Changes self . df inplace .
Parameters
self : MagicDataFrame
cols : array - like
list of column names
Returns
self .... | cols = list ( cols )
for col in cols :
if col not in self . df . columns :
self . df [ col ] = np . nan
short_df = self . df [ cols ]
# horrible , bizarre hack to test for pandas malfunction
tester = short_df . groupby ( short_df . index , sort = False ) . fillna ( method = 'ffill' )
if not_null ( tester ) ... |
def reload ( self , obj , extra_params = None ) :
"""Reload an object from server . This method is immutable and will return a new object .
: param obj : object to reload
: type obj : : py : obj : ` obj `
: param extra _ params : additional object specific extra query string params ( eg for activity )
: typ... | if not obj . _json_data . get ( 'url' ) : # pragma : no cover
raise NotFoundError ( "Could not reload object, there is no url for object '{}' configured" . format ( obj ) )
response = self . _request ( 'GET' , obj . _json_data . get ( 'url' ) , params = extra_params )
if response . status_code != requests . codes .... |
def path ( self , which = None ) :
"""Extend ` ` nailgun . entity _ mixins . Entity . path ` ` .
The format of the returned path depends on the value of ` ` which ` ` :
facts
/ discovered _ hosts / facts
` ` super ` ` is called otherwise .""" | if which == 'facts' :
return '{0}/{1}' . format ( super ( DiscoveredHost , self ) . path ( which = 'base' ) , which )
return super ( DiscoveredHost , self ) . path ( which ) |
def _save_documentation ( version , base_url = "https://spark.apache.org/docs" ) :
"""Write the spark property documentation to a file""" | target_dir = join ( dirname ( __file__ ) , 'spylon' , 'spark' )
with open ( join ( target_dir , "spark_properties_{}.json" . format ( version ) ) , 'w' ) as fp :
all_props = _fetch_documentation ( version = version , base_url = base_url )
all_props = sorted ( all_props , key = lambda x : x [ 0 ] )
all_props... |
def read_file ( self ) :
"""Grabs filename and enables it to be read .
: return : raw _ file = unaltered text ; file _ lines = text split by lines .""" | with open ( self . filename , mode = 'r+' , encoding = 'utf8' ) as text_file :
self . raw_file = text_file . read ( )
# pylint : disable = attribute - defined - outside - init
self . file_lines = [ x . rstrip ( ) for x in self . raw_file . splitlines ( ) ] |
def partial_fit ( self , sequence , y = None ) :
"""Fit Preprocessing to X .
Parameters
sequence : array - like , [ sequence _ length , n _ features ]
A multivariate timeseries .
y : None
Ignored
Returns
self""" | s = super ( MultiSequencePreprocessingMixin , self )
if hasattr ( s , 'fit' ) :
return s . fit ( sequence )
return self |
def select_to_constraint ( cls , dataset , selection ) :
"""Transform a selection dictionary to an iris Constraint .""" | import iris
def get_slicer ( start , end ) :
def slicer ( cell ) :
return start <= cell . point < end
return slicer
constraint_kwargs = { }
for dim , constraint in selection . items ( ) :
if isinstance ( constraint , slice ) :
constraint = ( constraint . start , constraint . stop )
if is... |
def effect_from_model ( model , ref , ref_rc , alt , alt_rc , methods , mutation_positions , out_annotation_all_outputs , extra_args = None , ** argv ) :
"""Convenience function to execute multiple effect predictions in one call
# Arguments
model : Keras model
ref : Input sequence with the reference genotype ... | assert isinstance ( methods , list )
if isinstance ( extra_args , list ) :
assert ( len ( extra_args ) == len ( methods ) )
else :
extra_args = [ None ] * len ( methods )
main_args = { "model" : model , "ref" : ref , "ref_rc" : ref_rc , "alt" : alt , "alt_rc" : alt_rc , "mutation_positions" : mutation_positions... |
def GrowInstanceDisk ( r , instance , disk , amount , wait_for_sync = False ) :
"""Grows a disk of an instance .
More details for parameters can be found in the RAPI documentation .
@ type instance : string
@ param instance : Instance name
@ type disk : integer
@ param disk : Disk index
@ type amount : ... | body = { "amount" : amount , "wait_for_sync" : wait_for_sync , }
return r . request ( "post" , "/2/instances/%s/disk/%s/grow" % ( instance , disk ) , content = body ) |
def is_nondominated_pathetic ( self , obs_df ) :
"""identify which candidate solutions are pareto non - dominated -
super patheically slow . . .
Parameters
obs _ df : pandas . DataFrame
dataframe with columns of observation names and rows of realizations
Returns
is _ dominated : pandas . Series
series... | obj_df = obs_df . loc [ : , self . obs_obj_names ]
is_nondom = [ ]
for i , iidx in enumerate ( obj_df . index ) :
ind = True
for jidx in obj_df . index :
if iidx == jidx :
continue
# if dominates ( jidx , iidx ) :
# ind = False
# break
if self . dominates ( ob... |
def chain ( self , certlist ) :
"""Construct the chain of certificates leading from ' self ' to the
self signed root using the certificates in ' certlist ' . If the
list does not provide all the required certs to go to the root
the function returns a incomplete chain starting with the
certificate . This fac... | d = { }
for c in certlist : # XXX we should check if we have duplicate
d [ c . subject ] = c
res = [ self ]
cur = self
while not cur . isSelfSigned ( ) :
if cur . issuer in d :
possible_issuer = d [ cur . issuer ]
if cur . isIssuerCert ( possible_issuer ) :
res . append ( possible_is... |
def register ( linter ) :
'''required method to auto register this checker''' | linter . register_checker ( StringCurlyBracesFormatIndexChecker ( linter ) )
linter . register_checker ( StringLiteralChecker ( linter ) ) |
def _process_file ( self ) :
'''Process rebase file into dict with name and cut site information .''' | print 'Processing file'
with open ( self . _rebase_file , 'r' ) as f :
raw = f . readlines ( )
names = [ line . strip ( ) [ 3 : ] for line in raw if line . startswith ( '<1>' ) ]
seqs = [ line . strip ( ) [ 3 : ] for line in raw if line . startswith ( '<5>' ) ]
if len ( names ) != len ( seqs ) :
raise Exception... |
def pulsation ( feature , ** kwargs ) :
"""Create parameters for a pulsation feature
Generally , this will be used as input to the method argument in
: meth : ` phoebe . frontend . bundle . Bundle . add _ feature `
: parameter * * kwargs : defaults for the values of any of the parameters
: return : a : clas... | if not conf . devel :
raise NotImplementedError ( "'pulsation' feature not officially supported for this release. Enable developer mode to test." )
params = [ ]
params += [ FloatParameter ( qualifier = 'radamp' , value = kwargs . get ( 'radamp' , 0.1 ) , default_unit = u . dimensionless_unscaled , description = 'R... |
def to_networkx ( self , directed = None ) :
'''Converts this Graph object to a networkx - compatible object .
Requires the networkx library .''' | import networkx as nx
directed = directed if directed is not None else self . is_directed ( )
cls = nx . DiGraph if directed else nx . Graph
adj = self . matrix ( )
if ss . issparse ( adj ) :
return nx . from_scipy_sparse_matrix ( adj , create_using = cls ( ) )
return nx . from_numpy_matrix ( adj , create_using = c... |
def read ( self , size = - 1 ) :
"""Returns data bytes of size size from the current segment . If size is - 1 it returns all the remaining data bytes from memory segment""" | if size < - 1 :
raise Exception ( 'You shouldnt be doing this' )
if size == - 1 :
t = self . current_segment . remaining_len ( self . current_position )
if not t :
return None
old_new_pos = self . current_position
self . current_position = self . current_segment . end_address
return self... |
def activate ( name , lbn , target , profile = 'default' , tgt_type = 'glob' ) :
'''. . versionchanged : : 2017.7.0
The ` ` expr _ form ` ` argument has been renamed to ` ` tgt _ type ` ` , earlier
releases must use ` ` expr _ form ` ` .
Activate the named worker from the lbn load balancers at the targeted
... | return _talk2modjk ( name , lbn , target , 'worker_activate' , profile , tgt_type ) |
def global_confirm ( question , default = True ) :
"""Shows a confirmation that applies to all hosts
by temporarily disabling parallel execution in Fabric""" | if env . abort_on_prompts :
return True
original_parallel = env . parallel
env . parallel = False
result = confirm ( question , default )
env . parallel = original_parallel
return result |
def poller_processor_handler ( event , context ) : # pylint : disable = W0613
"""Historical Security Group Poller Processor .
This will receive events from the Poller Tasker , and will list all objects of a given technology for an
account / region pair . This will generate ` polling events ` which simulate chan... | LOG . debug ( '[@] Running Poller...' )
queue_url = get_queue_url ( os . environ . get ( 'POLLER_QUEUE_NAME' , 'HistoricalVPCPoller' ) )
records = deserialize_records ( event [ 'Records' ] )
for record in records : # Skip accounts that have role assumption errors :
try :
vpcs = describe_vpcs ( account_numbe... |
def do ( self , response , binding , relay_state = "" , mtype = "response" ) :
""": param response : The SAML response , transport encoded
: param binding : Which binding the query came in over""" | # tmp _ outstanding _ queries = dict ( self . outstanding _ queries )
if not response :
logger . info ( "Missing Response" )
resp = Unauthorized ( "Unknown user" )
return resp ( self . environ , self . start_response )
try :
conv_info = { "remote_addr" : self . environ [ "REMOTE_ADDR" ] , "request_uri" ... |
def pretty_flags ( flags ) :
"""Return pretty representation of code flags .""" | names = [ ]
result = "0x%08x" % flags
for i in range ( 32 ) :
flag = 1 << i
if flags & flag :
names . append ( COMPILER_FLAG_NAMES . get ( flag , hex ( flag ) ) )
flags ^= flag
if not flags :
break
else :
names . append ( hex ( flags ) )
names . reverse ( )
return "%s (%s... |
def release ( self , conn ) :
"""Release a previously acquired connection .
The connection is put back into the pool .""" | self . _pool_lock . acquire ( )
self . _pool . put ( ConnectionWrapper ( self . _pool , conn ) )
self . _current_acquired -= 1
self . _pool_lock . release ( ) |
def dependency_context ( package_names , aggressively_remove = False ) :
"""Install the supplied packages and yield . Finally , remove all packages
that were installed .
Currently assumes ' aptitude ' is available .""" | installed_packages = [ ]
log = logging . getLogger ( __name__ )
try :
if not package_names :
logging . debug ( 'No packages requested' )
if package_names :
lock = yg . lockfile . FileLock ( '/tmp/.pkg-context-lock' , timeout = 30 * 60 )
log . info ( 'Acquiring lock to perform install' )
... |
def get_activity_objective_bank_assignment_session ( self , proxy ) :
"""Gets the session for assigning activity to objective bank mappings .
arg : proxy ( osid . proxy . Proxy ) : a proxy
return : ( osid . learning . ActivityObjectiveBankAssignmentSession ) -
an ` ` ActivityObjectiveBankAssignmentSession ` `... | if not self . supports_activity_objective_bank_assignment ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . ActivityObjectiveBankAssignmentSession ( proxy = proxy , runtime = self . _runtime ) |
def _send_mail ( self , receivers_list , subject , body , log_files = None ) :
if not receivers_list :
self . log . info ( 'no valid addresses in requested addresses. Doing nothing' )
return
self . log . info ( 'sending notification to %s ...' , receivers_list )
"""Actually sends the mail wi... | if log_files :
msg = MIMEMultipart ( )
msg . attach ( MIMEText ( body ) )
for entry in log_files :
log_mime = MIMEBase ( 'application' , "octet-stream" )
log_file = entry [ 0 ]
# Output . file
log_file . seek ( 0 )
log_mime . set_payload ( log_file . read ( ) )
... |
def electric_field_amplitude_top ( P , a , Omega = 1e6 , units = "ad-hoc" ) :
"""Return the amplitude of the electric field for a top hat beam .
This is the amplitude of a laser beam of power P ( in Watts ) and a top - hat \
intensity distribution of radius a ( in meters ) . The value of E0 is given in \
resc... | e0 = hbar * Omega / ( e * a0 )
# This is the electric field scale .
E0 = sqrt ( ( c * mu0 * P ) / ( Pi * a ** 2 ) )
if units == "ad-hoc" :
E0 = E0 / e0
return E0 |
def encode ( self , pdu ) :
"""encode the contents of the NPCI into the PDU .""" | if _debug :
NPCI . _debug ( "encode %s" , repr ( pdu ) )
PCI . update ( pdu , self )
# only version 1 messages supported
pdu . put ( self . npduVersion )
# build the flags
if self . npduNetMessage is not None :
netLayerMessage = 0x80
else :
netLayerMessage = 0x00
# map the destination address
dnetPresent = ... |
def _ltf ( ins ) :
'''Compares & pops top 2 operands out of the stack , and checks
if the 1st operand < 2nd operand ( top of the stack ) .
Pushes 0 if False , 1 if True .
Floating Point version''' | op1 , op2 = tuple ( ins . quad [ 2 : ] )
output = _float_oper ( op1 , op2 )
output . append ( 'call __LTF' )
output . append ( 'push af' )
REQUIRES . add ( 'ltf.asm' )
return output |
def genestats ( args ) :
"""% prog genestats gffile
Print summary stats , including :
- Number of genes
- Number of single - exon genes
- Number of multi - exon genes
- Number of distinct exons
- Number of genes with alternative transcript variants
- Number of predicted transcripts
- Mean number of ... | p = OptionParser ( genestats . __doc__ )
p . add_option ( "--groupby" , default = "conf_class" , help = "Print separate stats groupby" )
p . set_outfile ( )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( not p . print_help ( ) )
gff_file , = args
gb = opts . groupby
g = make_index ( gff_f... |
def write ( self , filename ) :
"""Save detx file .""" | with open ( filename , 'w' ) as f :
f . write ( self . ascii )
self . print ( "Detector file saved as '{0}'" . format ( filename ) ) |
def genlmsg_len ( gnlh ) :
"""Return length of message payload including user header .
https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / genl / genl . c # L224
Positional arguments :
gnlh - - Generic Netlink message header ( genlmsghdr class instance ) .
Returns :
Length of user payl... | nlh = nlmsghdr ( bytearray_ptr ( gnlh . bytearray , - NLMSG_HDRLEN , oob = True ) )
return nlh . nlmsg_len - GENL_HDRLEN - NLMSG_HDRLEN |
def i2c_master_write ( self , i2c_address , data , flags = I2C_NO_FLAGS ) :
"""Make an I2C write access .
The given I2C device is addressed and data given as a string is
written . The transaction is finished with an I2C stop condition unless
I2C _ NO _ STOP is set in the flags .
10 bit addresses are support... | data = array . array ( 'B' , data )
status , _ = api . py_aa_i2c_write_ext ( self . handle , i2c_address , flags , len ( data ) , data )
_raise_i2c_status_code_error_if_failure ( status ) |
def layered ( self ) :
"""Yield list of [ [ ( name , image ) , . . . ] , [ ( name , image ) , . . . ] , . . . ]""" | result = [ ]
for layer in self . _layered :
nxt = [ ]
for name in layer :
nxt . append ( ( name , self . all_images [ name ] ) )
result . append ( nxt )
return result |
def _error_if_symbol_unused ( symbol_word , technical_words_dictionary , line_offset , col_offset ) :
"""Return SpellcheckError if this symbol is not used in the code .""" | result = technical_words_dictionary . corrections ( symbol_word , distance = 5 , prefix = 0 )
if not result . valid :
return SpellcheckError ( symbol_word , line_offset , col_offset , result . suggestions , SpellcheckError . TechnicalWord ) |
def quote_etag ( etag , weak = False ) :
"""Quote an etag .
: param etag : the etag to quote .
: param weak : set to ` True ` to tag it " weak " .""" | if '"' in etag :
raise ValueError ( 'invalid etag' )
etag = '"%s"' % etag
if weak :
etag = 'w/' + etag
return etag |
def list_styles ( self ) :
"""Print available styles and exit .""" | known = sorted ( self . defaults . known_styles )
if not known :
err_exit ( 'No styles' , 0 )
for style in known :
if style == self . defaults . default_style :
print ( style , '(default)' )
else :
print ( style )
sys . exit ( 0 ) |
def set_muted ( self , status ) :
"""Set client mute status .""" | new_volume = self . _client [ 'config' ] [ 'volume' ]
new_volume [ 'muted' ] = status
self . _client [ 'config' ] [ 'volume' ] [ 'muted' ] = status
yield from self . _server . client_volume ( self . identifier , new_volume )
_LOGGER . info ( 'set muted to %s on %s' , status , self . friendly_name ) |
def run_check_kind ( _ ) :
'''Running the script .''' | for kindv in router_post :
for rec_cat in MCategory . query_all ( kind = kindv ) :
catid = rec_cat . uid
catinfo = MCategory . get_by_uid ( catid )
for rec_post2tag in MPost2Catalog . query_by_catid ( catid ) :
postinfo = MPost . get_by_uid ( rec_post2tag . post_id )
... |
def read_kwfile ( fname ) :
"""Syntax used as of r452 in commissioning tests""" | d = { }
f = open ( fname )
for line in f :
try :
kvpair = re . findall ( "(.*):: (.*)=(.*)$" , line ) [ 0 ]
d [ 'name' ] = os . path . basename ( kvpair [ 0 ] )
key , val = kvpair [ 1 : ]
d [ key . lower ( ) ] = val
except ( ValueError , IndexError ) :
break
f . close ( )... |
def batchlobstr ( args ) :
"""% prog batchlobstr samples . csv
Run lobSTR sequentially on list of samples . Each line contains :
sample - name , s3 - location""" | p = OptionParser ( batchlobstr . __doc__ )
p . add_option ( "--sep" , default = "," , help = "Separator for building commandline" )
p . set_home ( "lobstr" , default = "s3://hli-mv-data-science/htang/str-build/lobSTR/" )
p . set_aws_opts ( store = "hli-mv-data-science/htang/str-data" )
opts , args = p . parse_args ( ar... |
def attach_lb_to_subnets ( self , name , subnets ) :
"""Attaches load balancer to one or more subnets .
Attaching subnets that are already registered with the
Load Balancer has no effect .
: type name : string
: param name : The name of the Load Balancer
: type subnets : List of strings
: param subnets ... | params = { 'LoadBalancerName' : name }
self . build_list_params ( params , subnets , 'Subnets.member.%d' )
return self . get_list ( 'AttachLoadBalancerToSubnets' , params , None ) |
def excepthook ( type , value , tb ) :
"""Report an exception .""" | if ( issubclass ( type , Error ) or issubclass ( type , lib50 . Error ) ) and str ( value ) :
for line in str ( value ) . split ( "\n" ) :
cprint ( str ( line ) , "yellow" )
else :
cprint ( _ ( "Sorry, something's wrong! Let sysadmins@cs50.harvard.edu know!" ) , "yellow" )
if excepthook . verbose :
... |
def euler_tour_dfs ( G , source = None ) :
"""adaptation of networkx dfs""" | if source is None : # produce edges for all components
nodes = G
else : # produce edges for components with source
nodes = [ source ]
yielder = [ ]
visited = set ( )
for start in nodes :
if start in visited :
continue
visited . add ( start )
stack = [ ( start , iter ( G [ start ] ) ) ]
w... |
def get_queryset ( self ) :
"""Overridde the get _ queryset method to
do some validations and build the search queryset .""" | entries = Entry . published . none ( )
if self . request . GET :
self . pattern = self . request . GET . get ( 'pattern' , '' )
if len ( self . pattern ) < 3 :
self . error = _ ( 'The pattern is too short' )
else :
entries = Entry . published . search ( self . pattern )
else :
self . err... |
def matched ( self , key , regex , ignore_case = False , multi_line = False ) :
"""增加查询条件 , 限制查询结果对象指定字段满足指定的正则表达式 。
: param key : 查询条件字段名
: param regex : 查询正则表达式
: param ignore _ case : 查询是否忽略大小写 , 默认不忽略
: param multi _ line : 查询是否匹配多行 , 默认不匹配
: rtype : Query""" | if not isinstance ( regex , six . string_types ) :
raise TypeError ( 'matched only accept str or unicode' )
self . _add_condition ( key , '$regex' , regex )
modifiers = ''
if ignore_case :
modifiers += 'i'
if multi_line :
modifiers += 'm'
if modifiers :
self . _add_condition ( key , '$options' , modifie... |
def _input_as_paths ( self , data ) :
"""Return data as a space delimited string with each path quoted
data : paths or filenames , most likely as a list of
strings""" | return self . _command_delimiter . join ( map ( str , map ( self . _input_as_path , data ) ) ) |
def _handle_adapter ( self , app ) :
"""Handle storage _ adapter configuration
: param app : Flask application""" | if 'IMAGINE_ADAPTER' in app . config and 'name' in app . config [ 'IMAGINE_ADAPTER' ] and app . config [ 'IMAGINE_ADAPTER' ] [ 'name' ] in self . _adapters . keys ( ) :
self . _adapter = self . _adapters [ app . config [ 'IMAGINE_ADAPTER' ] [ 'name' ] ] ( ** app . config [ 'IMAGINE_ADAPTER' ] )
else :
raise Val... |
def add_dependency ( self , from_task_name , to_task_name ) :
"""Add a dependency between two tasks .""" | logger . debug ( 'Adding dependency from {0} to {1}' . format ( from_task_name , to_task_name ) )
if not self . state . allow_change_graph :
raise DagobahError ( "job's graph is immutable in its current state: %s" % self . state . status )
self . add_edge ( from_task_name , to_task_name )
self . commit ( ) |
def read_busiest_date ( path : str ) -> Tuple [ datetime . date , FrozenSet [ str ] ] :
"""Find the earliest date with the most trips""" | feed = load_raw_feed ( path )
return _busiest_date ( feed ) |
def _process_output ( self , node , ** kwargs ) :
"""Processes an output node , which will contain things like ` Name ` and ` TemplateData ` nodes .""" | for n in node . nodes :
self . _process_node ( n , ** kwargs ) |
def require_app ( app_name , api_style = False ) :
"""Request the application to be automatically loaded .
If this is used for " api " style modules , which is imported by a client
application , set api _ style = True .
If this is used for client application module , set api _ style = False .""" | iterable = ( inspect . getmodule ( frame [ 0 ] ) for frame in inspect . stack ( ) )
modules = [ module for module in iterable if module is not None ]
if api_style :
m = modules [ 2 ]
# skip a frame for " api " module
else :
m = modules [ 1 ]
m . _REQUIRED_APP = getattr ( m , '_REQUIRED_APP' , [ ] )
m . _REQ... |
def list_runs ( self , project , entity = None ) :
"""Lists runs in W & B scoped by project .
Args :
project ( str ) : The project to scope the runs to
entity ( str , optional ) : The entity to scope this project to . Defaults to public models
Returns :
[ { " id " , name " , " description " } ]""" | query = gql ( '''
query Buckets($model: String!, $entity: String!) {
model(name: $model, entityName: $entity) {
buckets(first: 10) {
edges {
node {
id
name
... |
def exec_function ( ast , globals_map ) :
"""Execute a python code object in the given environment .
Args :
globals _ map : Dictionary to use as the globals context .
Returns :
locals _ map : Dictionary of locals from the environment after execution .""" | locals_map = globals_map
exec ast in globals_map , locals_map
return locals_map |
def fetch_credential ( self , credential = None , profile = None ) :
"""Fetch credential from credentials file .
Args :
credential ( str ) : Credential to fetch .
profile ( str ) : Credentials profile . Defaults to ` ` ' default ' ` ` .
Returns :
str , None : Fetched credential or ` ` None ` ` .""" | q = self . db . get ( self . query . profile == profile )
if q is not None :
return q . get ( credential ) |
def _execute_tasks ( self , * , input_args , out_degs , monitor ) :
"""Executes tasks comprising the workflow in the predetermined order .
: param input _ args : External input arguments to the workflow .
: type input _ args : Dict
: param out _ degs : Dictionary mapping vertices ( task IDs ) to their out - d... | done_tasks = set ( )
intermediate_results = { }
for dep in self . ordered_dependencies :
result = self . _execute_task ( dependency = dep , input_args = input_args , intermediate_results = intermediate_results , monitor = monitor )
intermediate_results [ dep ] = result
self . _relax_dependencies ( dependenc... |
def niceString2uri ( aUriString , namespaces = None ) :
"""From a string representing a URI possibly with the namespace qname , returns a URI instance .
gold : Citation = = > rdflib . term . URIRef ( u ' http : / / purl . org / linguistics / gold / Citation ' )
Namespaces are a list
[ ( ' xml ' , rdflib . URI... | if not namespaces :
namespaces = [ ]
for aNamespaceTuple in namespaces :
if aNamespaceTuple [ 0 ] and aUriString . find ( aNamespaceTuple [ 0 ] . __str__ ( ) + ":" ) == 0 :
aUriString_name = aUriString . split ( ":" ) [ 1 ]
return rdflib . term . URIRef ( aNamespaceTuple [ 1 ] + aUriString_name ... |
def get_node_mapping ( H ) :
"""Generates mappings between the set of nodes and integer indices ( where
every node corresponds to exactly 1 integer index ) .
: param H : the hypergraph to find the node mapping on .
: returns : dict - - for each integer index , maps the index to the node .
dict - - for each ... | node_set = H . get_node_set ( )
nodes_to_indices , indices_to_nodes = { } , { }
node_index = 0
for node in node_set :
nodes_to_indices . update ( { node : node_index } )
indices_to_nodes . update ( { node_index : node } )
node_index += 1
return indices_to_nodes , nodes_to_indices |
def file_encrypt ( blockchain_id , hostname , recipient_blockchain_id_and_hosts , input_path , output_path , passphrase = None , config_path = CONFIG_PATH , wallet_keys = None ) :
"""Encrypt a file for a set of recipients .
@ recipient _ blockchain _ id _ and _ hosts must contain a list of ( blockchain _ id , hos... | config_dir = os . path . dirname ( config_path )
# find our encryption key
key_info = file_key_lookup ( blockchain_id , 0 , hostname , config_path = config_path , wallet_keys = wallet_keys )
if 'error' in key_info :
return { 'error' : 'Failed to lookup encryption key' }
# find the encryption key IDs for the recipie... |
def export ( self , hashVal = None , hashPath = None , tags = None , galleries = None ) :
"""The export function needs to :
- Move source image to asset folder
- Rename to guid . ext
- Save thumbnail , small , and image versions""" | hashVal = hashVal or self . hash
hashPath = hashPath or self . parent / hashVal + self . ext
source = hashPath . replace ( '\\' , '/' ) . replace ( ROOT , '' )
galleries = galleries or [ ]
tags = tags or [ ]
imagefile = ROOT / source
if imagefile . ext == '.psd' :
psd = psd_tools . PSDImage . load ( imagefile )
... |
def _strptime ( self , time_str ) :
"""Convert an ISO 8601 formatted string in UTC into a
timezone - aware datetime object .""" | if time_str : # Parse UTC string into naive datetime , then add timezone
dt = datetime . strptime ( time_str , __timeformat__ )
return dt . replace ( tzinfo = UTC ( ) )
return None |
def parse_pretty_midi ( self , pm , mode = 'max' , algorithm = 'normal' , binarized = False , skip_empty_tracks = True , collect_onsets_only = False , threshold = 0 , first_beat_time = None ) :
"""Parse a : class : ` pretty _ midi . PrettyMIDI ` object . The data type of the
resulting pianorolls is automatically ... | if mode not in ( 'max' , 'sum' ) :
raise ValueError ( "`mode` must be one of {'max', 'sum'}." )
if algorithm not in ( 'strict' , 'normal' , 'custom' ) :
raise ValueError ( "`algorithm` must be one of {'normal', 'strict', " " 'custom'}." )
if algorithm == 'custom' :
if not isinstance ( first_beat_time , ( in... |
def smart_query ( query , filters = None , sort_attrs = None , schema = None ) :
"""Does magic Django - ish joins like post _ _ _ user _ _ _ name _ _ startswith = ' Bob '
( see https : / / goo . gl / jAgCyM )
Does filtering , sorting and eager loading at the same time .
And if , say , filters and sorting need... | if not filters :
filters = { }
if not sort_attrs :
sort_attrs = [ ]
if not schema :
schema = { }
# noinspection PyProtectedMember
root_cls = query . _joinpoint_zero ( ) . class_
# for example , User or Post
attrs = list ( filters . keys ( ) ) + list ( map ( lambda s : s . lstrip ( DESC_PREFIX ) , sort_attrs... |
def read_init_status ( self ) :
"""Read the initialization status of Vault .
Supported methods :
GET : / sys / init . Produces : 200 application / json
: return : The JSON response of the request .
: rtype : dict""" | api_path = '/v1/sys/init'
response = self . _adapter . get ( url = api_path , )
return response . json ( ) |
def addTransitions ( self , state , transitions ) :
"""Create a new L { TransitionTable } with all the same transitions as this
L { TransitionTable } plus a number of new transitions .
@ param state : The state for which the new transitions are defined .
@ param transitions : A L { dict } mapping inputs to ou... | table = self . _copy ( )
state = table . table . setdefault ( state , { } )
for ( input , ( output , nextState ) ) in transitions . items ( ) :
state [ input ] = Transition ( output , nextState )
return table |
def _all_keys ( self ) :
"""Return a list of all encoded key names .""" | file_keys = [ self . _filename_to_key ( fn ) for fn in self . _all_filenames ( ) ]
if self . _sync :
return set ( file_keys )
else :
return set ( file_keys + list ( self . _buffer ) ) |
def list_build_configuration_sets ( page_size = 200 , page_index = 0 , sort = "" , q = "" ) :
"""List all build configuration sets""" | data = list_build_configuration_sets_raw ( page_size , page_index , sort , q )
if data :
return utils . format_json_list ( data ) |
def _close_callback ( self ) :
"""Callback called when redis closed the connection .
The callback queue is emptied and we call each callback found
with None or with an exception object to wake up blocked client .""" | while True :
try :
callback = self . __callback_queue . popleft ( )
callback ( ConnectionError ( "closed connection" ) )
except IndexError :
break
if self . subscribed : # pubsub clients
self . _reply_list . append ( ConnectionError ( "closed connection" ) )
self . _condition . n... |
def delete_customer ( self , customer_id ) :
"""Delete a customer .""" | content = self . _fetch ( "/customer/%s" % customer_id , method = "DELETE" )
return self . _status ( content ) |
def add ( a , b , allow_overflow = False ) :
"""Adds two instances of ` Money ` .
Args :
a ( : class : ` endpoints _ management . gen . servicecontrol _ v1 _ messages . Money ` ) : one money
value
b ( : class : ` endpoints _ management . gen . servicecontrol _ v1 _ messages . Money ` ) : another
money val... | for m in ( a , b ) :
if not isinstance ( m , sc_messages . Money ) :
raise ValueError ( u'Inputs should be of type %s' % ( sc_messages . Money , ) )
if a . currencyCode != b . currencyCode :
raise ValueError ( u'Money values need the same currency to be summed' )
nano_carry , nanos_sum = _sum_nanos ( a ... |
def enable_apt_repositories ( prefix , url , version , repositories ) :
"""adds an apt repository""" | with settings ( hide ( 'warnings' , 'running' , 'stdout' ) , warn_only = False , capture = True ) :
sudo ( 'apt-add-repository "%s %s %s %s"' % ( prefix , url , version , repositories ) )
with hide ( 'running' , 'stdout' ) :
output = sudo ( "DEBIAN_FRONTEND=noninteractive /usr/bin/apt-get update" )
... |
def sid_day_index ( self , sid , day ) :
"""Parameters
sid : int
The asset identifier .
day : datetime64 - like
Midnight of the day for which data is requested .
Returns
int
Index into the data tape for the given sid and day .
Raises a NoDataOnDate exception if the given day and sid is before
or a... | try :
day_loc = self . sessions . get_loc ( day )
except Exception :
raise NoDataOnDate ( "day={0} is outside of calendar={1}" . format ( day , self . sessions ) )
offset = day_loc - self . _calendar_offsets [ sid ]
if offset < 0 :
raise NoDataBeforeDate ( "No data on or before day={0} for sid={1}" . format... |
def to_obj ( self , wd = False , pack = False , relpath = None ) :
"""Return the step as an dict that can be written to a yaml file .
Returns :
dict : yaml representation of the step .""" | obj = CommentedMap ( )
if pack :
obj [ 'run' ] = self . orig
elif relpath is not None :
if self . from_url :
obj [ 'run' ] = self . run
else :
obj [ 'run' ] = os . path . relpath ( self . run , relpath )
elif wd :
if self . from_url :
obj [ 'run' ] = self . run
else :
... |
def error_text ( error , context = "client" ) :
"""Returns a textual explanation of a given error number
: param error : an error integer
: param context : server , client or partner
: returns : the error string""" | assert context in ( "client" , "server" , "partner" )
logger . debug ( "error text for %s" % hex ( error ) )
len_ = 1024
text_type = c_char * len_
text = text_type ( )
library = load_library ( )
if context == "client" :
library . Cli_ErrorText ( error , text , len_ )
elif context == "server" :
library . Srv_Err... |
def get_page ( self , project , wiki_identifier , path = None , recursion_level = None , version_descriptor = None , include_content = None ) :
"""GetPage .
Gets metadata or content of the wiki page for the provided path . Content negotiation is done based on the ` Accept ` header sent in the request .
: param ... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
if wiki_identifier is not None :
route_values [ 'wikiIdentifier' ] = self . _serialize . url ( 'wiki_identifier' , wiki_identifier , 'str' )
query_parameters = { }
if path is not None... |
def iso8601 ( self ) :
"""Returns an ISO 8601 representation of the MayaDT .""" | # Get a timezone - naive datetime .
dt = self . datetime ( naive = True )
return '{}Z' . format ( dt . isoformat ( ) ) |
def schema ( self ) :
"""The nested Schema object .
. . versionchanged : : 1.0.0
Renamed from ` serializer ` to ` schema `""" | if not self . __schema : # Inherit context from parent .
context = getattr ( self . parent , 'context' , { } )
if isinstance ( self . nested , SchemaABC ) :
self . __schema = self . nested
self . __schema . context . update ( context )
else :
if isinstance ( self . nested , type ) an... |
def __search_obj ( self , obj , item , parent , parents_ids = frozenset ( { } ) , is_namedtuple = False ) :
"""Search objects""" | found = False
if obj == item :
found = True
# We report the match but also continue inside the match to see if there are
# furthur matches inside the ` looped ` object .
self . __report ( report_key = 'matched_values' , key = parent , value = obj )
try :
if is_namedtuple :
obj = obj . _asdic... |
def when_ends ( self , timeformat = 'unix' ) :
"""Returns the GMT time of the end of the forecast coverage , which is the
time of the most recent * Weather * item in the forecast
: param timeformat : the format for the time value . May be :
' * unix * ' ( default ) for UNIX time
' * iso * ' for ISO8601 - fo... | end_coverage = max ( [ item . get_reference_time ( ) for item in self . _forecast ] )
return timeformatutils . timeformat ( end_coverage , timeformat ) |
def add_issue_attribute ( self , name , ** attrs ) :
"""Add a new Issue attribute and return a : class : ` IssueAttribute ` object .
: param name : name of the : class : ` IssueAttribute `
: param attrs : optional attributes for : class : ` IssueAttribute `""" | return IssueAttributes ( self . requester ) . create ( self . id , name , ** attrs ) |
def remove_unnecessary_stuff ( self ) :
"""Remove unnecessary functions and data
: return : None""" | glibc_functions_blacklist = { '_start' , '_init' , '_fini' , '__gmon_start__' , '__do_global_dtors_aux' , 'frame_dummy' , 'atexit' , 'deregister_tm_clones' , 'register_tm_clones' , '__x86.get_pc_thunk.bx' , '__libc_csu_init' , '__libc_csu_fini' , }
glibc_data_blacklist = { '__TMC_END__' , '_GLOBAL_OFFSET_TABLE_' , '__J... |
def detect_metadata_url_scheme ( url ) :
"""detect whether a url is a Service type that HHypermap supports""" | scheme = None
url_lower = url . lower ( )
if any ( x in url_lower for x in [ 'wms' , 'service=wms' ] ) :
scheme = 'OGC:WMS'
if any ( x in url_lower for x in [ 'wmts' , 'service=wmts' ] ) :
scheme = 'OGC:WMTS'
elif all ( x in url for x in [ '/MapServer' , 'f=json' ] ) :
scheme = 'ESRI:ArcGIS:MapServer'
elif ... |
def advance ( self , blocksize , timeout = 10 ) :
"""Advanced buffer blocksize seconds .
Add blocksize seconds more to the buffer , push blocksize seconds
from the beginning .
Parameters
blocksize : int
The number of seconds to attempt to read from the channel
Returns
status : boolean
Returns True i... | ts = super ( StrainBuffer , self ) . attempt_advance ( blocksize , timeout = timeout )
self . blocksize = blocksize
# We have given up so there is no time series
if ts is None :
logging . info ( "%s frame is late, giving up" , self . detector )
self . null_advance_strain ( blocksize )
if self . state :
... |
def delete_node ( manager , handle_id ) :
"""Deletes the node and all its relationships .
: param manager : Neo4jDBSessionManager
: param handle _ id : Unique id
: rtype : bool""" | q = """
MATCH (n:Node {handle_id: {handle_id}})
OPTIONAL MATCH (n)-[r]-()
DELETE n,r
"""
with manager . session as s :
s . run ( q , { 'handle_id' : handle_id } )
return True |
def nstar ( self , image , star_groups ) :
"""Fit , as appropriate , a compound or single model to the given
` ` star _ groups ` ` . Groups are fitted sequentially from the
smallest to the biggest . In each iteration , ` ` image ` ` is
subtracted by the previous fitted group .
Parameters
image : numpy . n... | result_tab = Table ( )
for param_tab_name in self . _pars_to_output . keys ( ) :
result_tab . add_column ( Column ( name = param_tab_name ) )
unc_tab = Table ( )
for param , isfixed in self . psf_model . fixed . items ( ) :
if not isfixed :
unc_tab . add_column ( Column ( name = param + "_unc" ) )
y , x... |
def subscribe ( object_type : str , subscriber : str , callback_handler : Callable = None ) -> EventQueue :
"""Subscribe to the specified object type .
Returns an EventQueue object which can be used to query events
associated with the object type for this subscriber .
Args :
object _ type ( str ) : Object t... | key = _keys . subscribers ( object_type )
DB . remove_from_list ( key , subscriber )
DB . append_to_list ( key , subscriber )
return EventQueue ( object_type , subscriber , callback_handler ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.