signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def delete_entity ( self , table_name , partition_key , row_key , if_match = '*' , timeout = None ) :
'''Deletes an existing entity in a table . Throws if the entity does not exist .
When an entity is successfully deleted , the entity is immediately marked
for deletion and is no longer accessible to clients . T... | _validate_not_none ( 'table_name' , table_name )
request = _delete_entity ( partition_key , row_key , if_match )
request . host_locations = self . _get_host_locations ( )
request . query [ 'timeout' ] = _int_to_str ( timeout )
request . path = _get_entity_path ( table_name , partition_key , row_key )
self . _perform_re... |
def check ( self , url_data ) :
"""Check content for invalid anchors .""" | headers = [ ]
for name , value in url_data . headers . items ( ) :
if name . startswith ( self . prefixes ) :
headers . append ( name )
if headers :
items = [ u"%s=%s" % ( name . capitalize ( ) , url_data . headers [ name ] ) for name in headers ]
info = u"HTTP headers %s" % u", " . join ( items )
... |
def _set_cfm ( self , v , load = False ) :
"""Setter method for cfm , mapped from YANG variable / protocol / cfm ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ cfm is considered as a private
method . Backends looking to populate this variable should
d... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = cfm . cfm , is_container = 'container' , presence = True , yang_name = "cfm" , rest_name = "cfm" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions = { u... |
def program ( self , file_or_path , file_format = None , ** kwargs ) :
"""! @ brief Program a file into flash .
@ param self
@ param file _ or _ path Either a string that is a path to a file , or a file - like object .
@ param file _ format Optional file format name , one of " bin " , " hex " , " elf " , " ax... | isPath = isinstance ( file_or_path , six . string_types )
# Check for valid path first .
if isPath and not os . path . isfile ( file_or_path ) :
raise FileNotFoundError_ ( errno . ENOENT , "No such file: '{}'" . format ( file_or_path ) )
# If no format provided , use the file ' s extension .
if not file_format :
... |
def robots_cannot_follow ( cls , element ) :
'''Return whether we cannot follow links due to robots . txt directives .''' | return ( element . tag == 'meta' and element . attrib . get ( 'name' , '' ) . lower ( ) == 'robots' and 'nofollow' in element . attrib . get ( 'value' , '' ) . lower ( ) ) |
def resource_get ( self , resource_name ) :
"""Return resource info
: param resource _ name : Resource name as returned by resource _ get _ list ( )
: type resource _ name : str
: return : Resource information ( empty if not found )
name : Resource name
hash : Resource hash
path : Path to resource
che... | try :
with self . _resource_lock :
res = self . _resources [ resource_name ]
except KeyError :
return { }
return res |
def remover ( self , id_equipment , id_environment ) :
"""Remove Related Equipment with Environment from by the identifier .
: param id _ equipment : Identifier of the Equipment . Integer value and greater than zero .
: param id _ environment : Identifier of the Environment . Integer value and greater than zero... | if not is_valid_int_param ( id_equipment ) :
raise InvalidParameterError ( u'The identifier of Equipment is invalid or was not informed.' )
if not is_valid_int_param ( id_environment ) :
raise InvalidParameterError ( u'The identifier of Environment is invalid or was not informed.' )
url = 'equipment/' + str ( i... |
def _default_styles_xml ( cls ) :
"""Return a bytestream containing XML for a default styles part .""" | path = os . path . join ( os . path . split ( __file__ ) [ 0 ] , '..' , 'templates' , 'default-styles.xml' )
with open ( path , 'rb' ) as f :
xml_bytes = f . read ( )
return xml_bytes |
def combine_first ( self , other ) :
"""Combine Series values , choosing the calling Series ' s values
first . Result index will be the union of the two indexes
Parameters
other : Series
Returns
y : Series""" | if isinstance ( other , SparseSeries ) :
other = other . to_dense ( )
dense_combined = self . to_dense ( ) . combine_first ( other )
return dense_combined . to_sparse ( fill_value = self . fill_value ) |
def ReplaceStopTimeObject ( self , stoptime , schedule = None ) :
"""Replace a StopTime object from this trip with the given one .
Keys the StopTime object to be replaced by trip _ id , stop _ sequence
and stop _ id as ' stoptime ' , with the object ' stoptime ' .""" | if schedule is None :
schedule = self . _schedule
new_secs = stoptime . GetTimeSecs ( )
cursor = schedule . _connection . cursor ( )
cursor . execute ( "DELETE FROM stop_times WHERE trip_id=? and " "stop_sequence=? and stop_id=?" , ( self . trip_id , stoptime . stop_sequence , stoptime . stop_id ) )
if cursor . row... |
def setsebool ( boolean , value , persist = False ) :
'''Set the value for a boolean
CLI Example :
. . code - block : : bash
salt ' * ' selinux . setsebool virt _ use _ usb off''' | if persist :
cmd = 'setsebool -P {0} {1}' . format ( boolean , value )
else :
cmd = 'setsebool {0} {1}' . format ( boolean , value )
return not __salt__ [ 'cmd.retcode' ] ( cmd , python_shell = False ) |
def from_json ( cls , service_dict ) :
"""Create a service object from a JSON string .""" | sd = service_dict . copy ( )
service_endpoint = sd . get ( cls . SERVICE_ENDPOINT )
if not service_endpoint :
logger . error ( 'Service definition in DDO document is missing the "serviceEndpoint" key/value.' )
raise IndexError
_type = sd . get ( 'type' )
if not _type :
logger . error ( 'Service definition i... |
def connections ( self , cls = None ) :
"""Returns a list of connections from the scene that match the inputed
class for this node .
: param cls | < subclass of XNodeConnection > | | None
: return [ < XNodeConnection > , . . ]""" | scene = self . scene ( )
if ( not scene ) :
return [ ]
if ( not cls ) :
cls = XNodeConnection
output = [ ]
for item in scene . items ( ) :
if ( not isinstance ( item , cls ) ) :
continue
if ( item . inputNode ( ) == self or item . outputNode ( ) == self ) :
output . append ( item )
retur... |
def del_alias ( alias ) :
"""sometimes you goof up .""" | with Database ( "aliases" ) as mydb :
try :
print ( "removing alias of %s to %s" % ( alias , mydb . pop ( alias ) ) )
except KeyError :
print ( "No such alias key" )
print ( "Check alias db:" )
print ( zip ( list ( mydb . keys ( ) ) , list ( mydb . values ( ) ) ) ) |
def unlink ( self , key , * keys ) :
"""Delete a key asynchronously in another thread .""" | return wait_convert ( self . execute ( b'UNLINK' , key , * keys ) , int ) |
def poll ( self ) :
"""Retrieves older requests that may not make it back quick
enough""" | if self . redis_connected :
json_item = request . get_json ( )
result = None
try :
key = "rest:poll:{u}" . format ( u = json_item [ 'poll_id' ] )
result = self . redis_conn . get ( key )
if result is not None :
result = json . loads ( result )
self . logger . ... |
def is_child_of_catalog ( self , id_ , catalog_id ) :
"""Tests if a catalog is a direct child of another .
arg : id ( osid . id . Id ) : an ` ` Id ` `
arg : catalog _ id ( osid . id . Id ) : the ` ` Id ` ` of a catalog
return : ( boolean ) - ` ` true ` ` if the ` ` id ` ` is a child of
` ` catalog _ id , ` ... | # Implemented from template for
# osid . resource . BinHierarchySession . is _ child _ of _ bin
if self . _catalog_session is not None :
return self . _catalog_session . is_child_of_catalog ( id_ = id_ , catalog_id = catalog_id )
return self . _hierarchy_session . is_child ( id_ = catalog_id , child_id = id_ ) |
def main ( ) :
"""Executed on run""" | args = parse_args ( )
if args . version :
from . __init__ import __version__ , __release_date__
print ( 'elkme %s (release date %s)' % ( __version__ , __release_date__ ) )
print ( '(c) 2015-2017 46elks AB <hello@46elks.com>' )
print ( small_elk )
exit ( 0 )
conf , conf_status = config . init_config ... |
def expand_python_version ( version ) :
"""Expand Python versions to all identifiers used on PyPI .
> > > expand _ python _ version ( ' 3.5 ' )
[ ' 3.5 ' , ' py3 ' , ' py2 . py3 ' , ' cp35 ' ]""" | if not re . match ( r"^\d\.\d$" , version ) :
return [ version ]
major , minor = version . split ( "." )
patterns = [ "{major}.{minor}" , "cp{major}{minor}" , "py{major}" , "py{major}.{minor}" , "py{major}{minor}" , "source" , "py2.py3" , ]
return set ( pattern . format ( major = major , minor = minor ) for pattern... |
def getIndividual ( self , id_ ) :
"""Returns the Individual with the specified id , or raises
a IndividualNotFoundException otherwise .""" | if id_ not in self . _individualIdMap :
raise exceptions . IndividualNotFoundException ( id_ )
return self . _individualIdMap [ id_ ] |
def ReadStoredProcedure ( self , sproc_link , options = None ) :
"""Reads a stored procedure .
: param str sproc _ link :
The link to the stored procedure .
: param dict options :
The request options for the request .
: return :
The read Stored Procedure .
: rtype :
dict""" | if options is None :
options = { }
path = base . GetPathFromLink ( sproc_link )
sproc_id = base . GetResourceIdOrFullNameFromLink ( sproc_link )
return self . Read ( path , 'sprocs' , sproc_id , None , options ) |
def set_sessid ( sessid ) :
"""Save this current sessid in ` ` $ HOME / . profrc ` `""" | filename = path . join ( path . expanduser ( '~' ) , '.profrc' )
config = configparser . ConfigParser ( )
config . read ( filename )
config . set ( 'DEFAULT' , 'Session' , sessid )
with open ( filename , 'w' ) as configfile :
print ( "write a new sessid" )
config . write ( configfile ) |
def transformer_tall_finetune_tied ( ) :
"""Tied means fine - tune CNN / DM summarization as LM .""" | hparams = transformer_tall ( )
hparams . multiproblem_max_input_length = 750
hparams . multiproblem_max_target_length = 100
hparams . multiproblem_schedule_max_examples = 0
hparams . learning_rate_schedule = ( "linear_warmup*constant*cosdecay" )
hparams . learning_rate_constant = 5e-5
hparams . learning_rate_warmup_ste... |
def get_obj ( path ) :
"""Return obj for given dotted path .
Typical inputs for ` path ` are ' os ' or ' os . path ' in which case you get a
module ; or ' os . path . exists ' in which case you get a function from that
module .
Just returns the given input in case it is not a str .
Note : Relative imports... | # Since we usually pass in mocks here ; duck typing is not appropriate
# ( mocks respond to every attribute ) .
if not isinstance ( path , str ) :
return path
if path . startswith ( '.' ) :
raise TypeError ( 'relative imports are not supported' )
parts = path . split ( '.' )
head , tail = parts [ 0 ] , parts [ ... |
def rodrigues_axis_angle_rotate ( x , vec , theta ) :
"""Rotated the input vector or set of vectors ` x ` around the axis
` vec ` by the angle ` theta ` .
Parameters
x : array _ like
The vector or array of vectors to transform . Must have shape""" | x = np . array ( x ) . T
vec = np . array ( vec ) . T
theta = np . array ( theta ) . T [ ... , None ]
out = np . cos ( theta ) * x + np . sin ( theta ) * np . cross ( vec , x ) + ( 1 - np . cos ( theta ) ) * ( vec * x ) . sum ( axis = - 1 ) [ ... , None ] * vec
return out . T |
def discard_member ( self , member , pipe = None ) :
"""Remove * member * from the collection , unconditionally .""" | pipe = self . redis if pipe is None else pipe
pipe . zrem ( self . key , self . _pickle ( member ) ) |
def put ( self , key , value , ttl = 0 ) :
"""Associates the specified value with the specified key in this map . If the map previously contained a mapping for
the key , the old value is replaced by the specified value . If ttl is provided , entry will expire and get evicted
after the ttl .
: param key : ( ob... | check_not_none ( key , "key can't be None" )
check_not_none ( key , "value can't be None" )
key_data = self . _to_data ( key )
value_data = self . _to_data ( value )
return self . _encode_invoke_on_key ( replicated_map_put_codec , key_data , key = key_data , value = value_data , ttl = to_millis ( ttl ) ) |
def tilequeue_rawr_seed_all ( cfg , peripherals ) :
"""command to enqueue all the tiles at the group - by zoom""" | rawr_yaml = cfg . yml . get ( 'rawr' )
assert rawr_yaml is not None , 'Missing rawr configuration in yaml'
group_by_zoom = rawr_yaml . get ( 'group-zoom' )
assert group_by_zoom is not None , 'Missing group-zoom rawr config'
max_coord = 2 ** group_by_zoom
# creating the list of all coordinates here might be a lot of mem... |
def inspectorDataRange ( inspector , percentage ) :
"""Calculates the range from the inspectors ' sliced array . Discards percentage of the minimum
and percentage of the maximum values of the inspector . slicedArray
Meant to be used with functools . partial for filling the autorange methods combobox .
The fir... | logger . debug ( "Discarding {}% from id: {}" . format ( percentage , id ( inspector . slicedArray ) ) )
return maskedNanPercentile ( inspector . slicedArray , ( percentage , 100 - percentage ) ) |
def time_sp ( self ) :
"""Writing specifies the amount of time the motor will run when using the
` run - timed ` command . Reading returns the current value . Units are in
milliseconds .""" | self . _time_sp , value = self . get_attr_int ( self . _time_sp , 'time_sp' )
return value |
def bgyellow ( cls , string , auto = False ) :
"""Color - code entire string .
: param str string : String to colorize .
: param bool auto : Enable auto - color ( dark / light terminal ) .
: return : Class instance for colorized string .
: rtype : Color""" | return cls . colorize ( 'bgyellow' , string , auto = auto ) |
def split_args ( self , arg_dict ) :
"""given a dictionary of arguments , split them into
args and kwargs
note : this destroys the arg _ dict passed . if you need it ,
create a copy first .""" | pos_args = [ ]
for arg in self . args :
pos_args . append ( arg_dict [ arg . name ] )
del arg_dict [ arg . name ]
return pos_args , arg_dict |
def get_instance ( self , payload ) :
"""Build an instance of IpAccessControlListInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . api . v2010 . account . sip . ip _ access _ control _ list . IpAccessControlListInstance
: rtype : twilio . rest . api . v2010 . account . ... | return IpAccessControlListInstance ( self . _version , payload , account_sid = self . _solution [ 'account_sid' ] , ) |
def _get_frame_info ( stacklevel , context = 1 ) :
"""Get a Traceback for the given ` stacklevel ` .
For example :
` stacklevel = 0 ` means this function ' s frame ( _ get _ frame _ info ( ) ) .
` stacklevel = 1 ` means the calling function ' s frame .
See https : / / docs . python . org / 2 / library / ins... | frame_list = inspect . getouterframes ( inspect . currentframe ( ) , context = context )
frame_stack_index = stacklevel if stacklevel < len ( frame_list ) else len ( frame_list ) - 1
return frame_list [ frame_stack_index ] |
def get_commands ( self ) :
"""Returns commands available to execute
: return : list of ( name , doc ) tuples""" | commands = [ ]
for name , value in inspect . getmembers ( self ) :
if not inspect . isgeneratorfunction ( value ) :
continue
if name . startswith ( '_' ) or name == 'run' :
continue
doc = inspect . getdoc ( value )
commands . append ( ( name , doc ) )
return commands |
def scheduling_blocks ( ) :
"""Return list of Scheduling Block instances known to SDP .""" | sbi_list = SchedulingBlockInstanceList ( )
return dict ( active = sbi_list . active , completed = sbi_list . completed , aborted = sbi_list . aborted ) |
def square_batch_region ( data , region , bam_files , vrn_files , out_file ) :
"""Perform squaring of a batch in a supplied region , with input BAMs""" | from bcbio . variation import sentieon , strelka2
if not utils . file_exists ( out_file ) :
jointcaller = tz . get_in ( ( "config" , "algorithm" , "jointcaller" ) , data )
if jointcaller in [ "%s-joint" % x for x in SUPPORTED [ "general" ] ] :
_square_batch_bcbio_variation ( data , region , bam_files , ... |
def format_docstring ( elt , arg_comments : dict = { } , alt_doc_string : str = '' , ignore_warn : bool = False ) -> str :
"Merge and format the docstring definition with ` arg _ comments ` and ` alt _ doc _ string ` ." | parsed = ""
doc = parse_docstring ( inspect . getdoc ( elt ) )
description = alt_doc_string or f"{doc['short_description']} {doc['long_description']}"
if description :
parsed += f'\n\n{link_docstring(inspect.getmodule(elt), description)}'
resolved_comments = { ** doc . get ( 'comments' , { } ) , ** arg_comments }
#... |
def ParseBookmarkAnnotationRow ( self , parser_mediator , query , row , ** unused_kwargs ) :
"""Parses a bookmark annotation row .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
query ( str ) : query that created the row... | query_hash = hash ( query )
event_data = FirefoxPlacesBookmarkAnnotationEventData ( )
event_data . content = self . _GetRowValue ( query_hash , row , 'content' )
event_data . offset = self . _GetRowValue ( query_hash , row , 'id' )
event_data . query = query
event_data . title = self . _GetRowValue ( query_hash , row ,... |
def _array_parallel ( fn , cls , genelist , chunksize = 250 , processes = 1 , ** kwargs ) :
"""Returns an array of genes in ` genelist ` , using ` bins ` bins .
` genelist ` is a list of pybedtools . Interval objects
Splits ` genelist ` into pieces of size ` chunksize ` , creating an array
for each chunk and ... | pool = multiprocessing . Pool ( processes )
chunks = list ( chunker ( genelist , chunksize ) )
# pool . map can only pass a single argument to the mapped function , so you
# need this trick for passing multiple arguments ; idea from
# http : / / stackoverflow . com / questions / 5442910/
# python - multiprocessing - po... |
def best_periods ( self ) :
"""Compute the scores under the various models
Parameters
periods : array _ like
array of periods at which to compute scores
Returns
best _ periods : dict
Dictionary of best periods . Dictionary keys are the unique filter
names passed to fit ( )""" | for ( key , model ) in self . models_ . items ( ) :
model . optimizer = self . optimizer
return dict ( ( filt , model . best_period ) for ( filt , model ) in self . models_ . items ( ) ) |
def collect ( self ) :
"""Collector GPU stats""" | stats_config = self . config [ 'stats' ]
if USE_PYTHON_BINDING :
collect_metrics = self . collect_via_pynvml
else :
collect_metrics = self . collect_via_nvidia_smi
collect_metrics ( stats_config ) |
def query_metric ( self , metric_type , metric_id , start = None , end = None , ** query_options ) :
"""Query for metrics datapoints from the server .
: param metric _ type : MetricType to be matched ( required )
: param metric _ id : Exact string matching metric id
: param start : Milliseconds since epoch or... | if start is not None :
if type ( start ) is datetime :
query_options [ 'start' ] = datetime_to_time_millis ( start )
else :
query_options [ 'start' ] = start
if end is not None :
if type ( end ) is datetime :
query_options [ 'end' ] = datetime_to_time_millis ( end )
else :
... |
def encode ( self ) :
"""Encode this matrix in binary suitable for including in a PDF""" | return '{:.6f} {:.6f} {:.6f} {:.6f} {:.6f} {:.6f}' . format ( self . a , self . b , self . c , self . d , self . e , self . f ) . encode ( ) |
def get_auth_data ( cls , instance ) :
'''Generate a Security Parameters object based on the instance ' s
configuration .
See http : / / pysnmp . sourceforge . net / docs / current / security - configuration . html''' | if "community_string" in instance : # SNMP v1 - SNMP v2
# See http : / / pysnmp . sourceforge . net / docs / current / security - configuration . html
if int ( instance . get ( "snmp_version" , 2 ) ) == 1 :
return hlapi . CommunityData ( instance [ 'community_string' ] , mpModel = 0 )
return hlapi . Com... |
def get_vcs_root ( path ) :
"""Return VCS root directory path
Return None if path is not within a supported VCS repository""" | previous_path = path
while get_vcs_info ( path ) is None :
path = abspardir ( path )
if path == previous_path :
return
else :
previous_path = path
return osp . abspath ( path ) |
def exit_if_path_not_found ( path ) :
"""Exit if the path is not found .""" | if not os . path . exists ( path ) :
ui . error ( c . MESSAGES [ "path_missing" ] , path )
sys . exit ( 1 ) |
def get_pos_hint ( poshints , sizehintx , sizehinty ) :
"""Return a tuple of ` ` ( pos _ hint _ x , pos _ hint _ y ) ` ` even if neither of
those keys are present in the provided ` ` poshints ` ` - - they can be
computed using the available keys together with ` ` size _ hint _ x ` `
and ` ` size _ hint _ y ` ... | return ( get_pos_hint_x ( poshints , sizehintx ) , get_pos_hint_y ( poshints , sizehinty ) ) |
def new_file ( self , path , track_idx , copy_file = False ) :
"""Adds a new audio file to the corpus with the given data .
Parameters :
path ( str ) : Path of the file to add .
track _ idx ( str ) : The id to associate the file - track with .
copy _ file ( bool ) : If True the file is copied to the data se... | new_file_idx = track_idx
new_file_path = os . path . abspath ( path )
# Add index to idx if already existing
if new_file_idx in self . _tracks . keys ( ) :
new_file_idx = naming . index_name_if_in_list ( new_file_idx , self . _tracks . keys ( ) )
# Copy file to default file dir
if copy_file :
if not os . path .... |
def handle_dims ( opts ) :
'''Script option handling .''' | use , res = [ ] , [ ] ;
if opts [ '--X' ] :
use . append ( 'x' ) ;
res . append ( int ( opts [ '--xres' ] ) ) ;
if opts [ '--Y' ] :
use . append ( 'y' ) ;
res . append ( int ( opts [ '--yres' ] ) ) ;
if opts [ '--Z' ] :
use . append ( 'z' ) ;
res . append ( int ( opts [ '--zres' ] ) ) ;
if use =... |
def generate_pdf_report ( self , impact_function , iface , scenario_name ) :
"""Generate and store map and impact report from impact function .
Directory where the report stored is specified by user input from the
dialog . This function is adapted from analysis _ utilities . py
: param impact _ function : Imp... | # output folder
output_dir = self . output_directory . text ( )
file_path = os . path . join ( output_dir , scenario_name )
# create impact table report instance
table_report_metadata = ReportMetadata ( metadata_dict = standard_impact_report_metadata_pdf )
impact_table_report = ImpactReport ( iface , table_report_metad... |
def cancel_milestone_close ( self , id , ** kwargs ) :
"""Cancel Product Milestone Release process .
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please define a ` callback ` function
to be invoked when receiving the response .
> > > def callback _ functio... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . cancel_milestone_close_with_http_info ( id , ** kwargs )
else :
( data ) = self . cancel_milestone_close_with_http_info ( id , ** kwargs )
return data |
def update_search_space ( self , search_space ) :
"""Update search space definition in tuner by search _ space in parameters .
Will called when first setup experiemnt or update search space in WebUI .
Parameters
search _ space : dict""" | self . json = search_space
search_space_instance = json2space ( self . json )
rstate = np . random . RandomState ( )
trials = hp . Trials ( )
domain = hp . Domain ( None , search_space_instance , pass_expr_memo_ctrl = None )
algorithm = self . _choose_tuner ( self . algorithm_name )
self . rval = hp . FMinIter ( algori... |
def search ( cls , term , fields = ( ) ) :
"""Generic SQL search function that uses SQL ` ` LIKE ` ` to search the
database for matching records . The records are sorted by their
relavancey to the search term .
The query searches and sorts on the folling criteria , in order , where
the target string is ` ` ... | if not any ( ( cls . _meta . search_fields , fields ) ) :
raise AttributeError ( "A list of searchable fields must be provided in the class's " "search_fields or provided to this function in the `fields` " "kwarg." )
# If fields are provided , override the ones in the class
if not fields :
fields = cls . _meta ... |
def to_digital ( d , num ) :
"""进制转换 , 从10进制转到指定机制
: param d :
: param num :
: return :""" | if not isinstance ( num , int ) or not 1 < num < 10 :
raise ValueError ( 'digital num must between 1 and 10' )
d = int ( d )
result = [ ]
x = d % num
d = d - x
result . append ( str ( x ) )
while d > 0 :
d = d // num
x = d % num
d = d - x
result . append ( str ( x ) )
return '' . join ( result [ : :... |
def obfn_cns ( self ) :
r"""Compute constraint violation measure : math : ` \ |
P ( \ mathbf { y } ) - \ mathbf { y } \ | _ 2 ` .""" | return np . linalg . norm ( ( self . Pcn ( self . X ) - self . X ) ) |
def use_comparative_objective_view ( self ) :
"""Pass through to provider ObjectiveLookupSession . use _ comparative _ objective _ view""" | self . _object_views [ 'objective' ] = COMPARATIVE
# self . _ get _ provider _ session ( ' objective _ lookup _ session ' ) # To make sure the session is tracked
for session in self . _get_provider_sessions ( ) :
try :
session . use_comparative_objective_view ( )
except AttributeError :
pass |
def nicename ( name ) :
'''Make ` ` name ` ` a more user friendly string .
Capitalise the first letter and replace dash and underscores with a space''' | name = to_string ( name )
return capfirst ( ' ' . join ( name . replace ( '-' , ' ' ) . replace ( '_' , ' ' ) . split ( ) ) ) |
def is_virtual_environment ( path ) :
"""Check if a given path is a virtual environment ' s root .
This is done by checking if the directory contains a Python executable in
its bin / Scripts directory . Not technically correct , but good enough for
general usage .""" | if not path . is_dir ( ) :
return False
for bindir_name in ( 'bin' , 'Scripts' ) :
for python in path . joinpath ( bindir_name ) . glob ( 'python*' ) :
try :
exeness = python . is_file ( ) and os . access ( str ( python ) , os . X_OK )
except OSError :
exeness = False
... |
def add_include ( self , name , module_spec ) :
"""Adds a module as an included module .
: param name :
Name under which the included module should be exposed in the
current module .
: param module _ spec :
ModuleSpec of the included module .""" | assert name , 'name is required'
assert self . can_include
if name in self . includes :
raise ThriftCompilerError ( 'Cannot include module "%s" as "%s" in "%s". ' 'The name is already taken.' % ( module_spec . name , name , self . path ) )
self . includes [ name ] = module_spec
self . scope . add_include ( name , m... |
def _cts_or_stc ( data ) :
"""Does the data look like a Client to Server ( cts ) or Server to Client ( stc ) traffic ?""" | # UDP / TCP
if data [ 'transport' ] : # TCP flags
if data [ 'transport' ] [ 'type' ] == 'TCP' :
flags = data [ 'transport' ] [ 'flags' ]
# Syn / Ack or fin / ack is a server response
if 'syn_ack' in flags or 'fin_ack' in flags :
return 'STC'
# Syn or fin is a client respo... |
def _filter_defs_at_call_sites ( self , defs ) :
"""If we are not tracing into the function that are called in a real execution , we should properly filter the defs
to account for the behavior of the skipped function at this call site .
This function is a WIP . See TODOs inside .
: param defs :
: return :""... | # TODO : make definition killing architecture independent and calling convention independent
# TODO : use information from a calling convention analysis
filtered_defs = LiveDefinitions ( )
for variable , locs in defs . items ( ) :
if isinstance ( variable , SimRegisterVariable ) :
if self . project . arch .... |
def _generate_sympify_namespace ( independent_variables , dependent_variables , helper_functions ) :
"""Generate the link between the symbols of the derivatives and the
sympy Derivative operation .
Parameters
independent _ variable : str
name of the independant variable ( " x " )
dependent _ variables : i... | # noqa
independent_variable = independent_variables [ 0 ]
# TEMP FIX BEFORE REAL ND
symbolic_independent_variable = Symbol ( independent_variable )
def partial_derivative ( symbolic_independent_variable , i , expr ) :
return Derivative ( expr , symbolic_independent_variable , i )
namespace = { independent_variable ... |
def get_line_info ( tree , max_lines = None ) :
"""Shortcut for indented _ tree _ line _ generator ( ) that returns an array of
start references , an array of corresponding end references ( see
tree _ line _ generator ( ) docs ) , and an array of corresponding lines .""" | line_gen = indented_tree_line_generator ( tree , max_lines = max_lines )
line_gen_result = list ( zip ( * line_gen ) )
if line_gen_result :
return line_gen_result
else :
return [ ] , [ ] , [ ] |
def shape ( self ) :
"""Total spaces per axis , computed recursively .
The recursion ends at the fist level that does not have a shape .
Examples
> > > r2 , r3 = odl . rn ( 2 ) , odl . rn ( 3)
> > > pspace = odl . ProductSpace ( r2 , r3)
> > > pspace . shape
> > > pspace2 = odl . ProductSpace ( pspace ,... | if len ( self ) == 0 :
return ( )
elif self . is_power_space :
try :
sub_shape = self [ 0 ] . shape
except AttributeError :
sub_shape = ( )
else :
sub_shape = ( )
return ( len ( self ) , ) + sub_shape |
def on_success ( self , retval , task_id , args , kwargs ) :
"""Clears cache for the task .""" | key = self . _get_cache_key ( args , kwargs )
if cache . get ( key ) is not None :
cache . delete ( key )
logger . debug ( 'Penalty for the task %s has been removed.' % self . name )
return super ( PenalizedBackgroundTask , self ) . on_success ( retval , task_id , args , kwargs ) |
def main ( ) :
"""NAME
gofish . py
DESCRIPTION
calculates fisher parameters from dec inc data
INPUT FORMAT
takes dec / inc as first two columns in space delimited file
SYNTAX
gofish . py [ options ] [ < filename ]
OPTIONS
- h prints help message and quits
- i for interactive filename entry
- f... | if '-h' in sys . argv : # check if help is needed
print ( main . __doc__ )
sys . exit ( )
# graceful quit
if '-i' in sys . argv : # ask for filename
file = input ( "Enter file name with dec, inc data: " )
f = open ( file , 'r' )
data = f . readlines ( )
elif '-f' in sys . argv :
dat = [ ]
... |
def create_where ( ) :
"""Create a grammar for the ' where ' clause used by ' select '""" | conjunction = Forward ( ) . setResultsName ( "conjunction" )
nested = Group ( Suppress ( "(" ) + conjunction + Suppress ( ")" ) ) . setResultsName ( "conjunction" )
maybe_nested = nested | constraint
inverted = Group ( not_ + maybe_nested ) . setResultsName ( "not" )
full_constraint = maybe_nested | inverted
conjunctio... |
def finish ( self ) :
"""Converts gathere lists to numpy arrays and creates
BaseMesh instance .""" | self . _vertices = np . array ( self . _vertices , 'float32' )
if self . _faces :
self . _faces = np . array ( self . _faces , 'uint32' )
else : # Use vertices only
self . _vertices = np . array ( self . _v , 'float32' )
self . _faces = None
if self . _normals :
self . _normals = np . array ( self . _no... |
def slots ( self ) :
"""Iterate over the Slots of the Template .""" | if self . implied :
return ( )
data = clips . data . DataObject ( self . _env )
lib . EnvDeftemplateSlotNames ( self . _env , self . _tpl , data . byref )
return tuple ( TemplateSlot ( self . _env , self . _tpl , n . encode ( ) ) for n in data . value ) |
def parse_date ( date , default = None ) :
"""Parse a valid date""" | if date == "" :
if default is not None :
return default
else :
raise Exception ( "Unknown format for " + date )
for format_type in [ "%Y-%m-%d %H:%M:%S" , "%Y-%m-%d %H:%M" , "%Y-%m-%d %H" , "%Y-%m-%d" , "%d/%m/%Y %H:%M:%S" , "%d/%m/%Y %H:%M" , "%d/%m/%Y %H" , "%d/%m/%Y" ] :
try :
ret... |
def absent ( name , profile = 'grafana' ) :
'''Ensure the named grafana dashboard is absent .
name
Name of the grafana dashboard .
profile
A pillar key or dict that contains grafana information''' | ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } }
if isinstance ( profile , six . string_types ) :
profile = __salt__ [ 'config.option' ] ( profile )
url = 'db/{0}' . format ( name )
existing_dashboard = _get ( url , profile )
if existing_dashboard :
if __opts__ [ 'test' ] :
r... |
def visit_compare ( self , node , parent ) :
"""visit a Compare node by returning a fresh instance of it""" | newnode = nodes . Compare ( node . lineno , node . col_offset , parent )
newnode . postinit ( self . visit ( node . left , newnode ) , [ ( self . _cmp_op_classes [ op . __class__ ] , self . visit ( expr , newnode ) ) for ( op , expr ) in zip ( node . ops , node . comparators ) ] , )
return newnode |
def _check_listening_on_services_ports ( services , test = False ) :
"""Check that the unit is actually listening ( has the port open ) on the
ports that the service specifies are open . If test is True then the
function returns the services with ports that are open rather than
closed .
Returns an OrderedDi... | test = not ( not ( test ) )
# ensure test is True or False
all_ports = list ( itertools . chain ( * services . values ( ) ) )
ports_states = [ port_has_listener ( '0.0.0.0' , p ) for p in all_ports ]
map_ports = OrderedDict ( )
matched_ports = [ p for p , opened in zip ( all_ports , ports_states ) if opened == test ]
#... |
def _unpack_aar ( self , aar , arch ) :
'''Unpack content of . aar bundle and copy to current dist dir .''' | with temp_directory ( ) as temp_dir :
name = splitext ( basename ( aar ) ) [ 0 ]
jar_name = name + '.jar'
info ( "unpack {} aar" . format ( name ) )
debug ( " from {}" . format ( aar ) )
debug ( " to {}" . format ( temp_dir ) )
shprint ( sh . unzip , '-o' , aar , '-d' , temp_dir )
jar_src ... |
def fetch ( self ) :
"""Retrieve updated data about the command from the server .
@ return : A new ApiCommand object .""" | if self . id == ApiCommand . SYNCHRONOUS_COMMAND_ID :
return self
resp = self . _get_resource_root ( ) . get ( self . _path ( ) )
return ApiCommand . from_json_dict ( resp , self . _get_resource_root ( ) ) |
def install_gem ( name , version = None , install_args = None , override_args = False ) :
'''Instructs Chocolatey to install a package via Ruby ' s Gems .
name
The name of the package to be installed . Only accepts a single argument .
version
Install a specific version of the package . Defaults to latest ve... | return install ( name , version = version , source = 'ruby' , install_args = install_args , override_args = override_args ) |
def apply ( self , func , axis = 0 , subset = None , ** kwargs ) :
"""Apply a function column - wise , row - wise , or table - wise ,
updating the HTML representation with the result .
Parameters
func : function
` ` func ` ` should take a Series or DataFrame ( depending
on ` ` axis ` ` ) , and return an o... | self . _todo . append ( ( lambda instance : getattr ( instance , '_apply' ) , ( func , axis , subset ) , kwargs ) )
return self |
def execute_ccm_command ( self , ccm_args , is_displayed = True ) :
"""Execute a CCM command on the remote server
: param ccm _ args : CCM arguments to execute remotely
: param is _ displayed : True if information should be display ; false to return output
( default : true )
: return : A tuple defining the ... | return self . execute ( [ "ccm" ] + ccm_args , profile = self . profile ) |
def _transform_row ( self , in_row , out_row ) :
"""Transforms an input row to an output row ( i . e . ( partial ) dimensional data ) .
: param dict [ str , str ] in _ row : The input row .
: param dict [ str , T ] out _ row : The output row .
: rtype : ( str , str )""" | tmp_row = { }
for step in self . _steps :
park_info , ignore_info = step ( in_row , tmp_row , out_row )
if park_info or ignore_info :
return park_info , ignore_info
return None , None |
def And ( * predicates , ** kwargs ) :
"""` And ` predicate . Returns ` ` False ` ` at the first sub - predicate that returns ` ` False ` ` .""" | if kwargs :
predicates += Query ( ** kwargs ) ,
return _flatten ( _And , * predicates ) |
def plot_sfs_folded_scaled ( * args , ** kwargs ) :
"""Plot a folded scaled site frequency spectrum .
Parameters
s : array _ like , int , shape ( n _ chromosomes / 2 , )
Site frequency spectrum .
yscale : string , optional
Y axis scale .
bins : int or array _ like , int , optional
Allele count bins . ... | kwargs . setdefault ( 'yscale' , 'linear' )
ax = plot_sfs_folded ( * args , ** kwargs )
ax . set_ylabel ( 'scaled site frequency' )
n = kwargs . get ( 'n' , None )
if n :
ax . set_xlabel ( 'minor allele frequency' )
else :
ax . set_xlabel ( 'minor allele count' )
return ax |
def _CaptureRequestLogId ( self ) :
"""Captures the request log id if possible .
The request log id is stored inside the breakpoint labels .""" | # pylint : disable = not - callable
if callable ( request_log_id_collector ) :
request_log_id = request_log_id_collector ( )
if request_log_id : # We have a request _ log _ id , save it into the breakpoint labels
self . breakpoint [ 'labels' ] [ labels . Breakpoint . REQUEST_LOG_ID ] = request_log_id |
def humanize_filesize ( filesize : int ) -> Tuple [ str , str ] :
"""Return human readable pair of size and unit from the given filesize in bytes .""" | for unit in [ '' , 'K' , 'M' , 'G' , 'T' , 'P' , 'E' , 'Z' ] :
if filesize < 1024.0 :
return '{:3.1f}' . format ( filesize ) , unit + 'B'
filesize /= 1024.0 |
def space_references ( document ) :
"""Ensure a space around reference links , so there ' s a gap when they are removed .""" | for ref in document . xpath ( './/a/sup/span[@class="sup_ref"]' ) :
a = ref . getparent ( ) . getparent ( )
if a is not None :
atail = a . tail or ''
if not atail . startswith ( ')' ) and not atail . startswith ( ',' ) and not atail . startswith ( ' ' ) :
a . tail = ' ' + atail
retur... |
def init_argparser ( self , argparser ) :
"""Other runtimes ( or users of ArgumentParser ) can pass their
subparser into here to collect the arguments here for a
subcommand .""" | super ( PackageManagerRuntime , self ) . init_argparser ( argparser )
# Ideally , we could use more subparsers for each action ( i . e .
# init and install ) . However , this is complicated by the fact
# that setuptools has its own calling conventions through the
# setup . py file , and to present a consistent cli to e... |
def wait ( self , duration = None , count = 0 ) :
"""Publish publishes the data argument to the given subject .
Args :
duration ( float ) : will wait for the given number of seconds
count ( count ) : stop of wait after n messages from any subject""" | start = time . time ( )
total = 0
while True :
type , result = self . _recv ( MSG , PING , OK )
if type is MSG :
total += 1
if self . _handle_msg ( result ) is False :
break
if count and total >= count :
break
elif type is PING :
self . _handle_ping ( ... |
def get_checksum ( self ) :
"""Returns a checksum based on the IDL that ignores comments and
ordering , but detects changes to types , parameter order ,
and enum values .""" | arr = [ ]
for elem in self . parsed :
s = elem_checksum ( elem )
if s :
arr . append ( s )
arr . sort ( )
# print arr
return md5 ( json . dumps ( arr ) ) |
def all ( cls ) :
"""Get all consts
: return : list""" | result = [ ]
for name in dir ( cls ) :
if not name . isupper ( ) :
continue
value = getattr ( cls , name )
if isinstance ( value , ItemsList ) :
result . append ( value [ 0 ] )
else :
result . append ( value )
return result |
def stemmer_middle_high_german ( text_l , rem_umlauts = True , exceptions = exc_dict ) :
"""text _ l : text in string format
rem _ umlauts : choose whether to remove umlauts from string
exceptions : hard - coded dictionary for the cases the algorithm fails""" | # Normalize text
text_l = normalize_middle_high_german ( text_l , to_lower_all = False , to_lower_beginning = True )
# Tokenize text
word_tokenizer = WordTokenizer ( "middle_high_german" )
text_l = word_tokenizer . tokenize ( text_l )
text = [ ]
for word in text_l :
try :
text . append ( exceptions [ word ]... |
def connect_post_namespaced_pod_attach ( self , name , namespace , ** kwargs ) : # noqa : E501
"""connect _ post _ namespaced _ pod _ attach # noqa : E501
connect POST requests to attach of Pod # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , pleas... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . connect_post_namespaced_pod_attach_with_http_info ( name , namespace , ** kwargs )
# noqa : E501
else :
( data ) = self . connect_post_namespaced_pod_attach_with_http_info ( name , namespace , ** kwargs )
# noqa :... |
def set_base_prompt ( self , * args , ** kwargs ) :
"""Cisco ASA in multi - context mode needs to have the base prompt updated
( if you switch contexts i . e . ' changeto ' )
This switch of ASA contexts can occur in configuration mode . If this
happens the trailing ' ( config * ' needs stripped off .""" | cur_base_prompt = super ( CiscoAsaSSH , self ) . set_base_prompt ( * args , ** kwargs )
match = re . search ( r"(.*)\(conf.*" , cur_base_prompt )
if match : # strip off ( conf . * from base _ prompt
self . base_prompt = match . group ( 1 )
return self . base_prompt |
def vel_disp_one ( self , gamma , rho0_r0_gamma , r_eff , r_ani , R_slit , dR_slit , FWHM ) :
"""computes one realisation of the velocity dispersion realized in the slit
: param gamma : power - law slope of the mass profile ( isothermal = 2)
: param rho0 _ r0 _ gamma : combination of Einstein radius and power -... | a = 0.551 * r_eff
while True :
r = self . P_r ( a )
# draw r
R , x , y = self . R_r ( r )
# draw projected R
x_ , y_ = self . displace_PSF ( x , y , FWHM )
# displace via PSF
bool = self . check_in_slit ( x_ , y_ , R_slit , dR_slit )
if bool is True :
break
sigma_s2 = self . sigm... |
def rigid_particles ( self , rigid_id = None ) :
"""Generate all particles in rigid bodies .
If a rigid _ id is specified , then this function will only yield particles
with a matching rigid _ id .
Parameters
rigid _ id : int , optional
Include only particles with this rigid body ID
Yields
mb . Compou... | for particle in self . particles ( ) :
if rigid_id is not None :
if particle . rigid_id == rigid_id :
yield particle
else :
if particle . rigid_id is not None :
yield particle |
def param_get ( param ) :
"""` ` param _ get < instance _ number > < param _ symbol > ` `
get the value of the request control
e . g . : :
param _ get 0 gain
: param Lv2Param param : Parameter that will be get your current value""" | instance = param . effect . instance
return 'param_get {} {}' . format ( instance , param . symbol ) |
def find ( self , id , columns = None ) :
"""Find a model by its primary key
: param id : The primary key value
: type id : mixed
: param columns : The columns to retrieve
: type columns : list
: return : The found model
: rtype : orator . Model""" | if columns is None :
columns = [ "*" ]
if isinstance ( id , list ) :
return self . find_many ( id , columns )
self . _query . where ( self . _model . get_qualified_key_name ( ) , "=" , id )
return self . first ( columns ) |
def uncolorize ( text ) :
"""uncolorize ( text )""" | match = re . match ( '(.*)\033\[[0-9;]+m(.+?)\033\[0m(.*)' , text )
try :
return '' . join ( match . groups ( ) )
except :
return text |
def _recv_close_ok ( self , method_frame ) :
'''Receive a close ack from the broker .''' | self . channel . _closed = True
self . channel . _closed_cb ( ) |
def clause_tokenize ( sentence ) :
"""Split on comma or parenthesis , if there are more then three words for each clause
> > > context = ' While I was walking home , this bird fell down in front of me . '
> > > clause _ tokenize ( context )
[ ' While I was walking home , ' , ' this bird fell down in front of ... | clause_re = re . compile ( r'((?:\S+\s){2,}\S+,|(?:\S+\s){3,}(?=\((?:\S+\s){2,}\S+\)))' )
clause_stem = clause_re . sub ( r'\1###clausebreak###' , sentence )
return [ c for c in clause_stem . split ( '###clausebreak###' ) if c != '' ] |
def get_model_string ( model ) :
"""This function returns the conventional action designator for a given model .""" | name = model if isinstance ( model , str ) else model . __name__
return normalize_string ( name ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.