signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def popall ( self , key , default = _marker ) :
"""Remove all occurrences of key and return the list of corresponding
values .
If key is not found , default is returned if given , otherwise
KeyError is raised .""" | found = False
identity = self . _title ( key )
ret = [ ]
for i in range ( len ( self . _impl . _items ) - 1 , - 1 , - 1 ) :
item = self . _impl . _items [ i ]
if item [ 0 ] == identity :
ret . append ( item [ 2 ] )
del self . _impl . _items [ i ]
self . _impl . incr_version ( )
f... |
def get_views ( self , mo_refs , properties = None ) :
"""Get a list of local view ' s for multiple managed objects .
: param mo _ refs : The list of ManagedObjectReference ' s that views are to be created for .
: type mo _ refs : ManagedObjectReference
: param properties : The properties to retrieve in the v... | property_specs = [ ]
for mo_ref in mo_refs :
property_spec = self . create ( 'PropertySpec' )
property_spec . type = str ( mo_ref . _type )
if properties is None :
properties = [ ]
else : # Only retrieve the requested properties
if properties == "all" :
property_spec . all = ... |
def cancel ( self , caller ) :
"""Recursively cancel all threaded background processes of this Callable .
This is called automatically for actions if program deactivates .""" | for o in { i for i in self . children if isinstance ( i , AbstractCallable ) } :
o . cancel ( caller ) |
def get_code ( self ) :
"""Get the stub code for this class .
: sig : ( ) - > List [ str ]
: return : Lines of stub code for this class .""" | stub = [ ]
bases = ( "(" + ", " . join ( self . bases ) + ")" ) if len ( self . bases ) > 0 else ""
slots = { "n" : self . name , "b" : bases }
if ( len ( self . children ) == 0 ) and ( len ( self . variables ) == 0 ) :
stub . append ( "class %(n)s%(b)s: ..." % slots )
else :
stub . append ( "class %(n)s%(b)s:"... |
def sparklines ( numbers = [ ] , num_lines = 1 , emph = None , verbose = False , minimum = None , maximum = None , wrap = None ) :
"""Return a list of ' sparkline ' strings for a given list of input numbers .
The list of input numbers may contain None values , too , for which the
resulting sparkline will contai... | assert num_lines > 0
if len ( numbers ) == 0 :
return [ '' ]
# raise warning for negative numbers
_check_negatives ( numbers )
values = scale_values ( numbers , num_lines = num_lines , minimum = minimum , maximum = maximum )
# find values to be highlighted
emphasized = _check_emphasis ( numbers , emph ) if emph els... |
def list_external_store ( self , project_name , external_store_name_pattern = None , offset = 0 , size = 100 ) :
"""list the logstore in a projectListLogStoreResponse
Unsuccessful opertaion will cause an LogException .
: type project _ name : string
: param project _ name : the Project name
: type logstore ... | # need to use extended method to get more
if int ( size ) == - 1 or int ( size ) > MAX_LIST_PAGING_SIZE :
return list_more ( self . list_external_store , int ( offset ) , int ( size ) , MAX_LIST_PAGING_SIZE , project_name , external_store_name_pattern )
headers = { }
params = { }
resource = "/externalstores"
if ext... |
def import_image ( self , name , tags = None ) :
"""Import image tags from a Docker registry into an ImageStream
: return : bool , whether tags were imported""" | stream_import_file = os . path . join ( self . os_conf . get_build_json_store ( ) , 'image_stream_import.json' )
with open ( stream_import_file ) as f :
stream_import = json . load ( f )
return self . os . import_image ( name , stream_import , tags = tags ) |
def prjs_view_prj ( self , * args , ** kwargs ) :
"""View the , in the projects table view selected , project .
: returns : None
: rtype : None
: raises : None""" | i = self . prjs_tablev . currentIndex ( )
item = i . internalPointer ( )
if item :
prj = item . internal_data ( )
self . view_prj ( prj ) |
def matches ( self , string , context = None ) :
"""Search for all matches with current configuration against input _ string
: param string : string to search into
: type string : str
: param context : context to use
: type context : dict
: return : A custom list of matches
: rtype : Matches""" | matches = Matches ( input_string = string )
if context is None :
context = { }
self . _matches_patterns ( matches , context )
self . _execute_rules ( matches , context )
return matches |
def select_channel ( self , channel ) :
"""Select a channel .
: param channel : Number of channel .""" | for i in str ( channel ) :
key = int ( i ) + 0xe300
self . send_key ( key ) |
def change_custom_svc_var ( self , service , varname , varvalue ) :
"""Change custom service variable
Format of the line that triggers function call : :
CHANGE _ CUSTOM _ SVC _ VAR ; < host _ name > ; < service _ description > ; < varname > ; < varvalue >
: param service : service to edit
: type service : a... | if varname . upper ( ) in service . customs :
service . modified_attributes |= DICT_MODATTR [ "MODATTR_CUSTOM_VARIABLE" ] . value
service . customs [ varname . upper ( ) ] = varvalue
self . send_an_element ( service . get_update_status_brok ( ) ) |
def create_from_name_and_dictionary ( self , name , datas ) :
"""Return a populated object Category from dictionary datas""" | category = ObjectCategory ( name )
self . set_common_datas ( category , name , datas )
if "order" in datas :
category . order = int ( datas [ "order" ] )
return category |
def _create_channel ( self , channel ) :
"""Create channel with optional ban and invite exception lists .""" | super ( ) . _create_channel ( channel )
if 'EXCEPTS' in self . _isupport :
self . channels [ channel ] [ 'exceptlist' ] = None
if 'INVEX' in self . _isupport :
self . channels [ channel ] [ 'inviteexceptlist' ] = None |
def get_data_home ( data_home = None ) :
"""Return the path of the arviz data dir .
This folder is used by some dataset loaders to avoid downloading the
data several times .
By default the data dir is set to a folder named ' arviz _ data ' in the
user home folder .
Alternatively , it can be set by the ' A... | if data_home is None :
data_home = os . environ . get ( "ARVIZ_DATA" , os . path . join ( "~" , "arviz_data" ) )
data_home = os . path . expanduser ( data_home )
if not os . path . exists ( data_home ) :
os . makedirs ( data_home )
return data_home |
def compare_vm_configs ( new_config , current_config ) :
'''Compares virtual machine current and new configuration , the current is the
one which is deployed now , and the new is the target config . Returns the
differences between the objects in a dictionary , the keys are the
configuration parameter keys and... | diffs = { }
keys = set ( new_config . keys ( ) )
# These values identify the virtual machine , comparison is unnecessary
keys . discard ( 'name' )
keys . discard ( 'datacenter' )
keys . discard ( 'datastore' )
for property_key in ( 'version' , 'image' ) :
if property_key in keys :
single_value_diff = recurs... |
def list_backups ( self , limit = 20 , marker = 0 ) :
"""Returns a paginated list of backups for this instance .""" | return self . manager . _list_backups_for_instance ( self , limit = limit , marker = marker ) |
def get_enabled_references ( self , datas , meta_references ) :
"""Get enabled manifest references declarations .
Enabled references are defined through meta references declaration ,
every other references are ignored .
Arguments :
datas ( dict ) : Data where to search for reference declarations .
This is... | references = OrderedDict ( )
for section in meta_references :
references [ section ] = self . get_reference ( datas , section )
return references |
def _set_show_mpls_ldp_targeted_peer_one ( self , v , load = False ) :
"""Setter method for show _ mpls _ ldp _ targeted _ peer _ one , mapped from YANG variable / brocade _ mpls _ rpc / show _ mpls _ ldp _ targeted _ peer _ one ( rpc )
If this variable is read - only ( config : false ) in the
source YANG file ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = show_mpls_ldp_targeted_peer_one . show_mpls_ldp_targeted_peer_one , is_leaf = True , yang_name = "show-mpls-ldp-targeted-peer-one" , rest_name = "show-mpls-ldp-targeted-peer-one" , parent = self , path_helper = self . _path_h... |
def write_out_config ( self , config_file ) :
"""Write out the configuration file
: param config _ file :
: return :
Note : this will erase all comments from the config file""" | with open ( config_file , 'w' ) as f :
json . dump ( self . params , f , indent = 2 , separators = ( ',' , ': ' ) ) |
def is_connection_error ( e ) :
"""Checks if error e pertains to a connection issue""" | return ( isinstance ( e , err . InterfaceError ) and e . args [ 0 ] == "(0, '')" ) or ( isinstance ( e , err . OperationalError ) and e . args [ 0 ] in operation_error_codes . values ( ) ) |
def error ( self , nCells = 15 ) :
'''calculate the standard deviation of all fitted images ,
averaged to a grid''' | s0 , s1 = self . fits [ 0 ] . shape
aR = s0 / s1
if aR > 1 :
ss0 = int ( nCells )
ss1 = int ( ss0 / aR )
else :
ss1 = int ( nCells )
ss0 = int ( ss1 * aR )
L = len ( self . fits )
arr = np . array ( self . fits )
arr [ np . array ( self . _fit_masks ) ] = np . nan
avg = np . tile ( np . nanmean ( arr , ... |
def checkout ( self , ref , branch = None ) :
"""Do a git checkout of ` ref ` .""" | return git_checkout ( self . repo_dir , ref , branch = branch ) |
def on_records ( self , records ) :
"""Called when one or more RECORD messages have been received .""" | handler = self . handlers . get ( "on_records" )
if callable ( handler ) :
handler ( records ) |
def encode_request ( username , password , uuid , owner_uuid , is_owner_connection , client_type , serialization_version , client_hazelcast_version ) :
"""Encode request into client _ message""" | client_message = ClientMessage ( payload_size = calculate_size ( username , password , uuid , owner_uuid , is_owner_connection , client_type , serialization_version , client_hazelcast_version ) )
client_message . set_message_type ( REQUEST_TYPE )
client_message . set_retryable ( RETRYABLE )
client_message . append_str ... |
def new_bundle ( self , name : str , created_at : dt . datetime = None ) -> models . Bundle :
"""Create a new file bundle .""" | new_bundle = self . Bundle ( name = name , created_at = created_at )
return new_bundle |
async def count ( self , text , opts = None ) :
'''Count the number of nodes which result from a storm query .
Args :
text ( str ) : Storm query text .
opts ( dict ) : Storm query options .
Returns :
( int ) : The number of nodes resulting from the query .''' | i = 0
async for _ in self . cell . eval ( text , opts = opts , user = self . user ) :
i += 1
return i |
def get_transactions_filtered ( self , asset_id , operation = None ) :
"""Get a list of transactions filtered on some criteria""" | txids = backend . query . get_txids_filtered ( self . connection , asset_id , operation )
for txid in txids :
yield self . get_transaction ( txid ) |
def starargs ( self ) :
"""The positional arguments that unpack something .
: type : list ( Starred )""" | args = self . args or [ ]
return [ arg for arg in args if isinstance ( arg , Starred ) ] |
def get_config ( name , region = None , key = None , keyid = None , profile = None ) :
'''Get the configuration for a cache cluster .
CLI example : :
salt myminion boto _ elasticache . get _ config myelasticache''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
if not conn :
return None
try :
cc = conn . describe_cache_clusters ( name , show_cache_node_info = True )
except boto . exception . BotoServerError as e :
msg = 'Failed to get config for cache cluster {0}.' . format ( name... |
def cmd_link_ports ( self ) :
'''show available ports''' | ports = mavutil . auto_detect_serial ( preferred_list = [ '*FTDI*' , "*Arduino_Mega_2560*" , "*3D_Robotics*" , "*USB_to_UART*" , '*PX4*' , '*FMU*' ] )
for p in ports :
print ( "%s : %s : %s" % ( p . device , p . description , p . hwid ) ) |
async def async_init ( self ) :
"""During async init we just need to create a HTTP session so we can keep
outgoing connexions to the platform alive .""" | self . session = aiohttp . ClientSession ( )
asyncio . get_event_loop ( ) . create_task ( self . _deferred_init ( ) ) |
def postpend_location ( bel_string : str , location_model ) -> str :
"""Rip off the closing parentheses and adds canonicalized modification .
I did this because writing a whole new parsing model for the data would be sad and difficult
: param bel _ string : BEL string representing node
: param dict location _... | if not all ( k in location_model for k in { NAMESPACE , NAME } ) :
raise ValueError ( 'Location model missing namespace and/or name keys: {}' . format ( location_model ) )
return "{}, loc({}:{}))" . format ( bel_string [ : - 1 ] , location_model [ NAMESPACE ] , ensure_quotes ( location_model [ NAME ] ) ) |
def cast ( self , dtype ) :
"""Cast data and gradient of this Parameter to a new data type .
Parameters
dtype : str or numpy . dtype
The new data type .""" | self . dtype = dtype
if self . _data is None :
return
with autograd . pause ( ) :
self . _data = [ i . astype ( dtype ) for i in self . _data ]
if self . _grad is None :
return
self . _grad = [ i . astype ( dtype ) for i in self . _grad ]
autograd . mark_variables ( self . _data , self . _gr... |
def primitive ( self ) :
"""Entry as Python primitive .""" | primitive = { }
if self . entry_number is not None :
primitive [ 'entry-number' ] = self . entry_number
if self . item_hash is not None :
primitive [ 'item-hash' ] = self . item_hash
primitive [ 'timestamp' ] = self . timestamp . strftime ( fmt )
return primitive |
def deduplicate ( args ) :
"""% prog deduplicate fastafile
Wraps ` cd - hit - est ` to remove duplicate sequences .""" | p = OptionParser ( deduplicate . __doc__ )
p . set_align ( pctid = 96 , pctcov = 0 )
p . add_option ( "--fast" , default = False , action = "store_true" , help = "Place sequence in the first cluster" )
p . add_option ( "--consensus" , default = False , action = "store_true" , help = "Compute consensus sequences" )
p . ... |
def validate_path ( xj_path ) :
"""Validates XJ path .
: param str xj _ path : XJ Path
: raise : XJPathError if validation fails .""" | if not isinstance ( xj_path , str ) :
raise XJPathError ( 'XJPath must be a string' )
for path in split ( xj_path , '.' ) :
if path == '*' :
continue
if path . startswith ( '@' ) :
if path == '@first' or path == '@last' :
continue
try :
int ( path [ 1 : ] )
... |
def check_command ( args ) :
"""Checks that all dependencies in the specified requirements file are
up to date .""" | outdated = check_requirements_file ( args . requirements_file , args . skip_packages )
if outdated :
print ( 'Requirements in {} are out of date:' . format ( args . requirements_file ) )
for item in outdated :
print ( ' * {} is {} latest is {}.' . format ( * item ) )
sys . exit ( 1 )
else :
prin... |
def _process_marked_lines ( lines , markers ) :
"""Run regexes against message ' s marked lines to strip signature .
> > > _ process _ marked _ lines ( [ ' Some text ' , ' ' , ' Bob ' ] , ' tes ' )
( [ ' Some text ' , ' ' ] , [ ' Bob ' ] )""" | # reverse lines and match signature pattern for reversed lines
signature = RE_REVERSE_SIGNATURE . match ( markers [ : : - 1 ] )
if signature :
return ( lines [ : - signature . end ( ) ] , lines [ - signature . end ( ) : ] )
return ( lines , None ) |
def to_numpy_vectors ( self , variable_order = None , dtype = np . float , index_dtype = np . int64 , sort_indices = False ) :
"""Convert a binary quadratic model to numpy arrays .
Args :
variable _ order ( iterable , optional ) :
If provided , labels the variables ; otherwise , row / column indices are used ... | linear = self . linear
quadratic = self . quadratic
num_variables = len ( linear )
num_interactions = len ( quadratic )
irow = np . empty ( num_interactions , dtype = index_dtype )
icol = np . empty ( num_interactions , dtype = index_dtype )
qdata = np . empty ( num_interactions , dtype = dtype )
if variable_order is N... |
def users ( self , request , uuid = None ) :
"""A list of users connected to the project""" | project = self . get_object ( )
queryset = project . get_users ( )
# we need to handle filtration manually because we want to filter only project users , not projects .
filter_backend = filters . UserConcatenatedNameOrderingBackend ( )
queryset = filter_backend . filter_queryset ( request , queryset , self )
queryset =... |
def real_value ( value , digit ) :
"""function to calculate the real value
we need to devide the value by the digit
e . g .
value = 100
digit = 2
return : " 1.0" """ | return str ( float ( value ) / math . pow ( 10 , float ( digit ) ) ) |
def send_many ( kwargs_list ) :
"""Similar to mail . send ( ) , but this function accepts a list of kwargs .
Internally , it uses Django ' s bulk _ create command for efficiency reasons .
Currently send _ many ( ) can ' t be used to send emails with priority = ' now ' .""" | emails = [ ]
for kwargs in kwargs_list :
emails . append ( send ( commit = False , ** kwargs ) )
Email . objects . bulk_create ( emails ) |
def send ( self , data ) :
"""Send data to the child process through .""" | self . stdin . write ( data )
self . stdin . flush ( ) |
def getGraphFieldCount ( self , graph_name ) :
"""Returns number of fields for graph with name graph _ name .
@ param graph _ name : Graph Name
@ return : Number of fields for graph .""" | graph = self . _getGraph ( graph_name , True )
return graph . getFieldCount ( ) |
def get_context_data ( self , ** kwargs ) :
"""Returns the context data to provide to the template .""" | context = kwargs
if 'view' not in context :
context [ 'view' ] = self
# Insert the considered forum , topic and post into the context
context [ 'forum' ] = self . get_forum ( )
context [ 'topic' ] = self . get_topic ( )
context [ 'post' ] = self . get_post ( )
# Handles the preview of the attachments
if context [ '... |
def triangle_area ( e1 , e2 , e3 ) :
"""Get the area of triangle formed by three vectors .
Parameters are three three - dimensional numpy arrays representing
vectors of triangle ' s edges in Cartesian space .
: returns :
Float number , the area of the triangle in squared units of coordinates ,
or numpy ar... | # calculating edges length
e1_length = numpy . sqrt ( numpy . sum ( e1 * e1 , axis = - 1 ) )
e2_length = numpy . sqrt ( numpy . sum ( e2 * e2 , axis = - 1 ) )
e3_length = numpy . sqrt ( numpy . sum ( e3 * e3 , axis = - 1 ) )
# calculating half perimeter
s = ( e1_length + e2_length + e3_length ) / 2.0
# applying Heron '... |
def authorize ( credentials , client_class = Client ) :
"""Login to Google API using OAuth2 credentials .
This is a shortcut function which
instantiates : class : ` gspread . client . Client `
and performs login right away .
: returns : : class : ` gspread . Client ` instance .""" | client = client_class ( auth = credentials )
client . login ( )
return client |
def find_static_library ( library_name , library_path ) :
"""Given the raw name of a library in ` library _ name ` , tries to find a
static library with this name in the given ` library _ path ` . ` library _ path `
is automatically extended with common library directories on Linux and Mac
OS X .""" | variants = [ "lib{0}.a" , "{0}.a" , "{0}.lib" , "lib{0}.lib" ]
if is_unix_like ( ) :
extra_libdirs = [ "/usr/local/lib64" , "/usr/local/lib" , "/usr/lib64" , "/usr/lib" , "/lib64" , "/lib" ]
else :
extra_libdirs = [ ]
for path in extra_libdirs :
if path not in library_path and os . path . isdir ( path ) :
... |
def import_fonts ( style_less , fontname , font_subdir ) :
"""Copy all custom fonts to ~ / . jupyter / custom / fonts / and
write import statements to style _ less""" | ftype_dict = { 'woff2' : 'woff2' , 'woff' : 'woff' , 'ttf' : 'truetype' , 'otf' : 'opentype' , 'svg' : 'svg' }
define_font = ( "@font-face {{font-family: {fontname};\n\tfont-weight:" "{weight};\n\tfont-style: {style};\n\tsrc: local('{fontname}')," "\n\turl('fonts{sepp}{fontfile}') format('{ftype}');}}\n" )
fontname = f... |
def _serve_experiment_runs ( self , request ) :
"""Serve a JSON runs of an experiment , specified with query param
` experiment ` , with their nested data , tag , populated . Runs returned are
ordered by started time ( aka first event time ) with empty times sorted last ,
and then ties are broken by sorting o... | results = [ ]
if self . _db_connection_provider :
exp_id = request . args . get ( 'experiment' )
runs_dict = collections . OrderedDict ( )
db = self . _db_connection_provider ( )
cursor = db . execute ( '''
SELECT
Runs.run_id,
Runs.run_name,
Runs.started_time,
... |
def iter_singleton_referents ( self ) :
"""Iterator of all of the singleton members of the context set .
NOTE : this evaluates entities one - at - a - time , and does not handle relational constraints .""" | try :
for member in self . __dict__ [ 'referential_domain' ] . iter_entities ( ) :
if self [ 'target' ] . is_entailed_by ( member ) and ( self [ 'distractor' ] . empty ( ) or not self [ 'distractor' ] . is_entailed_by ( member ) ) :
yield member [ 'num' ] , member
except KeyError :
raise Exc... |
def _copyPort ( port : LPort , targetParent : Union [ LPort ] , reverseDirection ) :
"""add port to LPort for interface""" | d = port . direction
side = port . side
if reverseDirection :
d = PortType . opposite ( d )
side = PortSide . opposite ( side )
newP = LPort ( targetParent . parentNode , d , side , name = port . name )
if isinstance ( targetParent , LPort ) :
targetParent . children . append ( newP )
newP . parent = ta... |
def nl_list_del ( obj ) :
"""https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / include / netlink / list . h # L49.
Positional arguments :
obj - - nl _ list _ head class instance .""" | obj . next . prev = obj . prev
obj . prev . next_ = obj . next_ |
def parse ( self , filePath , skipLines = 0 , separator = ',' , stringSeparator = '"' , lineSeparator = '\n' ) :
"""Loads a CSV file""" | self . filename = filePath
f = open ( filePath )
if lineSeparator == '\n' :
lines = f . readlines ( )
else :
lines = f . read ( ) . split ( lineSeparator )
f . flush ( )
f . close ( )
lines = lines [ skipLines : ]
self . lines = [ ]
self . comments = [ ]
for l in lines : # print l
if len ( l ) != 0 and l [ ... |
def scale_and_crop_with_ranges ( im , size , size_range = None , crop = False , upscale = False , zoom = None , target = None , ** kwargs ) :
"""An easy _ thumbnails processor that accepts a ` size _ range ` tuple , which
indicates that one or both dimensions can give by a number of pixels in
order to minimize ... | min_width , min_height = size
# if there ' s no restriction on range , or range isn ' t given , just act as
# normal
if min_width == 0 or min_height == 0 or not size_range :
return scale_and_crop ( im , size , crop , upscale , zoom , target , ** kwargs )
max_width = min_width + size_range [ 0 ]
max_height = min_hei... |
def placeholder_data_view ( self , request , id ) :
"""Return placeholder data for the given layout ' s template .""" | # See : ` fluent _ pages . pagetypes . fluentpage . admin . FluentPageAdmin ` .
try :
layout = models . Layout . objects . get ( pk = id )
except models . Layout . DoesNotExist :
json = { 'success' : False , 'error' : 'Layout not found' }
status = 404
else :
placeholders = layout . get_placeholder_data ... |
def GetMemActiveMB ( self ) :
'''Retrieves the amount of memory the virtual machine is actively using its
estimated working set size .''' | counter = c_uint ( )
ret = vmGuestLib . VMGuestLib_GetMemActiveMB ( self . handle . value , byref ( counter ) )
if ret != VMGUESTLIB_ERROR_SUCCESS :
raise VMGuestLibException ( ret )
return counter . value |
def sign_serialize ( privkey , expire_after = 3600 , requrl = None , algorithm_name = DEFAULT_ALGO , ** kwargs ) :
"""Produce a JWT compact serialization by generating a header , payload ,
and signature using the privkey and algorithm specified .
The privkey object must contain at least a member named pubkey . ... | assert algorithm_name in ALGORITHM_AVAILABLE
algo = ALGORITHM_AVAILABLE [ algorithm_name ]
addy = algo . pubkey_serialize ( privkey . pubkey )
header = _jws_header ( addy , algo ) . decode ( 'utf8' )
payload = _build_payload ( expire_after , requrl , ** kwargs )
signdata = "{}.{}" . format ( header , payload )
signatur... |
def rsl_push_reading ( self , value , stream_id ) :
"""Push a reading to the RSL directly .""" | # FIXME : Fix this with timestamp from clock manager task
err = self . sensor_log . push ( stream_id , 0 , value )
return [ err ] |
def params ( self ) :
"""Raises an ` ` AttributeError ` ` if the definition is not callable .
Otherwise returns a list of ` ValueElement ` that represents the params .""" | if self . context . el_type in [ Function , Subroutine ] :
return self . evaluator . element . parameters |
def head ( self , limit = 25 , ** fetch_kwargs ) :
"""shortcut to fetch the first few entries from query expression .
Equivalent to fetch ( order _ by = " KEY " , limit = 25)
: param limit : number of entries
: param fetch _ kwargs : kwargs for fetch
: return : query result""" | return self . fetch ( order_by = "KEY" , limit = limit , ** fetch_kwargs ) |
def remove_all_events ( self , calendar_id ) :
'''Removes all events from a calendar . WARNING : Be very careful using this .''' | # todo : incomplete
now = datetime . now ( tz = self . timezone )
# timezone ?
start_time = datetime ( year = now . year - 1 , month = now . month , day = now . day , hour = now . hour , minute = now . minute , second = now . second , tzinfo = self . timezone )
end_time = datetime ( year = now . year + 1 , month = now ... |
def dates ( self , start_date , end_date , return_name = False ) :
"""Calculate holidays observed between start date and end date
Parameters
start _ date : starting date , datetime - like , optional
end _ date : ending date , datetime - like , optional
return _ name : bool , optional , default = False
If ... | start_date = Timestamp ( start_date )
end_date = Timestamp ( end_date )
filter_start_date = start_date
filter_end_date = end_date
if self . year is not None :
dt = Timestamp ( datetime ( self . year , self . month , self . day ) )
if return_name :
return Series ( self . name , index = [ dt ] )
else ... |
def __authenticate ( self , login , password , authz_id = b"" , authmech = None ) :
"""AUTHENTICATE command
Actually , it is just a wrapper to the real commands ( one by
mechanism ) . We try all supported mechanisms ( from the
strongest to the weakest ) until we find one supported by the
server .
Then we ... | if "SASL" not in self . __capabilities :
raise Error ( "SASL not supported by the server" )
srv_mechanisms = self . get_sasl_mechanisms ( )
if authmech is None or authmech not in SUPPORTED_AUTH_MECHS :
mech_list = SUPPORTED_AUTH_MECHS
else :
mech_list = [ authmech ]
for mech in mech_list :
if mech not i... |
def use ( self , url , name = 'mytable' ) :
'''Changes the data provider
> > > yql . use ( ' http : / / myserver . com / mytables . xml ' )''' | self . yql_table_url = url
self . yql_table_name = name
return { 'table url' : url , 'table name' : name } |
def subkeys ( self , path ) :
"""A generalized form that can return multiple subkeys .""" | for _ in subpaths_for_path_range ( path , hardening_chars = "'pH" ) :
yield self . subkey_for_path ( _ ) |
def _round_field ( values , name , freq ) :
"""Indirectly access pandas rounding functions by wrapping data
as a Series and calling through ` . dt ` attribute .
Parameters
values : np . ndarray or dask . array - like
Array - like container of datetime - like values
name : str ( ceil , floor , round )
Na... | if isinstance ( values , dask_array_type ) :
from dask . array import map_blocks
return map_blocks ( _round_series , values , name , freq = freq , dtype = np . datetime64 )
else :
return _round_series ( values , name , freq ) |
def list_entitlements_options ( f ) :
"""Options for list entitlements subcommand .""" | @ common_entitlements_options
@ decorators . common_cli_config_options
@ decorators . common_cli_list_options
@ decorators . common_cli_output_options
@ decorators . common_api_auth_options
@ decorators . initialise_api
@ click . argument ( "owner_repo" , metavar = "OWNER/REPO" , callback = validators . validate_owner_... |
def reconnect ( self ) :
"""Reconnect with the last arguments passed to self . connect ( )""" | self . connect ( * self . _saved_connect . args , ** self . _saved_connect . kwargs ) |
def _set_initial ( self , initial ) :
"""If no option is selected initially , select the first option .""" | super ( Select , self ) . _set_initial ( initial )
if not self . _value and self . options :
self . value = self . options [ 0 ] |
def get_identity ( self , record : Record ) -> str :
"""Evaluates and returns the identity as specified in the schema .
: param record : Record which is used to determine the identity .
: return : The evaluated identity
: raises : IdentityError if identity cannot be determined .""" | context = self . schema_context . context
context . add_record ( record )
identity = self . identity . evaluate ( context )
if not identity :
raise IdentityError ( 'Could not determine identity using {}. Record is {}' . format ( self . identity . code_string , record ) )
context . remove_record ( )
return identity |
def _get_hostname ( self , hostname , metric ) :
"""If hostname is None , look at label _ to _ hostname setting""" | if hostname is None and self . label_to_hostname is not None :
for label in metric . label :
if label . name == self . label_to_hostname :
return label . value + self . label_to_hostname_suffix
return hostname |
def _safemembers ( members ) :
"""Check members of a tar archive for safety .
Ensure that they do not contain paths or links outside of where we
need them - this would only happen if the archive wasn ' t made by
eqcorrscan .
: type members : : class : ` tarfile . TarFile `
: param members : an open tarfil... | base = _resolved ( "." )
for finfo in members :
if _badpath ( finfo . name , base ) :
print ( finfo . name , "is blocked (illegal path)" )
elif finfo . issym ( ) and _badlink ( finfo , base ) :
print ( finfo . name , "is blocked: Hard link to" , finfo . linkname )
elif finfo . islnk ( ) and ... |
def add_table ( self , t ) :
"""remember to call pop _ element after done with table""" | self . push_element ( )
self . _page . append ( t . node )
self . cur_element = t |
def select_deployment_to_run ( env_name , deployments = None , command = 'build' ) : # noqa pylint : disable = too - many - branches , too - many - statements , too - many - locals
"""Query user for deployments to run .""" | if deployments is None or not deployments :
return [ ]
deployments_to_run = [ ]
num_deployments = len ( deployments )
if num_deployments == 1 :
selected_deployment_index = 1
else :
print ( '' )
print ( 'Configured deployments:' )
for i , deployment in enumerate ( deployments ) :
print ( " %d... |
def set_color ( self , fg = None , bg = None , intensify = False , target = sys . stdout ) :
"""Set foreground - and background colors and intensity .""" | raise NotImplementedError |
def update_campaign_start ( self , campaign_id , ** kwargs ) : # noqa : E501
"""Start a campaign . # noqa : E501
This command will begin the process of starting a campaign . # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass asynchronous ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . update_campaign_start_with_http_info ( campaign_id , ** kwargs )
# noqa : E501
else :
( data ) = self . update_campaign_start_with_http_info ( campaign_id , ** kwargs )
# noqa : E501
return data |
def ssh ( host , forward_agent = False , sudoable = False , max_attempts = 1 , max_timeout = 5 , ssh_password = None ) :
"""Manages a SSH connection to the desired host .
Will leverage your ssh config at ~ / . ssh / config if available
: param host : the server to connect to
: type host : str
: param forwar... | with closing ( SSHClient ( ) ) as client :
client . set_missing_host_key_policy ( AutoAddPolicy ( ) )
cfg = { "hostname" : host , "timeout" : max_timeout , }
if ssh_password :
cfg [ 'password' ] = ssh_password
ssh_config = SSHConfig ( )
user_config_file = os . path . expanduser ( "~/.ssh/con... |
def monitor ( msg , * args , ** kwargs ) :
"""Log a message with severity ' MON ' on the root logger .""" | if len ( logging . root . handlers ) == 0 :
logging . basicConfig ( )
logging . root . monitor ( msg , * args , ** kwargs ) |
def _open_terminal ( ) :
"""Open pty master and return ( master _ fd , tty _ name ) .""" | for x in 'pqrstuvwxyzPQRST' :
for y in '0123456789abcdef' :
pty_name = '/dev/pty' + x + y
try :
fd = os . open ( pty_name , os . O_RDWR )
except OSError :
continue
return ( fd , '/dev/tty' + x + y )
raise OSError ( 'out of pty devices' ) |
def get_processor_status ( self , p , x , y ) :
"""Get the status of a given core and the application executing on it .
Returns
: py : class : ` . ProcessorStatus `
Representation of the current state of the processor .""" | # Get the VCPU base
address = ( self . read_struct_field ( "sv" , "vcpu_base" , x , y ) + self . structs [ b"vcpu" ] . size * p )
# Get the VCPU data
data = self . read ( address , self . structs [ b"vcpu" ] . size , x , y )
# Build the kwargs that describe the current state
state = { name . decode ( 'utf-8' ) : struct... |
def set_debug_level ( self , level ) :
"""Sets the debug level for this router ( default is 0 ) .
: param level : level number""" | yield from self . _hypervisor . send ( 'vm set_debug_level "{name}" {level}' . format ( name = self . _name , level = level ) ) |
def parameters ( self ) :
"""Return the model parameters .""" | try :
return self . _parameters
except AttributeError :
None
parameters = [ ]
parameters . extend ( self . grid_points . dtype . names )
model_configuration = self . _configuration . get ( "model" , { } )
# Continuum
# Note : continuum cannot just be ' True ' , it should be a dictionary
n = len ( parameters )
c... |
def argrelmax ( data , axis = 0 , order = 1 , mode = 'clip' ) :
"""Calculate the relative maxima of ` data ` .
. . versionadded : : 0.11.0
Parameters
data : ndarray
Array in which to find the relative maxima .
axis : int , optional
Axis over which to select from ` data ` . Default is 0.
order : int , ... | return argrelextrema ( data , np . greater , axis , order , mode ) |
def build_report ( self , msg = '' ) :
"""Resposible for constructing a report to be output as part of the build .
Returns report as a string .""" | shutit_global . shutit_global_object . yield_to_draw ( )
s = '\n'
s += '################################################################################\n'
s += '# COMMAND HISTORY BEGIN ' + shutit_global . shutit_global_object . build_id + '\n'
s += self . get_commands ( )
s += '# COMMAND HISTORY END ' + shutit_global ... |
def set_elem ( elem_ref , elem ) :
"""Sets element referenced by the elem _ ref . Returns the elem .
: param elem _ ref :
: param elem :
: return :""" | if elem_ref is None or elem_ref == elem or not is_elem_ref ( elem_ref ) :
return elem
elif elem_ref [ 0 ] == ElemRefObj :
setattr ( elem_ref [ 1 ] , elem_ref [ 2 ] , elem )
return elem
elif elem_ref [ 0 ] == ElemRefArr :
elem_ref [ 1 ] [ elem_ref [ 2 ] ] = elem
return elem |
def tag_subcat_info ( mrf_lines , subcat_rules ) :
'''Adds subcategorization information ( hashtags ) to verbs and adpositions ;
Argument subcat _ rules must be a dict containing subcategorization information ,
loaded via method load _ subcat _ info ( ) ;
Performs word lemma lookups in subcat _ rules , and in... | i = 0
while ( i < len ( mrf_lines ) ) :
line = mrf_lines [ i ]
if line . startswith ( ' ' ) :
lemma_match = analysisLemmaPat . match ( line )
if lemma_match :
lemma = lemma_match . group ( 1 )
# Find whether there is subcategorization info associated
# with t... |
def crypt ( header , body_bytes , secret ) :
"""TACACS + uses a shared secret key ( known to both the client and server )
to obfuscate the body of sent packets . Only the packet body ( not
the header ) is obfuscated .
https : / / datatracker . ietf . org / doc / draft - ietf - opsawg - tacacs / ? include _ te... | # noqa
# B = unsigned char
# ! I = network - order ( big - endian ) unsigned int
body_length = len ( body_bytes )
unhashed = ( struct . pack ( '!I' , header . session_id ) + six . b ( secret ) + struct . pack ( 'B' , header . version ) + struct . pack ( 'B' , header . seq_no ) )
pad = hashed = md5 ( unhashed ) . digest... |
def _write ( self , context , report_dir , report_name , assets_dir = None , template = None ) :
"""Writes the data in ` context ` in the report ' s template to
` report _ name ` in ` report _ dir ` .
If ` assets _ dir ` is supplied , copies all assets for this report
to the specified directory .
If ` templ... | if template is None :
template = self . _get_template ( )
report = template . render ( context )
output_file = os . path . join ( report_dir , report_name )
with open ( output_file , 'w' , encoding = 'utf-8' ) as fh :
fh . write ( report )
if assets_dir :
self . _copy_static_assets ( assets_dir ) |
def do_work_spec ( self , args ) :
'''dump the contents of an existing work spec''' | work_spec_name = self . _get_work_spec_name ( args )
spec = self . task_master . get_work_spec ( work_spec_name )
if args . json :
self . stdout . write ( json . dumps ( spec , indent = 4 , sort_keys = True ) + '\n' )
else :
yaml . safe_dump ( spec , self . stdout ) |
def prepare_index_file ( self ) :
"""Makes sure that GIT index file we use per job ( by modifying environment variable GIT _ INDEX _ FILE )
is not locked and empty . Git . fetch _ job uses ` git read - tree ` to updates this index . For new jobs , we start
with an empty index - that ' s why we delete it every t... | if os . getenv ( 'AETROS_GIT_INDEX_FILE' ) :
self . index_path = os . getenv ( 'AETROS_GIT_INDEX_FILE' )
return
import tempfile
h , path = tempfile . mkstemp ( 'aetros-git' , '' , self . temp_path )
self . index_path = path
# we give git a unique file path for that index . However , git expect it to be non - ex... |
def _set_cfunctions ( self ) :
"""Set all ctypes functions and attach them to attributes .""" | void = ctypes . c_void_p
pointer = ctypes . POINTER
self . _cfactory ( attr = self . user32 , func = "GetSystemMetrics" , argtypes = [ INT ] , restype = INT )
self . _cfactory ( attr = self . user32 , func = "EnumDisplayMonitors" , argtypes = [ HDC , void , self . monitorenumproc , LPARAM ] , restype = BOOL , )
self . ... |
def compile_dictionary ( self , lang , wordlists , encoding , output ) :
"""Compile user dictionary .""" | cmd = [ self . binary , '--lang' , lang , '--encoding' , codecs . lookup ( filters . PYTHON_ENCODING_NAMES . get ( encoding , encoding ) . lower ( ) ) . name , 'create' , 'master' , output ]
wordlist = ''
try :
output_location = os . path . dirname ( output )
if not os . path . exists ( output_location ) :
... |
def process_fastq_minimal ( fastq , ** kwargs ) :
"""Swiftly extract minimal features ( length and timestamp ) from a rich fastq file""" | infastq = handle_compressed_input ( fastq )
try :
df = pd . DataFrame ( data = [ rec for rec in fq_minimal ( infastq ) if rec ] , columns = [ "timestamp" , "lengths" ] )
except IndexError :
logging . error ( "Fatal: Incorrect file structure for fastq_minimal" )
sys . exit ( "Error: file does not match expec... |
def run ( self , burst = False ) :
"""Periodically check whether there ' s any job that should be put in the queue ( score
lower than current time ) .""" | self . register_birth ( )
self . _install_signal_handlers ( )
try :
while True :
self . log . debug ( "Entering run loop" )
start_time = time . time ( )
if self . acquire_lock ( ) :
self . enqueue_jobs ( )
self . remove_lock ( )
if burst :
... |
def get_asset_content_form_for_update ( self , asset_content_id ) :
"""Gets the asset content form for updating an existing asset content .
A new asset content form should be requested for each update
transaction .
arg : asset _ content _ id ( osid . id . Id ) : the ` ` Id ` ` of the
` ` AssetContent ` `
... | # Implemented from template for
# osid . repository . AssetAdminSession . get _ asset _ content _ form _ for _ update _ template
from dlkit . abstract_osid . id . primitives import Id as ABCId
from . objects import AssetContentForm
collection = JSONClientValidated ( 'repository' , collection = 'Asset' , runtime = self ... |
def make_make_email_data ( to , cc = None , bcc = None , subject = None , body = None ) :
"""Creates either a simple " mailto : " URL or complete e - mail message with
( blind ) carbon copies and a subject and a body .
: param str | iterable to : The email address ( recipient ) . Multiple
values are allowed .... | def multi ( val ) :
if not val :
return ( )
if isinstance ( val , str_type ) :
return ( val , )
return tuple ( val )
delim = '?'
data = [ 'mailto:' ]
if not to :
raise ValueError ( '"to" must not be empty or None' )
data . append ( ',' . join ( multi ( to ) ) )
for key , val in ( ( 'cc' ... |
def write_json_to_file ( json_data , filename = "metadata" ) :
"""Write all JSON in python dictionary to a new json file .
: param dict json _ data : JSON data
: param str filename : Target filename ( defaults to ' metadata . jsonld ' )
: return None :""" | logger_jsons . info ( "enter write_json_to_file" )
json_data = rm_empty_fields ( json_data )
# Use demjson to maintain unicode characters in output
json_bin = demjson . encode ( json_data , encoding = 'utf-8' , compactly = False )
# Write json to file
try :
open ( "{}.jsonld" . format ( filename ) , "wb" ) . write ... |
def expand ( self , url ) :
"""Base expand method . Only visits the link , and return the response
url""" | url = self . clean_url ( url )
response = self . _get ( url )
if response . ok :
return response . url
raise ExpandingErrorException |
def addElement ( self , * ele ) :
"""add element to lattice element list
: param ele : magnetic element defined in element module
return total element number""" | for el in list ( Models . flatten ( ele ) ) :
e = copy . deepcopy ( el )
self . _lattice_eleobjlist . append ( e )
self . _lattice_elenamelist . append ( e . name )
self . _lattice_elecnt += 1
# update lattice , i . e . beamline element
# self . _ lattice . setConf ( Models . makeLatticeString ( self . ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.