signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _AddPropertiesForField ( field , cls ) :
"""Adds a public property for a protocol message field .
Clients can use this property to get and ( in the case
of non - repeated scalar fields ) directly set the value
of a protocol message field .
Args :
field : A FieldDescriptor for this field .
cls : The ... | # Catch it if we add other types that we should
# handle specially here .
assert _FieldDescriptor . MAX_CPPTYPE == 10
constant_name = field . name . upper ( ) + "_FIELD_NUMBER"
setattr ( cls , constant_name , field . number )
if field . label == _FieldDescriptor . LABEL_REPEATED :
_AddPropertiesForRepeatedField ( f... |
def execute_message_call ( laser_evm , callee_address , caller_address , origin_address , code , data , gas_limit , gas_price , value , track_gas = False , ) -> Union [ None , List [ GlobalState ] ] :
"""Execute a message call transaction from all open states .
: param laser _ evm :
: param callee _ address :
... | # TODO : Resolve circular import between . transaction and . . svm to import LaserEVM here
open_states = laser_evm . open_states [ : ]
del laser_evm . open_states [ : ]
for open_world_state in open_states :
next_transaction_id = get_next_transaction_id ( )
transaction = MessageCallTransaction ( world_state = op... |
def process_request ( self ) :
"""Processing the call and set response _ data .""" | self . response = self . request_handler . process_request ( self . method , self . request_data ) |
def add_item ( self , item , field_name = None ) :
"""Add the item to the specified section .
Intended for use with items of settings . ARMSTRONG _ SECTION _ ITEM _ MODEL .
Behavior on other items is undefined .""" | field_name = self . _choose_field_name ( field_name )
related_manager = getattr ( item , field_name )
related_manager . add ( self ) |
def ftdetect ( filename ) :
"""Determine if filename is markdown or notebook ,
based on the file extension .""" | _ , extension = os . path . splitext ( filename )
md_exts = [ '.md' , '.markdown' , '.mkd' , '.mdown' , '.mkdn' , '.Rmd' ]
nb_exts = [ '.ipynb' ]
if extension in md_exts :
return 'markdown'
elif extension in nb_exts :
return 'notebook'
else :
return None |
def GetByteSize ( self ) :
"""Retrieves the byte size of the data type definition .
Returns :
int : data type size in bytes or None if size cannot be determined .""" | if self . _byte_size is None and self . members :
self . _byte_size = 0
for member_definition in self . members :
byte_size = member_definition . GetByteSize ( )
if byte_size is None :
self . _byte_size = None
break
self . _byte_size = max ( self . _byte_size , by... |
def _apex2qd_nonvectorized ( self , alat , alon , height ) :
"""Convert from apex to quasi - dipole ( not - vectorised )
Parameters
alat : ( float )
Apex latitude in degrees
alon : ( float )
Apex longitude in degrees
height : ( float )
Height in km
Returns
qlat : ( float )
Quasi - dipole latitud... | alat = helpers . checklat ( alat , name = 'alat' )
# convert modified apex to quasi - dipole :
qlon = alon
# apex height
hA = self . get_apex ( alat )
if hA < height :
if np . isclose ( hA , height , rtol = 0 , atol = 1e-5 ) : # allow for values that are close
hA = height
else :
estr = 'height {... |
def read_value ( hive , key , vname = None , use_32bit_registry = False ) :
r'''Reads a registry value entry or the default value for a key . To read the
default value , don ' t pass ` ` vname ` `
Args :
hive ( str ) : The name of the hive . Can be one of the following :
- HKEY _ LOCAL _ MACHINE or HKLM
-... | return __utils__ [ 'reg.read_value' ] ( hive = hive , key = key , vname = vname , use_32bit_registry = use_32bit_registry ) |
def set_virtualization_realm_type ( self ) :
"""Sets the virtualization realm type from deployment properties
: return : None""" | log = logging . getLogger ( self . cls_logger + '.set_virtualization_realm_type' )
self . virtualization_realm_type = self . get_value ( 'cons3rt.deploymentRun.virtRealm.type' )
log . info ( 'Found virtualization realm type : {t}' . format ( t = self . virtualization_realm_type ) ) |
def build_wheel ( self , wheel , directory , compile_c = True ) : # type : ( str , str , bool ) - > None
"""Build an sdist into a wheel file .""" | arguments = [ '--no-deps' , '--wheel-dir' , directory , wheel ]
env_vars = self . _osutils . environ ( )
shim = ''
if not compile_c :
env_vars . update ( pip_no_compile_c_env_vars )
shim = pip_no_compile_c_shim
# Ignore rc and stderr from this command since building the wheels
# may fail and we will find out wh... |
def do_email_reply ( self , comment , entry , site ) :
"""Send email notification of a new comment to
the authors of the previous comments .""" | if not self . email_reply :
return
exclude_list = ( self . mail_comment_notification_recipients + [ author . email for author in entry . authors . all ( ) ] + [ comment . email ] )
recipient_list = ( set ( [ other_comment . email for other_comment in entry . comments if other_comment . email ] ) - set ( exclude_lis... |
def _is_boot_mode_uefi ( self ) :
"""Checks if the system is in uefi boot mode .
: return : ' True ' if the boot mode is uefi else ' False '""" | boot_mode = self . get_current_boot_mode ( )
return ( boot_mode == BOOT_MODE_MAP . get ( sys_cons . BIOS_BOOT_MODE_UEFI ) ) |
def children_to_list ( node ) :
"""Organize children structure .""" | if node [ 'type' ] == 'item' and len ( node [ 'children' ] ) == 0 :
del node [ 'children' ]
else :
node [ 'type' ] = 'folder'
node [ 'children' ] = list ( node [ 'children' ] . values ( ) )
node [ 'children' ] . sort ( key = lambda x : x [ 'name' ] )
node [ 'children' ] = map ( children_to_list , no... |
def toString ( self ) :
"""Returns almost original string .
If you want prettified string , try : meth : ` . prettify ` .
Returns :
str : Complete representation of the element with childs , endtag and so on .""" | output = ""
if self . childs or self . isOpeningTag ( ) :
output += self . tagToString ( )
for c in self . childs :
output += c . toString ( )
if self . endtag is not None :
output += self . endtag . tagToString ( )
elif not self . isEndTag ( ) :
output += self . tagToString ( )
return o... |
def _get_unique_child ( xtag , eltname ) :
"""Get the unique child element under xtag with name eltname""" | try :
results = xtag . findall ( eltname )
if len ( results ) > 1 :
raise Exception ( "Multiple elements found where 0/1 expected" )
elif len ( results ) == 1 :
return results [ 0 ]
else :
return None
except Exception :
return None |
def move_window ( self , destination = "" , session = None ) :
"""Move the current : class : ` Window ` object ` ` $ tmux move - window ` ` .
Parameters
destination : str , optional
the ` ` target window ` ` or index to move the window to , default :
empty string
session : str , optional
the ` ` target ... | session = session or self . get ( 'session_id' )
proc = self . cmd ( 'move-window' , '-s%s:%s' % ( self . get ( 'session_id' ) , self . index ) , '-t%s:%s' % ( session , destination ) , )
if proc . stderr :
raise exc . LibTmuxException ( proc . stderr )
self . server . _update_windows ( ) |
def _get_block_header ( self , block_hash , num ) :
"""Get block header by block header hash & number .
: param block _ hash :
: param num :
: return :""" | header_key = header_prefix + num + block_hash
block_header_data = self . db . get ( header_key )
header = rlp . decode ( block_header_data , sedes = BlockHeader )
return header |
def prepare_plot_data ( data_file ) :
"""Return a list of Plotly elements representing the network graph""" | G = ig . Graph . Read_GML ( data_file )
layout = G . layout ( 'graphopt' )
labels = list ( G . vs [ 'label' ] )
N = len ( labels )
E = [ e . tuple for e in G . es ]
community = G . community_multilevel ( ) . membership
communities = len ( set ( community ) )
color_list = community_colors ( communities )
Xn = [ layout [... |
def aggregate_detail ( slug_list , with_data_table = False ) :
"""Template Tag to display multiple metrics .
* ` ` slug _ list ` ` - - A list of slugs to display
* ` ` with _ data _ table ` ` - - if True , prints the raw data in a table .""" | r = get_r ( )
metrics_data = [ ]
granularities = r . _granularities ( )
# XXX converting granularties into their key - name for metrics .
keys = [ 'seconds' , 'minutes' , 'hours' , 'day' , 'week' , 'month' , 'year' ]
key_mapping = { gran : key for gran , key in zip ( GRANULARITIES , keys ) }
keys = [ key_mapping [ gran... |
def selection_range ( self ) :
""": rtype : int , int , int , int""" | selected = self . selectionModel ( ) . selection ( )
# type : QItemSelection
if self . selection_is_empty :
return - 1 , - 1 , - 1 , - 1
def range_to_tuple ( rng ) :
return rng . row ( ) , rng . column ( )
top_left = min ( range_to_tuple ( rng . topLeft ( ) ) for rng in selected )
bottom_right = max ( range_to_... |
def produceResource ( self , request , segments , webViewer ) :
"""Return a C { ( resource , subsegments ) } tuple or None , depending on whether
I wish to return an L { IResource } provider for the given set of segments
or not .""" | def thunk ( ) :
cr = getattr ( self , 'createResource' , None )
if cr is not None :
return cr ( )
else :
return self . createResourceWith ( webViewer )
return self . _produceIt ( segments , thunk ) |
def send_file ( self , filename , status = 200 ) :
"""Reads in the file ' filename ' and sends bytes to client
Parameters
filename : str
Filename of the file to read
status : int , optional
The HTTP status code , defaults to 200 ( OK )""" | if isinstance ( filename , Path ) and sys . version_info >= ( 3 , 5 ) :
self . message = filename . read_bytes ( )
else :
with io . FileIO ( str ( filename ) ) as f :
self . message = f . read ( )
self . status_code = status
self . send_headers ( )
self . write ( )
self . write_eof ( ) |
def get_more ( collection_name , num_to_return , cursor_id , ctx = None ) :
"""Get a * * getMore * * message .""" | if ctx :
return _get_more_compressed ( collection_name , num_to_return , cursor_id , ctx )
return _get_more_uncompressed ( collection_name , num_to_return , cursor_id ) |
def effective_info ( network ) :
"""Return the effective information of the given network .
. . note : :
For details , see :
Hoel , Erik P . , Larissa Albantakis , and Giulio Tononi .
“ Quantifying causal emergence shows that macro can beat micro . ”
Proceedings of the
National Academy of Sciences 110.4... | validate . is_network ( network )
sbs_tpm = convert . state_by_node2state_by_state ( network . tpm )
avg_repertoire = np . mean ( sbs_tpm , 0 )
return np . mean ( [ entropy ( repertoire , avg_repertoire , 2.0 ) for repertoire in sbs_tpm ] ) |
def wait ( self , timeout = None ) :
"""Wait for this operation to finish .
You can specify an optional timeout that defaults to no timeout if
None is passed . The result of the operation is returned from this
method . If the operation raised an exception , it is reraised from this
method .
Args :
timeo... | flag = self . _finished . wait ( timeout = timeout )
if flag is False :
raise TimeoutExpiredError ( "Timeout waiting for response to event loop operation" )
if self . _exception is not None :
self . _raise_exception ( )
return self . _result |
def addTransceiver ( self , trackOrKind , direction = 'sendrecv' ) :
"""Add a new : class : ` RTCRtpTransceiver ` .""" | self . __assertNotClosed ( )
# determine track or kind
if hasattr ( trackOrKind , 'kind' ) :
kind = trackOrKind . kind
track = trackOrKind
else :
kind = trackOrKind
track = None
if kind not in [ 'audio' , 'video' ] :
raise InternalError ( 'Invalid track kind "%s"' % kind )
# check direction
if direc... |
def split_words ( sentence , modify = True , keep_shorts = False ) :
"""Extract and yield the keywords from the sentence :
- Drop keywords that are too short ( keep _ shorts = False )
- Drop the accents ( modify = True )
- Make everything lower case ( modify = True )
- Try to separate the words as much as p... | if ( sentence == "*" ) :
yield sentence
return
# TODO : i18n
if modify :
sentence = sentence . lower ( )
sentence = strip_accents ( sentence )
words = FORCED_SPLIT_KEYWORDS_REGEX . split ( sentence )
if keep_shorts :
word_iter = words
else :
word_iter = __cleanup_word_array ( words )
for word in... |
def generate_ha_relation_data ( service , extra_settings = None ) :
"""Generate relation data for ha relation
Based on configuration options and unit interfaces , generate a json
encoded dict of relation data items for the hacluster relation ,
providing configuration for DNS HA or VIP ' s + haproxy clone sets... | _haproxy_res = 'res_{}_haproxy' . format ( service )
_relation_data = { 'resources' : { _haproxy_res : 'lsb:haproxy' , } , 'resource_params' : { _haproxy_res : 'op monitor interval="5s"' } , 'init_services' : { _haproxy_res : 'haproxy' } , 'clones' : { 'cl_{}_haproxy' . format ( service ) : _haproxy_res } , }
if extra_... |
def prepare_metadata ( metadata , source_metadata = None , append = False , append_list = False ) :
"""Prepare a metadata dict for an
: class : ` S3PreparedRequest < S3PreparedRequest > ` or
: class : ` MetadataPreparedRequest < MetadataPreparedRequest > ` object .
: type metadata : dict
: param metadata : ... | # Make a deepcopy of source _ metadata if it exists . A deepcopy is
# necessary to avoid modifying the original dict .
source_metadata = { } if not source_metadata else copy . deepcopy ( source_metadata )
prepared_metadata = { }
# Functions for dealing with metadata keys containing indexes .
def get_index ( key ) :
... |
def _LoadArtifactsFromFiles ( self , file_paths , overwrite_if_exists = True ) :
"""Load artifacts from file paths as json or yaml .""" | loaded_files = [ ]
loaded_artifacts = [ ]
for file_path in file_paths :
try :
with io . open ( file_path , mode = "r" , encoding = "utf-8" ) as fh :
logging . debug ( "Loading artifacts from %s" , file_path )
for artifact_val in self . ArtifactsFromYaml ( fh . read ( ) ) :
... |
def expand_defaults ( default , client = False , getenv = True , getshell = True ) :
"""Compile env , client _ env , shell and client _ shell commands
Execution rules :
- env ( ) and shell ( ) execute where the cat is loaded , if getenv and getshell
are True , respectively
- client _ env ( ) and client _ sh... | r = re . match ( r'env\((.*)\)' , default )
if r and not client and getenv :
default = os . environ . get ( r . groups ( ) [ 0 ] , '' )
r = re . match ( r'client_env\((.*)\)' , default )
if r and client and getenv :
default = os . environ . get ( r . groups ( ) [ 0 ] , '' )
r = re . match ( r'shell\((.*)\)' , d... |
def linkify_es_by_h ( self , hosts ) :
"""Add each escalation object into host . escalation attribute
: param hosts : host list , used to look for a specific host
: type hosts : alignak . objects . host . Hosts
: return : None""" | for escal in self : # If no host , no hope of having a service
if ( not hasattr ( escal , 'host_name' ) or escal . host_name . strip ( ) == '' or ( hasattr ( escal , 'service_description' ) and escal . service_description . strip ( ) != '' ) ) :
continue
# I must be NOT a escalation on for service
f... |
def remove_rule ( self , name ) :
"""Remove a rule from attributes .
Arguments :
name ( string ) : Rule name to remove .""" | self . _rule_attrs . remove ( name )
delattr ( self , name ) |
def _abs8 ( ins ) :
"""Absolute value of top of the stack ( 8 bits in AF )""" | output = _8bit_oper ( ins . quad [ 2 ] )
output . append ( 'call __ABS8' )
output . append ( 'push af' )
REQUIRES . add ( 'abs8.asm' )
return output |
def shrink_patch ( patch_path , target_file ) :
"""Shrinks a patch on patch _ path to contain only changes for target _ file .
: param patch _ path : path to the shrinked patch file
: param target _ file : filename of a file of which changes should be kept
: return : True if the is a section containing change... | logging . debug ( "Shrinking patch file %s to keep only %s changes." , patch_path , target_file )
shrinked_lines = [ ]
patch_file = None
try :
patch_file = open ( patch_path )
adding = False
search_line = "diff --git a/%s b/%s" % ( target_file , target_file )
for line in patch_file . read ( ) . split ( ... |
def notify_slack_channel ( self ) :
"""Post message to a defined Slack channel .""" | message = get_template ( template_file = 'slack/pipeline-prepare-ran.j2' , info = self . info )
if self . settings [ 'pipeline' ] [ 'notifications' ] [ 'slack' ] :
post_slack_message ( message = message , channel = self . settings [ 'pipeline' ] [ 'notifications' ] [ 'slack' ] , username = 'pipeline-bot' , icon_emo... |
def to_export ( export ) :
"""Serializes export to id string
: param export : object to serialize
: return : string id""" | from sevenbridges . models . storage_export import Export
if not export :
raise SbgError ( 'Export is required!' )
elif isinstance ( export , Export ) :
return export . id
elif isinstance ( export , six . string_types ) :
return export
else :
raise SbgError ( 'Invalid export parameter!' ) |
def urlunparse ( parts ) :
"""Unparse and encode parts of a URI .""" | scheme , netloc , path , params , query , fragment = parts
# Avoid encoding the windows drive letter colon
if RE_DRIVE_LETTER_PATH . match ( path ) :
quoted_path = path [ : 3 ] + parse . quote ( path [ 3 : ] )
else :
quoted_path = parse . quote ( path )
return parse . urlunparse ( ( parse . quote ( scheme ) , p... |
def select_by_value ( self , value ) :
"""Select all options that have a value matching the argument . That is , when given " foo " this
would select an option like :
< option value = " foo " > Bar < / option >
: Args :
- value - The value to match against
throws NoSuchElementException If there is no opti... | css = "option[value =%s]" % self . _escapeString ( value )
opts = self . _el . find_elements ( By . CSS_SELECTOR , css )
matched = False
for opt in opts :
self . _setSelected ( opt )
if not self . is_multiple :
return
matched = True
if not matched :
raise NoSuchElementException ( "Cannot locate ... |
def list_greps ( self , repo , packages ) :
"""Grep packages""" | pkg_list , pkg_size = [ ] , [ ]
for line in packages . splitlines ( ) :
if repo == "sbo" :
if line . startswith ( "SLACKBUILD NAME: " ) :
pkg_list . append ( line [ 17 : ] . strip ( ) )
pkg_size . append ( "0 K" )
else :
if line . startswith ( "PACKAGE NAME: " ) :
... |
def rename_columns ( columns , name_lists ) :
'''Renames numerical indices in column names returned by patsy dmatrix /
dmatrices calls based on the corresponding string levels .
Args :
columns ( list ) : List of cols from dmatrix ' s . design _ info . column _ names
name _ lists ( list ) : List of lists , w... | def _replace ( c , args ) :
grps = re . findall ( '([^\]]*)(\[(\d+)\])' , c )
for i , ( prefix , box , ind ) in enumerate ( grps ) :
c = c . replace ( prefix + box , prefix + '[%s]' % args [ i ] [ int ( ind ) ] )
return c
return [ _replace ( c , name_lists ) for c in columns ] |
def generate_numa ( self , vcpu_num ) :
"""Generate guest CPU < numa > XML child
Configures 1 , 2 or 4 vCPUs per cell .
Args :
vcpu _ num ( str ) : number of virtual CPUs
Returns :
lxml . etree . Element : numa XML element""" | if int ( vcpu_num ) == 2 : # 2 vCPUs is a special case .
# We wish to have 2 cells ,
# with 1 vCPU in each .
# This is also the common case .
total_cells = 2
cpus_per_cell = 1
elif int ( vcpu_num ) == 4 : # 4 vCPU is a special case .
# We wish to have 2 cells ,
# with 2 vCPUs in each .
total_cells = 2
c... |
def _find_child ( self , tag ) :
"""Find the child C { etree . Element } with the matching C { tag } .
@ raises L { WSDLParseError } : If more than one such elements are found .""" | tag = self . _get_namespace_tag ( tag )
children = self . _root . findall ( tag )
if len ( children ) > 1 :
raise WSDLParseError ( "Duplicate tag '%s'" % tag )
if len ( children ) == 0 :
return None
return children [ 0 ] |
def readImages ( self , path , recursive = False , numPartitions = - 1 , dropImageFailures = False , sampleRatio = 1.0 , seed = 0 ) :
"""Reads the directory of images from the local or remote source .
. . note : : If multiple jobs are run in parallel with different sampleRatio or recursive flag ,
there may be a... | warnings . warn ( "`ImageSchema.readImage` is deprecated. " + "Use `spark.read.format(\"image\").load(path)` instead." , DeprecationWarning )
spark = SparkSession . builder . getOrCreate ( )
image_schema = spark . _jvm . org . apache . spark . ml . image . ImageSchema
jsession = spark . _jsparkSession
jresult = image_s... |
def is_valid_poes ( self ) :
"""When computing hazard maps and / or uniform hazard spectra ,
the poes list must be non - empty .""" | if self . hazard_maps or self . uniform_hazard_spectra :
return bool ( self . poes )
else :
return True |
def dfs_grid_recursive ( grid , i , j , mark = 'X' , free = '.' ) :
"""DFS on a grid , mark connected component , iterative version
: param grid : matrix , 4 - neighborhood
: param i , j : cell in this matrix , start of DFS exploration
: param free : symbol for walkable cells
: param mark : symbol to overwr... | height = len ( grid )
width = len ( grid [ 0 ] )
grid [ i ] [ j ] = mark
# mark path
for ni , nj in [ ( i + 1 , j ) , ( i , j + 1 ) , ( i - 1 , j ) , ( i , j - 1 ) ] :
if 0 <= ni < height and 0 <= nj < width :
if grid [ ni ] [ nj ] == free :
dfs_grid ( grid , ni , nj ) |
def restart ( self ) :
"""Restarts the whole wizard from the beginning .""" | # hide all of the pages
for page in self . _pages . values ( ) :
page . hide ( )
pageId = self . startId ( )
try :
first_page = self . _pages [ pageId ]
except KeyError :
return
self . _currentId = pageId
self . _navigation = [ pageId ]
page_size = self . pageSize ( )
x = ( self . width ( ) - page_size . wi... |
def __replace_image_links ( self ) :
"""Replace links of placeholder images ( the name of which starts with
" py3o . " ) to point to a file saved the " Pictures " directory of the
archive .""" | image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self . content_trees : # Find draw : frame tags .
for draw_frame in content_tree . xpath ( image_expr , namespaces = self . namespaces ) : # Find the identifier of the image ( py3o . [ identifier ] ) .
image_id = draw_frame . ... |
def per_distro_data ( self ) :
"""Return download data by distro name and version .
: return : dict of cache data ; keys are datetime objects , values are
dict of distro name / version ( str ) to count ( int ) .
: rtype : dict""" | ret = { }
for cache_date in self . cache_dates :
data = self . _cache_get ( cache_date )
ret [ cache_date ] = { }
for distro_name , distro_data in data [ 'by_distro' ] . items ( ) :
if distro_name . lower ( ) == 'red hat enterprise linux server' :
distro_name = 'RHEL'
for distro_... |
def push_from ( iterable ) :
"""Creates a | push | object from an iterable . The resulting function
is not a coroutine , but can be chained to another | push | .
: param iterable : an iterable object .
: type iterable : : py : class : ` ~ collections . abc . Iterable `
: rtype : | push |""" | def p ( sink ) :
sink = sink ( )
for x in iterable :
sink . send ( x )
return push ( p , dont_wrap = True ) |
def get_objective_banks_by_ids ( self , objective_bank_ids = None ) :
"""Gets a ObjectiveBankList corresponding to the given IdList .
In plenary mode , the returned list contains all of the objective
banks specified in the Id list , in the order of the list ,
including duplicates , or an error results if an I... | if objective_bank_ids is None :
raise NullArgument ( )
banks = [ ]
# The following runs really slow . Perhaps get all banks and then inspect result for ids
for i in objective_bank_ids :
bank = None
url_path = construct_url ( 'objective_banks' , bank_id = i )
try :
bank = self . _get_request ( ur... |
def get_local_variable_or_declare_one ( self , raw_name , type = None ) :
'''This function will first check if raw _ name has been used to create some variables . If yes , the latest one
named in self . variable _ name _ mapping [ raw _ name ] will be returned . Otherwise , a new variable will be created and
th... | onnx_name = self . get_onnx_variable_name ( raw_name )
if onnx_name in self . variables :
return self . variables [ onnx_name ]
else :
variable = Variable ( raw_name , onnx_name , self . name , type )
self . variables [ onnx_name ] = variable
if raw_name in self . variable_name_mapping :
self . ... |
def require_clean_submodules ( repo_root , submodules ) :
"""Check on git submodules before distutils can do anything
Since distutils cannot be trusted to update the tree
after everything has been set in motion ,
this is not a distutils command .""" | # PACKAGERS : Add a return here to skip checks for git submodules
# don ' t do anything if nothing is actually supposed to happen
for do_nothing in ( '-h' , '--help' , '--help-commands' , 'clean' , 'submodule' ) :
if do_nothing in sys . argv :
return
status = _check_submodule_status ( repo_root , submodules... |
def add_sample ( self , name , labels , value , timestamp = None , exemplar = None ) :
"""Add a sample to the metric .
Internal - only , do not use .""" | self . samples . append ( Sample ( name , labels , value , timestamp , exemplar ) ) |
def preloop ( self ) :
"""adds the banner to the preloop""" | lines = textwrap . dedent ( self . banner ) . split ( "\n" )
for line in lines :
Console . _print ( "BLUE" , "" , line ) |
def shell ( cmd ) :
"Simple wrapper for calling docker , returning None on error and the output on success" | try :
return subprocess . check_output ( [ 'docker' ] + cmd , stderr = subprocess . STDOUT ) . decode ( 'utf8' ) . strip ( )
except subprocess . CalledProcessError :
return None |
def eval_grad ( self ) :
"""Compute gradient in Fourier domain .""" | # Compute D X - S
self . Ryf [ : ] = self . eval_Rf ( self . Yf )
# Map to spatial domain to multiply by mask
Ry = sl . irfftn ( self . Ryf , self . cri . Nv , self . cri . axisN )
# Multiply by mask
self . WRy [ : ] = ( self . W ** 2 ) * Ry
# Map back to frequency domain
WRyf = sl . rfftn ( self . WRy , self . cri . N... |
def rm ( venv_name ) :
"""Removes the venv by name""" | inenv = InenvManager ( )
venv = inenv . get_venv ( venv_name )
click . confirm ( "Delete dir {}" . format ( venv . path ) )
shutil . rmtree ( venv . path ) |
def extract_statements ( self ) :
"""Extract the statements from the json .""" | for p_info in self . _json :
para = RlimspParagraph ( p_info , self . doc_id_type )
self . statements . extend ( para . get_statements ( ) )
return |
def _candidate_tempdir_list ( ) :
"""Generate a list of candidate temporary directories which
_ get _ default _ tempdir will try .""" | dirlist = [ ]
# First , try the environment .
for envname in 'TMPDIR' , 'TEMP' , 'TMP' :
dirname = _os . getenv ( envname )
if dirname :
dirlist . append ( dirname )
# Failing that , try OS - specific locations .
if _os . name == 'nt' :
dirlist . extend ( [ r'c:\temp' , r'c:\tmp' , r'\temp' , r'\tmp... |
def http_basic_auth_group_member_required ( groups ) :
"""Decorator . Use it to specify a RPC method is available only to logged users with given permissions""" | if isinstance ( groups , six . string_types ) : # Check user is in a group
return auth . set_authentication_predicate ( http_basic_auth_check_user , [ auth . user_in_group , groups ] )
else : # Check user is in many group
return auth . set_authentication_predicate ( http_basic_auth_check_user , [ auth . user_in... |
def clean_twitter_list ( twitter_list , sent_tokenize , _treebank_word_tokenize , tagger , lemmatizer , lemmatize , stopset , first_cap_re , all_cap_re , digits_punctuation_whitespace_re , pos_set ) :
"""Extracts the * set * of keywords found in a Twitter list ( name + description ) .
Inputs : - twitter _ list : ... | name_lemmas , name_lemma_to_keywordbag = clean_document ( twitter_list [ "name" ] . replace ( "_" , " " ) . replace ( "-" , " " ) , sent_tokenize , _treebank_word_tokenize , tagger , lemmatizer , lemmatize , stopset , first_cap_re , all_cap_re , digits_punctuation_whitespace_re , pos_set )
description_lemmas , descript... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'url' ) and self . url is not None :
_dict [ 'url' ] = self . url
if hasattr ( self , 'limit_to_starting_hosts' ) and self . limit_to_starting_hosts is not None :
_dict [ 'limit_to_starting_hosts' ] = self . limit_to_starting_hosts
if hasattr ( self , 'crawl_speed' ) and self . c... |
def set_entry ( self , jid , * , name = _Sentinel , add_to_groups = frozenset ( ) , remove_from_groups = frozenset ( ) , timeout = None ) :
"""Set properties of a roster entry or add a new roster entry . The roster
entry is identified by its bare ` jid ` .
If an entry already exists , all values default to thos... | existing = self . items . get ( jid , Item ( jid ) )
post_groups = ( existing . groups | add_to_groups ) - remove_from_groups
post_name = existing . name
if name is not _Sentinel :
post_name = name
item = roster_xso . Item ( jid = jid , name = post_name , groups = [ roster_xso . Group ( name = group_name ) for grou... |
def best_model ( self ) :
"""Rebuilds the top scoring model from an optimisation .
Returns
model : AMPAL
Returns an AMPAL model of the top scoring parameters .
Raises
AttributeError
Raises a name error if the optimiser has not been run .""" | if not hasattr ( self , 'halloffame' ) :
raise AttributeError ( 'No best model found, have you ran the optimiser?' )
model = self . build_fn ( ( self . specification , self . sequences , self . parse_individual ( self . halloffame [ 0 ] ) ) )
return model |
def verification_list ( self , limit = 10 ) :
"""Get list of verifications . Uses GET to / verifications interface .
: Returns : ( list ) Verification list as specified ` here < https : / / cloud . knuverse . com / docs / api / # api - Verifications - Get _ verification _ list > ` _ .""" | # TODO add arguments for paging and stuff
params = { }
params [ "limit" ] = limit
response = self . _get ( url . verifications , params = params )
self . _check_response ( response , 200 )
return self . _create_response ( response ) . get ( "verifications" ) |
def on_lxml_loads ( self , lxml , config , content , ** kwargs ) :
"""The ` lxml < https : / / pypi . org / project / lxml / > ` _ loads method .
: param module lxml : The ` ` lxml ` ` module
: param class config : The loading config class
: param str content : The content to deserialize
: param str encodin... | # NOTE : lazy import of XMLParser because class requires lxml to exist on import
from . . contrib . xml_parser import XMLParser
return XMLParser . from_xml ( content , encoding = kwargs . pop ( "encoding" , "utf-8" ) ) . to_dict ( ) |
def EAS2TAS ( ARSP , GPS , BARO , ground_temp = 25 ) :
'''EAS2TAS from ARSP . Temp''' | tempK = ground_temp + 273.15 - 0.0065 * GPS . Alt
return sqrt ( 1.225 / ( BARO . Press / ( 287.26 * tempK ) ) ) |
def update_teams_listwidgets ( self ) :
"""Clears all items from the listwidgets and then adds everything from the self . agents list again to the right team
: return :""" | self . bot_names_to_agent_dict . clear ( )
self . blue_listwidget . clear ( )
self . orange_listwidget . clear ( )
for agent in self . agents :
name = self . validate_name ( agent . ingame_name , agent )
if not agent . get_team ( ) :
self . blue_listwidget . addItem ( name )
else :
self . or... |
def stage_tc_create_attribute ( self , attribute_type , attribute_value , resource ) :
"""Add an attribute to a resource .
Args :
attribute _ type ( str ) : The attribute type ( e . g . , Description ) .
attribute _ value ( str ) : The attribute value .
resource ( obj ) : An instance of tcex resource class ... | attribute_data = { 'type' : str ( attribute_type ) , 'value' : str ( attribute_value ) }
# handle default description and source
if attribute_type in [ 'Description' , 'Source' ] :
attribute_data [ 'displayed' ] = True
attrib_resource = resource . attributes ( )
attrib_resource . body = json . dumps ( attribute_dat... |
def get_magicc_region_to_openscm_region_mapping ( inverse = False ) :
"""Get the mappings from MAGICC to OpenSCM regions .
This is not a pure inverse of the other way around . For example , we never provide
" GLOBAL " as a MAGICC return value because it ' s unnecesarily confusing when we also
have " World " .... | def get_openscm_replacement ( in_region ) :
world = "World"
if in_region in ( "WORLD" , "GLOBAL" ) :
return world
if in_region in ( "BUNKERS" ) :
return DATA_HIERARCHY_SEPARATOR . join ( [ world , "Bunkers" ] )
elif in_region . startswith ( ( "NH" , "SH" ) ) :
in_region = in_regi... |
def get_network_by_id ( self , network_id : int ) -> Network :
"""Get a network from the database by its identifier .""" | return self . session . query ( Network ) . get ( network_id ) |
def as_html ( self , labels = None , predict_proba = True , show_predicted_value = True , ** kwargs ) :
"""Returns the explanation as an html page .
Args :
labels : desired labels to show explanations for ( as barcharts ) .
If you ask for a label for which an explanation wasn ' t
computed , will throw an ex... | def jsonize ( x ) :
return json . dumps ( x , ensure_ascii = False )
if labels is None and self . mode == "classification" :
labels = self . available_labels ( )
this_dir , _ = os . path . split ( __file__ )
bundle = open ( os . path . join ( this_dir , 'bundle.js' ) , encoding = "utf8" ) . read ( )
out = u'''<... |
def call_rename ( * args , ** kwargs ) :
'''Rename a device .
Options :
* * * id * * : Specifies a device ID . Only one device at a time .
* * * title * * : Title of the device .
CLI Example :
. . code - block : : bash
salt ' * ' hue . rename id = 1 title = ' WC for cats ' ''' | dev_id = _get_devices ( kwargs )
if len ( dev_id ) > 1 :
raise CommandExecutionError ( "Only one device can be renamed at a time" )
if 'title' not in kwargs :
raise CommandExecutionError ( "Title is missing" )
return _set ( dev_id [ 0 ] , { "name" : kwargs [ 'title' ] } , method = "" ) |
def format_time ( date_obj , time_obj = None , datebox = False , dt_type = None , classes = None ) :
"""Returns formatted HTML5 elements based on given datetime object .
By default returns a time element , but will return a . datebox if requested .
dt _ type allows passing dt _ start or dt _ end for hcal format... | if not time_obj :
time_obj = getattr ( date_obj , 'time' , None )
if dt_type :
classes = '{0} {1}' . format ( classes , dt_type )
if datebox :
classes = '{0} {1}' . format ( classes , datebox )
return { 'date_obj' : date_obj , 'time_obj' : time_obj , 'datebox' : datebox , 'current_year' : datetime . date . ... |
def build ( self , id , ** kwargs ) :
"""Builds the Configurations for the Specified Set
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 _ function ( response... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . build_with_http_info ( id , ** kwargs )
else :
( data ) = self . build_with_http_info ( id , ** kwargs )
return data |
def layers_to_solr ( self , layers ) :
"""Sync n layers in Solr .""" | layers_dict_list = [ ]
layers_success_ids = [ ]
layers_errors_ids = [ ]
for layer in layers :
layer_dict , message = layer2dict ( layer )
if not layer_dict :
layers_errors_ids . append ( [ layer . id , message ] )
LOGGER . error ( message )
else :
layers_dict_list . append ( layer_di... |
def _checkObjectToInfer ( self , sensationList ) :
"""Checks that objects have the correct format before being sent to the
experiment .""" | for sensations in sensationList :
if set ( sensations . keys ( ) ) != set ( range ( self . numColumns ) ) :
raise ValueError ( "Invalid number of cortical column sensations sent to experiment" )
for pair in sensations . values ( ) :
if not isinstance ( pair , tuple ) or len ( pair ) != 2 or not ... |
def logpdf_sum ( self , f , y , Y_metadata = None ) :
"""Convenience function that can overridden for functions where this could
be computed more efficiently""" | return np . sum ( self . logpdf ( f , y , Y_metadata = Y_metadata ) ) |
def new_tag ( self , name : str , category : str = None ) -> models . Tag :
"""Create a new tag .""" | new_tag = self . Tag ( name = name , category = category )
return new_tag |
def rn ( op , rc = None , r = None ) : # pylint : disable = redefined - outer - name , invalid - name
"""This function is a wrapper for
: meth : ` ~ pywbem . WBEMConnection . ReferenceNames ` .
Instance - level use : Retrieve the instance paths of the association
instances referencing a source instance .
Cl... | return CONN . ReferenceNames ( op , ResultClass = rc , Role = r ) |
def connect_inputs ( self , datas ) :
"""Connects input ` ` Pipers ` ` to " datas " input data in the correct order
determined , by the ` ` Piper . ornament ` ` attribute and the ` ` Dagger . _ cmp ` `
function .
It is assumed that the input data is in the form of an iterator and
that all inputs have the sa... | start_pipers = self . get_inputs ( )
self . log . debug ( '%s trying to connect inputs in the order %s' % ( repr ( self ) , repr ( start_pipers ) ) )
for piper , data in izip ( start_pipers , datas ) :
piper . connect ( [ data ] )
self . log . debug ( '%s succesfuly connected inputs' % repr ( self ) ) |
def export ( self , nidm_version , export_dir ) :
"""Create prov entities and activities .""" | # Create " Excursion set " entity
self . add_attributes ( ( ( PROV [ 'type' ] , self . type ) , ( NIDM_IN_COORDINATE_SPACE , self . coord_space . id ) , ( PROV [ 'label' ] , self . label ) , ) )
if self . visu is not None :
self . add_attributes ( ( ( DC [ 'description' ] , self . visu . id ) , ) )
if self . clust_... |
def remove_nan_observations ( x , y , z ) :
r"""Remove all x , y , and z where z is nan .
Will not destroy original values .
Parameters
x : array _ like
x coordinate
y : array _ like
y coordinate
z : array _ like
observation value
Returns
x , y , z
List of coordinate observation pairs without ... | x_ = x [ ~ np . isnan ( z ) ]
y_ = y [ ~ np . isnan ( z ) ]
z_ = z [ ~ np . isnan ( z ) ]
return x_ , y_ , z_ |
def tokentype ( self , s ) :
"""Parses string and returns a ( Tokenizer . TYPE , value ) tuple .""" | a = s [ 0 ] if len ( s ) > 0 else ""
b = s [ 1 ] if len ( s ) > 1 else ""
if a . isdigit ( ) or ( a in [ "+" , "-" ] and b . isdigit ( ) ) :
return self . parse_number ( s )
elif a == '"' :
return self . parse_string ( s )
elif a == ':' :
return self . parse_colon ( s )
elif a == ';' :
return self . par... |
def prependsitedir ( projdir , * args ) :
"""like sys . addsitedir ( ) but gives the added directory preference
over system directories . The paths will be normalized for dots and
slash direction before being added to the path .
projdir : the path you want to add to sys . path . If its a
a file , the parent... | # let the user be lazy and send a file , we will convert to parent directory
# of file
if path . isfile ( projdir ) :
projdir = path . dirname ( projdir )
projdir = path . abspath ( projdir )
# any args are considered paths that need to be joined to the
# projdir to get to the correct directory .
libpaths = [ ]
for... |
def timedelta_total_minutes ( td , strict = False ) :
"""Convert / round a : cls : ` timedelta ` to an integral number of minutes .
If ` ` strict ` ` is true than raises : exc : ` ValueError ` if the
: cls : ` ~ datetime . timedelta ` is not a integral multiple of 60 seconds .""" | minutes , seconds = divmod ( td . days * 24 * 3600 + td . seconds , 60 )
if seconds or td . microseconds :
if strict :
raise ValueError ( "%r is not an integral multiple of 60 seconds" , td )
if seconds > 30 or ( seconds == 30 and td . microseconds > 0 ) :
minutes += 1
return minutes |
def missingDataValue ( self ) :
"""Returns the value to indicate missing data .""" | value = getMissingDataValue ( self . _array )
fieldNames = self . _array . dtype . names
# If the missing value attibute is a list with the same length as the number of fields ,
# return the missing value for field that equals the self . nodeName .
if hasattr ( value , '__len__' ) and len ( value ) == len ( fieldNames ... |
def connect_euca ( host = None , aws_access_key_id = None , aws_secret_access_key = None , port = 8773 , path = '/services/Eucalyptus' , is_secure = False , ** kwargs ) :
"""Connect to a Eucalyptus service .
: type host : string
: param host : the host name or ip address of the Eucalyptus server
: type aws _ ... | from boto . ec2 import EC2Connection
from boto . ec2 . regioninfo import RegionInfo
# Check for values in boto config , if not supplied as args
if not aws_access_key_id :
aws_access_key_id = config . get ( 'Credentials' , 'euca_access_key_id' , None )
if not aws_secret_access_key :
aws_secret_access_key = confi... |
def create ( self , field_type , unique_name ) :
"""Create a new FieldInstance
: param unicode field _ type : The Field Type of this field
: param unicode unique _ name : An application - defined string that uniquely identifies the new resource
: returns : Newly created FieldInstance
: rtype : twilio . rest... | data = values . of ( { 'FieldType' : field_type , 'UniqueName' : unique_name , } )
payload = self . _version . create ( 'POST' , self . _uri , data = data , )
return FieldInstance ( self . _version , payload , assistant_sid = self . _solution [ 'assistant_sid' ] , task_sid = self . _solution [ 'task_sid' ] , ) |
def build_current_graph ( ) :
"""Read current state of SQL items from the current project state .
Returns :
( SQLStateGraph ) Current project state graph .""" | graph = SQLStateGraph ( )
for app_name , config in apps . app_configs . items ( ) :
try :
module = import_module ( '.' . join ( ( config . module . __name__ , SQL_CONFIG_MODULE ) ) )
sql_items = module . sql_items
except ( ImportError , AttributeError ) :
continue
for sql_item in sql... |
def create ( model_config , model , source , storage , start_letter , length , temperature ) :
"""Vel factory function""" | return GenerateTextCommand ( model_config , model , source , storage , start_letter , length , temperature ) |
def feature_extraction ( self , algorithms ) :
"""Get a list of features .
Every algorithm has to return the features as a list .""" | assert type ( algorithms ) is list
features = [ ]
for algorithm in algorithms :
new_features = algorithm ( self )
assert len ( new_features ) == algorithm . get_dimension ( ) , "Expected %i features from algorithm %s, got %i features" % ( algorithm . get_dimension ( ) , str ( algorithm ) , len ( new_features ) ... |
def convert ( self , names , src = None , to = 'ISO3' , enforce_list = False , not_found = 'not found' , exclude_prefix = [ 'excl\\w.*' , 'without' , 'w/o' ] ) :
"""Convert names from a list to another list .
Note
A lot of the functionality can also be done directly in Pandas
DataFrames .
For example :
co... | # The list to tuple conversion is necessary for Matlab interface
names = list ( names ) if ( isinstance ( names , tuple ) or isinstance ( names , set ) ) else names
names = names if isinstance ( names , list ) else [ names ]
names = [ str ( n ) for n in names ]
outlist = names . copy ( )
to = [ self . _validate_input_p... |
def setup_app ( command , conf , vars ) :
"""Place any commands to setup tg2raptorized here""" | load_environment ( conf . global_conf , conf . local_conf )
setup_schema ( command , conf , vars )
bootstrap . bootstrap ( command , conf , vars ) |
def help ( self , * arg , ** kwargs ) :
"""Help helps you figure out what commands do .
Example usage : ! help code
To see all commands : ! commands""" | name = arg [ 0 ]
try :
callback = self . _commands [ name ]
except KeyError :
self . _logger . info ( ' !help not found for: %s' , name )
return self . do_help . __doc__
return callback . __doc__ |
def is_invalid_params_py3 ( func , * args , ** kwargs ) :
"""Use inspect . signature instead of inspect . getargspec or
inspect . getfullargspec ( based on inspect . signature itself ) as it provides
more information about function parameters .
. . versionadded : 1.11.2""" | signature = inspect . signature ( func )
parameters = signature . parameters
unexpected = set ( kwargs . keys ( ) ) - set ( parameters . keys ( ) )
if len ( unexpected ) > 0 :
return True
params = [ parameter for name , parameter in parameters . items ( ) if name not in kwargs ]
params_required = [ param for param ... |
def focusInEvent ( self , event ) :
"""Processes when this widget recieves focus .
: param event | < QFocusEvent >""" | if not self . signalsBlocked ( ) :
self . focusChanged . emit ( True )
self . focusEntered . emit ( )
return super ( XTextEdit , self ) . focusInEvent ( event ) |
def delete ( gandi , resource , force ) :
"""Delete a hosted certificate .
Resource can be a FQDN or an ID""" | infos = gandi . hostedcert . infos ( resource )
if not infos :
return
if not force :
proceed = click . confirm ( 'Are you sure to delete the following hosted ' 'certificates ?\n' + '\n' . join ( [ '%s: %s' % ( res [ 'id' ] , res [ 'subject' ] ) for res in infos ] ) + '\n' )
if not proceed :
return
f... |
def update ( input , refdir = "jref$" , local = None , interactive = False , wcsupdate = True ) :
"""Updates headers of files given as input to point to the new reference files
NPOLFILE and D2IMFILE required with the new C version of MultiDrizzle .
Parameters
input : string or list
Name of input file or fil... | print ( 'UPDATENPOL Version' , __version__ + '(' + __version_date__ + ')' )
# expand ( as needed ) the list of input files
files , fcol = parseinput . parseinput ( input )
if not interactive : # expand reference directory name ( if necessary ) to
# interpret IRAF or environment variable names
rdir = fu . osfn ( ref... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.