signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def f_rollup ( items , times , freq ) :
"""Use : func : ` groupby _ freq ` to rollup items
: param items : items in timeseries
: param times : times corresponding to items
: param freq : One of the ` ` dateutil . rrule ` ` frequency constants
: type freq : str""" | rollup = [ np . sum ( item for __ , item in ts ) for _ , ts in groupby_freq ( items , times , freq ) ]
return np . array ( rollup ) |
def sort_variants ( vcf_handle ) :
"""Sort the variants of a vcf file
Args :
vcf _ handle
mode ( str ) : position or rank score
Returns :
sorted _ variants ( Iterable ) : An iterable with sorted variants""" | logger . debug ( "Creating temp file" )
temp_file = NamedTemporaryFile ( delete = False )
temp_file . close ( )
logger . debug ( "Opening temp file with codecs" )
temp_file_handle = codecs . open ( temp_file . name , mode = 'w' , encoding = 'utf-8' , errors = 'replace' )
try :
with codecs . open ( temp_file . name ... |
def add ( node_name , ** kwargs ) :
"""Create a new node and generate a token for it""" | result = { }
kwargs = kwargs . copy ( )
overwrite = kwargs . pop ( 'overwrite' , False )
node = nago . core . get_node ( node_name )
if not node :
node = nago . core . Node ( )
elif not overwrite :
result [ 'status' ] = 'error'
result [ 'message' ] = "node %s already exists. add argument overwrite=1 to over... |
def handleMatch ( self , m ) :
"""Handles user input into [ magic ] tag , processes it ,
and inserts the returned URL into an < img > tag
through a Python ElementTree < img > Element .""" | userStr = m . group ( 3 )
# print ( userStr )
imgURL = processString ( userStr )
# print ( imgURL )
el = etree . Element ( 'img' )
# Sets imgURL to ' src ' attribute of < img > tag element
el . set ( 'src' , imgURL )
el . set ( 'alt' , userStr )
el . set ( 'title' , userStr )
return el |
def pre_process_method_headers ( method , headers ) :
'''Returns the lowered method .
Capitalize headers , prepend HTTP _ and change - to _ .''' | method = method . lower ( )
# Standard WSGI supported headers
_wsgi_headers = [ "content_length" , "content_type" , "query_string" , "remote_addr" , "remote_host" , "remote_user" , "request_method" , "server_name" , "server_port" ]
_transformed_headers = { }
# For every header , replace - to _ , prepend http _ if neces... |
def custom_scale_mixture_prior_builder ( getter , name , * args , ** kwargs ) :
"""A builder for the gaussian scale - mixture prior of Fortunato et al .
Please see https : / / arxiv . org / abs / 1704.02798 , section 7.1
Args :
getter : The ` getter ` passed to a ` custom _ getter ` . Please see the
documen... | # This specific prior formulation doesn ' t need any of the arguments forwarded
# from ` get _ variable ` .
del getter
del name
del args
del kwargs
return CustomScaleMixture ( FLAGS . prior_pi , FLAGS . prior_sigma1 , FLAGS . prior_sigma2 ) |
def gramschmidt ( vin , uin ) :
"""Returns that part of the first input vector
that is orthogonal to the second input vector .
The output vector is not normalized .
Args :
vin ( numpy array ) :
first input vector
uin ( numpy array ) :
second input vector""" | vin_uin = np . inner ( vin , uin )
uin_uin = np . inner ( uin , uin )
if uin_uin <= 0.0 :
raise ValueError ( "Zero or negative inner product!" )
return vin - ( vin_uin / uin_uin ) * uin |
def sanitize_label ( label : str ) -> str :
"""Sanitize a BIO label - this deals with OIE
labels sometimes having some noise , as parentheses .""" | if "-" in label :
prefix , suffix = label . split ( "-" )
suffix = suffix . split ( "(" ) [ - 1 ]
return f"{prefix}-{suffix}"
else :
return label |
def is_traditional ( s ) :
"""Check if a string ' s Chinese characters are Traditional .
This is equivalent to :
> > > identify ( ' foo ' ) in ( TRADITIONAL , BOTH )""" | chinese = _get_hanzi ( s )
if not chinese :
return False
elif chinese . issubset ( _SHARED_CHARACTERS ) :
return True
elif chinese . issubset ( _TRADITIONAL_CHARACTERS ) :
return True
return False |
def set_status ( self , name , text = '' , row = 0 , fg = 'black' , bg = 'white' ) :
'''set a status value''' | if self . is_alive ( ) :
self . parent_pipe_send . send ( Value ( name , text , row , fg , bg ) ) |
def type_inherits_of_type ( inheriting_type , base_type ) :
"""Checks whether inheriting _ type inherits from base _ type
: param str inheriting _ type :
: param str base _ type :
: return : True is base _ type is base of inheriting _ type""" | assert isinstance ( inheriting_type , type ) or isclass ( inheriting_type )
assert isinstance ( base_type , type ) or isclass ( base_type )
if inheriting_type == base_type :
return True
else :
if len ( inheriting_type . __bases__ ) != 1 :
return False
return type_inherits_of_type ( inheriting_type .... |
def get_entity ( self , entity_id , at = None ) :
"""Returns entity with given ID , optionally until position .""" | # Get a snapshot ( None if none exist ) .
if self . _snapshot_strategy is not None :
snapshot = self . _snapshot_strategy . get_snapshot ( entity_id , lte = at )
else :
snapshot = None
# Decide the initial state of the entity , and the
# version of the last item applied to the entity .
if snapshot is None :
... |
def _grid_widgets ( self ) :
"""Put the widgets in the correct position based on self . _ _ compound .""" | orient = str ( self . _scale . cget ( 'orient' ) )
self . _scale . grid ( row = 2 , column = 2 , sticky = 'ew' if orient == tk . HORIZONTAL else 'ns' , padx = ( 0 , self . __entryscalepad ) if self . __compound is tk . RIGHT else ( self . __entryscalepad , 0 ) if self . __compound is tk . LEFT else 0 , pady = ( 0 , sel... |
def wrap_object ( func , before , after ) :
'''before / after call will encapsulate callable object''' | def _wrapper ( * args , ** kwargs ) :
before ( )
try :
return func ( * args , ** kwargs )
except Exception as e :
raise e
finally :
after ( )
return _wrapper |
def smooth_rectangle ( x , y , rec_w , rec_h , gaussian_width_x , gaussian_width_y ) :
"""Rectangle with a solid central region , then Gaussian fall - off at the edges .""" | gaussian_x_coord = abs ( x ) - rec_w / 2.0
gaussian_y_coord = abs ( y ) - rec_h / 2.0
box_x = np . less ( gaussian_x_coord , 0.0 )
box_y = np . less ( gaussian_y_coord , 0.0 )
sigmasq_x = gaussian_width_x * gaussian_width_x
sigmasq_y = gaussian_width_y * gaussian_width_y
with float_error_ignore ( ) :
falloff_x = x ... |
def determine_module_class ( path , class_path ) :
"""Determine type of module and return deployment module class .""" | if not class_path : # First check directory name for type - indicating suffix
basename = os . path . basename ( path )
if basename . endswith ( '.sls' ) :
class_path = 'runway.module.serverless.Serverless'
elif basename . endswith ( '.tf' ) :
class_path = 'runway.module.terraform.Terraform'
... |
async def async_get_state ( self , field : str ) -> dict :
"""Get state of object in deCONZ .
Field is a string representing an API endpoint or lower
e . g . field = ' / lights ' .
See Dresden Elektroniks REST API documentation for details :
http : / / dresden - elektronik . github . io / deconz - rest - do... | session = self . session . get
url = self . api_url + field
response_dict = await async_request ( session , url )
return response_dict |
def get ( self , type_name , obj_id , base_fields = None , nested_fields = None ) :
"""Get the resource by resource id .
: param nested _ fields : nested resource fields .
: param type _ name : Resource type . For example , pool , lun , nasServer .
: param obj _ id : Resource id
: param base _ fields : Reso... | base_fields = self . get_fields ( type_name , base_fields , nested_fields )
url = '/api/instances/{}/{}' . format ( type_name , obj_id )
return self . rest_get ( url , fields = base_fields ) |
def assert_unordered_list_eq ( expected , actual , message = None ) :
"""Raises an AssertionError if the objects contained
in expected are not equal to the objects contained
in actual without regard to their order .
This takes quadratic time in the umber of elements in actual ; don ' t use it for very long li... | missing_in_actual = [ ]
missing_in_expected = list ( actual )
for x in expected :
try :
missing_in_expected . remove ( x )
except ValueError :
missing_in_actual . append ( x )
if missing_in_actual or missing_in_expected :
if not message :
message = ( "%r not equal to %r; missing item... |
def __zipped_files_data ( self ) :
"""Get a dict of all files of interest from the FA release zipfile .""" | files = { }
with zipfile . ZipFile ( self . __zip_file ) as thezip :
for zipinfo in thezip . infolist ( ) :
if zipinfo . filename . endswith ( 'metadata/icons.json' ) :
with thezip . open ( zipinfo ) as compressed_file :
files [ 'icons.json' ] = compressed_file . read ( )
... |
def _term ( self , term ) :
"""Add a term to the query .
Arguments :
term ( str ) : The term to add .
Returns :
SearchHelper : Self""" | # All terms must be strings for Elasticsearch
term = str ( term )
if term :
self . __query [ "q" ] += term
return self |
def _imload ( self , filepath , kwds ) :
"""Load an image file , guessing the format , and return a numpy
array containing an RGB image . If EXIF keywords can be read
they are returned in the dict _ kwds _ .""" | start_time = time . time ( )
typ , enc = mimetypes . guess_type ( filepath )
if not typ :
typ = 'image/jpeg'
typ , subtyp = typ . split ( '/' )
self . logger . debug ( "MIME type is %s/%s" % ( typ , subtyp ) )
data_loaded = False
if have_opencv and subtyp not in [ 'gif' ] : # First choice is OpenCv , because it sup... |
def put_settings ( self , sensors = [ ] , actuators = [ ] , auth_token = None , endpoint = None , blink = None , discovery = None , dht_sensors = [ ] , ds18b20_sensors = [ ] ) :
"""Sync settings to the Konnected device""" | url = self . base_url + '/settings'
payload = { "sensors" : sensors , "actuators" : actuators , "dht_sensors" : dht_sensors , "ds18b20_sensors" : ds18b20_sensors , "token" : auth_token , "apiUrl" : endpoint }
if blink is not None :
payload [ 'blink' ] = blink
if discovery is not None :
payload [ 'discovery' ] =... |
def text ( self , quantity : int = 5 ) -> str :
"""Generate the text .
: param quantity : Quantity of sentences .
: return : Text .""" | text = ''
for _ in range ( quantity ) :
text += ' ' + self . random . choice ( self . _data [ 'text' ] )
return text . strip ( ) |
def draw_circle ( self , x , y , r , color ) :
"""Draw a circle .
Args :
x ( int ) : The x coordinate of the center of the circle .
y ( int ) : The y coordinate of the center of the circle .
r ( int ) : The radius of the circle .
color ( Tuple [ int , int , int , int ] ) : The color of the circle .
Rais... | check_int_err ( lib . circleRGBA ( self . _ptr , x , y , r , color [ 0 ] , color [ 1 ] , color [ 2 ] , color [ 3 ] ) ) |
def random_color ( dtype = np . uint8 ) :
"""Return a random RGB color using datatype specified .
Parameters
dtype : numpy dtype of result
Returns
color : ( 4 , ) dtype , random color that looks OK""" | hue = np . random . random ( ) + .61803
hue %= 1.0
color = np . array ( colorsys . hsv_to_rgb ( hue , .99 , .99 ) )
if np . dtype ( dtype ) . kind in 'iu' :
max_value = ( 2 ** ( np . dtype ( dtype ) . itemsize * 8 ) ) - 1
color *= max_value
color = np . append ( color , max_value ) . astype ( dtype )
return col... |
def group ( self , p_todos ) :
"""Groups the todos according to the given group string .""" | # preorder todos for the group sort
p_todos = _apply_sort_functions ( p_todos , self . pregroupfunctions )
# initialize result with a single group
result = OrderedDict ( [ ( ( ) , p_todos ) ] )
for ( function , label ) , _ in self . groupfunctions :
oldresult = result
result = OrderedDict ( )
for oldkey , o... |
def parse_cookie ( self , string ) :
'''Parses a cookie string like returned in a Set - Cookie header
@ param string : The cookie string
@ return : the cookie dict''' | results = re . findall ( '([^=]+)=([^\;]+);?\s?' , string )
my_dict = { }
for item in results :
my_dict [ item [ 0 ] ] = item [ 1 ]
return my_dict |
def getNeighbors ( self , id , depth = 1 , blankNodes = 'false' , relationshipType = None , direction = 'BOTH' , project = '*' , callback = None , output = 'application/json' ) :
"""Get neighbors from : / graph / neighbors / { id }
Arguments :
id : This ID should be either a CURIE or an IRI
depth : How far to... | kwargs = { 'id' : id , 'depth' : depth , 'blankNodes' : blankNodes , 'relationshipType' : relationshipType , 'direction' : direction , 'project' : project , 'callback' : callback }
kwargs = { k : dumps ( v ) if type ( v ) is dict else v for k , v in kwargs . items ( ) }
param_rest = self . _make_rest ( 'id' , ** kwargs... |
def get ( self , name = None ) :
"""Returns the plugin object with the given name .
Or if a name is not given , the complete plugin dictionary is returned .
: param name : Name of a plugin
: return : None , single plugin or dictionary of plugins""" | if name is None :
return self . _plugins
else :
if name not in self . _plugins . keys ( ) :
return None
else :
return self . _plugins [ name ] |
def get_diff ( source , dest ) :
"""Get the diff between two records list in this order :
- to _ create
- to _ delete""" | # First build a dict from the lists , with the ID as the key .
source_dict = { record [ 'id' ] : record for record in source }
dest_dict = { record [ 'id' ] : record for record in dest }
source_keys = set ( source_dict . keys ( ) )
dest_keys = set ( dest_dict . keys ( ) )
to_create = source_keys - dest_keys
to_delete =... |
def _from_dict ( cls , _dict ) :
"""Initialize a QueryRelationsRelationship object from a json dictionary .""" | args = { }
if 'type' in _dict :
args [ 'type' ] = _dict . get ( 'type' )
if 'frequency' in _dict :
args [ 'frequency' ] = _dict . get ( 'frequency' )
if 'arguments' in _dict :
args [ 'arguments' ] = [ QueryRelationsArgument . _from_dict ( x ) for x in ( _dict . get ( 'arguments' ) ) ]
if 'evidence' in _dict... |
def punsubscribe ( self , * args ) :
"""Unsubscribe from the supplied patterns . If empty , unsubscribe from
all patterns .""" | if args :
args = list_or_args ( args [ 0 ] , args [ 1 : ] )
patterns = self . _normalize_keys ( dict . fromkeys ( args ) )
else :
patterns = self . patterns
self . pending_unsubscribe_patterns . update ( patterns )
return self . execute_command ( 'PUNSUBSCRIBE' , * args ) |
def exchange_partitions ( self , partitionSpecs , source_db , source_table_name , dest_db , dest_table_name ) :
"""Parameters :
- partitionSpecs
- source _ db
- source _ table _ name
- dest _ db
- dest _ table _ name""" | self . send_exchange_partitions ( partitionSpecs , source_db , source_table_name , dest_db , dest_table_name )
return self . recv_exchange_partitions ( ) |
def get_nodes ( self , coord , coords ) :
"""Get the variables containing the definition of the nodes
Parameters
coord : xarray . Coordinate
The mesh variable
coords : dict
The coordinates to use to get node coordinates""" | def get_coord ( coord ) :
return coords . get ( coord , self . ds . coords . get ( coord ) )
return list ( map ( get_coord , coord . attrs . get ( 'node_coordinates' , '' ) . split ( ) [ : 2 ] ) ) |
def convert_to_py_error ( error_message ) :
"""Raise specific exceptions for ease of error handling""" | message = error_message . lower ( )
for err_msg , err_type in ERR_MSGS :
if err_msg in message :
return err_type ( error_message )
else :
return IndicoError ( error_message ) |
def fit_transform ( self , X , y ) :
"""Encode categorical columns into average target values .
Args :
X ( pandas . DataFrame ) : categorical columns to encode
y ( pandas . Series ) : the target column
Returns :
X ( pandas . DataFrame ) : encoded columns""" | self . target_encoders = [ None ] * X . shape [ 1 ]
self . target_mean = y . mean ( )
for i , col in enumerate ( X . columns ) :
self . target_encoders [ i ] = self . _get_target_encoder ( X [ col ] , y )
X . loc [ : , col ] = X [ col ] . fillna ( NAN_INT ) . map ( self . target_encoders [ i ] ) . fillna ( self... |
def get_context_data ( self , ** kwargs ) :
"""Add context data to view""" | context = super ( ) . get_context_data ( ** kwargs )
tabs = self . get_active_tabs ( )
context . update ( { 'page_detail_tabs' : tabs , 'active_tab' : tabs [ 0 ] . code if tabs else '' , 'app_label' : self . get_app_label ( ) , 'model_name' : self . get_model_name ( ) , 'model_alias' : self . get_model_alias ( ) , 'mod... |
def socket_reader ( connection : socket , buffer_size : int = 1024 ) :
"""read data from adb socket""" | while connection is not None :
try :
buffer = connection . recv ( buffer_size )
# no output
if not len ( buffer ) :
raise ConnectionAbortedError
except ConnectionAbortedError : # socket closed
print ( 'connection aborted' )
connection . close ( )
yield... |
def cannon_normalize ( spec_raw ) :
"""Normalize according to The Cannon""" | spec = np . array ( [ spec_raw ] )
wl = np . arange ( 0 , spec . shape [ 1 ] )
w = continuum_normalization . gaussian_weight_matrix ( wl , L = 50 )
ivar = np . ones ( spec . shape ) * 0.5
cont = continuum_normalization . _find_cont_gaussian_smooth ( wl , spec , ivar , w )
norm_flux , norm_ivar = continuum_normalization... |
def _filter_in ( self , term_list , field_name , field_type , is_not ) :
"""Returns a query that matches exactly ANY term in term _ list .
Notice that :
A in { B , C } < = > ( A = B or A = C )
~ ( A in { B , C } ) < = > ~ ( A = B or A = C )
Because OP _ AND _ NOT ( C , D ) < = > ( C and ~ D ) , then D = ( A... | query_list = [ self . _filter_exact ( term , field_name , field_type , is_not = False ) for term in term_list ]
if is_not :
return xapian . Query ( xapian . Query . OP_AND_NOT , self . _all_query ( ) , xapian . Query ( xapian . Query . OP_OR , query_list ) )
else :
return xapian . Query ( xapian . Query . OP_OR... |
def get_epoch_namespace_receive_fees_period ( block_height , namespace_id ) :
"""how long can a namespace receive register / renewal fees ?""" | epoch_config = get_epoch_config ( block_height )
if epoch_config [ 'namespaces' ] . has_key ( namespace_id ) :
return epoch_config [ 'namespaces' ] [ namespace_id ] [ 'NAMESPACE_RECEIVE_FEES_PERIOD' ]
else :
return epoch_config [ 'namespaces' ] [ '*' ] [ 'NAMESPACE_RECEIVE_FEES_PERIOD' ] |
def ssh_sa_ssh_server_cipher ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
ssh_sa = ET . SubElement ( config , "ssh-sa" , xmlns = "urn:brocade.com:mgmt:brocade-sec-services" )
ssh = ET . SubElement ( ssh_sa , "ssh" )
server = ET . SubElement ( ssh , "server" )
cipher = ET . SubElement ( server , "cipher" )
cipher . text = kwargs . pop ( 'cipher' )
callback =... |
def validate_version ( self ) :
"""Ensure this package works with the installed version of dbt .""" | installed = get_installed_version ( )
if not versions_compatible ( * self . dbt_version ) :
msg = IMPOSSIBLE_VERSION_ERROR . format ( package = self . project_name , version_spec = [ x . to_version_string ( ) for x in self . dbt_version ] )
raise DbtProjectError ( msg )
if not versions_compatible ( installed , ... |
def plot_qq_exp ( fignum , I , title , subplot = False ) :
"""plots data against an exponential distribution in 0 = > 90.
Parameters
_ _ _ _ _
fignum : matplotlib figure number
I : data
title : plot title
subplot : boolean , if True plot as subplot with 1 row , two columns with fignum the plot number""" | if subplot == True :
plt . subplot ( 1 , 2 , fignum )
else :
plt . figure ( num = fignum )
X , Y , dpos , dneg = [ ] , [ ] , 0. , 0.
rad = old_div ( np . pi , 180. )
xsum = 0
for i in I :
theta = ( 90. - i ) * rad
X . append ( 1. - np . cos ( theta ) )
xsum += X [ - 1 ]
X . sort ( )
n = float ( len ... |
def untag ( self , querystring , tags , afterwards = None ) :
"""removes tags from messages that match ` querystring ` .
This appends an untag operation to the write queue and raises
: exc : ` ~ errors . DatabaseROError ` if in read only mode .
: param querystring : notmuch search string
: type querystring ... | if self . ro :
raise DatabaseROError ( )
self . writequeue . append ( ( 'untag' , afterwards , querystring , tags ) ) |
def merge_truthy ( * dicts ) :
"""Merge multiple dictionaries , keeping the truthy values in case of key collisions .
Accepts any number of dictionaries , or any other object that returns a 2 - tuple of
key and value pairs when its ` . items ( ) ` method is called .
If a key exists in multiple dictionaries pa... | merged = { }
for d in dicts :
for k , v in d . items ( ) :
merged [ k ] = v or merged . get ( k , v )
return merged |
def select_spread ( list_of_elements = None , number_of_elements = None ) :
"""This function returns the specified number of elements of a list spread
approximately evenly .""" | if len ( list_of_elements ) <= number_of_elements :
return list_of_elements
if number_of_elements == 0 :
return [ ]
if number_of_elements == 1 :
return [ list_of_elements [ int ( round ( ( len ( list_of_elements ) - 1 ) / 2 ) ) ] ]
return [ list_of_elements [ int ( round ( ( len ( list_of_elements ) - 1 ) /... |
def flatten_dict ( dct , separator = '-->' , allowed_types = [ int , float , bool ] ) :
"""Returns a list of string identifiers for each element in dct .
Recursively scans through dct and finds every element whose type is in
allowed _ types and adds a string indentifier for it .
eg :
dct = {
' a ' : ' a s... | flat_list = [ ]
for key in sorted ( dct ) :
if key [ : 2 ] == '__' :
continue
key_type = type ( dct [ key ] )
if key_type in allowed_types :
flat_list . append ( str ( key ) )
elif key_type is dict :
sub_list = flatten_dict ( dct [ key ] )
sub_list = [ str ( key ) + separ... |
def _get_field_by_name ( table : LdapObjectClass , name : str ) -> tldap . fields . Field :
"""Lookup a field by its name .""" | fields = table . get_fields ( )
return fields [ name ] |
def _get_scale_and_shape ( self , transformed_lvs ) :
"""Obtains model scale , shape and skewness latent variables
Parameters
transformed _ lvs : np . array
Transformed latent variable vector
Returns
- Tuple of model scale , model shape , model skewness""" | if self . scale is True :
if self . shape is True :
model_shape = transformed_lvs [ - 1 ]
model_scale = transformed_lvs [ - 2 ]
else :
model_shape = 0
model_scale = transformed_lvs [ - 1 ]
else :
model_scale = 0
model_shape = 0
if self . skewness is True :
model_skewn... |
def convert_notebooks ( ) :
"""Converts IPython Notebooks to proper . rst files and moves static
content to the _ static directory .""" | convert_status = call ( [ 'ipython' , 'nbconvert' , '--to' , 'rst' , '*.ipynb' ] )
if convert_status != 0 :
raise SystemError ( 'Conversion failed! Status was %s' % convert_status )
notebooks = [ x for x in os . listdir ( '.' ) if '.ipynb' in x and os . path . isfile ( x ) ]
names = [ os . path . splitext ( x ) [ 0... |
def get_attachable_volumes ( self , start = 0 , count = - 1 , filter = '' , query = '' , sort = '' , scope_uris = '' , connections = '' ) :
"""Gets the volumes that are connected on the specified networks based on the storage system port ' s expected
network connectivity .
A volume is attachable if it satisfies... | uri = self . URI + '/attachable-volumes'
if connections :
uri += str ( '?' + 'connections=' + connections . __str__ ( ) )
return self . _client . get_all ( start , count , filter = filter , query = query , sort = sort , uri = uri , scope_uris = scope_uris ) |
def jwt_verify_token ( headers ) :
"""Verify the JWT token .
: param dict headers : The request headers .
: returns : The token data .
: rtype : dict""" | # Get the token from headers
token = headers . get ( current_app . config [ 'OAUTH2SERVER_JWT_AUTH_HEADER' ] )
if token is None :
raise JWTInvalidHeaderError
# Get authentication type
authentication_type = current_app . config [ 'OAUTH2SERVER_JWT_AUTH_HEADER_TYPE' ]
# Check if the type should be checked
if authenti... |
def dorogokupets2015_pth ( v , temp , v0 , gamma0 , gamma_inf , beta , theta01 , m1 , theta02 , m2 , n , z , t_ref = 300. , three_r = 3. * constants . R ) :
"""calculate thermal pressure for Dorogokupets 2015 EOS
: param v : unit - cell volume in A ^ 3
: param temp : temperature in K
: param v0 : unit - cell ... | # x = v / v0
# a = a0 * np . power ( x , m )
v_mol = vol_uc2mol ( v , z )
gamma = altshuler_grun ( v , v0 , gamma0 , gamma_inf , beta )
theta1 = altshuler_debyetemp ( v , v0 , gamma0 , gamma_inf , beta , theta01 )
theta2 = altshuler_debyetemp ( v , v0 , gamma0 , gamma_inf , beta , theta02 )
if isuncertainties ( [ v , t... |
def importfile ( filename ) :
"""Imports a module specifically from a file .
: param filename | < str >
: return < module > | | None""" | pkg = packageFromPath ( filename , includeModule = True )
root = packageRootPath ( filename )
if root not in sys . path :
sys . path . insert ( 0 , root )
__import__ ( pkg )
return sys . modules [ pkg ] |
def add_argparser ( self , root , parents ) :
"""Add arguments for this command .""" | parents . append ( tools . argparser )
parser = root . add_parser ( 'auth' , parents = parents )
parser . set_defaults ( func = self )
parser . add_argument ( '--secrets' , dest = 'secrets' , action = 'store' , help = 'Path to the authorization secrets file (client_secrets.json).' )
return parser |
def _parse_ftp_error ( error ) : # type : ( ftplib . Error ) - > Tuple [ Text , Text ]
"""Extract code and message from ftp error .""" | code , _ , message = text_type ( error ) . partition ( " " )
return code , message |
def canonicalize ( method , resource , query_parameters , headers ) :
"""Canonicalize method , resource
: type method : str
: param method : The HTTP verb that will be used when requesting the URL .
Defaults to ` ` ' GET ' ` ` . If method is ` ` ' RESUMABLE ' ` ` then the
signature will additionally contain... | headers , _ = get_canonical_headers ( headers )
if method == "RESUMABLE" :
method = "POST"
headers . append ( "x-goog-resumable:start" )
if query_parameters is None :
return _Canonical ( method , resource , [ ] , headers )
normalized_qp = sorted ( ( key . lower ( ) , value and value . strip ( ) or "" ) for ... |
def upload_submit ( self , upload_request ) :
"""The method is submitting dataset upload""" | path = '/api/1.0/upload/save'
return self . _api_post ( definition . DatasetUploadResponse , path , upload_request ) |
def patch_statusreporter ( ) :
"""Monkey patch robotframework to do postmortem debugging""" | from robot . running . statusreporter import StatusReporter
orig_exit = StatusReporter . __exit__
def __exit__ ( self , exc_type , exc_val , exc_tb ) :
if exc_val and isinstance ( exc_val , Exception ) :
set_pdb_trace ( pm = True )
return orig_exit ( self , exc_type , exc_val , exc_tb )
StatusReporter .... |
def _write_mef ( self , key , extlist , outfile ) :
"""Write out regular multi - extension FITS data .""" | channel = self . fv . get_channel ( self . chname )
with fits . open ( outfile , mode = 'update' ) as pf : # Process each modified data extension
for idx in extlist :
k = '{0}[{1}]' . format ( key , self . _format_extname ( idx ) )
image = channel . datasrc [ k ]
# Insert data and header int... |
def recvline ( sock ) :
"""Receive a single line from the socket .""" | reply = io . BytesIO ( )
while True :
c = sock . recv ( 1 )
if not c :
return None
# socket is closed
if c == b'\n' :
break
reply . write ( c )
result = reply . getvalue ( )
log . debug ( '-> %r' , result )
return result |
def colorize ( arr , colors , values ) :
"""Colorize a monochromatic array * arr * , based * colors * given for
* values * . Interpolation is used . * values * must be in ascending order .""" | hcolors = np . array ( [ rgb2hcl ( * i [ : 3 ] ) for i in colors ] )
# unwrap colormap in hcl space
hcolors [ : , 0 ] = np . rad2deg ( np . unwrap ( np . deg2rad ( np . array ( hcolors ) [ : , 0 ] ) ) )
channels = [ np . interp ( arr , np . array ( values ) , np . array ( hcolors ) [ : , i ] ) for i in range ( 3 ) ]
ch... |
def destroy ( self ) :
"""Destroy a Partner of given handle .
Before destruction the Partner is stopped , all clients disconnected and
all shared memory blocks released .""" | if self . library :
return self . library . Par_Destroy ( ctypes . byref ( self . pointer ) ) |
def delete_service ( self , name ) :
"""Delete a service by name .
@ param name : Service name
@ return : The deleted ApiService object""" | return services . delete_service ( self . _get_resource_root ( ) , name , self . name ) |
def fix_size ( self , content ) :
"""Adjusts the width and height of the file switcher
based on the relative size of the parent and content .""" | # Update size of dialog based on relative size of the parent
if content :
width , height = self . get_item_size ( content )
# Width
parent = self . parent ( )
relative_width = parent . geometry ( ) . width ( ) * 0.65
if relative_width > self . MAX_WIDTH :
relative_width = self . MAX_WIDTH
... |
def pos ( self ) :
"""Renvoie un caractère représentant la catégorie ( part of speech , orationis ) du lemme .
: return : Caractère représentant la catégorie ( part of speech , orationis ) du lemme .
: rtype : str""" | if not self . _pos and self . _renvoi :
lr = self . _lemmatiseur . lemme ( self . _renvoi )
if lr :
return lr . pos ( )
return self . _pos |
def hasAttribute ( self , attrName ) :
'''hasAttribute - Checks for the existance of an attribute . Attribute names are all lowercase .
@ param attrName < str > - The attribute name
@ return < bool > - True or False if attribute exists by that name''' | attrName = attrName . lower ( )
# Check if requested attribute is present on this node
return bool ( attrName in self . _attributes ) |
def update_share_image ( liststore , tree_iters , col , large_col , pcs_files , dir_name , icon_size , large_icon_size ) :
'''下载文件缩略图 , 并将它显示到liststore里 .
需要同时更新两列里的图片 , 用不同的缩放尺寸 .
pcs _ files - 里面包含了几个必要的字段 .
dir _ name - 缓存目录 , 下载到的图片会保存这个目录里 .''' | def update_image ( filepath , tree_iter ) :
try :
tree_path = liststore . get_path ( tree_iter )
if tree_path is None :
return
pix = GdkPixbuf . Pixbuf . new_from_file ( filepath )
width = pix . get_width ( )
height = pix . get_height ( )
small_pix = pix .... |
def authenticationRequest ( ) :
"""AUTHENTICATION REQUEST Section 9.2.2""" | a = TpPd ( pd = 0x5 )
b = MessageType ( mesType = 0x12 )
# 00010010
c = CiphKeySeqNrAndSpareHalfOctets ( )
d = AuthenticationParameterRAND ( )
packet = a / b / c / d
return packet |
def tryAccessModifiers ( self , block ) :
"""Check for private , protected , public , signals etc . . . and assume we are in a
class definition . Try to find a previous private / protected / private . . . or
class and return its indentation or null if not found .""" | if CFG_ACCESS_MODIFIERS < 0 :
return None
if not re . match ( r'^\s*((public|protected|private)\s*(slots|Q_SLOTS)?|(signals|Q_SIGNALS)\s*):\s*$' , block . text ( ) ) :
return None
try :
block , notUsedColumn = self . findBracketBackward ( block , 0 , '{' )
except ValueError :
return None
indentation = s... |
def lazy ( func ) :
"""Decorator , which can be used for lazy imports
@ lazy
def yaml ( ) :
import yaml
return yaml""" | try :
frame = sys . _getframe ( 1 )
except Exception :
_locals = None
else :
_locals = frame . f_locals
func_name = func . func_name if six . PY2 else func . __name__
return LazyStub ( func_name , func , _locals ) |
def get_current_shutit_pexpect_session_environment ( self , note = None ) :
"""Returns the current environment from the currently - set default
pexpect child .""" | self . handle_note ( note )
current_session = self . get_current_shutit_pexpect_session ( )
if current_session is not None :
res = current_session . current_environment
else :
res = None
self . handle_note_after ( note )
return res |
def isiterable ( element , exclude = None ) :
"""Check whatever or not if input element is an iterable .
: param element : element to check among iterable types .
: param type / tuple exclude : not allowed types in the test .
: Example :
> > > isiterable ( { } )
True
> > > isiterable ( { } , exclude = d... | # check for allowed type
allowed = exclude is None or not isinstance ( element , exclude )
result = allowed and isinstance ( element , Iterable )
return result |
def get_current_branch ( self ) -> str :
""": return : current branch
: rtype : str""" | current_branch : str = self . repo . active_branch . name
LOGGER . debug ( 'current branch: %s' , current_branch )
return current_branch |
def _update_header ( orig_vcf , base_file , new_lines , chrom_process_fn = None ) :
"""Fix header with additional lines and remapping of generic sample names .""" | new_header = "%s-sample_header.txt" % utils . splitext_plus ( base_file ) [ 0 ]
with open ( new_header , "w" ) as out_handle :
chrom_line = None
with utils . open_gzipsafe ( orig_vcf ) as in_handle :
for line in in_handle :
if line . startswith ( "##" ) :
out_handle . write (... |
def configure ( self , settings_module = None , ** kwargs ) :
"""Allows user to reconfigure settings object passing a new settings
module or separated kwargs
: param settings _ module : defines the setttings file
: param kwargs : override default settings""" | default_settings . reload ( )
environment_var = self . _kwargs . get ( "ENVVAR_FOR_DYNACONF" , default_settings . ENVVAR_FOR_DYNACONF )
settings_module = settings_module or os . environ . get ( environment_var )
compat_kwargs ( kwargs )
kwargs . update ( self . _kwargs )
self . _wrapped = Settings ( settings_module = s... |
def iterate ( self , image , feature_extractor , feature_vector ) :
"""iterate ( image , feature _ extractor , feature _ vector ) - > bounding _ box
Scales the given image , and extracts features from all possible bounding boxes .
For each of the sampled bounding boxes , this function fills the given pre - allo... | for scale , scaled_image_shape in self . scales ( image ) : # prepare the feature extractor to extract features from the given image
feature_extractor . prepare ( image , scale )
for bb in self . sample_scaled ( scaled_image_shape ) : # extract features for
feature_extractor . extract_indexed ( bb , fea... |
def get_or_set_score ( self , member , default = 0 ) :
"""If * member * is in the collection , return its value . If not , store it
with a score of * default * and return * default * . * default * defaults to""" | default = float ( default )
def get_or_set_score_trans ( pipe ) :
pickled_member = self . _pickle ( member )
score = pipe . zscore ( self . key , pickled_member )
if score is None :
pipe . zadd ( self . key , { self . _pickle ( member ) : default } )
return default
return score
return se... |
def Get ( self , path , follow_symlink = True ) :
"""Stats given file or returns a cached result if available .
Args :
path : A path to the file to perform ` stat ` on .
follow _ symlink : True if ` stat ` of a symlink should be returned instead of
a file that it points to . For non - symlinks this setting ... | key = self . _Key ( path = path , follow_symlink = follow_symlink )
try :
return self . _cache [ key ]
except KeyError :
value = Stat . FromPath ( path , follow_symlink = follow_symlink )
self . _cache [ key ] = value
# If we are not following symlinks and the file is a not symlink then
# the stat r... |
def dre_dtau ( self , pars ) :
r""": math : Add formula""" | self . _set_parameters ( pars )
# term 1
num1 = self . c * self . w * self . otc1 * np . cos ( self . ang )
term1 = num1 / self . denom
# term 2
num2a = self . otc * np . cos ( self . ang )
num2b = 1 + num2a
denom2 = self . denom ** 2
term2 = num2b / denom2
# term 3
term3 = 2 * self . c * self . w * self . otc1 * np . ... |
def _indirect_jump_resolved ( self , jump , jump_addr , resolved_by , targets ) :
"""Called when an indirect jump is successfully resolved .
: param IndirectJump jump : The resolved indirect jump .
: param IndirectJumpResolver resolved _ by : The resolver used to resolve this indirect jump .
: param list targ... | from . indirect_jump_resolvers . jumptable import JumpTableResolver
source_addr = jump . addr
if isinstance ( resolved_by , JumpTableResolver ) : # Fill in the jump _ tables dict
self . jump_tables [ jump . addr ] = jump
jump . resolved_targets = targets
all_targets = set ( targets )
for addr in all_targets :
t... |
def binary_tlv_to_python ( binary_string , result = None ) :
"""Recursively decode a binary string and store output in result object
: param binary _ string : a bytearray object of tlv data
: param result : result store for recursion
: return :""" | result = { } if result is None else result
if not binary_string :
return result
byte = binary_string [ 0 ]
kind = byte & type_mask
id_length = get_id_length ( byte )
payload_length = get_value_length ( byte )
# start after the type indicator
offset = 1
item_id = str ( combine_bytes ( binary_string [ offset : offset... |
def vinet_k ( p , v0 , k0 , k0p , numerical = False ) :
"""calculate bulk modulus , wrapper for cal _ k _ vinet
cannot handle uncertainties
: param p : pressure in GPa
: param v0 : unit - cell volume in A ^ 3 at 1 bar
: param k0 : bulk modulus at reference conditions
: param k0p : pressure derivative of b... | f_u = uct . wrap ( cal_k_vinet )
return f_u ( p , [ v0 , k0 , k0p ] ) |
def get_xyz ( self , list_of_names = None ) :
"""Get xyz coordinates for these electrodes
Parameters
list _ of _ names : list of str
list of electrode names to use
Returns
list of tuples of 3 floats ( x , y , z )
list of xyz coordinates for all the electrodes
TODO
coordinate system of electrodes""" | if list_of_names is not None :
filter_lambda = lambda x : x [ 'name' ] in list_of_names
else :
filter_lambda = None
return self . electrodes . get ( filter_lambda = filter_lambda , map_lambda = lambda e : ( float ( e [ 'x' ] ) , float ( e [ 'y' ] ) , float ( e [ 'z' ] ) ) ) |
def wheel ( self , load ) :
'''Send a master control function back to the wheel system''' | # All wheel ops pass through eauth
auth_type , err_name , key = self . _prep_auth_info ( load )
# Authenticate
auth_check = self . loadauth . check_authentication ( load , auth_type , key = key , show_username = True )
error = auth_check . get ( 'error' )
if error : # Authentication error occurred : do not continue .
... |
def get ( self , section , key ) :
"""Return the ' value ' of all lines matching the section / key .
Yields :
values for matching lines .""" | line = self . _make_line ( key )
for line in self . get_line ( section , line ) :
yield line . value |
def log_task ( task , logger = logging , level = 'info' , propagate_fail = True , uuid = None ) :
"""Parameterized decorator to wrap a function in a log task
Example :
> > > @ log _ task ( ' mytask ' )
. . . def do _ something ( ) :
. . . pass""" | def decorator ( func ) :
@ wraps ( func )
def wrapper ( * args , ** kwargs ) :
with LogTask ( task , logger = logger , level = level , propagate_fail = propagate_fail , uuid = uuid ) :
return func ( * args , ** kwargs )
return wrapper
return decorator |
def pcolormesh ( self , * args , ** kwargs ) :
"""Create a pseudocolor plot of a 2 - D array .
If a 3D or higher Data object is passed , a lower dimensional
channel can be plotted , provided the ` ` squeeze ` ` of the channel
has ` ` ndim = = 2 ` ` and the first two axes do not span dimensions
other than th... | args , kwargs = self . _parse_plot_args ( * args , ** kwargs , plot_type = "pcolormesh" )
return super ( ) . pcolormesh ( * args , ** kwargs ) |
def _get_filter ( sdk_filter , attr_map ) :
"""Common functionality for filter structures
: param sdk _ filter : { field : constraint , field : { operator : constraint } , . . . }
: return : { field _ _ operator : constraint , . . . }""" | if not isinstance ( sdk_filter , dict ) :
raise CloudValueError ( 'filter value must be a dictionary, was %r' % ( sdk_filter , ) )
custom = sdk_filter . pop ( 'custom_attributes' , { } )
new_filter = _normalise_key_values ( filter_obj = sdk_filter , attr_map = attr_map )
new_filter . update ( { 'custom_attributes__... |
def api_notifications ( ) :
"""Receive MTurk REST notifications .""" | event_type = request . values [ 'Event.1.EventType' ]
assignment_id = request . values [ 'Event.1.AssignmentId' ]
# Add the notification to the queue .
db . logger . debug ( 'rq: Queueing %s with id: %s for worker_function' , event_type , assignment_id )
q . enqueue ( worker_function , event_type , assignment_id , None... |
def make_and_return_path_from_path_and_folder_names ( path , folder_names ) :
"""For a given path , create a directory structure composed of a set of folders and return the path to the inner - most folder .
For example , if path = ' / path / to / folders ' , and folder _ names = [ ' folder1 ' , ' folder2 ' ] , th... | for folder_name in folder_names :
path += folder_name + '/'
try :
os . makedirs ( path )
except FileExistsError :
pass
return path |
def parse_text ( self , text , ** kwargs ) :
"""Parses given text with VISLCG3 based syntactic analyzer .
As a result of parsing , the input Text object will obtain a new
layer named LAYER _ VISLCG3 , which contains a list of dicts .
Each dicts corresponds to analysis of a single word token , and
has the fo... | # a ) get the configuration :
apply_tag_analysis = False
augment_words = False
all_return_types = [ "text" , "vislcg3" , "trees" , "dep_graphs" ]
return_type = all_return_types [ 0 ]
for argName , argVal in kwargs . items ( ) :
if argName . lower ( ) == 'return_type' :
if argVal . lower ( ) in all_return_ty... |
def find_tool ( name , additional_paths = [ ] , path_last = False ) :
"""Attempts to find tool ( binary ) named ' name ' in PATH and in
' additional - paths ' . If found in path , returns ' name ' . If
found in additional paths , returns full name . If the tool
is found in several directories , returns the fi... | assert isinstance ( name , basestring )
assert is_iterable_typed ( additional_paths , basestring )
assert isinstance ( path_last , ( int , bool ) )
programs = path . programs_path ( )
match = path . glob ( programs , [ name , name + '.exe' ] )
additional_match = path . glob ( additional_paths , [ name , name + '.exe' ]... |
def highlightCharacters ( self , widgetObj , setPos , colorCode , fontWeight , charFormat = None ) :
"""Change the character format of one or more characters .
If ` ` charFormat ` ` is * * None * * then only the color and font
weight of the characters are changed to ` ` colorCode ` ` and
` ` fontWeight ` ` , ... | # Get the text cursor and character format .
textCursor = widgetObj . textCursor ( )
oldPos = textCursor . position ( )
retVal = [ ]
# Change the character formats of all the characters placed at
# the positions ` ` setPos ` ` .
for ii , pos in enumerate ( setPos ) : # Extract the position of the character to modify .
... |
def clear_text ( self , label ) :
"""stub""" | if label not in self . my_osid_object_form . _my_map [ 'texts' ] :
raise NotFound ( )
del self . my_osid_object_form . _my_map [ 'texts' ] [ label ] |
def _is_2D_matrix ( matrix ) :
"""Checks to see if a ndarray is 2D or a list of lists is 2D""" | return ( ( isinstance ( matrix [ 0 ] , list ) and _rectangular ( matrix ) and not isinstance ( matrix [ 0 ] [ 0 ] , list ) ) or ( not isinstance ( matrix , list ) and matrix . shape == 2 ) ) |
def dataframe ( self ) :
"""Returns a pandas DataFrame containing all other class properties and
values . The index for the DataFrame is the string abbreviation of the
team , such as ' PURDUE ' .""" | fields_to_include = { 'abbreviation' : self . abbreviation , 'assist_percentage' : self . assist_percentage , 'assists' : self . assists , 'away_losses' : self . away_losses , 'away_wins' : self . away_wins , 'block_percentage' : self . block_percentage , 'blocks' : self . blocks , 'conference' : self . conference , 'c... |
def get_extents ( self ) :
"""measure the extents of the sprite ' s graphics .""" | if self . _sprite_dirty : # redrawing merely because we need fresh extents of the sprite
context = cairo . Context ( cairo . ImageSurface ( cairo . FORMAT_A1 , 0 , 0 ) )
context . transform ( self . get_matrix ( ) )
self . emit ( "on-render" )
self . __dict__ [ "_sprite_dirty" ] = False
self . graph... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.