signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def maybe_automatically_publish_drafts_on_save ( sender , instance , ** kwargs ) :
"""If automatic publishing is enabled , immediately publish a draft copy after
it has been saved .""" | # Skip processing if auto - publishing is not enabled
if not is_automatic_publishing_enabled ( sender ) :
return
# Skip missing or unpublishable instances
if not instance or not hasattr ( instance , 'publishing_linked' ) :
return
# Ignore saves of published copies
if instance . is_published :
return
# Ignor... |
def invalidate_files ( self , direct_filenames ) :
"""Invalidates the given filenames in an internal product Graph instance .""" | invalidated = self . _scheduler . invalidate_files ( direct_filenames )
self . _maybe_visualize ( )
return invalidated |
def pair ( self ) :
"""return ( container _ port , ( ip , host _ port ) ) or ( container _ port , host _ port )""" | if self . ip is NotSpecified :
if self . ip is NotSpecified :
second = self . host_port
else :
second = ( self . ip , )
else :
second = ( self . ip , self . host_port )
return self . container_port . port_str , second |
def build_etag ( self , response , include_etag = True , ** kwargs ) :
"""Add an etag to the response body .
Uses spooky where possible because it is empirically fast and well - regarded .
See : http : / / blog . reverberate . org / 2012/01 / state - of - hash - functions - 2012 . html""" | if not include_etag :
return
if not spooky : # use built - in md5
response . add_etag ( )
return
# use spooky
response . headers [ "ETag" ] = quote_etag ( hexlify ( spooky . hash128 ( response . get_data ( ) , ) . to_bytes ( 16 , "little" ) , ) . decode ( "utf-8" ) , ) |
def _put_many ( self , items ) :
'''store items in sqlite database''' | for item in items :
if not isinstance ( item , self . _item_class ) :
raise RuntimeError ( 'Items mismatch for %s and %s' % ( self . _item_class , type ( item ) ) )
self . _put_one ( item ) |
def array2bytes ( arr , bytes_type = bytes ) :
"""Wraps NumPy ' s save function to return bytes .
We use : func : ` numpy . save ` rather than : meth : ` numpy . ndarray . tobytes ` because
it encodes endianness and order .
Args :
arr ( : obj : ` numpy . ndarray ` ) :
Array to be saved .
bytes _ type ( ... | bio = io . BytesIO ( )
np . save ( bio , arr , allow_pickle = False )
return bytes_type ( bio . getvalue ( ) ) |
def QueryItemsChangeFeed ( self , collection_link , options = None ) :
"""Queries documents change feed in a collection .
: param str collection _ link :
The link to the document collection .
: param dict options :
The request options for the request .
options may also specify partition key range id .
:... | partition_key_range_id = None
if options is not None and 'partitionKeyRangeId' in options :
partition_key_range_id = options [ 'partitionKeyRangeId' ]
return self . _QueryChangeFeed ( collection_link , "Documents" , options , partition_key_range_id ) |
def avg_rate ( self ) :
"""Average receiving rate in MB / s over the entire run .
If the result is not from a success run , this property is None .""" | if not self . _has_data or 'sum' not in self . result [ 'end' ] :
return None
bps = self . result [ 'end' ] [ 'sum' ] [ 'bits_per_second' ]
return bps / 8 / 1024 / 1024 |
def _request_login ( self , login , password ) :
"""Sends Login request""" | return self . _request_internal ( "Login" , login = login , password = password ) |
def build_url ( self ) :
"""Construct URL
e . g . , : http : / / site2 . enigmabridge . com : 12000/1.0 / testAPI / GetAllAPIKeys / abcdef012345
: return :""" | url = "%s/1.0/%s/%s/%s" % ( self . request . endpoint . get_url ( ) , self . request . api_object , self . request . api_method , to_hex ( self . request . nonce ) )
return url |
def set_options_from_dict ( self , data_dict , filename = None ) :
"""Load options from a dictionary .
: param dict data _ dict : Dictionary with the options to load .
: param str filename : If provided , assume that non - absolute
paths provided are in reference to the file .""" | if filename is not None :
filename = os . path . dirname ( filename )
for k in data_dict :
if not isinstance ( data_dict [ k ] , dict ) :
raise ValueError ( "The input data has to be a dict of dict" )
for sk in data_dict [ k ] :
if self . gc [ ( self . gc [ "k1" ] == k ) & ( self . gc [ "k2"... |
def get_lightcurve ( data , copy = False , name = None , predictor = None , periodogram = Lomb_Scargle , sigma_clipping = mad , scoring = 'r2' , scoring_cv = 3 , scoring_processes = 1 , period = None , min_period = 0.2 , max_period = 32 , coarse_precision = 1e-5 , fine_precision = 1e-9 , period_processes = 1 , sigma = ... | data = numpy . ma . array ( data , copy = copy )
phases = numpy . linspace ( 0 , 1 , n_phases , endpoint = False )
# TODO # # #
# Replace dA _ 0 with error matrix dA
if predictor is None :
predictor = make_predictor ( scoring = scoring , scoring_cv = scoring_cv )
while True :
signal = get_signal ( data )
if... |
def check_bulkhead ( self , source , dependencies , slow_dest , rate ) :
"""Asserts bulkheads by ensuring that the rate of requests to other dests is kept when slow _ dest is slow
: param source the source service name
: param dependencies list of dependency names of source
: param slow _ dest the name of the... | # Remove slow dest
dependencies . remove ( slow_dest )
s = str ( float ( 1 ) / float ( rate ) )
max_spacing = _parse_duration ( s + 's' )
for dest in dependencies :
data = self . _es . search ( body = { "size" : max_query_results , "query" : { "filtered" : { "query" : { "match_all" : { } } , "filter" : { "bool" : {... |
def extract_tables ( sql ) :
"""Extract the table names from an SQL statment .
Returns a list of ( schema , table , alias ) tuples""" | parsed = sqlparse . parse ( sql )
if not parsed :
return [ ]
# INSERT statements must stop looking for tables at the sign of first
# Punctuation . eg : INSERT INTO abc ( col1 , col2 ) VALUES ( 1 , 2)
# abc is the table name , but if we don ' t stop at the first lparen , then
# we ' ll identify abc , col1 and col2 a... |
def run_on_ui_thread ( f ) :
'''Decorator to create automatically a : class : ` Runnable ` object with the
function . The function will be delayed and call into the Activity thread .''' | def f2 ( * args , ** kwargs ) :
Runnable ( f ) ( * args , ** kwargs )
return f2 |
def major_rise_per_monomer ( self ) :
"""Rise along super - helical axis per monomer .""" | return numpy . cos ( numpy . deg2rad ( self . curve . alpha ) ) * self . minor_rise_per_residue |
def count_variants_function_builder ( function_name , filterable_variant_function = None ) :
"""Creates a function that counts variants that are filtered by the provided filterable _ variant _ function .
The filterable _ variant _ function is a function that takes a filterable _ variant and returns True or False ... | @ count_function
def count ( row , cohort , filter_fn , normalized_per_mb , ** kwargs ) :
def count_filter_fn ( filterable_variant , ** kwargs ) :
assert filter_fn is not None , "filter_fn should never be None, but it is."
return ( ( filterable_variant_function ( filterable_variant ) if filterable_v... |
def update_task_positions_obj ( self , positions_obj_id , revision , values ) :
'''Updates the ordering of tasks in the positions object with the given ID to the ordering in the given values .
See https : / / developer . wunderlist . com / documentation / endpoints / positions for more info
Return :
The updat... | return positions_endpoints . update_task_positions_obj ( self , positions_obj_id , revision , values ) |
def to_bool ( value ) :
"""Converts human boolean - like values to Python boolean .
Falls back to : class : ` bool ` when ` ` value ` ` is not recognized .
: param value : the value to convert
: returns : ` ` True ` ` if value is truthy , ` ` False ` ` otherwise
: rtype : bool""" | cases = { '0' : False , 'false' : False , 'no' : False , '1' : True , 'true' : True , 'yes' : True , }
value = value . lower ( ) if isinstance ( value , basestring ) else value
return cases . get ( value , bool ( value ) ) |
def block_range ( self , lineno ) :
"""Get a range from the given line number to where this node ends .
: param lineno : The line number to start the range at .
: type lineno : int
: returns : The range of line numbers that this node belongs to ,
starting at the given line number .
: rtype : tuple ( int ,... | if lineno == self . body [ 0 ] . fromlineno :
return lineno , lineno
if lineno <= self . body [ - 1 ] . tolineno :
return lineno , self . body [ - 1 ] . tolineno
return self . _elsed_block_range ( lineno , self . orelse , self . body [ 0 ] . fromlineno - 1 ) |
def replace ( self , col : str , searchval : str , replaceval : str ) :
"""Replace a value in a column in the main dataframe
: param col : column name
: type col : str
: param searchval : value to replace
: type searchval : str
: param replaceval : new value
: type replaceval : str
: example : ` ` ds ... | try :
self . df [ col ] = self . df [ col ] . replace ( searchval , replaceval )
except Exception as e :
self . err ( e , "Can not replace value in column" ) |
def out_of_bag_samples ( self ) :
"""Returns the out - of - bag samples list , inside a wrapper to keep track
of modifications .""" | # TODO : replace with more a generic pass - through wrapper ?
class O ( object ) :
def __init__ ( self , tree ) :
self . tree = tree
def __len__ ( self ) :
return len ( self . tree . _out_of_bag_samples )
def append ( self , v ) :
self . tree . _out_of_bag_mae_clean = False
r... |
def create ( cls , name , protocol_number , protocol_agent = None , comment = None ) :
"""Create the IP Service
: param str name : name of ip - service
: param int protocol _ number : ip proto number for this service
: param str , ProtocolAgent protocol _ agent : optional protocol agent for
this service
:... | json = { 'name' : name , 'protocol_number' : protocol_number , 'protocol_agent_ref' : element_resolver ( protocol_agent ) or None , 'comment' : comment }
return ElementCreator ( cls , json ) |
def addImgStream ( self , img ) :
'''add images using a continous stream
- stop when max number of images is reached''' | if self . findCount > self . max_images :
raise EnoughImages ( 'have enough images' )
return self . addImg ( img ) |
def check_action_type ( self , value ) :
"""Set the value for the CheckActionType , validating input""" | if value is not None :
if not isinstance ( value , ActionType ) :
raise AttributeError ( "Invalid check action %s" % value )
self . _check_action_type = value |
def finalize ( self ) :
'''Release all connections contained in the pool .
. . note : : This should be called to cleanly shutdown the pool , i . e .
on process exit .''' | self . _condition . acquire ( )
try :
if self . _nconnections != len ( self . _pool ) :
warnings . warn ( 'finalize() called with unreleased connections' , RuntimeWarning , 2 )
while self . _pool :
self . _close ( self . _pool . pop ( ) . connection )
self . _nconnections = 0
finally :
s... |
def get_arthur_params_from_url ( cls , url ) : # In the url the org and the repository are included
params = url . split ( )
"""Get the arthur params given a URL for the data source""" | params = { "owner" : params [ 0 ] , "repository" : params [ 1 ] }
return params |
def create_time_step ( cls , observation = None , done = False , raw_reward = None , processed_reward = None , action = None ) :
"""Creates a TimeStep with both rewards and actions as optional .""" | return cls ( observation , done , raw_reward , processed_reward , action ) |
async def disconnect ( self , expected = True ) :
"""Disconnect from server .""" | if self . connected : # Unschedule ping checker .
if self . _ping_checker_handle :
self . _ping_checker_handle . cancel ( )
# Schedule disconnect .
await self . _disconnect ( expected ) |
def full ( shape , val , ctx = None , dtype = mx_real_t , out = None ) :
"""Returns a new array of given shape and type , filled with the given value ` val ` .
Parameters
shape : int or tuple of int
The shape of the new array .
val : scalar
Fill value .
ctx : Context , optional
Device context ( defaul... | out = empty ( shape , ctx , dtype ) if out is None else out
out [ : ] = val
return out |
def console_put_char_ex ( con : tcod . console . Console , x : int , y : int , c : Union [ int , str ] , fore : Tuple [ int , int , int ] , back : Tuple [ int , int , int ] , ) -> None :
"""Draw the character c at x , y using the colors fore and back .
Args :
con ( Console ) : Any Console instance .
x ( int )... | lib . TCOD_console_put_char_ex ( _console ( con ) , x , y , _int ( c ) , fore , back ) |
def Sens_t ( poly , dist , ** kws ) :
"""Variance - based decomposition
AKA Sobol ' indices
Total effect sensitivity index
Args :
poly ( Poly ) :
Polynomial to find first order Sobol indices on .
dist ( Dist ) :
The distributions of the input used in ` ` poly ` ` .
Returns :
( numpy . ndarray ) : ... | dim = len ( dist )
if poly . dim < dim :
poly = chaospy . poly . setdim ( poly , len ( dist ) )
zero = [ 1 ] * dim
out = numpy . zeros ( ( dim , ) + poly . shape , dtype = float )
V = Var ( poly , dist , ** kws )
for i in range ( dim ) :
zero [ i ] = 0
out [ i ] = ( ( V - Var ( E_cond ( poly , zero , dist ,... |
def complete ( self ) :
"""Custom completion check that invokes the task ' s * workflow _ complete * if it is callable , or
just does the default completion check otherwise .""" | if callable ( self . task . workflow_complete ) :
return self . task . workflow_complete ( )
else :
return super ( BaseWorkflowProxy , self ) . complete ( ) |
def get_logger ( self , logfilename = None ) :
"""Setup logger .
Allow outputting to both a log file and console at the
same time .""" | if self . _logger is None :
self . _logger = logging . getLogger ( 'invenio_upgrader' )
self . _logger . setLevel ( logging . INFO )
if logfilename :
fh = logging . FileHandler ( logfilename )
fh . setLevel ( logging . INFO )
fh . setFormatter ( self . _logger_file_fmtter )
s... |
def findLowerElevation ( self , source , world ) :
'''Try to find a lower elevation with in a range of an increasing
circle ' s radius and try to find the best path and return it''' | x , y = source
currentRadius = 1
maxRadius = 40
lowestElevation = world . layers [ 'elevation' ] . data [ y , x ]
destination = [ ]
notFound = True
isWrapped = False
wrapped = [ ]
while notFound and currentRadius <= maxRadius :
for cx in range ( - currentRadius , currentRadius + 1 ) :
for cy in range ( - cu... |
def _get_prompt ( onto = "" , entity = "" ) :
"""Global util that changes the prompt contextually
: return : [ Ontospy ] > ( cidoc _ crm _ v5.0 . . . ) > ( class : E1 . CRM _ Entity ) >""" | base_text , onto_text , entity_text = "" , "" , ""
base_color , onto_color , entity_color = Fore . RED + Style . BRIGHT , Fore . BLACK + Style . DIM , Fore . BLACK
if not onto and not entity :
base_text = base_color + '[Ontospy]' + Style . RESET_ALL
if onto and not entity :
_tmp = onto_color + '(%s)' % onto
... |
def _get_ipv6addrs ( self ) :
"""Returns the IPv6 addresses associated with this NIC . If no IPv6
addresses are used , empty dict is returned .""" | addrs = self . _get_addrs ( )
ipv6addrs = addrs . get ( netifaces . AF_INET6 )
if not ipv6addrs :
return { }
return ipv6addrs [ 0 ] |
def _aws_model_ref_from_swagger_ref ( self , r ) :
'''Helper function to reference models created on aws apigw''' | model_name = r . split ( '/' ) [ - 1 ]
return 'https://apigateway.amazonaws.com/restapis/{0}/models/{1}' . format ( self . restApiId , model_name ) |
def _get_pastel_colour ( self , lighten = 127 ) :
"""Create a pastel colour hex colour string""" | def r ( ) :
return random . randint ( 0 , 128 ) + lighten
return r ( ) , r ( ) , r ( ) |
def compress ( in_bam , data ) :
"""Compress a BAM file to CRAM , providing indexed CRAM file .
Does 8 bin compression of quality score and read name removal
using bamUtils squeeze if ` cram ` specified :
http : / / genome . sph . umich . edu / wiki / BamUtil : _ squeeze
Otherwise does ` cram - lossless ` w... | out_dir = utils . safe_makedir ( os . path . join ( dd . get_work_dir ( data ) , "archive" ) )
out_file = os . path . join ( out_dir , "%s.cram" % os . path . splitext ( os . path . basename ( in_bam ) ) [ 0 ] )
cores = dd . get_num_cores ( data )
ref_file = dd . get_ref_file ( data )
if not utils . file_exists ( out_f... |
def get_gradebook_hierarchy_session ( self , proxy ) :
"""Gets the session traversing gradebook hierarchies .
arg : proxy ( osid . proxy . Proxy ) : a proxy
return : ( osid . grading . GradebookHierarchySession ) - a
` ` GradebookHierarchySession ` `
raise : NullArgument - ` ` proxy ` ` is ` ` null ` `
ra... | if not self . supports_gradebook_hierarchy ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . GradebookHierarchySession ( proxy = proxy , runtime = self . _runtime ) |
def parse_rrule ( component , tz = UTC ) :
"""Extract a dateutil . rrule object from an icalendar component . Also includes
the component ' s dtstart and exdate properties . The rdate and exrule
properties are not yet supported .
: param component : icalendar component
: param tz : timezone for DST handling... | if component . get ( 'rrule' ) : # component [ ' rrule ' ] can be both a scalar and a list
rrules = component [ 'rrule' ]
if not isinstance ( rrules , list ) :
rrules = [ rrules ]
# Since DTSTART are always made timezone aware , UNTIL with no tzinfo
# must be converted to UTC .
for rule in r... |
def is_dry_run ( self , override : bool = None ) -> bool :
"""Returns whether current task is a dry _ run or not .""" | return override if override is not None else self . nornir . data . dry_run |
def check_status ( self ) :
"""Check the output of the summary route until
the experiment is complete , then we can stop monitoring Heroku
subprocess output .""" | self . out . log ( "Recruitment is complete. Waiting for experiment completion..." )
base_url = get_base_url ( )
status_url = base_url + "/summary"
while not self . complete :
time . sleep ( 10 )
try :
resp = requests . get ( status_url )
exp_data = resp . json ( )
except ( ValueError , requ... |
def read_file ( rel_path , paths = None , raw = False , as_list = False , as_iter = False , * args , ** kwargs ) :
'''find a file that lives somewhere within a set of paths and
return its contents . Default paths include ' static _ dir ' ''' | if not rel_path :
raise ValueError ( "rel_path can not be null!" )
paths = str2list ( paths )
# try looking the file up in a directory called static relative
# to SRC _ DIR , eg assuming metrique git repo is in ~ / metrique
# we ' d look in ~ / metrique / static
paths . extend ( [ STATIC_DIR , os . path . join ( SR... |
def runlist_view ( name , ** kwargs ) :
"""Show configuration content for a specified runlist .""" | ctx = Context ( ** kwargs )
ctx . execute_action ( 'runlist:view' , ** { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name } ) |
def get_composition_repository_assignment_session ( self , proxy ) :
"""Gets the session for assigning composition to repository mappings .
arg : proxy ( osid . proxy . Proxy ) : a proxy
return : ( osid . repository . CompositionRepositoryAssignmentSession )
- a ` ` CompositionRepositoryAssignmentSession ` ` ... | if not self . supports_composition_repository_assignment ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . CompositionRepositoryAssignmentSession ( proxy = proxy , runtime = self . _runtime ) |
def drawItem ( self , item , painter , option ) :
"""Draws the inputed item as a bar graph .
: param item | < XChartDatasetItem >
painter | < QPainter >
option | < QStyleOptionGraphicsItem >""" | dataset = item . dataset ( )
painter . save ( )
painter . setRenderHint ( painter . Antialiasing )
pen = QPen ( dataset . color ( ) )
pen . setWidth ( 0.75 )
painter . setPen ( pen )
for path in item . buildData ( 'subpaths' , [ ] ) :
gradient = QLinearGradient ( )
clr = QColor ( dataset . color ( ) )
clr .... |
def build_vcf_deletion ( x , genome_2bit ) :
"""Provide representation of deletion from BedPE breakpoints .""" | base1 = genome_2bit [ x . chrom1 ] . get ( x . start1 , x . start1 + 1 ) . upper ( )
id1 = "hydra{0}" . format ( x . name )
return VcfLine ( x . chrom1 , x . start1 , id1 , base1 , "<DEL>" , _vcf_single_end_info ( x , "DEL" , True ) ) |
def submit ( self , data , runtime_dir , argv ) :
"""Run process .
For details , see
: meth : ` ~ resolwe . flow . managers . workload _ connectors . base . BaseConnector . submit ` .""" | queue = 'ordinary'
if data . process . scheduling_class == Process . SCHEDULING_CLASS_INTERACTIVE :
queue = 'hipri'
logger . debug ( __ ( "Connector '{}' running for Data with id {} ({}) in celery queue {}, EAGER is {}." , self . __class__ . __module__ , data . id , repr ( argv ) , queue , getattr ( settings , 'CEL... |
def output ( self , _filename ) :
"""_ filename is not used
Args :
_ filename ( string )""" | txt = ""
for c in self . contracts :
( name , _inheritance , _var , func_summaries , _modif_summaries ) = c . get_summary ( )
txt += blue ( "\n+ Contract %s\n" % name )
# ( c _ name , f _ name , visi , _ , _ , _ , _ , _ ) in func _ summaries
public = [ ( elem [ 0 ] , ( elem [ 1 ] , elem [ 2 ] ) ) for el... |
def validatePushCData ( self , data , len ) :
"""check the CData parsed for validation in the current stack""" | ret = libxml2mod . xmlValidatePushCData ( self . _o , data , len )
return ret |
def _pkcs1imify ( self , data ) :
"""turn a 20 - byte SHA1 hash into a blob of data as large as the key ' s N ,
using PKCS1 ' s \" emsa - pkcs1 - v1_5 \" encoding . totally bizarre .""" | size = len ( util . deflate_long ( self . n , 0 ) )
filler = max_byte * ( size - len ( SHA1_DIGESTINFO ) - len ( data ) - 3 )
return zero_byte + one_byte + filler + zero_byte + SHA1_DIGESTINFO + data |
def order_expr ( cls_or_alias , * columns ) :
"""Forms expressions like [ desc ( User . first _ name ) , asc ( User . phone ) ]
from list like [ ' - first _ name ' , ' phone ' ]
Example for 1 column :
db . query ( User ) . order _ by ( * User . order _ expr ( ' - first _ name ' ) )
# will compile to ORDER B... | if isinstance ( cls_or_alias , AliasedClass ) :
mapper , cls = cls_or_alias , inspect ( cls_or_alias ) . mapper . class_
else :
mapper = cls = cls_or_alias
expressions = [ ]
for attr in columns :
fn , attr = ( desc , attr [ 1 : ] ) if attr . startswith ( DESC_PREFIX ) else ( asc , attr )
if attr not in ... |
def remove ( self , decoration ) :
"""Removes a text decoration from the editor .
: param decoration : Text decoration to remove
: type decoration : spyder . api . TextDecoration""" | try :
self . _decorations . remove ( decoration )
self . update ( )
return True
except ValueError :
return False
except RuntimeError : # This is needed to fix issue 9173
pass |
def get_json ( self , instance = True , origin = 'openconfig' ) :
'''get _ json
High - level api : get _ json returns json _ val of the config node .
Parameters
instance : ` bool `
True if only one instance of list or leaf - list is required . False if
all instances of list or leaf - list are needed .
R... | def get_json_instance ( node ) :
pk = Parker ( xml_fromstring = _fromstring , dict_type = OrderedDict )
default_ns = { }
for item in node . iter ( ) :
parents = [ p for p in node . iter ( ) if item in p ]
if parents and id ( parents [ 0 ] ) in default_ns :
ns , tag = self . devic... |
def set_rate_limiting ( rate_limit , min_wait = timedelta ( milliseconds = 50 ) ) :
'''Enable or disable rate limiting on requests to the Mediawiki servers .
If rate limiting is not enabled , under some circumstances ( depending on
load on Wikipedia , the number of requests you and other ` wikipedia ` users
a... | global RATE_LIMIT
global RATE_LIMIT_MIN_WAIT
global RATE_LIMIT_LAST_CALL
RATE_LIMIT = rate_limit
if not rate_limit :
RATE_LIMIT_MIN_WAIT = None
else :
RATE_LIMIT_MIN_WAIT = min_wait
RATE_LIMIT_LAST_CALL = None |
def result ( self , raise_exception = True ) :
"""Waits until TransferFuture is done and returns the result
If the TransferFuture succeeded , it will return the result . If the
TransferFuture failed , it will raise the exception associated to the
failure .""" | _status = None
_exception = None
self . _done_event . wait ( MAXINT )
# first wait for session global
if self . is_failed ( ) : # global exception set
_exception = self . _exception
_status = enumAsperaControllerStatus . FAILED
else :
for _session in self . _sessions . values ( ) :
_status_tmp , _ex... |
def lookup_mac ( self , ip ) :
"""Look up a lease object with given ip address and return the
associated mac address .
@ type ip : str
@ rtype : str or None
@ raises ValueError :
@ raises OmapiError :
@ raises OmapiErrorNotFound : if no lease object with the given ip could be found
@ raises OmapiError... | res = self . lookup_by_lease ( ip = ip )
try :
return res [ "hardware-address" ]
except KeyError :
raise OmapiErrorAttributeNotFound ( ) |
def filterlet ( function = bool , iterable = None ) :
"""Filter chunks of data from an iterable or a chain
: param function : callable selecting valid elements
: type function : callable
: param iterable : object providing chunks via iteration
: type iterable : iterable or None
For any chunk in ` ` iterab... | if iterable is None :
return _filterlet ( function = function )
else :
return iterlet ( elem for elem in iterable if function ( elem ) ) |
def handle_register_or_upload ( post_data , files , user , repository ) :
"""Process a ` register ` or ` upload ` comment issued via distutils .
This method is called with the authenticated user .""" | name = post_data . get ( 'name' )
version = post_data . get ( 'version' )
if settings . LOCALSHOP_VERSIONING_TYPE :
scheme = get_versio_versioning_scheme ( settings . LOCALSHOP_VERSIONING_TYPE )
try :
Version ( version , scheme = scheme )
except AttributeError :
response = HttpResponseBadReq... |
def make_stmt_from_sort_key ( key , verb ) :
"""Make a Statement from the sort key .
Specifically , the sort key used by ` group _ and _ sort _ statements ` .""" | def make_agent ( name ) :
if name == 'None' or name is None :
return None
return Agent ( name )
StmtClass = get_statement_by_name ( verb )
inps = list ( key [ 1 ] )
if verb == 'Complex' :
stmt = StmtClass ( [ make_agent ( name ) for name in inps ] )
elif verb == 'Conversion' :
stmt = StmtClass (... |
def pixels_farther_than ( self , depth_im , filter_equal_depth = False ) :
"""Returns the pixels that are farther away
than those in the corresponding depth image .
Parameters
depth _ im : : obj : ` DepthImage `
depth image to query replacement with
filter _ equal _ depth : bool
whether or not to mark d... | # take closest pixel
if filter_equal_depth :
farther_px = np . where ( ( self . data > depth_im . data ) & ( np . isfinite ( depth_im . data ) ) )
else :
farther_px = np . where ( ( self . data >= depth_im . data ) & ( np . isfinite ( depth_im . data ) ) )
farther_px = np . c_ [ farther_px [ 0 ] , farther_px [ ... |
def create ( entropy_coefficient , value_coefficient , cliprange , max_grad_norm , discount_factor , normalize_advantage = True , gae_lambda = 1.0 ) :
"""Vel factory function""" | return PpoPolicyGradient ( entropy_coefficient , value_coefficient , cliprange , max_grad_norm , discount_factor = discount_factor , normalize_advantage = normalize_advantage , gae_lambda = gae_lambda ) |
def _get_scale_and_shape_sim ( self , transformed_lvs ) :
"""Obtains model scale , shape , skewness latent variables for
a 2d array of simulations .
Parameters
transformed _ lvs : np . array
Transformed latent variable vector ( 2d - with draws of each variable )
Returns
- Tuple of np . arrays ( each bei... | if self . scale is True :
if self . shape is True :
model_shape = self . latent_variables . z_list [ - 1 ] . prior . transform ( transformed_lvs [ - 1 , : ] )
model_scale = self . latent_variables . z_list [ - 2 ] . prior . transform ( transformed_lvs [ - 2 , : ] )
else :
model_shape = n... |
def make_route_refresh_request ( self , peer_ip , * route_families ) :
"""Request route - refresh for peer with ` peer _ ip ` for given
` route _ families ` .
Will make route - refresh request for a given ` route _ family ` only if such
capability is supported and if peer is in ESTABLISHED state . Else , such... | LOG . debug ( 'Route refresh requested for peer %s and route families %s' , peer_ip , route_families )
if not SUPPORTED_GLOBAL_RF . intersection ( route_families ) :
raise ValueError ( 'Given route family(s) % is not supported.' % route_families )
peer_list = [ ]
# If route - refresh is requested for all peers .
if... |
def login ( self , username , password , namespace = None ) :
"""Performs the login against zimbra
( sends AuthRequest , receives AuthResponse ) .
: param namespace : if specified , the namespace used for authetication
( if the client namespace is not suitable for
authentication ) .""" | if namespace is None :
namespace = self . client . NAMESPACE
data = self . client . request ( 'Auth' , { 'account' : zobjects . Account ( name = username ) . to_selector ( ) , 'password' : { '_content' : password } } , namespace )
self . authToken = data [ 'authToken' ]
lifetime = int ( data [ 'lifetime' ] )
self .... |
def sync_sources ( self , force = False ) :
"""Sync in only the sources . csv file""" | from ambry . orm . file import File
self . dstate = self . STATES . BUILDING
synced = 0
for fc in [ File . BSFILE . SOURCES ] :
bsf = self . build_source_files . file ( fc )
if bsf . fs_is_newer or force :
self . log ( 'Syncing {}' . format ( bsf . file_name ) )
bsf . fs_to_objects ( )
s... |
def remove_scoped_variable ( self , scoped_variable_id , destroy = True ) :
"""Remove a scoped variable from the container state
: param scoped _ variable _ id : the id of the scoped variable to remove
: raises exceptions . AttributeError : if the id of the scoped variable already exists""" | if scoped_variable_id not in self . _scoped_variables :
raise AttributeError ( "A scoped variable with id %s does not exist" % str ( scoped_variable_id ) )
# delete all data flows connected to scoped _ variable
if destroy :
self . remove_data_flows_with_data_port_id ( scoped_variable_id )
# delete scoped variab... |
def delete_account ( self ) :
"""Delete a user ' s account .
Deleting the user ' s account can only be done if the user ' s domain is controlled by the authorized organization ,
and removing the account will also remove the user from all organizations with access to that domain .
: return : None , because you... | if self . id_type == IdentityTypes . adobeID :
raise ArgumentError ( "You cannot delete an Adobe ID account." )
self . append ( removeFromDomain = { } )
return None |
def add_package ( self , package_item ) :
"""Adds a package to the ship request .
@ type package _ item : WSDL object , type of RequestedPackageLineItem
WSDL object .
@ keyword package _ item : A RequestedPackageLineItem , created by
calling create _ wsdl _ object _ of _ type ( ' RequestedPackageLineItem ' ... | self . RequestedShipment . RequestedPackageLineItems . append ( package_item )
package_weight = package_item . Weight . Value
self . RequestedShipment . TotalWeight . Value += package_weight
self . RequestedShipment . PackageCount += 1 |
def check_argument_types ( cllable = None , call_args = None , clss = None , caller_level = 0 ) :
"""Can be called from within a function or method to apply typechecking to
the arguments that were passed in by the caller . Checking is applied w . r . t .
type hints of the function or method hosting the call to ... | return _check_caller_type ( False , cllable , call_args , clss , caller_level + 1 ) |
def correspondent ( self ) :
""": returns : The username of the user with whom the logged in user is
conversing in this : class : ` ~ . MessageThread ` .""" | try :
return self . _correspondent_xpb . one_ ( self . _thread_element ) . strip ( )
except IndexError :
raise errors . NoCorrespondentError ( ) |
def store ( self , loc , df ) :
"""Store dataframe in the given location .
Store some arbitrary dataframe :
> > > data . store ( ' my _ data ' , df )
Now recover it from the global store .
> > > data . my _ data""" | path = "%s.%s" % ( self . _root / "processed" / loc , FILE_EXTENSION )
WRITE_DF ( df , path , ** WRITE_DF_OPTS )
self . _cache [ loc ] = df |
def get_parameters ( self , packet_count = None ) :
"""Returns the special tshark parameters to be used according to the configuration of this class .""" | params = super ( LiveCapture , self ) . get_parameters ( packet_count = packet_count )
# Read from STDIN
params += [ '-r' , '-' ]
return params |
def bleu_score ( logits , labels ) :
"""Approximate BLEU score computation between labels and predictions .
An approximate BLEU scoring method since we do not glue word pieces or
decode the ids and tokenize the output . By default , we use ngram order of 4
and use brevity penalty . Also , this does not have b... | predictions = tf . to_int32 ( tf . argmax ( logits , axis = - 1 ) )
# TODO : Look into removing use of py _ func
bleu = tf . py_func ( compute_bleu , ( labels , predictions ) , tf . float32 )
return bleu , tf . constant ( 1.0 ) |
def hscan ( key , cursor = 0 , match = None , count = None , host = None , port = None , db = None , password = None ) :
'''Incrementally iterate hash fields and associated values .
. . versionadded : : 2017.7.0
CLI Example :
. . code - block : : bash
salt ' * ' redis . hscan foo _ hash match = ' field _ pr... | server = _connect ( host , port , db , password )
return server . hscan ( key , cursor = cursor , match = match , count = count ) |
def do_file_upload ( client , args ) :
"""Upload files""" | # Sanity check
if len ( args . paths ) > 1 : # destination must be a directory
try :
resource = client . get_resource_by_uri ( args . dest_uri )
except ResourceNotFoundError :
resource = None
if resource and not isinstance ( resource , Folder ) :
print ( "file-upload: " "target '{}' ... |
def _region_code_for_number_from_list ( numobj , regions ) :
"""Find the region in a list that matches a number""" | national_number = national_significant_number ( numobj )
for region_code in regions : # If leading _ digits is present , use this . Otherwise , do full
# validation .
# Metadata cannot be None because the region codes come from
# the country calling code map .
metadata = PhoneMetadata . metadata_for_region ( region... |
def create_instances ( cls , name , atts , capacity ) :
"""Creates a new Instances .
: param name : the relation name
: type name : str
: param atts : the list of attributes to use for the dataset
: type atts : list of Attribute
: param capacity : how many data rows to reserve initially ( see compactify )... | attributes = [ ]
for att in atts :
attributes . append ( att . jobject )
return Instances ( javabridge . make_instance ( "weka/core/Instances" , "(Ljava/lang/String;Ljava/util/ArrayList;I)V" , name , javabridge . make_list ( attributes ) , capacity ) ) |
def parse_show ( prs ) :
"""Convert and print JSON .
Argument :
prs : parser object of argparse""" | prs_show = prs . add_parser ( 'show' , help = 'show converted JSON' )
set_option ( prs_show , 'infile' )
prs_show . set_defaults ( func = show ) |
def getAttributesDict ( self ) :
'''getAttributesDict - Get a copy of all attributes as a dict map of name - > value
ALL values are converted to string and copied , so modifications will not affect the original attributes .
If you want types like " style " to work as before , you ' ll need to recreate those ele... | return { tostr ( name ) [ : ] : tostr ( value ) [ : ] for name , value in self . _attributes . items ( ) } |
def interface_temperature ( Ts , Tatm , ** kwargs ) :
'''Compute temperature at model layer interfaces .''' | # Actually it ' s not clear to me how the RRTM code uses these values
lev = Tatm . domain . axes [ 'lev' ] . points
lev_bounds = Tatm . domain . axes [ 'lev' ] . bounds
# Interpolate to layer interfaces
f = interp1d ( lev , Tatm , axis = - 1 )
# interpolation function
Tinterp = f ( lev_bounds [ 1 : - 1 ] )
# add TOA va... |
def table ( self , tableName ) :
"""Returns the specified table as a : class : ` DataFrame ` .
: return : : class : ` DataFrame `
> > > df . createOrReplaceTempView ( " table1 " )
> > > df2 = spark . table ( " table1 " )
> > > sorted ( df . collect ( ) ) = = sorted ( df2 . collect ( ) )
True""" | return DataFrame ( self . _jsparkSession . table ( tableName ) , self . _wrapped ) |
def generateNoise ( self ) :
"""Generate noise time series based on input parameters
Returns
time _ series : np . array
Time series with colored noise .
len ( time _ series ) = = nr""" | # Fill wfb array with white noise based on given discrete variance
wfb = np . zeros ( self . nr * 2 )
wfb [ : self . nr ] = np . random . normal ( 0 , np . sqrt ( self . qd ) , self . nr )
# Generate the hfb coefficients based on the noise type
mhb = - self . b / 2.0
hfb = np . zeros ( self . nr * 2 )
hfb = np . zeros ... |
def _member_defs ( self ) :
"""A single string containing the aggregated member definitions section
of the documentation page""" | members = self . _clsdict [ '__members__' ]
member_defs = [ self . _member_def ( member ) for member in members if member . name is not None ]
return '\n' . join ( member_defs ) |
def shot_remove_asset ( self , * args , ** kwargs ) :
"""Remove the , in the asset table view selected , asset .
: returns : None
: rtype : None
: raises : None""" | if not self . cur_shot :
return
i = self . shot_asset_treev . currentIndex ( )
item = i . internalPointer ( )
if item :
asset = item . internal_data ( )
if not isinstance ( asset , djadapter . models . Asset ) :
return
log . debug ( "Removing asset %s." , asset . name )
item . set_parent ( N... |
def assert_await_scene_loaded ( cli , scene_name , is_loaded = DEFAULT_SCENE_LOADED , timeout_seconds = DEFAULT_TIMEOUT_SECONDS ) :
"""Asserts that we successfully awaited for the scene to be loaded based on is _ loaded . If the timeout passes
or the expression is _ registered ! = actual state , then it will fail... | result = commands . await_scene_loaded ( cli , scene_name , is_loaded , timeout_seconds )
assert result is True
return result |
def data_sub_graph ( self , pv , simplified = True , killing_edges = False , excluding_types = None ) :
"""Get a subgraph from the data graph or the simplified data graph that starts from node pv .
: param ProgramVariable pv : The starting point of the subgraph .
: param bool simplified : When True , the simpli... | result = networkx . MultiDiGraph ( )
result . add_node ( pv )
base_graph = self . simplified_data_graph if simplified else self . data_graph
if pv not in base_graph :
return result
# traverse all edges and add them to the result graph if needed
queue = [ pv ]
traversed = set ( )
while queue :
elem = queue [ 0 ]... |
async def update_websub ( self , config , hub ) :
"""Update WebSub hub to know about this feed""" | try :
LOGGER . debug ( "WebSub: Notifying %s of %s" , hub , self . url )
request = await utils . retry_post ( config , hub , data = { 'hub.mode' : 'publish' , 'hub.url' : self . url } )
if request . success :
LOGGER . info ( "%s: WebSub notification sent to %s" , self . url , hub )
else :
... |
async def upload_sticker_file ( self , user_id : base . Integer , png_sticker : base . InputFile ) -> types . File :
"""Use this method to upload a . png file with a sticker for later use in createNewStickerSet
and addStickerToSet methods ( can be used multiple times ) .
Source : https : / / core . telegram . o... | payload = generate_payload ( ** locals ( ) , exclude = [ 'png_sticker' ] )
files = { }
prepare_file ( payload , files , 'png_sticker' , png_sticker )
result = await self . request ( api . Methods . UPLOAD_STICKER_FILE , payload , files )
return types . File ( ** result ) |
def abort ( self , abort_message = '' ) :
"""Mark the entire pipeline up to the root as aborted .
Note this should only be called from * outside * the context of a running
pipeline . Synchronous and generator pipelines should raise the ' Abort '
exception to cause this behavior during execution .
Args :
a... | # TODO : Use thread - local variable to enforce that this is not called
# while a pipeline is executing in the current thread .
if ( self . async and self . _root_pipeline_key == self . _pipeline_key and not self . try_cancel ( ) ) : # Handle the special case where the root pipeline is async and thus
# cannot be aborte... |
def terminate ( self ) :
"""Terminates an active session""" | self . _backend_client . clear ( )
self . _needs_save = False
self . _started = False
self . _expire_cookie = True
self . _send_cookie = True |
def cli ( source_f , raster_f , output , verbose ) :
"""Converts 2D geometries to 3D using GEOS sample through fiona .
Example :
drape point . shp elevation . tif - o point _ z . shp""" | with fiona . open ( source_f , 'r' ) as source :
source_driver = source . driver
source_crs = source . crs
sink_schema = source . schema . copy ( )
source_geom = source . schema [ 'geometry' ]
if source_geom == 'Point' :
sink_schema [ 'geometry' ] = '3D Point'
elif source_geom == 'LineSt... |
def handle_output ( self , workunit , label , s ) :
"""Implementation of Reporter callback .""" | if not self . is_under_main_root ( workunit ) :
return
tool_output_format = self . _get_tool_output_format ( workunit )
if tool_output_format == ToolOutputFormat . INDENT :
self . emit ( self . _prefix ( workunit , s ) )
elif tool_output_format == ToolOutputFormat . UNINDENTED :
self . emit ( s )
self . flu... |
def _get_module_name_from_fname ( fname ) :
"""Get module name from module file name .""" | fname = fname . replace ( ".pyc" , ".py" )
for mobj in sys . modules . values ( ) :
if ( hasattr ( mobj , "__file__" ) and mobj . __file__ and ( mobj . __file__ . replace ( ".pyc" , ".py" ) == fname ) ) :
module_name = mobj . __name__
return module_name
raise RuntimeError ( "Module could not be foun... |
def frequency_app ( parser , cmd , args ) : # pragma : no cover
"""perform frequency analysis on a value .""" | parser . add_argument ( 'value' , help = 'the value to analyse, read from stdin if omitted' , nargs = '?' )
args = parser . parse_args ( args )
data = frequency ( six . iterbytes ( pwnypack . main . binary_value_or_stdin ( args . value ) ) )
return '\n' . join ( '0x%02x (%c): %d' % ( key , chr ( key ) , value ) if key ... |
def context_exclude ( zap_helper , name , pattern ) :
"""Exclude a pattern from a given context .""" | console . info ( 'Excluding regex {0} from context with name: {1}' . format ( pattern , name ) )
with zap_error_handler ( ) :
result = zap_helper . zap . context . exclude_from_context ( contextname = name , regex = pattern )
if result != 'OK' :
raise ZAPError ( 'Excluding regex from context failed: {}'... |
def parse_reaction_list ( path , reactions , default_compartment = None ) :
"""Parse a structured list of reactions as obtained from a YAML file
Yields tuples of reaction ID and reaction object . Path can be given as a
string or a context .""" | context = FilePathContext ( path )
for reaction_def in reactions :
if 'include' in reaction_def :
include_context = context . resolve ( reaction_def [ 'include' ] )
for reaction in parse_reaction_file ( include_context , default_compartment ) :
yield reaction
else :
yield par... |
def get_proficiencies_for_resources ( self , resource_ids ) :
"""Gets a ` ` ProficiencyList ` ` relating to the given resources .
arg : resource _ ids ( osid . id . IdList ) : the resource ` ` Ids ` `
return : ( osid . learning . ProficiencyList ) - the returned
` ` Proficiency ` ` list
raise : NullArgument... | # Implemented from template for
# osid . relationship . RelationshipLookupSession . get _ relationships _ for _ source
# NOTE : This implementation currently ignores plenary and effective views
collection = JSONClientValidated ( 'learning' , collection = 'Proficiency' , runtime = self . _runtime )
result = collection .... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.