signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def create ( cls , data = None , api_key = None , endpoint = None , add_headers = None , ** kwargs ) :
"""Create an event on your PagerDuty account .""" | cls . validate ( data )
inst = cls ( api_key = api_key )
endpoint = ''
return inst . request ( 'POST' , endpoint = endpoint , data = data , query_params = kwargs , add_headers = add_headers , ) |
def delete_cookies ( ) :
"""Deletes cookie ( s ) as provided by the query string and redirects to cookie list .
tags :
- Cookies
parameters :
- in : query
name : freeform
explode : true
allowEmptyValue : true
schema :
type : object
additionalProperties :
type : string
style : form
produces... | cookies = dict ( request . args . items ( ) )
r = app . make_response ( redirect ( url_for ( "view_cookies" ) ) )
for key , value in cookies . items ( ) :
r . delete_cookie ( key = key )
return r |
def setLayout ( self , value ) :
"""Sets the worksheet layout , keeping it sorted by position
: param value : the layout to set""" | new_layout = sorted ( value , key = lambda k : k [ 'position' ] )
self . getField ( 'Layout' ) . set ( self , new_layout ) |
def match_any ( self , match ) :
"""Matches any object .
arg : match ( boolean ) : ` ` true ` ` to match any object ` ` , ` `
` ` false ` ` to match no objects
* compliance : mandatory - - This method must be implemented . *""" | match_key = '_id'
param = '$exists'
if match :
flag = 'true'
else :
flag = 'false'
if match_key in self . _query_terms :
self . _query_terms [ match_key ] [ param ] = flag
else :
self . _query_terms [ match_key ] = { param : flag } |
def fit ( self , inputs = None , job_name = None , include_cls_metadata = False , ** kwargs ) :
"""Start a hyperparameter tuning job .
Args :
inputs : Information about the training data . Please refer to the ` ` fit ( ) ` ` method of
the associated estimator , as this can take any of the following forms :
... | if isinstance ( inputs , list ) or isinstance ( inputs , RecordSet ) :
self . estimator . _prepare_for_training ( inputs , ** kwargs )
else :
self . estimator . _prepare_for_training ( job_name )
self . _prepare_for_training ( job_name = job_name , include_cls_metadata = include_cls_metadata )
self . latest_tun... |
def start_runs ( logdir , steps , run_name , thresholds , mask_every_other_prediction = False ) :
"""Generate a PR curve with precision and recall evenly weighted .
Arguments :
logdir : The directory into which to store all the runs ' data .
steps : The number of steps to run for .
run _ name : The name of ... | tf . compat . v1 . reset_default_graph ( )
tf . compat . v1 . set_random_seed ( 42 )
# Create a normal distribution layer used to generate true color labels .
distribution = tf . compat . v1 . distributions . Normal ( loc = 0. , scale = 142. )
# Sample the distribution to generate colors . Lets generate different numbe... |
def create_detector ( self , detector ) :
"""Creates a new detector .
Args :
detector ( object ) : the detector model object . Will be serialized as
JSON .
Returns :
dictionary of the response ( created detector model ) .""" | resp = self . _post ( self . _u ( self . _DETECTOR_ENDPOINT_SUFFIX ) , data = detector )
resp . raise_for_status ( )
return resp . json ( ) |
def get_data_from_ilx ( self , ilx_id ) :
'''Gets full meta data ( expect their annotations and relationships ) from is ILX ID''' | ilx_id = self . fix_ilx ( ilx_id )
url_base = self . base_path + "ilx/search/identifier/{identifier}?key={APIKEY}"
url = url_base . format ( identifier = ilx_id , APIKEY = self . APIKEY )
output = self . get ( url )
# Can be a successful request , but not a successful response
success = self . check_success ( output )
... |
def _ExpandArtifactGroupSource ( self , source , requested ) :
"""Recursively expands an artifact group source .""" | artifact_list = [ ]
if "names" in source . attributes :
artifact_list = source . attributes [ "names" ]
for artifact_name in artifact_list :
if artifact_name in self . processed_artifacts :
continue
artifact_obj = artifact_registry . REGISTRY . GetArtifact ( artifact_name )
for expanded_artifact... |
def _get_struct_blurfilter ( self ) :
"""Get the values for the BLURFILTER record .""" | obj = _make_object ( "BlurFilter" )
obj . BlurX = unpack_fixed16 ( self . _src )
obj . BlurY = unpack_fixed16 ( self . _src )
bc = BitConsumer ( self . _src )
obj . Passes = bc . u_get ( 5 )
obj . Reserved = bc . u_get ( 3 )
return obj |
def _fromstring ( value ) :
'''_ fromstring
Convert XML string value to None , boolean , int or float .''' | if not value :
return None
std_value = value . strip ( ) . lower ( )
if std_value == 'true' :
return 'true'
elif std_value == 'false' :
return 'false'
# try :
# return int ( std _ value )
# except ValueError :
# pass
# try :
# return float ( std _ value )
# except ValueError :
# pass
return value |
def __encode_time ( self , t ) :
"""Encode a timestamp so that it can be read on the timeclock""" | # formula taken from zkemsdk . c - EncodeTime
# can also be found in the technical manual
d = ( ( ( t . year % 100 ) * 12 * 31 + ( ( t . month - 1 ) * 31 ) + t . day - 1 ) * ( 24 * 60 * 60 ) + ( t . hour * 60 + t . minute ) * 60 + t . second )
return d |
def volumes ( self ) :
"""This property prepares the list of volumes
: return a list of volumes .""" | return sys_volumes . VolumeCollection ( self . _conn , utils . get_subresource_path_by ( self , 'Volumes' ) , redfish_version = self . redfish_version ) |
def arff_to_orange_table ( arff ) :
'''Convert a string in arff format to an Orange table .
: param arff : string in arff format
: return : Orange data table object constructed from the arff string
: rtype : orange . ExampleTable''' | with tempfile . NamedTemporaryFile ( suffix = '.arff' , delete = True ) as f :
f . write ( arff )
f . flush ( )
table = orange . ExampleTable ( f . name )
return table |
def configure ( ) :
'''Configure the transfer environment and store''' | completer = Completer ( )
readline . set_completer_delims ( '\t' )
readline . parse_and_bind ( 'tab: complete' )
readline . set_completer ( completer . path_completer )
home = os . path . expanduser ( '~' )
if os . path . isfile ( os . path . join ( home , '.transfer' , 'config.yaml' ) ) :
with open ( os . path . j... |
def summary ( self ) :
""": rtype : twilio . rest . insights . v1 . summary . CallSummaryList""" | if self . _summary is None :
self . _summary = CallSummaryList ( self )
return self . _summary |
def set_source ( self , controller , zone , source ) :
"""Set source for a zone - 0 based value for source""" | _LOGGER . info ( "Begin - controller= %s, zone= %s change source to %s." , controller , zone , source )
send_msg = self . create_send_message ( "F0 @cc 00 7F 00 @zz @kk 05 02 00 00 00 F1 3E 00 00 00 @pr 00 01" , controller , zone , source )
try :
self . lock . acquire ( )
_LOGGER . debug ( 'Zone %s - acquired l... |
def _bend_angle_low ( a , b , deriv ) :
"""Similar to bend _ angle , but with relative vectors""" | result = _bend_cos_low ( a , b , deriv )
return _cos_to_angle ( result , deriv ) |
def get_func_args ( func ) :
"""Given a callable , return a tuple of argument names . Handles
` functools . partial ` objects and class - based callables .
. . versionchanged : : 3.0.0a1
Do not return bound arguments , eg . ` ` self ` ` .""" | if isinstance ( func , functools . partial ) :
return _signature ( func . func )
if inspect . isfunction ( func ) or inspect . ismethod ( func ) :
return _signature ( func )
# Callable class
return _signature ( func . __call__ ) |
def get_output ( vcbat , args = None , env = None ) :
"""Parse the output of given bat file , with given args .""" | if env is None : # Create a blank environment , for use in launching the tools
env = SCons . Environment . Environment ( tools = [ ] )
# TODO : This is a hard - coded list of the variables that ( may ) need
# to be imported from os . environ [ ] for v [ sc ] * vars * . bat file
# execution to work . This list shoul... |
def one_hot_encoding ( labels , num_classes , scope = None ) :
"""Transform numeric labels into onehot _ labels .
Args :
labels : [ batch _ size ] target labels .
num _ classes : total number of classes .
scope : Optional scope for name _ scope .
Returns :
one hot encoding of the labels .""" | with tf . name_scope ( scope , 'OneHotEncoding' , [ labels ] ) :
batch_size = labels . get_shape ( ) [ 0 ]
indices = tf . expand_dims ( tf . range ( 0 , batch_size ) , 1 )
labels = tf . cast ( tf . expand_dims ( labels , 1 ) , indices . dtype )
concated = tf . concat ( axis = 1 , values = [ indices , la... |
def _load_upgrades ( self , remove_applied = True ) :
"""Load upgrade modules .
: param remove _ applied : if True , already applied upgrades will not
be included , if False the entire upgrade graph will be
returned .""" | if remove_applied :
self . load_history ( )
for entry_point in iter_entry_points ( 'invenio_upgrader.upgrades' ) :
upgrade = entry_point . load ( ) ( )
self . __class__ . _upgrades [ upgrade . name ] = upgrade
return self . __class__ . _upgrades |
def merge_leading_dims ( array_or_tensor , n_dims = 2 ) :
"""Merge the first dimensions of a tensor .
Args :
array _ or _ tensor : Tensor to have its first dimensions merged . Can also
be an array or numerical value , which will be converted to a tensor
for batch application , if needed .
n _ dims : Numbe... | tensor = tf . convert_to_tensor ( array_or_tensor )
tensor_shape_static = tensor . get_shape ( )
# Check if the rank of the input tensor is well - defined .
if tensor_shape_static . dims is None :
raise ValueError ( "Can't merge leading dimensions of tensor of unknown " "rank." )
tensor_shape_list = tensor_shape_st... |
async def iterUnivRows ( self , prop ) :
'''Iterate ( buid , valu ) rows for the given universal prop''' | penc = prop . encode ( )
pref = penc + b'\x00'
for _ , pval in self . layrslab . scanByPref ( pref , db = self . byuniv ) :
buid = s_msgpack . un ( pval ) [ 0 ]
byts = self . layrslab . get ( buid + penc , db = self . bybuid )
if byts is None :
continue
valu , indx = s_msgpack . un ( byts )
... |
def is_numeric ( value ) :
"""Test if a value is numeric .""" | return type ( value ) in [ int , float , np . int8 , np . int16 , np . int32 , np . int64 , np . float16 , np . float32 , np . float64 , np . float128 ] |
def bigquery_field_to_ibis_dtype ( field ) :
"""Convert BigQuery ` field ` to an ibis type .""" | typ = field . field_type
if typ == 'RECORD' :
fields = field . fields
assert fields , 'RECORD fields are empty'
names = [ el . name for el in fields ]
ibis_types = list ( map ( dt . dtype , fields ) )
ibis_type = dt . Struct ( names , ibis_types )
else :
ibis_type = _LEGACY_TO_STANDARD . get ( t... |
def traverse_data ( obj , use_numpy = True , buffers = None ) :
'''Recursively traverse an object until a flat list is found .
If NumPy is available , the flat list is converted to a numpy array
and passed to transform _ array ( ) to handle ` ` nan ` ` , ` ` inf ` ` , and
` ` - inf ` ` .
Otherwise , iterate... | if use_numpy and all ( isinstance ( el , np . ndarray ) for el in obj ) :
return [ transform_array ( el , buffers = buffers ) for el in obj ]
obj_copy = [ ]
for item in obj : # Check the base / common case first for performance reasons
# Also use type ( x ) is float because it ' s faster than isinstance
if type... |
def match ( list_a , list_b , not_found = 'not_found' , enforce_sublist = False , country_data = COUNTRY_DATA_FILE , additional_data = None ) :
"""Matches the country names given in two lists into a dictionary .
This function matches names given in list _ a to the one provided in list _ b
using regular expressi... | if isinstance ( list_a , str ) :
list_a = [ list_a ]
if isinstance ( list_b , str ) :
list_b = [ list_b ]
if isinstance ( list_a , tuple ) :
list_a = list ( list_a )
if isinstance ( list_b , tuple ) :
list_b = list ( list_b )
coco = CountryConverter ( country_data , additional_data )
name_dict_a = dict ... |
def array_metadata_to_n5 ( array_metadata ) :
'''Convert array metadata from zarr to N5 format .''' | for f , t in zarr_to_n5_keys :
array_metadata [ t ] = array_metadata [ f ]
del array_metadata [ f ]
del array_metadata [ 'zarr_format' ]
try :
dtype = np . dtype ( array_metadata [ 'dataType' ] )
except TypeError : # pragma : no cover
raise TypeError ( "data type %s not supported by N5" % array_metadata... |
def handle_gateway_ready ( msg ) : # pylint : disable = useless - return
"""Process an internal gateway ready message .""" | _LOGGER . info ( 'n:%s c:%s t:%s s:%s p:%s' , msg . node_id , msg . child_id , msg . type , msg . sub_type , msg . payload )
msg . gateway . alert ( msg )
return None |
def post ( self , url , entity ) :
"""To make a POST request to Falkonry API server
: param url : string
: param entity : Instantiated class object""" | try :
if entity is None or entity == "" :
jsonData = ""
else :
jsonData = entity . to_json ( )
except Exception as e :
jsonData = jsonpickle . pickler . encode ( entity )
response = requests . post ( self . host + url , jsonData , headers = { "Content-Type" : "application/json" , 'Authorizat... |
def global_start_index ( self , value ) :
"""Set the global start index .""" | if not isinstance ( value , int ) and value is not None :
raise TypeError ( 'global_start_index attribute must be of int ' 'type.' )
self . _global_start_index = value |
def plot_traindata ( self , name : str = 'dataplot' ) -> None :
"""Plots traindata . . . . choo choo . . .""" | traindata = self . get_traindata ( )
plt . figure ( figsize = ( 16 , 16 ) )
plt . scatter ( traindata [ : , 1 ] , traindata [ : , 2 ] , c = traindata [ : , 5 ] , marker = 'o' , label = 'Datastore Points' )
plt . xlabel ( r'$\log_{10}$ Noise' )
plt . ylabel ( r'$\log_{10}$ Curvature' )
plt . legend ( loc = 2 , fontsize ... |
def _relation_exists ( cls , connection , relation ) :
"""Returns True if relation exists in the postgres db . Otherwise returns False .
Args :
connection : connection to postgres database who stores mpr data .
relation ( str ) : name of the table , view or materialized view .
Note :
relation means table ... | schema_name , table_name = relation . split ( '.' )
exists_query = '''
SELECT 1
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = %s
AND c.relname = %s
AND (c.relkind = 'r' OR c.relkind... |
def _local_to_utc ( self , timestamp , local_zone = "America/Los_Angeles" ) :
"""Convert local timestamp to UTC .
Parameters
timestamp : pd . DataFrame ( )
Input Pandas dataframe whose index needs to be changed .
local _ zone : str
Name of local zone . Defaults to PST .
Returns
pd . DataFrame ( )
Da... | timestamp_new = pd . to_datetime ( timestamp , infer_datetime_format = True , errors = 'coerce' )
timestamp_new = timestamp_new . tz_localize ( local_zone ) . tz_convert ( pytz . utc )
timestamp_new = timestamp_new . strftime ( '%Y-%m-%d %H:%M:%S' )
return timestamp_new |
def send_emails_from_template ( to_emails , from_email , subject , markdown_template = None , text_template = None , html_template = None , fail_silently = False , context = None , attachments = None , ** kwargs ) :
"""Send many emails from single template . Each email address listed in the
` ` to _ emails ` ` wi... | if not to_emails :
return
if context is None :
context = { }
if markdown_template :
try :
from markdown import markdown
except ImportError :
raise ImportError ( 'The application is attempting to send an email by using the ' '"markdown" library, but markdown is not installed. Please ' 'i... |
def set_channel_access ( channel = 14 , access_update_mode = 'non_volatile' , alerting = False , per_msg_auth = False , user_level_auth = False , access_mode = 'always' , privilege_update_mode = 'non_volatile' , privilege_level = 'administrator' , ** kwargs ) :
'''Set channel access
: param channel : number [ 1:7... | with _IpmiCommand ( ** kwargs ) as s :
return s . set_channel_access ( channel , access_update_mode , alerting , per_msg_auth , user_level_auth , access_mode , privilege_update_mode , privilege_level ) |
def install_mp_handler ( logger = None ) :
"""Wraps the handlers in the given Logger with an MultiProcessingHandler .
: param logger : whose handlers to wrap . By default , the root logger .""" | if logger is None :
logger = logging . getLogger ( )
for i , orig_handler in enumerate ( list ( logger . handlers ) ) :
handler = MultiProcessingHandler ( 'mp-handler-{0}' . format ( i ) , sub_handler = orig_handler )
logger . removeHandler ( orig_handler )
logger . addHandler ( handler ) |
def from_string ( self , value ) :
"""Convert string to dictionary .""" | # Remove optional { }
if value . startswith ( '{' ) and value . endswith ( '}' ) :
text = value [ 1 : - 1 ] . strip ( )
else :
text = value . strip ( )
# Result is a dictionary
result = { }
# Convert each pair of < int > : < float > into a key , value pair .
for val in text . split ( ',' ) :
tokens = val . ... |
def reduce ( self , colors ) :
"""Converts color codes into optimized text
This optimizer works by merging adjacent colors so we don ' t
have to repeat the same escape codes for each pixel . There is
no loss of information .
: param colors : Iterable yielding an xterm color code for each
pixel , None to i... | need_reset = False
line = [ ]
for color , items in itertools . groupby ( colors ) :
if color is None :
if need_reset :
line . append ( "\x1b[49m" )
need_reset = False
line . append ( self . pad * len ( list ( items ) ) )
elif color == "EOL" :
if need_reset :
... |
def main ( self ) :
"""Run the methods in the correct order for pipelines""" | # Find the target files
self . targets ( )
# Use bbduk to bait the FASTQ reads matching the target sequences
self . bait ( )
# If desired , use bbduk to bait the target sequences with the previously baited FASTQ files
if self . revbait :
self . reversebait ( )
# Run the bowtie2 read mapping module
self . mapping ( ... |
def handle_set_command_list ( self , line : str , position : int , tokens : ParseResults ) -> ParseResults :
"""Handle a ` ` SET X = { " Y " , " Z " , . . . } ` ` statement .""" | key , values = tokens [ 'key' ] , tokens [ 'values' ]
for value in values :
self . raise_for_invalid_annotation_value ( line , position , key , value )
self . annotations [ key ] = set ( values )
return tokens |
def verify_signature ( self , signedtext , cert_file = None , cert_type = 'pem' , node_name = NODE_NAME , node_id = None , id_attr = '' ) :
"""Verifies the signature of a XML document .
: param signedtext : The XML document as a string
: param cert _ file : The public key that was used to sign the document
: ... | # This is only for testing purposes , otherwise when would you receive
# stuff that is signed with your key ! ?
if not cert_file :
cert_file = self . cert_file
cert_type = self . cert_type
if not id_attr :
id_attr = self . id_attr
return self . crypto . validate_signature ( signedtext , cert_file = cert_fil... |
def breaks_from_bins ( x_range , bins = 30 , center = None , boundary = None ) :
"""Calculate breaks given binwidth
Parameters
x _ range : array _ like
Range over with to calculate the breaks . Must be
of size 2.
bins : int
Number of bins
center : float
The center of one of the bins
boundary : flo... | if bins < 1 :
raise PlotnineError ( "Need at least one bin." )
elif bins == 1 :
binwidth = x_range [ 1 ] - x_range [ 0 ]
boundary = x_range [ 1 ]
else :
binwidth = ( x_range [ 1 ] - x_range [ 0 ] ) / ( bins - 1 )
return breaks_from_binwidth ( x_range , binwidth , center , boundary ) |
def _get_reporoot ( ) :
"""Returns the absolute path to the repo root directory on the current
system .""" | from os import path
import acorn
medpath = path . abspath ( acorn . __file__ )
return path . dirname ( path . dirname ( medpath ) ) |
def set ( self , agent_id , name = None , description = None , redirect_domain = None , logo_media_id = None , report_location_flag = 0 , is_report_user = True , is_report_enter = True ) :
"""设置应用
https : / / work . weixin . qq . com / api / doc # 90000/90135/90228
: param agent _ id : 企业应用的id
: param name : ... | agent_data = optionaldict ( )
agent_data [ 'agentid' ] = agent_id
agent_data [ 'name' ] = name
agent_data [ 'description' ] = description
agent_data [ 'redirect_domain' ] = redirect_domain
agent_data [ 'logo_mediaid' ] = logo_media_id
agent_data [ 'report_location_flag' ] = report_location_flag
agent_data [ 'isreporten... |
def norm_page_cnt ( page , max_number = None ) :
"""Normalize a integer ( page ) .
* Ensure that it is greater than Zero , and is not None .
- If less than 1 , or None , set it to 1
* if max _ number is None , then do not check for max _ number
* if greater than max _ number , reset it to be max _ number""" | if page == None or page < 1 :
page = 1
if max_number != None :
if page > max_number :
page = max_number
return page |
def fetch_coords ( self , query ) :
"""Pull down coordinate data from the endpoint .""" | q = query . add_query_parameter ( req = 'coord' )
return self . _parse_messages ( self . get_query ( q ) . content ) |
def create_equipamento ( self ) :
"""Get an instance of equipamento services facade .""" | return Equipamento ( self . networkapi_url , self . user , self . password , self . user_ldap ) |
def run ( self ) :
'''compile the JS , then run superclass implementation''' | if subprocess . call ( [ 'npm' , '--version' ] ) != 0 :
raise RuntimeError ( 'npm is required to build the HTML renderer.' )
self . check_call ( [ 'npm' , 'install' ] , cwd = HTML_RENDERER_DIR )
self . check_call ( [ 'npm' , 'run' , 'build' ] , cwd = HTML_RENDERER_DIR )
self . copy_file ( HTML_RENDERER_DIR + '/dist... |
def pack ( cls , data ) :
'''Pack the provided data into a Response''' | return struct . pack ( '>ll' , len ( data ) + 4 , cls . FRAME_TYPE ) + data |
def downloadFiles ( self , prompt = True , extract = False ) :
"""Download files from the repository""" | # First , get the download urls
data = self . data
downloadUrls = self . getDownloadUrls ( )
# Then , confirm the user wants to do this
if prompt :
confirm = raw_input ( "Download files [Y/N]? " )
if confirm . lower ( ) != 'y' :
self . printd ( "Operation aborted by user input" )
return
# Now , ... |
def get_from_cache ( url : str , cache_dir : str = None ) -> str :
"""Given a URL , look for the corresponding dataset in the local cache .
If it ' s not there , download it . Then return the path to the cached file .""" | if cache_dir is None :
cache_dir = CACHE_DIRECTORY
os . makedirs ( cache_dir , exist_ok = True )
# Get eTag to add to filename , if it exists .
if url . startswith ( "s3://" ) :
etag = s3_etag ( url )
else :
response = requests . head ( url , allow_redirects = True )
if response . status_code != 200 :
... |
def show_user_variables ( input_dict , environment_dict ) :
"""< Purpose >
Seash callback to allow user to check all variables that they defined .
< Arguments >
input _ dict : Input dictionary generated by seash _ dictionary . parse _ command ( ) .
environment _ dict : Dictionary describing the current seas... | for variable , value in uservariables . iteritems ( ) :
print variable + ": '" + value + "'" |
def try_to_create_directory ( directory_path ) :
"""Attempt to create a directory that is globally readable / writable .
Args :
directory _ path : The path of the directory to create .""" | logger = logging . getLogger ( "ray" )
directory_path = os . path . expanduser ( directory_path )
if not os . path . exists ( directory_path ) :
try :
os . makedirs ( directory_path )
except OSError as e :
if e . errno != errno . EEXIST :
raise e
logger . warning ( "Attempted... |
def _build_menu ( self , context_menu : QMenu ) :
"""Build the context menu .""" | logger . debug ( "Show tray icon enabled in settings: {}" . format ( cm . ConfigManager . SETTINGS [ cm . SHOW_TRAY_ICON ] ) )
# Items selected for display are shown on top
self . _fill_context_menu_with_model_item_actions ( context_menu )
# The static actions are added at the bottom
context_menu . addAction ( self . a... |
def remove_subscriptions ( self , server_id , sub_paths ) : # pylint : disable = line - too - long
"""Remove indication subscription ( s ) from a WBEM server , by deleting the
indication subscription instances in the server .
The indication subscriptions must be owned or permanent ( i . e . not
static ) .
P... | # noqa : E501
# Validate server _ id
server = self . _get_server ( server_id )
# If list , recursively call this function with each list item .
if isinstance ( sub_paths , list ) :
for sub_path in sub_paths :
self . remove_subscriptions ( server_id , sub_path )
return
# Here , the variable will be a sin... |
def _parse_credentials ( username , password , database , options ) :
"""Parse authentication credentials .""" | mechanism = options . get ( 'authmechanism' , 'DEFAULT' )
if username is None and mechanism != 'MONGODB-X509' :
return None
source = options . get ( 'authsource' , database or 'admin' )
return _build_credentials_tuple ( mechanism , source , username , password , options ) |
def archive_dir ( env_dir ) :
"""Compresses the directory and writes to its parent
Parameters
env _ dir : str
Returns
str""" | output_filename = env_dir + ".zip"
log . info ( "Archiving conda environment: %s -> %s" , env_dir , output_filename )
subprocess . check_call ( [ "zip" , "-r" , "-0" , "-q" , output_filename , env_dir ] )
return output_filename |
def exclude_topics ( excl_topic_indices , doc_topic_distrib , topic_word_distrib = None , renormalize = True , return_new_topic_mapping = False ) :
"""Exclude topics with the indices ` excl _ topic _ indices ` from the document - topic distribution ` doc _ topic _ distrib ` ( i . e .
delete the respective columns... | new_theta = np . delete ( doc_topic_distrib , excl_topic_indices , axis = 1 )
if renormalize :
new_theta /= new_theta . sum ( axis = 1 ) [ : , None ]
if topic_word_distrib is not None :
new_phi = np . delete ( topic_word_distrib , excl_topic_indices , axis = 0 )
res_tuple = ( new_theta , new_phi )
else :
... |
def elapsed ( self ) :
'''Returns elapsed crawl time as a float in seconds .
This metric includes all the time that a site was in active rotation ,
including any time it spent waiting for its turn to be brozzled .
In contrast ` Site . active _ brozzling _ time ` only counts time when a
brozzler worker claim... | dt = 0
for ss in self . starts_and_stops [ : - 1 ] :
dt += ( ss [ 'stop' ] - ss [ 'start' ] ) . total_seconds ( )
ss = self . starts_and_stops [ - 1 ]
if ss [ 'stop' ] :
dt += ( ss [ 'stop' ] - ss [ 'start' ] ) . total_seconds ( )
else : # crawl is active
dt += ( doublethink . utcnow ( ) - ss [ 'start' ] ) ... |
def _prep_datum ( self , datum , dialect , col , needs_conversion ) :
"""Puts a value in proper format for a SQL string""" | if datum is None or ( needs_conversion and not str ( datum ) . strip ( ) ) :
return 'NULL'
pytype = self . columns [ col ] [ 'pytype' ]
if needs_conversion :
if pytype == datetime . datetime :
datum = dateutil . parser . parse ( datum )
elif pytype == bool :
datum = th . coerce_to_specific (... |
def transform_slithir_vars_to_ssa ( function ) :
"""Transform slithIR vars to SSA ( TemporaryVariable , ReferenceVariable , TupleVariable )""" | variables = [ ]
for node in function . nodes :
for ir in node . irs_ssa :
if isinstance ( ir , OperationWithLValue ) and not ir . lvalue in variables :
variables += [ ir . lvalue ]
tmp_variables = [ v for v in variables if isinstance ( v , TemporaryVariable ) ]
for idx in range ( len ( tmp_varia... |
def listattrs ( x ) :
"""Get all instance and class attributes for an object
Get all instance and class attributes for an object except those that start
with " _ _ " ( double underscore ) .
_ _ dict _ _ of an object only reports the instance attributes while dir ( )
reports all of the attributes of an objec... | return [ attr for attr in dir ( x ) if not attr . startswith ( "__" ) and not callable ( getattr ( x , attr ) ) ] |
def _query ( cls , * args , ** kwds ) :
"""Create a Query object for this class .
Args :
distinct : Optional bool , short hand for group _ by = projection .
* args : Used to apply an initial filter
* * kwds : are passed to the Query ( ) constructor .
Returns :
A Query object .""" | # Validating distinct .
if 'distinct' in kwds :
if 'group_by' in kwds :
raise TypeError ( 'cannot use distinct= and group_by= at the same time' )
projection = kwds . get ( 'projection' )
if not projection :
raise TypeError ( 'cannot use distinct= without projection=' )
if kwds . pop ( 'd... |
def create_instances_from_document ( all_documents , document_index , max_seq_length , short_seq_prob , masked_lm_prob , max_predictions_per_seq , vocab_words , rng ) :
"""Creates ` TrainingInstance ` s for a single document .""" | document = all_documents [ document_index ]
# Account for [ CLS ] , [ SEP ] , [ SEP ]
max_num_tokens = max_seq_length - 3
# We * usually * want to fill up the entire sequence since we are padding
# to ` max _ seq _ length ` anyways , so short sequences are generally wasted
# computation . However , we * sometimes *
# (... |
def patch_namespaced_cron_job ( self , name , namespace , body , ** kwargs ) : # noqa : E501
"""patch _ namespaced _ cron _ job # noqa : E501
partially update the specified CronJob # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . patch_namespaced_cron_job_with_http_info ( name , namespace , body , ** kwargs )
# noqa : E501
else :
( data ) = self . patch_namespaced_cron_job_with_http_info ( name , namespace , body , ** kwargs )
# noqa : E50... |
def NR_plot ( stream , NR_stream , detections , false_detections = False , size = ( 18.5 , 10 ) , ** kwargs ) :
"""Plot Network response alongside the stream used .
Highlights detection times in the network response .
: type stream : obspy . core . stream . Stream
: param stream : Stream to plot
: type NR _... | import matplotlib . pyplot as plt
fig , axes = plt . subplots ( len ( stream ) + 1 , 1 , sharex = True , figsize = size )
if len ( stream ) > 1 :
axes = axes . ravel ( )
else :
return
mintime = stream . sort ( [ 'starttime' ] ) [ 0 ] . stats . starttime
stream . sort ( [ 'network' , 'station' , 'starttime' ] )
... |
def user_parse ( data ) :
"""Parse information from provider .""" | for email in data . get ( 'emails' , [ ] ) :
if email . get ( 'primary' ) :
yield 'id' , email . get ( 'email' )
yield 'email' , email . get ( 'email' )
break |
def parse_coordinate ( string_rep ) :
"""Parse a single coordinate""" | # Any CRTF coordinate representation ( sexagesimal or degrees )
if 'pix' in string_rep :
return u . Quantity ( string_rep [ : - 3 ] , u . dimensionless_unscaled )
if 'h' in string_rep or 'rad' in string_rep :
return coordinates . Angle ( string_rep )
if len ( string_rep . split ( '.' ) ) >= 3 :
string_rep =... |
def do_layout ( self , * args ) :
"""Layout each of my decks""" | if self . size == [ 1 , 1 ] :
return
for i in range ( 0 , len ( self . decks ) ) :
self . layout_deck ( i ) |
def search ( self , filters = None , fields = None , limit = None , page = 1 ) :
"""Retrieve order list by options using search api . Using this result can
be paginated
: param options : Dictionary of options .
: param filters : ` { < attribute > : { < operator > : < value > } } `
: param fields : [ < Strin... | options = { 'imported' : False , 'filters' : filters or { } , 'fields' : fields or [ ] , 'limit' : limit or 1000 , 'page' : page , }
return self . call ( 'sales_order.search' , [ options ] ) |
def list_all_countries_geo_zones ( cls , ** kwargs ) :
"""List CountriesGeoZones
Return a list of CountriesGeoZones
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . list _ all _ countries _ geo _ zones ( async = Tr... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _list_all_countries_geo_zones_with_http_info ( ** kwargs )
else :
( data ) = cls . _list_all_countries_geo_zones_with_http_info ( ** kwargs )
return data |
def _verify_state ( self , resp , state_data , state ) :
"""Will verify the state and throw and error if the state is invalid .
: type resp : AuthorizationResponse
: type state _ data : dict [ str , str ]
: type state : satosa . state . State
: param resp : The authorization response from the AS , created b... | is_known_state = "state" in resp and "state" in state_data and resp [ "state" ] == state_data [ "state" ]
if not is_known_state :
received_state = resp . get ( "state" , "" )
satosa_logging ( logger , logging . DEBUG , "Missing or invalid state [%s] in response!" % received_state , state )
raise SATOSAAuthe... |
def get_container_remove_kwargs ( self , action , container_name , kwargs = None ) :
"""Generates keyword arguments for the Docker client to remove a container .
: param action : Action configuration .
: type action : ActionConfig
: param container _ name : Container name or id .
: type container _ name : u... | c_kwargs = dict ( container = container_name )
update_kwargs ( c_kwargs , kwargs )
return c_kwargs |
def set ( self , item : Union [ Service , PublicKey ] ) -> 'DIDDoc' :
"""Add or replace service or public key ; return current DIDDoc .
Raise BadDIDDocItem if input item is neither service nor public key .
: param item : service or public key to set
: return : current DIDDoc""" | if isinstance ( item , Service ) :
self . service [ item . id ] = item
elif isinstance ( item , PublicKey ) :
self . pubkey [ item . id ] = item
else :
raise BadDIDDocItem ( 'Cannot add item {} to DIDDoc on DID {}' . format ( item , self . did ) ) |
def _link_to_img ( self ) :
"""Generates a link to the user ' s Gravatar .
> > > Gravatar ( ' gridaphobe @ gmail . com ' ) . _ link _ to _ img ( )
' http : / / www . gravatar . com / avatar / 16b87da510d278999c892cdbdd55c1b6 ? s = 80 & r = g '""" | # make sure options are valid
if self . rating . lower ( ) not in RATINGS :
raise InvalidRatingError ( self . rating )
if not ( MIN_SIZE <= self . size <= MAX_SIZE ) :
raise InvalidSizeError ( self . size )
url = ''
if self . secure :
url = SECURE_BASE_URL
else :
url = BASE_URL
options = { 's' : self . ... |
def horizon_dashboard_nav ( context ) :
"""Generates sub - navigation entries for the current dashboard .""" | if 'request' not in context :
return { }
dashboard = context [ 'request' ] . horizon [ 'dashboard' ]
panel_groups = dashboard . get_panel_groups ( )
non_empty_groups = [ ]
for group in panel_groups . values ( ) :
allowed_panels = [ ]
for panel in group :
if ( callable ( panel . nav ) and panel . nav... |
def get_descendants ( self , strategy = "levelorder" , is_leaf_fn = None ) :
"""Returns a list of all ( leaves and internal ) descendant nodes .""" | return [ n for n in self . iter_descendants ( strategy = strategy , is_leaf_fn = is_leaf_fn ) ] |
def delete ( self , directory_updated = False ) : # pylint : disable = W0212
"""Delete this configuration
: param directory _ updated : If True , tell ConfigurationAdmin to not
recall the directory of this deletion
( internal use only )""" | with self . __lock :
if self . __deleted : # Nothing to do
return
# Update status
self . __deleted = True
# Notify ConfigurationAdmin , notify services only if the
# configuration had been updated before
self . __config_admin . _delete ( self , self . __updated , directory_updated )
... |
def get_templates ( self ) :
""": return : list of Finger object""" | self . read_sizes ( )
if self . fingers == 0 :
return [ ]
templates = [ ]
templatedata , size = self . read_with_buffer ( const . CMD_DB_RRQ , const . FCT_FINGERTMP )
if size < 4 :
if self . verbose :
print ( "WRN: no user data" )
return [ ]
total_size = unpack ( 'i' , templatedata [ 0 : 4 ] ) [ 0 ]... |
def get_dimensions ( js_dict , naming ) :
"""Get dimensions from input data .
Args :
js _ dict ( dict ) : dictionary containing dataset data and metadata .
naming ( string , optional ) : dimension naming . Possible values : ' label ' or ' id ' .
Returns :
dimensions ( list ) : list of pandas data frames w... | dimensions = [ ]
dim_names = [ ]
if check_version_2 ( js_dict ) :
dimension_dict = js_dict
else :
dimension_dict = js_dict [ 'dimension' ]
for dim in dimension_dict [ 'id' ] :
dim_name = js_dict [ 'dimension' ] [ dim ] [ 'label' ]
if not dim_name :
dim_name = dim
if naming == 'label' :
... |
def _replace_none ( self , aDict ) :
"""Replace all None values in a dict with ' none '""" | for k , v in aDict . items ( ) :
if v is None :
aDict [ k ] = 'none' |
def to_dict ( self , ** kw ) :
u"""Converts the lxml object to a dict .
possible kwargs :
without _ comments : bool""" | _ , value = helpers . etree_to_dict ( self . _xml , ** kw ) . popitem ( )
return value |
def get_aligner_with_aliases ( aligner , data ) :
"""Retrieve aligner index retriever , including aliases for shared .
Handles tricky cases like gridss where we need bwa indices even with
no aligner specified since they ' re used internally within GRIDSS .""" | aligner_aliases = { "sentieon-bwa" : "bwa" }
from bcbio import structural
if not aligner and "gridss" in structural . get_svcallers ( data ) :
aligner = "bwa"
return aligner_aliases . get ( aligner ) or aligner |
def _bgzip_from_cram_sambamba ( cram_file , dirs , data ) :
"""Use sambamba to extract from CRAM via regions .""" | raise NotImplementedError ( "sambamba doesn't yet support retrieval from CRAM by BED file" )
region_file = ( tz . get_in ( [ "config" , "algorithm" , "variant_regions" ] , data ) if tz . get_in ( [ "config" , "algorithm" , "coverage_interval" ] , data ) in [ "regional" , "exome" ] else None )
base_name = utils . splite... |
def handle ( self , * app_labels , ** options ) :
"""Serializes objects from the database .
Works much like Django ' s ` ` manage . py dumpdata ` ` , except that it allows you to
limit and sort the apps that you ' re pulling in , as well as automatically follow
the dependency graph to pull in related objects ... | # TODO : excluded _ apps doesnt correctly handle foo . bar if you ' re not using app _ labels
format = options . get ( 'format' , 'json' )
indent = options . get ( 'indent' , None )
limit = options . get ( 'limit' , None )
sort = options . get ( 'sort' , None )
using = options . get ( 'database' , None )
exclude = opti... |
def has_cargo_fmt ( ) :
"""Runs a quick check to see if cargo fmt is installed .""" | try :
c = subprocess . Popen ( [ "cargo" , "fmt" , "--" , "--help" ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE , )
return c . wait ( ) == 0
except OSError :
return False |
def report_object ( self , key , filename , anchor_text = None , anchor_image = None , annotation = None ) :
"""Writes a string to self . pipeline _ objects _ file . Used to report figures and others .
: param str key : name ( key ) of the object
: param str filename : relative path to the file ( relative to pa... | # Default annotation is current pipeline name .
annotation = str ( annotation or self . name )
# In case the value is passed with trailing whitespace .
filename = str ( filename ) . strip ( )
if anchor_text :
anchor_text = str ( anchor_text ) . strip ( )
else :
anchor_text = str ( key ) . strip ( )
# better to ... |
def read ( self ) :
'''Execute the expression and capture its output , similar to backticks
or $ ( ) in the shell . This is a wrapper around run ( ) which captures
stdout , decodes it , trims it , and returns it directly .''' | result = self . stdout_capture ( ) . run ( )
stdout_str = decode_with_universal_newlines ( result . stdout )
return stdout_str . rstrip ( '\n' ) |
def _hash_item ( item ) :
"""Hash an item ( CIM value , CIM object ) , by delegating to its hash function .
The item may be ` None ` .""" | if isinstance ( item , list ) :
item = tuple ( item )
return hash ( item ) |
def oindex ( a , selection ) :
"""Implementation of orthogonal indexing with slices and ints .""" | selection = replace_ellipsis ( selection , a . shape )
drop_axes = tuple ( [ i for i , s in enumerate ( selection ) if is_integer ( s ) ] )
selection = ix_ ( selection , a . shape )
result = a [ selection ]
if drop_axes :
result = result . squeeze ( axis = drop_axes )
return result |
def add_protein_data ( proteins , pgdb , headerfields , genecentric = False , pool_to_output = False ) :
"""First creates a map with all master proteins with data ,
then outputs protein data dicts for rows of a tsv . If a pool
is given then only output for that pool will be shown in the
protein table .""" | proteindata = create_featuredata_map ( pgdb , genecentric = genecentric , psm_fill_fun = add_psms_to_proteindata , pgene_fill_fun = add_protgene_to_protdata , count_fun = count_peps_psms , pool_to_output = pool_to_output , get_uniques = True )
dataget_fun = { True : get_protein_data_genecentric , False : get_protein_da... |
def remove_BC ( self , pores = None ) :
r"""Removes all boundary conditions from the specified pores
Parameters
pores : array _ like
The pores from which boundary conditions are to be removed . If no
pores are specified , then BCs are removed from all pores . No error
is thrown if the provided pores do no... | if pores is None :
pores = self . Ps
if 'pore.bc_value' in self . keys ( ) :
self [ 'pore.bc_value' ] [ pores ] = np . nan
if 'pore.bc_rate' in self . keys ( ) :
self [ 'pore.bc_rate' ] [ pores ] = np . nan |
def __init_object ( self ) :
"""Create a new object for the pool .""" | # Check to see if the user created a specific initalization function for this object .
if self . init_function is not None :
new_obj = self . init_function ( )
self . __enqueue ( new_obj )
else :
raise TypeError ( "The Pool must have a non None function to fill the pool." ) |
def reset ( self ) :
"""Reset controller
It removes all information about previous session""" | self . _is_impersonating = False
self . _impersonation = None
self . user = None
self . password = None
self . api_key = None
self . enterprise = None
self . url = None |
def mmi_to_shapefile ( self , force_flag = False ) :
"""Convert grid . xml ' s mmi column to a vector shp file using ogr2ogr .
An ESRI shape file will be created .
: param force _ flag : bool ( Optional ) . Whether to force the regeneration
of the output file . Defaults to False .
: return : Path to the res... | LOGGER . debug ( 'mmi_to_shapefile requested.' )
shp_path = os . path . join ( self . output_dir , '%s-points.shp' % self . output_basename )
# Short circuit if the tif is already created .
if os . path . exists ( shp_path ) and force_flag is not True :
return shp_path
# Ensure the vrt mmi file exists ( it will gen... |
def run ( arguments : List [ str ] , execution_directory : str = None , execution_environment : Dict = None ) -> str :
"""Runs the given arguments from the given directory ( if given , else resorts to the ( undefined ) current directory ) .
: param arguments : the CLI arguments to run
: param execution _ direct... | process = subprocess . Popen ( arguments , stdout = subprocess . PIPE , stdin = subprocess . PIPE , stderr = subprocess . PIPE , cwd = execution_directory , env = execution_environment )
out , error = process . communicate ( )
stdout = out . decode ( _DATA_ENCODING ) . rstrip ( )
if process . returncode == _SUCCESS_RET... |
def config ( self , config_text , plane ) :
"""Apply config .""" | NO_CONFIGURATION_CHANGE = re . compile ( "No configuration changes to commit" )
CONFIGURATION_FAILED = re . compile ( "show configuration failed" )
CONFIGURATION_INCONSITENCY = re . compile ( "No configuration commits for this SDR will be allowed until " "a 'clear configuration inconsistency' command is performed." )
s... |
def random_subsets ( self , relative_sizes , by_duration = False , balance_labels = False , label_list_ids = None ) :
"""Create a bunch of subsets with the given sizes relative to the size or duration of the full corpus .
Basically the same as calling ` ` random _ subset ` ` or ` ` random _ subset _ by _ duration... | resulting_sets = { }
next_bigger_subset = self . corpus
for relative_size in reversed ( relative_sizes ) :
generator = SubsetGenerator ( next_bigger_subset , random_seed = self . random_seed )
if by_duration :
sv = generator . random_subset_by_duration ( relative_size , balance_labels = balance_labels ,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.