signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_setup_install_args ( self , pkgname , setup_py , develop = False ) :
"""Get setup . py install args for installing the supplied package in the virtualenv
: param str pkgname : The name of the package to install
: param str setup _ py : The path to the setup file of the package
: param bool develop : W... | headers = self . base_paths [ "headers" ]
headers = headers / "python{0}" . format ( self . python_version ) / pkgname
install_arg = "install" if not develop else "develop"
return [ self . python , "-u" , "-c" , SETUPTOOLS_SHIM % setup_py , install_arg , "--single-version-externally-managed" , "--install-headers={0}" .... |
def extract_kwargs ( docstring ) :
"""Extract keyword argument documentation from a function ' s docstring .
Parameters
docstring : str
The docstring to extract keyword arguments from .
Returns
list of ( str , str , list str )
str
The name of the keyword argument .
str
Its type .
str
Its docum... | lines = inspect . cleandoc ( docstring ) . split ( '\n' )
retval = [ ]
# 1 . Find the underlined ' Parameters ' section
# 2 . Once there , continue parsing parameters until we hit an empty line
while lines [ 0 ] != 'Parameters' :
lines . pop ( 0 )
lines . pop ( 0 )
lines . pop ( 0 )
while lines and lines [ 0 ] :
... |
def reply ( self , text ) :
"""POSTs reply to message with own message . Returns posted message .
URL : ` ` http : / / www . reddit . com / api / comment / ` `
: param text : body text of message""" | data = { 'thing_id' : self . name , 'id' : '#commentreply_{0}' . format ( self . name ) , 'text' : text , }
j = self . _reddit . post ( 'api' , 'comment' , data = data )
try :
return self . _reddit . _thingify ( j [ 'json' ] [ 'data' ] [ 'things' ] [ 0 ] , path = self . _path )
except Exception :
raise Unexpect... |
def clean_limit ( self ) :
"Ensure given limit is less than default if defined" | limit = self . cleaned_data . get ( 'limit' , None )
if ( settings . SELECTABLE_MAX_LIMIT is not None and ( not limit or limit > settings . SELECTABLE_MAX_LIMIT ) ) :
limit = settings . SELECTABLE_MAX_LIMIT
return limit |
def export_coreml ( self , filename , verbose = False ) :
"""Save the model in Core ML format . The Core ML model takes a grayscale
drawing of fixed size as input and produces two outputs :
` classLabel ` and ` labelProbabilities ` .
The first one , ` classLabel ` is an integer or string ( depending on the
... | import mxnet as _mx
from . . _mxnet . _mxnet_to_coreml import _mxnet_converter
import coremltools as _coremltools
batch_size = 1
image_shape = ( batch_size , ) + ( 1 , BITMAP_WIDTH , BITMAP_HEIGHT )
s_image = _mx . sym . Variable ( self . feature , shape = image_shape , dtype = _np . float32 )
from copy import copy as ... |
def get_evaluation_parameter ( self , parameter_name , default_value = None ) :
"""Get an evaluation parameter value that has been stored in meta .
Args :
parameter _ name ( string ) : The name of the parameter to store .
default _ value ( any ) : The default value to be returned if the parameter is not found... | if "evaluation_parameters" in self . _expectations_config and parameter_name in self . _expectations_config [ 'evaluation_parameters' ] :
return self . _expectations_config [ 'evaluation_parameters' ] [ parameter_name ]
else :
return default_value |
def _get_constrs_arithmetic ( self , gadget ) :
"""Generate constraints for the BinaryOperation gadgets :
dst < - src1 OP src2""" | # * dst * register has to have the value of * src1 op src2 * for all
# possibles assignments of * src1 * and * src2 * .
dst = self . analyzer . get_register_expr ( gadget . destination [ 0 ] . name , mode = "post" )
src1 = self . analyzer . get_register_expr ( gadget . sources [ 0 ] . name , mode = "pre" )
src2 = self ... |
def parse_wiod ( path , year = None , names = ( 'isic' , 'c_codes' ) , popvector = None ) :
"""Parse the wiod source files for the IOSystem
WIOD provides the MRIO tables in excel - format ( xlsx ) at
http : / / www . wiod . org / new _ site / database / wiots . htm ( release November 2013 ) .
To use WIOD in p... | # Path manipulation , should work cross platform
path = os . path . abspath ( os . path . normpath ( str ( path ) ) )
# wiot start and end
wiot_ext = '.xlsx'
wiot_start = 'wiot'
# determine which wiod file to be parsed
if not os . path . isdir ( path ) : # 1 . case - one file specified in path
if os . path . isfile... |
def save_user ( self , idvalue , options = None ) :
"""save user by a given id
http : / / getstarted . sailthru . com / api / user""" | options = options or { }
data = options . copy ( )
data [ 'id' ] = idvalue
return self . api_post ( 'user' , data ) |
def extra_create_kwargs ( self ) :
"""Inject the domain of the current user in the new model instances .""" | user = self . get_agnocomplete_context ( )
if user :
_ , domain = user . email . split ( '@' )
return { 'domain' : domain }
return { } |
def sign_apk ( filename , keystore , storepass ) :
"""Use jarsigner to sign an APK file .
: param filename : APK file on disk to sign ( path )
: param keystore : path to keystore
: param storepass : your keystorage passphrase""" | from subprocess import Popen , PIPE , STDOUT
# TODO use apksigner instead of jarsigner
cmd = Popen ( [ androconf . CONF [ "BIN_JARSIGNER" ] , "-sigalg" , "MD5withRSA" , "-digestalg" , "SHA1" , "-storepass" , storepass , "-keystore" , keystore , filename , "alias_name" ] , stdout = PIPE , stderr = STDOUT )
stdout , stde... |
def create ( self , reference , document_data ) :
"""Add a " change " to this batch to create a document .
If the document given by ` ` reference ` ` already exists , then this
batch will fail when : meth : ` commit ` - ed .
Args :
reference ( ~ . firestore _ v1beta1 . document . DocumentReference ) : A
d... | write_pbs = _helpers . pbs_for_create ( reference . _document_path , document_data )
self . _add_write_pbs ( write_pbs ) |
def globus_group ( * args , ** kwargs ) :
"""Wrapper over click . group which sets GlobusCommandGroup as the Class
Caution !
Don ' t get snake - bitten by this . ` globus _ group ` is a decorator which MUST
take arguments . It is not wrapped in our common detect - and - decorate pattern
to allow it to be us... | def inner_decorator ( f ) :
f = click . group ( * args , cls = GlobusCommandGroup , ** kwargs ) ( f )
f = common_options ( f )
return f
return inner_decorator |
def recall_at_fdr ( fg_vals , bg_vals , fdr_cutoff = 0.1 ) :
"""Computes the recall at a specific FDR ( default 10 % ) .
Parameters
fg _ vals : array _ like
The list of values for the positive set .
bg _ vals : array _ like
The list of values for the negative set .
fdr : float , optional
The FDR ( bet... | if len ( fg_vals ) == 0 :
return 0.0
y_true , y_score = values_to_labels ( fg_vals , bg_vals )
precision , recall , _ = precision_recall_curve ( y_true , y_score )
fdr = 1 - precision
cutoff_index = next ( i for i , x in enumerate ( fdr ) if x <= fdr_cutoff )
return recall [ cutoff_index ] |
def ilsr_rankings ( n_items , data , alpha = 0.0 , initial_params = None , max_iter = 100 , tol = 1e-8 ) :
"""Compute the ML estimate of model parameters using I - LSR .
This function computes the maximum - likelihood ( ML ) estimate of model
parameters given ranking data ( see : ref : ` data - rankings ` ) , u... | fun = functools . partial ( lsr_rankings , n_items = n_items , data = data , alpha = alpha )
return _ilsr ( fun , initial_params , max_iter , tol ) |
def get_instance_route53_names ( self , instance ) :
'''Check if an instance is referenced in the records we have from
Route53 . If it is , return the list of domain names pointing to said
instance . If nothing points to it , return an empty list .''' | instance_attributes = [ 'public_dns_name' , 'private_dns_name' , 'ip_address' , 'private_ip_address' ]
name_list = set ( )
for attrib in instance_attributes :
try :
value = getattr ( instance , attrib )
except AttributeError :
continue
if value in self . route53_records :
name_list .... |
def Batch ( items , size ) :
"""Divide items into batches of specified size .
In case where number of items is not evenly divisible by the batch size , the
last batch is going to be shorter .
Args :
items : An iterable or an iterator of items .
size : A size of the returned batches .
Yields :
Lists of... | batch = [ ]
for item in items :
batch . append ( item )
if len ( batch ) == size :
yield batch
batch = [ ]
if batch :
yield batch |
def remove_perm ( perm , user_or_group , forum = None ) :
"""Remove a permission to a user ( anonymous or not ) or a group .""" | user , group = get_identity ( user_or_group )
perm = ForumPermission . objects . get ( codename = perm )
if user :
UserForumPermission . objects . filter ( forum = forum , permission = perm , user = user if not user . is_anonymous else None , anonymous_user = user . is_anonymous , ) . delete ( )
if group :
Grou... |
def _decode_filename ( base_filename , problem_name , decode_hp ) :
"""Generates decode filename .
Args :
base _ filename : A string , base of the decode filename .
problem _ name : A string , name of the problem .
decode _ hp : HParams for decoding .
Returns :
A string , produced decode filename .""" | if decode_hp . shards > 1 :
base_filename = _add_shard_to_filename ( base_filename , decode_hp )
if ( "beam{beam}.alpha{alpha}.decodes" . format ( beam = str ( decode_hp . beam_size ) , alpha = str ( decode_hp . alpha ) ) in base_filename ) :
return base_filename
else :
return ( "{base}.{model}.{hp}.{proble... |
def get_sources ( self , plate , plate_value , sources = None ) :
"""Gets the source streams for a given plate value on a plate .
Also populates with source streams that are valid for the parent plates of this plate ,
with the appropriate meta - data for the parent plate .
: param plate : The plate being oper... | if sources is None :
sources = [ ]
if self . sources :
for si , source in enumerate ( self . sources ) :
if len ( source . streams ) == 1 and None in source . streams :
sources . append ( source . streams [ None ] )
elif plate_value in source . streams :
sources . append ... |
def recommend_add ( self , num_iid , session ) :
'''taobao . item . recommend . add 橱窗推荐一个商品
将当前用户指定商品设置为橱窗推荐状态 橱窗推荐需要用户有剩余橱窗位才可以顺利执行 这个Item所属卖家从传入的session中获取 , 需要session绑定 需要判断橱窗推荐是否已满 , 橱窗推荐已满停止调用橱窗推荐接口 , 2010年1月底开放查询剩余橱窗推荐数后可以按数量橱窗推荐商品''' | request = TOPRequest ( 'taobao.item.recommend.add' )
request [ 'num_iid' ] = num_iid
self . create ( self . execute ( request , session ) [ 'item' ] )
return self |
def remove_exponent ( d ) :
"""Remove exponent .""" | return d . quantize ( Decimal ( 1 ) ) if d == d . to_integral ( ) else d . normalize ( ) |
def as_db_get ( self , db_number ) :
"""This is the asynchronous counterpart of Cli _ DBGet .""" | logger . debug ( "db_get db_number: %s" % db_number )
_buffer = buffer_type ( )
result = self . library . Cli_AsDBGet ( self . pointer , db_number , byref ( _buffer ) , byref ( c_int ( buffer_size ) ) )
check_error ( result , context = "client" )
return bytearray ( _buffer ) |
def calculate_anim ( infiles , org_lengths ) :
"""Returns ANIm result dataframes for files in input directory .
- infiles - paths to each input file
- org _ lengths - dictionary of input sequence lengths , keyed by sequence
Finds ANI by the ANIm method , as described in Richter et al ( 2009)
Proc Natl Acad ... | logger . info ( "Running ANIm" )
logger . info ( "Generating NUCmer command-lines" )
deltadir = os . path . join ( args . outdirname , ALIGNDIR [ "ANIm" ] )
logger . info ( "Writing nucmer output to %s" , deltadir )
# Schedule NUCmer runs
if not args . skip_nucmer :
joblist = anim . generate_nucmer_jobs ( infiles ,... |
def _datatable_factory ( self ) :
"""creates a SQLAlchemy Table object with the appropriate number of
columns given the number of feeds""" | feed_cols = [ 'feed{0:03d}' . format ( i + 1 ) for i in range ( self . n_feeds ) ]
feed_cols = [ 'override_feed000' ] + feed_cols + [ 'failsafe_feed999' ]
ind_sqlatyp = indexingtypes [ self . index . indimp ] . sqlatyp
dat_sqlatyp = datadefs [ self . dtype . datadef ] . sqlatyp
atbl = Table ( self . name , Base . metad... |
def ServerLoggingStartupInit ( ) :
"""Initialize the server logging configuration .""" | global LOGGER
if local_log :
logging . debug ( "Using local LogInit from %s" , local_log )
local_log . LogInit ( )
logging . debug ( "Using local AppLogInit from %s" , local_log )
LOGGER = local_log . AppLogInit ( )
else :
LogInit ( )
LOGGER = AppLogInit ( ) |
def run ( self , iterator , play_context , result = 0 ) :
"""Arrange for a mitogen . master . Router to be available for the duration of
the strategy ' s real run ( ) method .""" | ansible_mitogen . process . MuxProcess . start ( )
run = super ( StrategyMixin , self ) . run
self . _add_plugin_paths ( )
self . _install_wrappers ( )
try :
return mitogen . core . _profile_hook ( 'Strategy' , lambda : run ( iterator , play_context ) )
finally :
self . _remove_wrappers ( ) |
def __parse_identities ( self , json ) :
"""Parse identities using Mozillians format .
The Mozillians identities format is a JSON document under the
" results " key . The document should follow the next schema :
" results " : [
" _ url " : " https : / / example . com / api / v2 / users / 1 / " ,
" alterna... | try :
for mozillian in json [ 'results' ] :
name = self . __encode ( mozillian [ 'full_name' ] [ 'value' ] )
email = self . __encode ( mozillian [ 'email' ] [ 'value' ] )
username = self . __encode ( mozillian [ 'username' ] )
uuid = username
uid = UniqueIdentity ( uuid = uui... |
def post_pr_comment ( self , patch ) :
"""Posts a comment to the GitHub PR if the diff results have issues .""" | if self . has_violations :
post_pr_comment = True
# Attempt to post a PR review . If posting the PR review fails because the bot account
# does not have permission to review the PR then simply revert to posting a regular PR
# comment .
try :
logger . info ( 'Deleting old PR review comments' ... |
def hybrid_forward ( self , F , inputs , token_types , valid_length = None ) : # pylint : disable = arguments - differ
# pylint : disable = unused - argument
"""Generate the unnormalized score for the given the input sequences .
Parameters
inputs : NDArray , shape ( batch _ size , seq _ length )
Input words f... | bert_output = self . bert ( inputs , token_types , valid_length )
output = self . span_classifier ( bert_output )
return output |
def operator_cross ( self , graph , solution , op_diff_round_digits ) : # TODO : check docstring
"""applies Cross inter - route operator to solution
Takes every node from every route and calculates savings when inserted
into all possible positions in other routes . Insertion is done at
position with max . sav... | # shorter var names for loop
dm = graph . _matrix
dn = graph . _nodes |
def loads ( self , value ) :
"""Deserialize value using ` ` msgpack . loads ` ` .
: param value : bytes
: returns : obj""" | raw = False if self . encoding == "utf-8" else True
if value is None :
return None
return msgpack . loads ( value , raw = raw , use_list = self . use_list ) |
def index ( in_bam , config , check_timestamp = True ) :
"""Index a BAM file , skipping if index present .
Centralizes BAM indexing providing ability to switch indexing approaches .""" | assert is_bam ( in_bam ) , "%s in not a BAM file" % in_bam
index_file = "%s.bai" % in_bam
alt_index_file = "%s.bai" % os . path . splitext ( in_bam ) [ 0 ]
if check_timestamp :
bai_exists = utils . file_uptodate ( index_file , in_bam ) or utils . file_uptodate ( alt_index_file , in_bam )
else :
bai_exists = uti... |
def osm_net_download ( lat_min = None , lng_min = None , lat_max = None , lng_max = None , network_type = 'walk' , timeout = 180 , memory = None , max_query_area_size = 50 * 1000 * 50 * 1000 , custom_osm_filter = None ) :
"""Download OSM ways and nodes within a bounding box from the Overpass API .
Parameters
la... | # create a filter to exclude certain kinds of ways based on the requested
# network _ type
if custom_osm_filter is None :
request_filter = osm_filter ( network_type )
else :
request_filter = custom_osm_filter
response_jsons_list = [ ]
response_jsons = [ ]
# server memory allocation in bytes formatted for Overpa... |
def _proxy ( self , url , urlparams = None ) :
"""Do the actual action of proxying the call .""" | for k , v in request . params . iteritems ( ) :
urlparams [ k ] = v
query = urlencode ( urlparams )
full_url = url
if query :
if not full_url . endswith ( "?" ) :
full_url += "?"
full_url += query
# build the request with its headers
req = urllib2 . Request ( url = full_url )
for header in request .... |
def storages ( self ) :
"""Lazy retrieval of list of storage handlers for the current tenant .
: return : A , a [ pf dir paths to an appropriate storage instance .""" | if self . _storages . get ( connection . schema_name , None ) is None :
schema_storages = OrderedDict ( )
for prefix , root in self . locations :
filesystem_storage = TenantStaticFilesStorage ( location = root )
filesystem_storage . prefix = prefix
schema_storages [ root ] = filesystem_s... |
def create_transaction ( self , outputs , fee = None , absolute_fee = False , leftover = None , combine = True , message = None , unspents = None ) : # pragma : no cover
"""Creates a signed P2PKH transaction .
: param outputs : A sequence of outputs you wish to send in the form
` ` ( destination , amount , curr... | try :
unspents = unspents or self . get_unspents ( )
except ConnectionError :
raise ConnectionError ( 'All APIs are unreachable. Please provide ' 'the unspents to spend from directly.' )
# If at least one input is from segwit the return address is for segwit
return_address = self . segwit_address if any ( [ u .... |
def serialize_streamnet ( streamnet_file , output_reach_file ) :
"""Eliminate reach with zero length and return the reach ID map .
Args :
streamnet _ file : original stream net ESRI shapefile
output _ reach _ file : serialized stream net , ESRI shapefile
Returns :
id pairs { origin : newly assigned }""" | FileClass . copy_files ( streamnet_file , output_reach_file )
ds_reach = ogr_Open ( output_reach_file , update = True )
layer_reach = ds_reach . GetLayer ( 0 )
layer_def = layer_reach . GetLayerDefn ( )
i_link = layer_def . GetFieldIndex ( FLD_LINKNO )
i_link_downslope = layer_def . GetFieldIndex ( FLD_DSLINKNO )
i_len... |
def row_append ( self , row_key , value_list ) :
"""append a new row to a DataRange
: param row _ key : a string
: param value _ list : a list""" | if row_key in self . _row_keys :
raise KeyError ( 'Key %s already exists in row keys.' % row_key )
if not len ( value_list ) == len ( self . _col_keys ) :
raise ValueError ( 'Length of data to set does not meet expected row length of %i' % len ( self . _col_keys ) )
self . _row_keys . append ( row_key )
for c ,... |
def default_reset_type ( self ) :
"""! @ brief One of the Target . ResetType enums .
@ todo Support multiple cores .""" | try :
resetSequence = self . _info . debugs [ 0 ] . attrib [ 'defaultResetSequence' ]
if resetSequence == 'ResetHardware' :
return Target . ResetType . HW
elif resetSequence == 'ResetSystem' :
return Target . ResetType . SW_SYSRESETREQ
elif resetSequence == 'ResetProcessor' :
ret... |
def analyze ( self , scratch , ** kwargs ) :
"""Run and return the results from the SpriteNaming plugin .""" | for sprite in self . iter_sprites ( scratch ) :
for default in self . default_names :
if default in sprite . name :
self . total_default += 1
self . list_default . append ( sprite . name ) |
def get_field_list ( fields , schema ) :
"""Convert a field list spec into a real list of field names .
For tables , we return only the top - level non - RECORD fields as Google charts
can ' t handle nested data .""" | # If the fields weren ' t supplied get them from the schema .
if isinstance ( fields , list ) :
return fields
if isinstance ( fields , basestring ) and fields != '*' :
return fields . split ( ',' )
if not schema :
return [ ]
return [ f [ 'name' ] for f in schema . _bq_schema if f [ 'type' ] != 'RECORD' ] |
def has_tensor ( obj ) -> bool :
"""Given a possibly complex data structure ,
check if it has any torch . Tensors in it .""" | if isinstance ( obj , torch . Tensor ) :
return True
elif isinstance ( obj , dict ) :
return any ( has_tensor ( value ) for value in obj . values ( ) )
elif isinstance ( obj , ( list , tuple ) ) :
return any ( has_tensor ( item ) for item in obj )
else :
return False |
def placeholders ( cls , dic ) :
"""Placeholders for fields names and value binds""" | keys = [ str ( x ) for x in dic ]
entete = "," . join ( keys )
placeholders = "," . join ( cls . named_style . format ( x ) for x in keys )
entete = f"({entete})"
placeholders = f"({placeholders})"
return entete , placeholders |
def serialize ( self , expires = None ) :
"""Serialize the secure cookie into a string .
If expires is provided , the session will be automatically invalidated
after expiration when you unseralize it . This provides better
protection against session cookie theft .
: param expires : an optional expiration da... | if self . secret_key is None :
raise RuntimeError ( 'no secret key defined' )
if expires :
self [ '_expires' ] = _date_to_unix ( expires )
result = [ ]
mac = hmac ( self . secret_key , None , self . hash_method )
for key , value in sorted ( self . items ( ) ) :
result . append ( ( '%s=%s' % ( url_quote_plus... |
def pointlist ( points , sr ) :
"""Convert a list of the form [ [ x , y ] . . . ] to a list of Point instances
with the given x , y coordinates .""" | assert all ( isinstance ( pt , Point ) or len ( pt ) == 2 for pt in points ) , "Point(s) not in [x, y] form"
return [ coord if isinstance ( coord , Point ) else Point ( coord [ 0 ] , coord [ 1 ] , sr ) for coord in points ] |
def sync_wf_cache ( current ) :
"""BG Job for storing wf state to DB""" | wf_cache = WFCache ( current )
wf_state = wf_cache . get ( )
# unicode serialized json to dict , all values are unicode
if 'role_id' in wf_state : # role _ id inserted by engine , so it ' s a sign that we get it from cache not db
try :
wfi = WFInstance . objects . get ( key = current . input [ 'token' ] )
... |
def memoized_parse_block ( code ) :
"""Memoized version of parse _ block .""" | success , result = parse_block_memo . get ( code , ( None , None ) )
if success is None :
try :
parsed = COMPILER . parse_block ( code )
except Exception as err :
success , result = False , err
else :
success , result = True , parsed
parse_block_memo [ code ] = ( success , result... |
def trim_shared_flanking_strings ( ref , alt ) :
"""Given two nucleotide or amino acid strings , identify
if they have a common prefix , a common suffix , and return
their unique components along with the prefix and suffix .
For example , if the input ref = " SYFFQGR " and alt = " SYMLLFIFQGR "
then the res... | ref , alt , prefix = trim_shared_prefix ( ref , alt )
ref , alt , suffix = trim_shared_suffix ( ref , alt )
return ref , alt , prefix , suffix |
def download_sig ( opts , sig , version = None ) :
"""Download signature from hostname""" | code = None
downloaded = False
useagent = 'ClamAV/0.101.1 (OS: linux-gnu, ARCH: x86_64, CPU: x86_64)'
manager = PoolManager ( headers = make_headers ( user_agent = useagent ) , cert_reqs = 'CERT_REQUIRED' , ca_certs = certifi . where ( ) , timeout = Timeout ( connect = 10.0 , read = 60.0 ) )
if version :
path = '/%... |
def sort_values ( self , by , axis = 0 , ascending = True , inplace = False , kind = 'quicksort' , na_position = 'last' ) :
"""Sort by the values along either axis
Wrapper around the : meth : ` pandas . DataFrame . sort _ values ` method .""" | if inplace :
self . _frame . sort_values ( by , axis = axis , ascending = ascending , inplace = inplace , kind = kind , na_position = na_position )
else :
new = self . __class__ ( self . _frame . sort_values ( by , axis = axis , ascending = ascending , inplace = inplace , kind = kind , na_position = na_position... |
def process_alias_create_namespace ( namespace ) :
"""Validate input arguments when the user invokes ' az alias create ' .
Args :
namespace : argparse namespace object .""" | namespace = filter_alias_create_namespace ( namespace )
_validate_alias_name ( namespace . alias_name )
_validate_alias_command ( namespace . alias_command )
_validate_alias_command_level ( namespace . alias_name , namespace . alias_command )
_validate_pos_args_syntax ( namespace . alias_name , namespace . alias_comman... |
def target_show ( self , id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / targets # show - target" | api_path = "/api/v2/targets/{id}.json"
api_path = api_path . format ( id = id )
return self . call ( api_path , ** kwargs ) |
def list_spiders ( self , project ) :
"""Lists all known spiders for a specific project . First class , maps
to Scrapyd ' s list spiders endpoint .""" | url = self . _build_url ( constants . LIST_SPIDERS_ENDPOINT )
params = { 'project' : project }
json = self . client . get ( url , params = params , timeout = self . timeout )
return json [ 'spiders' ] |
def _is_chunk_markdown ( source ) :
"""Return whether a chunk contains Markdown contents .""" | lines = source . splitlines ( )
if all ( line . startswith ( '# ' ) for line in lines ) : # The chunk is a Markdown * unless * it is commented Python code .
source = '\n' . join ( line [ 2 : ] for line in lines if not line [ 2 : ] . startswith ( '#' ) )
# skip headers
if not source :
return True
... |
def consume ( self , callback , bindings = None , queues = None , exchanges = None ) :
"""Consume messages from a message queue .
Simply define a callable to be used as the callback when messages are
delivered and specify the queue bindings . This call blocks . The callback
signature should accept a single po... | self . _bindings = bindings or config . conf [ "bindings" ]
self . _queues = queues or config . conf [ "queues" ]
self . _exchanges = exchanges or config . conf [ "exchanges" ]
# If the callback is a class , create an instance of it first
if inspect . isclass ( callback ) :
cb_obj = callback ( )
if not callable... |
def _set_ethernet_interface ( self , v , load = False ) :
"""Setter method for ethernet _ interface , mapped from YANG variable / rbridge _ id / router / router _ bgp / router _ bgp _ attributes / neighbor / neighbor _ ips / neighbor _ addr / update _ source / ethernet _ interface ( container )
If this variable i... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = ethernet_interface . ethernet_interface , is_container = 'container' , presence = False , yang_name = "ethernet-interface" , rest_name = "" , parent = self , choice = ( u'ch-update-source' , u'ca-eth' ) , path_helper = self .... |
def addCallback ( self , callback , * args , ** kw ) :
"""Add a success callback that will be run in the context of an eliot
action .
@ return : C { self }
@ rtype : L { DeferredContext }
@ raises AlreadyFinished : L { DeferredContext . addActionFinish } has been
called . This indicates a programmer error... | return self . addCallbacks ( callback , _passthrough , callbackArgs = args , callbackKeywords = kw ) |
def network_from_edgelist ( self , edgelist ) :
"""Defines a network from an array .
Parameters
edgelist : list of lists .
A list of lists which are 3 or 4 in length . For binary networks each sublist should be [ i , j , t ] where i and j are node indicies and t is the temporal index .
For weighted networks... | teneto . utils . check_TemporalNetwork_input ( edgelist , 'edgelist' )
if len ( edgelist [ 0 ] ) == 4 :
colnames = [ 'i' , 'j' , 't' , 'weight' ]
elif len ( edgelist [ 0 ] ) == 3 :
colnames = [ 'i' , 'j' , 't' ]
self . network = pd . DataFrame ( edgelist , columns = colnames )
self . _update_network ( ) |
def _broker_shutdown ( self ) :
"""Invoke : meth : ` Stream . on _ shutdown ` for every active stream , then allow
up to : attr : ` shutdown _ timeout ` seconds for the streams to unregister
themselves , logging an error if any did not unregister during the grace
period .""" | for _ , ( side , _ ) in self . poller . readers + self . poller . writers :
self . _call ( side . stream , side . stream . on_shutdown )
deadline = time . time ( ) + self . shutdown_timeout
while self . keep_alive ( ) and time . time ( ) < deadline :
self . _loop_once ( max ( 0 , deadline - time . time ( ) ) )
... |
def getIndex ( self , indexName , indexClass ) :
"""Retrieves an index with a given index name and class
@ params indexName : The index name
@ params indexClass : vertex or edge
@ return The Index object or None""" | if indexClass == "vertex" :
try :
return Index ( indexName , indexClass , "manual" , self . neograph . nodes . indexes . get ( indexName ) )
except client . NotFoundError :
return None
elif indexClass == "edge" :
try :
return Index ( indexName , indexClass , "manual" , self . neograp... |
def update_remaining_fldsdefprt ( self , min_ratio = None ) :
"""Finish updating self ( GOEnrichmentRecord ) field , is _ ratio _ different .""" | self . is_ratio_different = is_ratio_different ( min_ratio , self . study_count , self . study_n , self . pop_count , self . pop_n ) |
def _AcceptRPC ( self ) :
"""Reads RPC request from stdin and processes it , writing result to stdout .
Returns :
True as long as execution is to be continued , False otherwise .
Raises :
RpcException : if no function was specified in the RPC or no such API
function exists .""" | request = self . _ReadObject ( )
if request [ 'func' ] == '__kill__' :
self . ClearBreakpoints ( )
self . _WriteObject ( '__kill_ack__' )
return False
if 'func' not in request or request [ 'func' ] . startswith ( '_' ) :
raise RpcException ( 'Not a valid public API function.' )
rpc_result = getattr ( se... |
def connect_nodes ( nodes ) :
"""Connect the nodes in a list linearly .""" | for n , next_node in zip ( nodes , nodes [ 1 : ] ) :
if isinstance ( n , ControlFlowNode ) :
_connect_control_flow_node ( n , next_node )
elif isinstance ( next_node , ControlFlowNode ) :
n . connect ( next_node . test )
elif isinstance ( next_node , RestoreNode ) :
continue
elif... |
def generate_reciprocal_vectors_squared ( a1 , a2 , a3 , encut ) :
"""Generate reciprocal vector magnitudes within the cutoff along the specied
lattice vectors .
Args :
a1 : Lattice vector a ( in Bohrs )
a2 : Lattice vector b ( in Bohrs )
a3 : Lattice vector c ( in Bohrs )
encut : Reciprocal vector ener... | for vec in genrecip ( a1 , a2 , a3 , encut ) :
yield np . dot ( vec , vec ) |
def focus_changed ( self ) :
"""Editor focus has changed""" | fwidget = QApplication . focusWidget ( )
for finfo in self . data :
if fwidget is finfo . editor :
self . refresh ( )
self . editor_focus_changed . emit ( ) |
def generate ( env ) :
"""Add Builders and construction variables for aCC & cc to an Environment .""" | cc . generate ( env )
env [ 'CXX' ] = 'aCC'
env [ 'SHCCFLAGS' ] = SCons . Util . CLVar ( '$CCFLAGS +Z' ) |
def getCell ( self , row , column ) :
"""Returns the specified cell ( if a raster is set for the region )""" | row = int ( row )
column = int ( column )
if self . _raster [ 0 ] == 0 or self . _raster [ 1 ] == 0 :
return self
rowHeight = self . h / self . _raster [ 0 ]
columnWidth = self . h / self . _raster [ 1 ]
if column < 0 : # If column is negative , count backwards from the end
column = self . _raster [ 1 ] - colum... |
def map_uniprot_to_pdb ( self , seq_ident_cutoff = 0.0 , outdir = None , force_rerun = False ) :
"""Map the representative sequence ' s UniProt ID to PDB IDs using the PDBe " Best Structures " API .
Will save a JSON file of the results to the protein sequences folder .
The " Best structures " API is available a... | if not self . representative_sequence :
log . error ( '{}: no representative sequence set, cannot use best structures API' . format ( self . id ) )
return None
# Check if a UniProt ID is attached to the representative sequence
uniprot_id = self . representative_sequence . uniprot
if not uniprot_id :
log . e... |
def show_sls ( name , saltenv = 'base' ) :
r'''. . versionadded : : 2015.8.0
Display the rendered software definition from a specific sls file in the
local winrepo cache . This will parse all Jinja . Run pkg . refresh _ db to pull
the latest software definitions from the master .
. . note : :
This functio... | # Passed a filename
if os . path . exists ( name ) :
sls_file = name
# Use a winrepo path
else : # Get the location of the local repo
repo = _get_local_repo_dir ( saltenv )
# Add the sls file name to the path
repo = repo . split ( '\\' )
definition = name . split ( '.' )
repo . extend ( definiti... |
def upload ( self , # pylint : disable = too - many - arguments
path , name = None , resize = False , rotation = False , callback_url = None , callback_method = None , auto_align = False , ) :
"""Create a new model resource in the warehouse and uploads the path contents to it""" | if name is None :
head , tail = ntpath . split ( path )
name = tail or ntpath . basename ( head )
url = "http://models.{}/model/" . format ( self . config . host )
payload = { "name" : name , "allowed_transformations" : { "resize" : resize , "rotation" : rotation , } , "auto-align" : auto_align }
if callback_ur... |
def _sub16 ( ins ) :
'''Pops last 2 words from the stack and subtract them .
Then push the result onto the stack . Top of the stack is
subtracted Top - 1
Optimizations :
* If 2nd op is ZERO ,
then do NOTHING : A - 0 = A
* If any of the operands is < 4 , then
DEC is used
* If any of the operands is >... | op1 , op2 = tuple ( ins . quad [ 2 : 4 ] )
if is_int ( op2 ) :
op = int16 ( op2 )
output = _16bit_oper ( op1 )
if op == 0 :
output . append ( 'push hl' )
return output
if op < 4 :
output . extend ( [ 'dec hl' ] * op )
output . append ( 'push hl' )
return output
... |
def execute ( self , command ) :
"""Primary method to execute ipmitool commands
: param command : ipmi command to execute , str or list
e . g .
> ipmi = ipmitool ( ' consolename . prod ' , ' secretpass ' )
> ipmi . execute ( ' chassis status ' )""" | if isinstance ( command , str ) :
self . method ( command . split ( ) )
elif isinstance ( command , list ) :
self . method ( command )
else :
raise TypeError ( "command should be either a string or list type" )
if self . error :
raise IPMIError ( self . error )
else :
return self . status |
def url ( self , part ) :
"""Returns the full url for something . Typically used for getting a specific image .""" | return self . _server . url ( part , includeToken = True ) if part else None |
def _get_services_mapping ( ) :
'''Build a map of services based on the IANA assignment list :
http : / / www . iana . org / assignments / port - numbers
It will load the / etc / services file and will build the mapping on the fly ,
similar to the Capirca ' s SERVICES file :
https : / / github . com / googl... | if _SERVICES :
return _SERVICES
services_txt = ''
try :
with salt . utils . files . fopen ( '/etc/services' , 'r' ) as srv_f :
services_txt = salt . utils . stringutils . to_unicode ( srv_f . read ( ) )
except IOError as ioe :
log . error ( 'Unable to read from /etc/services:' )
log . error ( io... |
def maybe_copy_file_to_directory ( source_filepath , target_directory ) :
"""Copy a file to a directory if it is not already there .
Returns the target filepath .
Args :
source _ filepath : a string
target _ directory : a string
Returns :
a string""" | if not tf . gfile . Exists ( target_directory ) :
tf . logging . info ( "Creating directory %s" % target_directory )
os . mkdir ( target_directory )
target_filepath = os . path . join ( target_directory , os . path . basename ( source_filepath ) )
if not tf . gfile . Exists ( target_filepath ) :
tf . loggin... |
def set_filters ( self , include = None , exclude = None , write_errors = None , write_errors_tolerance = None , sigpipe = None ) :
"""Set various log data filters .
: param str | unicode | list include : Show only log lines matching the specified regexp .
. . note : : Requires enabled PCRE support .
: param ... | if write_errors is not None :
self . _set ( 'ignore-write-errors' , not write_errors , cast = bool )
if sigpipe is not None :
self . _set ( 'ignore-sigpipe' , not sigpipe , cast = bool )
self . _set ( 'write-errors-tolerance' , write_errors_tolerance )
for line in listify ( include ) :
self . _set ( 'log-fi... |
def get_default_commands ( self ) :
"""Returns the default commands of this application .
: rtype : list [ cleo . Command ]""" | commands = Application . get_default_commands ( self )
self . add ( ConstantsCommand ( ) )
self . add ( LoaderCommand ( ) )
self . add ( PyStratumCommand ( ) )
self . add ( WrapperCommand ( ) )
return commands |
def _get_deploy_options ( self , options ) :
"""Return the deployment options based on command line .""" | user_data = None
if options . user_data and options . b64_user_data :
raise CommandError ( "Cannot provide both --user-data and --b64-user-data." )
if options . b64_user_data :
user_data = options . b64_user_data
if options . user_data :
user_data = base64_file ( options . user_data ) . decode ( "ascii" )
r... |
def evaluate_reader ( reader , name , events , aux = 0. ) :
"""Evaluate a TMVA : : Reader over a NumPy array .
Parameters
reader : TMVA : : Reader
A TMVA : : Factory instance with variables booked in exactly the same
order as the columns in ` ` events ` ` .
name : string
The method name .
events : num... | if not isinstance ( reader , TMVA . Reader ) :
raise TypeError ( "reader must be a TMVA.Reader instance" )
events = np . ascontiguousarray ( events , dtype = np . float64 )
if events . ndim == 1 : # convert to 2D
events = events [ : , np . newaxis ]
elif events . ndim != 2 :
raise ValueError ( "events must ... |
def crossproduct ( d ) :
"""Create an SFrame containing the crossproduct of all provided options .
Parameters
d : dict
Each key is the name of an option , and each value is a list
of the possible values for that option .
Returns
out : SFrame
There will be a column for each key in the provided dictiona... | from . . import SArray
d = [ list ( zip ( list ( d . keys ( ) ) , x ) ) for x in _itertools . product ( * list ( d . values ( ) ) ) ]
sa = [ { k : v for ( k , v ) in x } for x in d ]
return SArray ( sa ) . unpack ( column_name_prefix = '' ) |
def generate_maximum_validator ( maximum , exclusiveMaximum = False , ** kwargs ) :
"""Generator function returning a callable for maximum value validation .""" | return functools . partial ( validate_maximum , maximum = maximum , is_exclusive = exclusiveMaximum ) |
def ver_to_tuple ( value ) :
"""Convert version like string to a tuple of integers .""" | return tuple ( int ( _f ) for _f in re . split ( r'\D+' , value ) if _f ) |
def _fillVolumesAndPaths ( self , paths ) :
"""Fill in paths .
: arg paths : = { Store . Volume : [ " linux path " , ] }""" | with self . btrfs as mount :
for bv in mount . subvolumes :
if not bv . readOnly :
continue
vol = self . _btrfsVol2StoreVol ( bv )
if vol is None :
continue
path = bv . fullPath
if path is None :
logger . info ( "Skipping deleted volume %s"... |
def comparebed ( args ) :
"""% prog comparebed AP . chr . bed infer . bed
Compare the scaffold links indicated in two bed files .""" | p = OptionParser ( comparebed . __doc__ )
opts , args = p . parse_args ( args )
if len ( args ) != 2 :
sys . exit ( not p . print_help ( ) )
abed , bbed = args
abed = Bed ( abed )
bbed = Bed ( bbed )
query_links ( abed , bbed )
query_links ( bbed , abed ) |
def delete ( self , full_path ) :
"""Delete a file in full _ path
> > > nd . delete ( ' / Picture / flower . png ' )
: param full _ path : The full path to delete the file to , * including the file name * .
: return : ` ` True ` ` if success to delete the file or ` ` False ` `""" | now = datetime . datetime . now ( ) . isoformat ( )
url = nurls [ 'delete' ] + full_path
headers = { 'userid' : self . user_id , 'useridx' : self . useridx , 'Content-Type' : "application/x-www-form-urlencoded; charset=UTF-8" , 'charset' : 'UTF-8' , 'Origin' : 'http://ndrive2.naver.com' , }
try :
r = self . session... |
def textfsm_extractor ( cls , template_name , raw_text ) :
"""Applies a TextFSM template over a raw text and return the matching table .
Main usage of this method will be to extract data form a non - structured output
from a network device and return the values in a table format .
: param cls : Instance of th... | textfsm_data = list ( )
cls . __class__ . __name__ . replace ( 'Driver' , '' )
current_dir = os . path . dirname ( os . path . abspath ( sys . modules [ cls . __module__ ] . __file__ ) )
template_dir_path = '{current_dir}/utils/textfsm_templates' . format ( current_dir = current_dir )
template_path = '{template_dir_pat... |
def _from_dict ( cls , _dict ) :
"""Initialize a LeadingSentence object from a json dictionary .""" | args = { }
if 'text' in _dict :
args [ 'text' ] = _dict . get ( 'text' )
if 'location' in _dict :
args [ 'location' ] = Location . _from_dict ( _dict . get ( 'location' ) )
if 'element_locations' in _dict :
args [ 'element_locations' ] = [ ElementLocations . _from_dict ( x ) for x in ( _dict . get ( 'elemen... |
def _setup_language_variables ( self , lang : str ) : # pylint : disable = no - self - use
"""Check for language availability and presence of tagger files .
: param lang : The language argument given to the class .
: type lang : str
: rtype : dict""" | assert lang in TAGGERS . keys ( ) , 'POS tagger not available for {0} language.' . format ( lang )
rel_path = os . path . join ( '~/cltk_data' , lang , 'model/' + lang + '_models_cltk/taggers/pos' )
# pylint : disable = C0301
path = os . path . expanduser ( rel_path )
tagger_paths = { }
for tagger_key , tagger_val in T... |
def label_image_centroids ( image , physical = False , convex = True , verbose = False ) :
"""Converts a label image to coordinates summarizing their positions
ANTsR function : ` labelImageCentroids `
Arguments
image : ANTsImage
image of integer labels
physical : boolean
whether you want physical space ... | d = image . shape
if len ( d ) != 3 :
raise ValueError ( 'image must be 3 dimensions' )
xcoords = np . asarray ( np . arange ( d [ 0 ] ) . tolist ( ) * ( d [ 1 ] * d [ 2 ] ) )
ycoords = np . asarray ( np . repeat ( np . arange ( d [ 1 ] ) , d [ 0 ] ) . tolist ( ) * d [ 2 ] )
zcoords = np . asarray ( np . repeat ( n... |
def from_learners ( cls , learn_gen : Learner , learn_crit : Learner , switcher : Callback = None , weights_gen : Tuple [ float , float ] = None , ** learn_kwargs ) :
"Create a GAN from ` learn _ gen ` and ` learn _ crit ` ." | losses = gan_loss_from_func ( learn_gen . loss_func , learn_crit . loss_func , weights_gen = weights_gen )
return cls ( learn_gen . data , learn_gen . model , learn_crit . model , * losses , switcher = switcher , ** learn_kwargs ) |
def to_vars_dict ( self ) :
"""Return local state which is relevant for the cluster setup process .""" | return { 'aws_access_key_id' : self . _access_key , 'aws_secret_access_key' : self . _secret_key , 'aws_region' : self . _region_name , 'aws_vpc_name' : ( self . _vpc or '' ) , 'aws_vpc_id' : ( self . _vpc_id or '' ) , } |
def get_groups ( self , filterTerm = None , groupName = None , groupDomain = None ) :
"""Return groups from the database""" | if groupDomain :
groupDomain = groupDomain . split ( '.' ) [ 0 ] . upper ( )
cur = self . conn . cursor ( )
if self . is_group_valid ( filterTerm ) :
cur . execute ( "SELECT * FROM groups WHERE id=? LIMIT 1" , [ filterTerm ] )
elif groupName and groupDomain :
cur . execute ( "SELECT * FROM groups WHERE LOWE... |
def get ( self , sid ) :
"""Constructs a TriggerContext
: param sid : The unique string that identifies the resource
: returns : twilio . rest . api . v2010 . account . usage . trigger . TriggerContext
: rtype : twilio . rest . api . v2010 . account . usage . trigger . TriggerContext""" | return TriggerContext ( self . _version , account_sid = self . _solution [ 'account_sid' ] , sid = sid , ) |
def matches ( self , regex , flags = 0 ) :
"""Run a regex test against a dict value ( whole string has to match ) .
> > > Query ( ) . f1 . matches ( r ' ^ \ w + $ ' )
: param regex : The regular expression to use for matching""" | return self . _generate_test ( lambda value : re . match ( regex , value , flags ) , ( 'matches' , self . _path , regex ) ) |
def from_status ( cls , status_line , msg = None ) :
"""Returns a class method from bottle . HTTPError . status _ line attribute .
Useful for patching ` bottle . HTTPError ` for web services .
Args :
status _ line ( str ) : bottle . HTTPError . status _ line text .
msg : The message data for response .
Re... | method = getattr ( cls , status_line . lower ( ) [ 4 : ] . replace ( ' ' , '_' ) )
return method ( msg ) |
def get_de_novos_in_transcript ( transcript , de_novos ) :
"""get the de novos within the coding sequence of a transcript
Args :
transcript : Transcript object , which defines the transcript coordinates
de _ novos : list of chromosome sequence positions for de novo events
Returns :
list of de novo positio... | in_transcript = [ ]
for de_novo in de_novos : # we check if the de novo is within the transcript by converting the
# chromosomal position to a CDS - based position . Variants outside the CDS
# will raise an error , which we catch and pass on . It ' s better to do
# this , rather than use the function in _ coding _ regi... |
def render ( self ) :
"""Render the canvas to an offscreen buffer and return the image
array .
Returns
image : array
Numpy array of type ubyte and shape ( h , w , 4 ) . Index [ 0 , 0 ] is the
upper - left corner of the rendered region .""" | self . set_current ( )
size = self . physical_size
fbo = FrameBuffer ( color = RenderBuffer ( size [ : : - 1 ] ) , depth = RenderBuffer ( size [ : : - 1 ] ) )
try :
fbo . activate ( )
self . events . draw ( )
return fbo . read ( )
finally :
fbo . deactivate ( ) |
def _safe_processing ( nsafefn , source , _globals = None , _locals = None ) :
"""Do a safe processing of input fn in using SAFE _ BUILTINS .
: param fn : function to call with input parameters .
: param source : source object to process with fn .
: param dict _ globals : global objects by name .
: param di... | if _globals is None :
_globals = SAFE_BUILTINS
else :
_globals . update ( SAFE_BUILTINS )
return nsafefn ( source , _globals , _locals ) |
def dropEvent ( self , event ) :
"""Override Qt method""" | mimeData = event . mimeData ( )
index_from = int ( mimeData . data ( "source-index" ) )
index_to = self . tabAt ( event . pos ( ) )
if index_to == - 1 :
index_to = self . count ( )
if int ( mimeData . data ( "tabbar-id" ) ) != id ( self ) :
tabwidget_from = to_text_string ( mimeData . data ( "tabwidget-id" ) )
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.