signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def convexHull ( actor_or_list , alphaConstant = 0 ) :
"""Create a 3D Delaunay triangulation of input points .
: param actor _ or _ list : can be either an ` ` Actor ` ` or a list of 3D points .
: param float alphaConstant : For a non - zero alpha value , only verts , edges , faces ,
or tetra contained within... | if vu . isSequence ( actor_or_list ) :
actor = vs . Points ( actor_or_list )
else :
actor = actor_or_list
apoly = actor . clean ( ) . polydata ( )
triangleFilter = vtk . vtkTriangleFilter ( )
triangleFilter . SetInputData ( apoly )
triangleFilter . Update ( )
poly = triangleFilter . GetOutput ( )
delaunay = vtk... |
def convert_dict2tuple ( value ) :
"""convert dict type to tuple to solve unhashable problem .""" | if isinstance ( value , dict ) :
for _keys in value :
value [ _keys ] = convert_dict2tuple ( value [ _keys ] )
return tuple ( sorted ( value . items ( ) ) )
else :
return value |
def start_client ( host , port ) :
'''connects to a host / port''' | pydev_log . info ( "Connecting to %s:%s" , host , port )
s = socket ( AF_INET , SOCK_STREAM )
# Set TCP keepalive on an open socket .
# It activates after 1 second ( TCP _ KEEPIDLE , ) of idleness ,
# then sends a keepalive ping once every 3 seconds ( TCP _ KEEPINTVL ) ,
# and closes the connection after 5 failed ping ... |
def doigrf ( lon , lat , alt , date , ** kwargs ) :
"""Calculates the interpolated ( < 2015 ) or extrapolated ( > 2015 ) main field and
secular variation coefficients and passes them to the Malin and Barraclough
routine ( function pmag . magsyn ) to calculate the field from the coefficients .
Parameters :
l... | from . import coefficients as cf
gh , sv = [ ] , [ ]
colat = 90. - lat
# ! convert to colatitude for MB routine
if lon < 0 :
lon = lon + 360.
# ensure all positive east longitudes
itype = 1
models , igrf12coeffs = cf . get_igrf12 ( )
if 'mod' in list ( kwargs . keys ( ) ) :
if kwargs [ 'mod' ] == 'arch3k' :
... |
def derive_key ( mode , version , salt , key , private_key , dh , auth_secret , keyid , keylabel = "P-256" ) :
"""Derive the encryption key
: param mode : operational mode ( encrypt or decrypt )
: type mode : enumerate ( ' encrypt ' , ' decrypt )
: param salt : encryption salt value
: type salt : str
: pa... | context = b""
keyinfo = ""
nonceinfo = ""
def build_info ( base , info_context ) :
return b"Content-Encoding: " + base + b"\0" + info_context
def derive_dh ( mode , version , private_key , dh , keylabel ) :
def length_prefix ( key ) :
return struct . pack ( "!H" , len ( key ) ) + key
if isinstance (... |
def _ufo_logging_ref ( ufo ) :
"""Return a string that can identify this UFO in logs .""" | if ufo . path :
return os . path . basename ( ufo . path )
return ufo . info . styleName |
def timeseries_subplot ( X , time = None , color = None , var_names = ( ) , highlightsX = ( ) , xlabel = '' , ylabel = 'gene expression' , yticks = None , xlim = None , legend = True , palette = None , color_map = 'viridis' ) :
"""Plot X .
Parameters
X : np . ndarray
Call this with :
X with one column , col... | if color is not None :
use_color_map = isinstance ( color [ 0 ] , float ) or isinstance ( color [ 0 ] , np . float32 )
palette = default_palette ( palette )
x_range = np . arange ( X . shape [ 0 ] ) if time is None else time
if X . ndim == 1 :
X = X [ : , None ]
if X . shape [ 1 ] > 1 :
colors = palette [ :... |
def _ixs ( self , i , axis = 0 ) :
"""Return the i - th value or values in the SparseSeries by location
Parameters
i : int , slice , or sequence of integers
Returns
value : scalar ( int ) or Series ( slice , sequence )""" | label = self . index [ i ]
if isinstance ( label , Index ) :
return self . take ( i , axis = axis )
else :
return self . _get_val_at ( i ) |
def EnableNetworkInterfaces ( self , interfaces , logger , dhclient_script = None ) :
"""Enable the list of network interfaces .
Args :
interfaces : list of string , the output device names to enable .
logger : logger object , used to write to SysLog and serial port .
dhclient _ script : string , the path t... | # Should always exist in EL 7.
if os . path . exists ( self . network_path ) :
self . _DisableNetworkManager ( interfaces , logger )
helpers . CallDhclient ( interfaces , logger ) |
def rename_motifs ( motifs , stats = None ) :
"""Rename motifs to GimmeMotifs _ 1 . . GimmeMotifs _ N .
If stats object is passed , stats will be copied .""" | final_motifs = [ ]
for i , motif in enumerate ( motifs ) :
old = str ( motif )
motif . id = "GimmeMotifs_{}" . format ( i + 1 )
final_motifs . append ( motif )
if stats :
stats [ str ( motif ) ] = stats [ old ] . copy ( )
if stats :
return final_motifs , stats
else :
return final_motifs |
def get_local_image ( self , src ) :
"""returns the bytes of the image file on disk""" | local_image = ImageUtils . store_image ( None , self . link_hash , src , self . config )
return local_image |
def auto_delete_pr_branch ( pr : PullRequestDetails ) -> bool :
"""References :
https : / / developer . github . com / v3 / git / refs / # delete - a - reference""" | open_pulls = list_open_pull_requests ( pr . repo , base_branch = pr . branch_name )
if any ( open_pulls ) :
log ( 'Not deleting branch {!r}. It is used elsewhere.' . format ( pr . branch_name ) )
return False
remote = pr . remote_repo
if pr . is_on_fork ( ) :
log ( 'Not deleting branch {!r}. It belongs to a... |
def start ( self ) :
"""Starts this bot in a separate thread . Therefore , this call is non - blocking .
It will listen to all new inbox messages created .""" | super ( ) . start ( )
inbox_thread = BotThread ( name = '{}-inbox-stream-thread' . format ( self . _name ) , target = self . _listen_inbox_messages )
inbox_thread . start ( )
self . _threads . append ( inbox_thread )
self . log . info ( 'Starting inbox stream ...' ) |
def bovy_ars ( domain , isDomainFinite , abcissae , hx , hpx , nsamples = 1 , hxparams = ( ) , maxn = 100 ) :
"""bovy _ ars : Implementation of the Adaptive - Rejection Sampling
algorithm by Gilks & Wild ( 1992 ) : Adaptive Rejection Sampling
for Gibbs Sampling , Applied Statistics , 41 , 337
Based on Wild & ... | # First set - up the upper and lower hulls
hull = setup_hull ( domain , isDomainFinite , abcissae , hx , hpx , hxparams )
# Then start sampling : call sampleone repeatedly
out = [ ]
nupdates = 0
for ii in range ( int ( nsamples ) ) :
thissample , hull , nupdates = sampleone ( hull , hx , hpx , domain , isDomainFini... |
def set_features ( self , filter_type ) :
"""Calls splitter to split percolator output into target / decoy
elements .
Writes two new xml files with features . Currently only psms and
peptides . Proteins not here , since one cannot do protein inference
before having merged and remapped multifraction data any... | elements_to_split = { 'psm' : self . allpsms , 'peptide' : self . allpeps }
self . features = self . splitfunc ( elements_to_split , self . ns , filter_type ) |
def get_tasker2_slabs ( self , tol = 0.01 , same_species_only = True ) :
"""Get a list of slabs that have been Tasker 2 corrected .
Args :
tol ( float ) : Tolerance to determine if atoms are within same plane .
This is a fractional tolerance , not an absolute one .
same _ species _ only ( bool ) : If True ,... | sites = list ( self . sites )
slabs = [ ]
sortedcsites = sorted ( sites , key = lambda site : site . c )
# Determine what fraction the slab is of the total cell size in the
# c direction . Round to nearest rational number .
nlayers_total = int ( round ( self . lattice . c / self . oriented_unit_cell . lattice . c ) )
n... |
def forkandlog ( function , filter = 'INFO5' , debug = False ) :
"""Fork a child process and read its CASA log output .
function
A function to run in the child process
filter
The CASA log level filter to apply in the child process : less urgent
messages will not be shown . Valid values are strings : " DEB... | import sys , os
readfd , writefd = os . pipe ( )
pid = os . fork ( )
if pid == 0 : # Child process . We never leave this branch .
# Log messages of priority > WARN are sent to stderr regardless of the
# status of log . showconsole ( ) . The idea is for this subprocess to be
# something super lightweight and constrained... |
def yule_walker_regression ( dx , Y , deg , res = None ) :
""": parameter X : time vector ( disabled )
: parameter Y : stationary time series
: parameter deg : AR model degree
: return :
* a : Yule Walker parameters
* sig : Standard deviation of the noise term
* aicc : corrected Akaike Information Crite... | # Defaults
a = 0
sig = 0
# If DPRES ( frequency resolution ) is set ,
# then process spectrum on a regular WAVENUMBER array
if res is None :
res = 1.0
# Demean first
Y -= np . mean ( Y )
N = len ( Y )
# Get autocorr
gamma = np . zeros ( N )
lag = np . arange ( N )
for i , l in enumerate ( lag ) :
gamma [ i ] = ... |
def save ( self ) :
"""Saves the instance to the datastore .""" | if not self . is_valid ( ) :
return self . _errors
_new = self . is_new ( )
if _new :
self . _initialize_id ( )
with Mutex ( self ) :
self . _write ( _new )
return True |
def p_finally ( self , p ) :
"""finally : FINALLY block""" | p [ 0 ] = self . asttypes . Finally ( elements = p [ 2 ] )
p [ 0 ] . setpos ( p ) |
def limitsSql ( startIndex = 0 , maxResults = 0 ) :
"""Construct a SQL LIMIT clause""" | if startIndex and maxResults :
return " LIMIT {}, {}" . format ( startIndex , maxResults )
elif startIndex :
raise Exception ( "startIndex was provided, but maxResults was not" )
elif maxResults :
return " LIMIT {}" . format ( maxResults )
else :
return "" |
def energy ( self , hamiltonian = None ) :
r"""The total energy * per unit mass * :
Returns
E : : class : ` ~ astropy . units . Quantity `
The total energy .""" | if self . hamiltonian is None and hamiltonian is None :
raise ValueError ( "To compute the total energy, a hamiltonian" " object must be provided!" )
from . . potential import PotentialBase
if isinstance ( hamiltonian , PotentialBase ) :
from . . potential import Hamiltonian
warnings . warn ( "This function... |
def nalu ( x , depth , epsilon = 1e-30 , name = None , reuse = None ) :
"""NALU as in https : / / arxiv . org / abs / 1808.00508.""" | with tf . variable_scope ( name , default_name = "nalu" , values = [ x ] , reuse = reuse ) :
x_shape = shape_list ( x )
x_flat = tf . reshape ( x , [ - 1 , x_shape [ - 1 ] ] )
gw = tf . get_variable ( "w" , [ x_shape [ - 1 ] , depth ] )
g = tf . nn . sigmoid ( tf . matmul ( x_flat , gw ) )
g = tf . ... |
def splitname ( path ) :
"""Split a path into a directory , name , and extensions .""" | dirpath , filename = os . path . split ( path )
# we don ' t use os . path . splitext here because we want all extensions ,
# not just the last , to be put in exts
name , exts = filename . split ( os . extsep , 1 )
return dirpath , name , exts |
def _safe_readinto ( self , b ) :
"""Same as _ safe _ read , but for reading into a buffer .""" | total_bytes = 0
mvb = memoryview ( b )
while total_bytes < len ( b ) :
if MAXAMOUNT < len ( mvb ) :
temp_mvb = mvb [ 0 : MAXAMOUNT ]
n = self . fp . readinto ( temp_mvb )
else :
n = self . fp . readinto ( mvb )
if not n :
raise IncompleteRead ( bytes ( mvb [ 0 : total_bytes ]... |
def setup_default_logger ( logfile = None , level = logging . DEBUG , formatter = None , maxBytes = 0 , backupCount = 0 , disableStderrLogger = False ) :
"""Deprecated . Use ` logzero . loglevel ( . . ) ` , ` logzero . logfile ( . . ) ` , etc .
Globally reconfigures the default ` logzero . logger ` instance .
U... | global logger
logger = setup_logger ( name = LOGZERO_DEFAULT_LOGGER , logfile = logfile , level = level , formatter = formatter , disableStderrLogger = disableStderrLogger )
return logger |
def variants ( self , case_id , skip = 0 , count = 1000 , filters = None ) :
"""Return all variants in the VCF .
This function will apply the given filter and return the ' count ' first
variants . If skip the first ' skip ' variants will not be regarded .
Args :
case _ id ( str ) : Path to a vcf file ( for ... | filters = filters or { }
case_obj = self . case ( case_id = case_id )
limit = count + skip
genes = set ( )
if filters . get ( 'gene_ids' ) :
genes = set ( [ gene_id . strip ( ) for gene_id in filters [ 'gene_ids' ] ] )
frequency = None
if filters . get ( 'frequency' ) :
frequency = float ( filters [ 'frequency'... |
def _make_reserved_tokens_re ( reserved_tokens ) :
"""Constructs compiled regex to parse out reserved tokens .""" | if not reserved_tokens :
return None
escaped_tokens = [ _re_escape ( rt ) for rt in reserved_tokens ]
pattern = "(%s)" % "|" . join ( escaped_tokens )
reserved_tokens_re = _re_compile ( pattern )
return reserved_tokens_re |
def get_provider_links ( self ) :
"""Gets the ` ` Resources ` ` representing the source of this asset in order from the most recent provider to the originating source .
return : ( osid . resource . ResourceList ) - the provider chain
raise : OperationFailed - unable to complete request
* compliance : mandator... | # Implemented from template for osid . learning . Activity . get _ assets _ template
if not bool ( self . _my_map [ 'providerLinkIds' ] ) :
raise errors . IllegalState ( 'no providerLinkIds' )
mgr = self . _get_provider_manager ( 'RESOURCE' )
if not mgr . supports_resource_lookup ( ) :
raise errors . OperationF... |
def preprocessRequest ( self , service_request , * args , ** kwargs ) :
"""Preprocesses a request .""" | processor = self . getPreprocessor ( service_request )
if processor is None :
return
args = ( service_request , ) + args
if hasattr ( processor , '_pyamf_expose_request' ) :
http_request = kwargs . get ( 'http_request' , None )
args = ( http_request , ) + args
return processor ( * args ) |
def widgets_from_abbreviations ( self , seq ) :
"""Given a sequence of ( name , abbrev , default ) tuples , return a sequence of Widgets .""" | result = [ ]
for name , abbrev , default in seq :
widget = self . widget_from_abbrev ( abbrev , default )
if not ( isinstance ( widget , ValueWidget ) or isinstance ( widget , fixed ) ) :
if widget is None :
raise ValueError ( "{!r} cannot be transformed to a widget" . format ( abbrev ) )
... |
def save_form ( self , commit = True ) :
"""This calls Django ' s ` ` ModelForm . save ( ) ` ` . It only takes care of
saving this actual form , and leaves the nested forms and formsets
alone .
We separate this out of the
: meth : ` ~ django _ superform . forms . SuperModelForm . save ` method to make
ext... | return super ( SuperModelFormMixin , self ) . save ( commit = commit ) |
def _html_escape ( string ) :
"""HTML escape all of these " & < >""" | html_codes = { '"' : '"' , '<' : '<' , '>' : '>' , }
# & must be handled first
string = string . replace ( '&' , '&' )
for char in html_codes :
string = string . replace ( char , html_codes [ char ] )
return string |
def get_firmware_version ( self ) :
"""Call PN532 GetFirmwareVersion function and return a tuple with the IC ,
Ver , Rev , and Support values .""" | response = self . call_function ( PN532_COMMAND_GETFIRMWAREVERSION , 4 )
if response is None :
raise RuntimeError ( 'Failed to detect the PN532! Make sure there is sufficient power (use a 1 amp or greater power supply), the PN532 is wired correctly to the device, and the solder joints on the PN532 headers are soli... |
def errors_as_dict ( self ) :
"""Return parse errors as a dict""" | errors = [ ]
for e in self . errors :
errors . append ( { 'file' : e . term . file_name , 'row' : e . term . row if e . term else '<unknown>' , 'col' : e . term . col if e . term else '<unknown>' , 'term' : e . term . join if e . term else '<unknown>' , 'error' : str ( e ) } )
return errors |
def utc_jpl ( self ) :
"""Convert to an ` ` A . D . 2014 - Jan - 18 01:35:37.5000 UT ` ` string .
Returns a string for this date and time in UTC , in the format
used by the JPL HORIZONS system . If this time is an array of
dates , then a sequence of strings is returned instead of a
single string .""" | offset = _half_second / 1e4
year , month , day , hour , minute , second = self . _utc_tuple ( offset )
second , fraction = divmod ( second , 1.0 )
fraction *= 1e4
bc = year < 1
year = abs ( year - bc )
era = where ( bc , 'B.C.' , 'A.D.' )
format = '%s %04d-%s-%02d %02d:%02d:%02d.%04d UT'
args = ( era , year , _months [... |
def add_files ( self , common_name , x509s , files = None , parent_ca = '' , is_ca = False , signees = None , serial = 0 , overwrite = False ) :
"""Add a set files comprising a certificate to Certipy
Used with all the defaults , Certipy will manage creation of file paths
to be used to store these files to disk ... | if common_name in self . store and not overwrite :
raise CertExistsError ( "Certificate {name} already exists!" " Set overwrite=True to force add." . format ( name = common_name ) )
elif common_name in self . store and overwrite :
record = self . get_record ( common_name )
serial = int ( record [ 'serial' ]... |
def _update_settings ( self , X ) :
"""Update the model argument .
: param X : The input data of the model .
: type X : list of ( candidate , features ) pairs""" | self . logger . info ( "Loading default parameters for Sparse LSTM" )
config = get_config ( ) [ "learning" ] [ "SparseLSTM" ]
for key in config . keys ( ) :
if key not in self . settings :
self . settings [ key ] = config [ key ]
self . settings [ "relation_arity" ] = len ( X [ 0 ] [ 0 ] )
self . settings [... |
def subdivide ( self , face_index = None ) :
"""Subdivide a mesh , with each subdivided face replaced with four
smaller faces .
Parameters
face _ index : ( m , ) int or None
If None all faces of mesh will be subdivided
If ( m , ) int array of indices : only specified faces will be
subdivided . Note that... | vertices , faces = remesh . subdivide ( vertices = self . vertices , faces = self . faces , face_index = face_index )
return Trimesh ( vertices = vertices , faces = faces ) |
def oidToValue ( self , syntax , identifier , impliedFlag = False , parentIndices = None ) :
"""Turn SMI table instance identifier into a value object .
SNMP SMI table objects are identified by OIDs composed of columnar
object ID and instance index . The index part can be composed
from the values of one or mo... | if not identifier :
raise error . SmiError ( 'Short OID for index %r' % ( syntax , ) )
if hasattr ( syntax , 'cloneFromName' ) :
return syntax . cloneFromName ( identifier , impliedFlag , parentRow = self , parentIndices = parentIndices )
baseTag = syntax . getTagSet ( ) . getBaseTag ( )
if baseTag == Integer .... |
def shuffle ( self ) :
"""If shuffle is enabled or not .""" | info = self . _get_command_info ( CommandInfo_pb2 . ChangeShuffleMode )
return None if info is None else info . shuffleMode |
def get_instance_aws_context ( ec2_client ) :
"""Returns : a dictionary of aws context
dictionary will contain these entries :
region , instance _ id , account , role , env , env _ short , service
Raises : IOError if couldn ' t read metadata or lookup attempt failed""" | result = { }
try :
result [ "region" ] = http_get_metadata ( "placement/availability-zone/" )
result [ "region" ] = result [ "region" ] [ : - 1 ]
result [ "instance_id" ] = http_get_metadata ( 'instance-id' )
except IOError as error :
raise IOError ( "Error looking up metadata:availability-zone or insta... |
def features_for_rank ( self , proc , results ) :
"""Compute features for ranking results from ES / geonames
Parameters
proc : dict
One dictionary from the list that comes back from geoparse or from make _ country _ features ( doesn ' t matter )
results : dict
the response from a geonames query
Returns ... | feature_list = [ ]
meta = [ ]
results = results [ 'hits' ] [ 'hits' ]
search_name = proc [ 'word' ]
code_mention = proc [ 'features' ] [ 'code_mention' ]
class_mention = proc [ 'features' ] [ 'class_mention' ]
for rank , entry in enumerate ( results ) : # go through the results and calculate some features
# get populat... |
def create_keyvault ( access_token , subscription_id , rgname , vault_name , location , template_deployment = True , tenant_id = None , object_id = None ) :
'''Create a new key vault in the named resource group .
Args :
access _ token ( str ) : A valid Azure authentication token .
subscription _ id ( str ) : ... | endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourcegroups/' , rgname , '/providers/Microsoft.KeyVault/vaults/' , vault_name , '?api-version=' , KEYVAULT_API ] )
# get tenant ID if not specified
if tenant_id is None :
ret = list_tenants ( access_token )
tenant_id = ret... |
def on_doctree_read ( _ , doctree ) :
"""When the doctree has been read in , and ` ` include ` ` directives have been
executed and replaced with the included file , walk the tree via
LinkToRefVisitor .""" | docname = os . path . splitext ( os . path . basename ( doctree . attributes [ 'source' ] ) ) [ 0 ]
if docname == 'changes' :
ref_mapping = { 'http://awslimitchecker.readthedocs.io/en/latest/limits.html#ec2' : [ label_ref_node , docname , 'limits.ec2' , 'the EC2 limit documentation' ] , 'https://awslimitchecker.rea... |
def trace_read ( self , offset , num_items ) :
"""Reads data from the trace buffer and returns it .
Args :
self ( JLink ) : the ` ` JLink ` ` instance .
offset ( int ) : the offset from which to start reading from the trace
buffer .
num _ items ( int ) : number of items to read from the trace buffer .
R... | buf_size = ctypes . c_uint32 ( num_items )
buf = ( structs . JLinkTraceData * num_items ) ( )
res = self . _dll . JLINKARM_TRACE_Read ( buf , int ( offset ) , ctypes . byref ( buf_size ) )
if ( res == 1 ) :
raise errors . JLinkException ( 'Failed to read from trace buffer.' )
return list ( buf ) [ : int ( buf_size ... |
def _convert_np_data ( data , data_type , num_elems ) : # @ NoSelf
'''Converts a single np data into byte stream .''' | if ( data_type == 51 or data_type == 52 ) :
if ( data == '' ) :
return ( '\x00' * num_elems ) . encode ( )
else :
return data . ljust ( num_elems , '\x00' ) . encode ( 'utf-8' )
elif ( data_type == 32 ) :
data_stream = data . real . tobytes ( )
data_stream += data . imag . tobytes ( )
... |
def rate_limiting ( self ) :
"""First value is requests remaining , second value is request limit .
: type : ( int , int )""" | remaining , limit = self . __requester . rate_limiting
if limit < 0 :
self . get_rate_limit ( )
return self . __requester . rate_limiting |
def bear ( a1 , b1 , a2 , b2 ) :
"""Find bearing / position angle between two points on a unit sphere .
Parameters
a1 , b1 : float
Longitude - like and latitude - like angles defining the first
point . Both are in radians .
a2 , b2 : float
Longitude - like and latitude - like angles defining the second ... | # Find perpendicular to the plane containing the base and
# z - axis . Then find the perpendicular to the plane containing
# the base and the target . The angle between these two is the
# position angle or bearing of the target w . r . t the base . Check
# sign of the z component of the latter vector to determine
# qua... |
def _download_gist ( self ) :
"""Download content from github ' s pastebin .""" | parts = parse . urlparse ( self . url )
url = "https://gist.github.com" + parts . path + "/raw"
return self . _download_raw ( url ) |
def roots ( cls , degree , domain , kind ) :
"""Return optimal collocation nodes for some orthogonal polynomial .""" | basis_coefs = cls . _basis_monomial_coefs ( degree )
basis_poly = cls . functions_factory ( basis_coefs , domain , kind )
return basis_poly . roots ( ) |
def check_syntax ( self , cmd , line ) :
"""Syntax check a line of RiveScript code .
Args :
str cmd : The command symbol for the line of code , such as one
of ` ` + ` ` , ` ` - ` ` , ` ` * ` ` , ` ` > ` ` , etc .
str line : The remainder of the line of code , such as the text of
a trigger or reply .
Ret... | # Run syntax checks based on the type of command .
if cmd == '!' : # ! Definition
# - Must be formatted like this :
# ! type name = value
# OR
# ! type = value
match = re . match ( RE . def_syntax , line )
if not match :
return "Invalid format for !Definition line: must be '! type name = value' OR '! ty... |
def insert_empty_rows ( self , y : int , amount : int = 1 ) -> None :
"""Insert a number of rows after the given row .""" | def transform_rows ( column : Union [ int , float ] , row : Union [ int , float ] ) -> Tuple [ Union [ int , float ] , Union [ int , float ] ] :
return column , row + ( amount if row >= y else 0 )
self . _transform_coordinates ( transform_rows ) |
def ConsultarPuerto ( self , sep = "||" ) :
"Consulta de Puertos habilitados" | ret = self . client . puertoConsultar ( auth = { 'token' : self . Token , 'sign' : self . Sign , 'cuit' : self . Cuit , } , ) [ 'puertoReturn' ]
self . __analizar_errores ( ret )
array = ret . get ( 'puertos' , [ ] )
return [ ( "%s %%s %s %%s %s" % ( sep , sep , sep ) ) % ( it [ 'codigoDescripcion' ] [ 'codigo' ] , it ... |
def create_post ( post_uid , post_data ) :
'''create the post .''' | title = post_data [ 'title' ] . strip ( )
if len ( title ) < 2 :
return False
cur_rec = MPost . get_by_uid ( post_uid )
if cur_rec :
return False
entry = TabPost . create ( title = title , date = datetime . now ( ) , cnt_md = tornado . escape . xhtml_escape ( post_data [ 'cnt_md' ] . strip ( ) ) , cnt_html = to... |
def add_library_search_paths ( self , paths , recursive = True , escape = False , target_name = None , configuration_name = None ) :
"""Adds paths to the LIBRARY _ SEARCH _ PATHS configuration .
: param paths : A string or array of strings
: param recursive : Add the paths as recursive ones
: param escape : E... | self . add_search_paths ( XCBuildConfigurationFlags . LIBRARY_SEARCH_PATHS , paths , recursive , escape , target_name , configuration_name ) |
def get_backward_star ( self , node ) :
"""Given a node , get a copy of that node ' s backward star .
: param node : node to retrieve the backward - star of .
: returns : set - - set of hyperedge _ ids for the hyperedges
in the node ' s backward star .
: raises : ValueError - - No such node exists .""" | if node not in self . _node_attributes :
raise ValueError ( "No such node exists." )
return self . _backward_star [ node ] . copy ( ) |
def is_cloudflare_challenge ( response ) :
"""Test if the given response contains the cloudflare ' s anti - bot protection""" | return ( response . status == 503 and response . headers . get ( 'Server' , '' ) . startswith ( b'cloudflare' ) and 'jschl_vc' in response . text and 'jschl_answer' in response . text ) |
def findCampaigns ( ra , dec ) :
"""Returns a list of the campaigns that cover a given position .
Parameters
ra , dec : float , float
Position in decimal degrees ( J2000 ) .
Returns
campaigns : list of int
A list of the campaigns that cover the given position .""" | # Temporary disable the logger to avoid the preliminary field warnings
logger . disabled = True
campaigns_visible = [ ]
for c in fields . getFieldNumbers ( ) :
fovobj = fields . getKeplerFov ( c )
if onSiliconCheck ( ra , dec , fovobj ) :
campaigns_visible . append ( c )
# Re - enable the logger
logger ... |
def kwargs ( self ) :
"""Returns a dict of the kwargs for this Struct which were not interpreted by the baseclass .
This excludes fields like ` extends ` , ` merges ` , and ` abstract ` , which are consumed by
SerializableFactory . create and Validatable . validate .""" | return { k : v for k , v in self . _kwargs . items ( ) if k not in self . _INTERNAL_FIELDS } |
def publish_apis ( self , path = 'doc' ) :
"""Publish all loaded apis on under the uri / < path > / < api - name > , by
redirecting to http : / / petstore . swagger . io /""" | assert path
if not self . apis :
raise Exception ( "You must call .load_apis() before .publish_apis()" )
# Infer the live host url from pym - config . yaml
proto = 'http'
if hasattr ( get_config ( ) , 'aws_cert_arn' ) :
proto = 'https'
live_host = "%s://%s" % ( proto , get_config ( ) . live_host )
# Allow cross... |
def range_end ( self ) :
'''" Showing 40 - 50 of 234 results''' | count = self . count
range_end = self . range_start + self . limit - 1
if count < range_end :
range_end = count
return range_end |
def commit_log ( self , log_json ) :
"""Commits a run log to the Mongo backend .
Due to limitations of maximum document size in Mongo ,
stdout and stderr logs are truncated to a maximum size for
each task .""" | log_json [ '_id' ] = log_json [ 'log_id' ]
append = { 'save_date' : datetime . utcnow ( ) }
for task_name , values in log_json . get ( 'tasks' , { } ) . items ( ) :
for key , size in TRUNCATE_LOG_SIZES_CHAR . iteritems ( ) :
if isinstance ( values . get ( key , None ) , str ) :
if len ( values [... |
def sphericalAngSepFast ( ra0 , dec0 , ra1 , dec1 , radians = False ) :
"""A faster ( but less accurate ) implementation of sphericalAngleSep
Taken from http : / / www . movable - type . co . uk / scripts / latlong . html
For additional speed , set wantSquare = True , and the return value
is the square of the... | if radians == False :
ra0 = np . radians ( ra0 )
dec0 = np . radians ( dec0 )
ra1 = np . radians ( ra1 )
dec1 = np . radians ( dec1 )
deltaRa = ra1 - ra0
deltaDec = dec1 - dec0
avgDec = .5 * ( dec0 + dec1 )
x = deltaRa * np . cos ( avgDec )
val = np . hypot ( x , deltaDec )
if radians == False :
val... |
def orbital_spin_nuclear_matrices ( L , S , II , ind = "z" ) :
ur"""Return the matrix representation of the orbita , electron - spin , and \
nuclear - spin angular momentum operators \
: math : ` \ hat { \ vec { L } } , \ hat { \ vec { L } } , \ hat { \ vec { L } } ` in the coupled basis \
: math : ` [ | J , ... | if ind == "all" :
LSIx = orbital_spin_nuclear_matrices ( L , S , II , "x" )
LSIy = orbital_spin_nuclear_matrices ( L , S , II , "y" )
LSIz = orbital_spin_nuclear_matrices ( L , S , II , "z" )
return [ [ LSIx [ i ] , LSIy [ i ] , LSIz [ i ] ] for i in range ( 3 ) ]
L0 = eye ( 2 * L + 1 )
S0 = eye ( 2 * S... |
def ifft2 ( a , s = None , axes = ( - 2 , - 1 ) , norm = None ) :
"""Compute the 2 - dimensional inverse discrete Fourier Transform .
This function computes the inverse of the 2 - dimensional discrete Fourier
Transform over any number of axes in an M - dimensional array by means of
the Fast Fourier Transform ... | return ifftn ( a , s = s , axes = axes , norm = norm ) |
def _reduce_method ( cls , func ) :
"""Return a wrapped function for injecting numpy and bottoleneck methods .
see ops . inject _ datasetrolling _ methods""" | def wrapped_func ( self , ** kwargs ) :
from . dataset import Dataset
reduced = OrderedDict ( )
for key , da in self . obj . data_vars . items ( ) :
if self . dim in da . dims :
reduced [ key ] = getattr ( self . rollings [ key ] , func . __name__ ) ( ** kwargs )
else :
... |
def flushInput ( self ) :
'''flush any pending input''' | self . buf = ''
saved_timeout = self . timeout
self . timeout = 0.5
self . _recv ( )
self . timeout = saved_timeout
self . buf = ''
self . debug ( "flushInput" ) |
def _initialize_inversion_matrix ( self ) :
"""the inversion""" | # The bt model is diagonal . The inversion is simply qh = - kappa * * 2 ph
self . a = - ( self . wv2i + self . kd2 ) [ np . newaxis , np . newaxis , : , : ] |
def apply ( self , strip = 0 , root = None ) :
"""Apply parsed patch , optionally stripping leading components
from file paths . ` root ` parameter specifies working dir .
return True on success""" | if root :
prevdir = os . getcwd ( )
os . chdir ( root )
total = len ( self . items )
errors = 0
if strip : # [ ] test strip level exceeds nesting level
# [ ] test the same only for selected files
# [ ] test if files end up being on the same level
try :
strip = int ( strip )
except ValueError :
... |
def create_command ( self , name , operation , ** kwargs ) :
"""Constructs the command object that can then be added to the command table""" | if not isinstance ( operation , six . string_types ) :
raise ValueError ( "Operation must be a string. Got '{}'" . format ( operation ) )
name = ' ' . join ( name . split ( ) )
client_factory = kwargs . get ( 'client_factory' , None )
def _command_handler ( command_args ) :
op = CLICommandsLoader . _get_op_hand... |
def parse ( stream , with_text = False ) : # type : ( Iterator [ str ] , bool ) - > Iterator [ Union [ Tuple [ str , LexicalUnit ] , LexicalUnit ] ]
"""Generates lexical units from a character stream .
Args :
stream ( Iterator [ str ] ) : A character stream containing lexical units , superblanks and other text ... | buffer = ''
text_buffer = ''
in_lexical_unit = False
in_superblank = False
for char in stream :
if in_superblank :
if char == ']' :
in_superblank = False
text_buffer += char
elif char == '\\' :
text_buffer += char
text_buffer += next ( stream )
... |
def register_classes_for_admin ( db_session , show_pks = True , name = 'admin' ) :
"""Registers classes for the Admin view that ultimately creates the admin
interface .
: param db _ session : handle to database session
: param list classes : list of classes to register with the admin
: param bool show _ pks... | with app . app_context ( ) :
admin_view = Admin ( current_app , name = name )
for cls in set ( cls for cls in current_app . class_references . values ( ) if cls . use_admin ) :
column_list = [ column . name for column in cls . __table__ . columns . values ( ) ]
if hasattr ( cls , '__view__' ) : ... |
def load ( language_dir , filename , encoding ) :
'''Open and return the supplied json file''' | global _DICTIONARY
try :
json_file = filename + '.json'
with io . open ( os . path . join ( language_dir , json_file ) , 'r' , encoding = encoding ) as f :
_DICTIONARY = json . load ( f )
except IOError :
raise IOError ( '{0} Language file not found at location {1}. ' 'Make sure that your translatio... |
def path ( self , which = None ) :
"""Extend ` ` nailgun . entity _ mixins . Entity . path ` ` .
The format of the returned path depends on the value of ` ` which ` ` :
content _ lifecycle _ environments
/ capsules / < id > / content / lifecycle _ environments
content _ sync
/ capsules / < id > / content ... | if which and which . startswith ( 'content_' ) :
return '{0}/content/{1}' . format ( super ( Capsule , self ) . path ( which = 'self' ) , which . split ( 'content_' ) [ 1 ] )
return super ( Capsule , self ) . path ( which ) |
def set_classifier_mask ( self , v , base_mask = True ) :
"""Computes the mask used to create the training and validation set""" | base = self . _base
v = tonparray ( v )
a = np . unique ( v )
if a [ 0 ] != - 1 or a [ 1 ] != 1 :
raise RuntimeError ( "The labels must be -1 and 1 (%s)" % a )
mask = np . zeros_like ( v )
cnt = min ( [ ( v == x ) . sum ( ) for x in a ] ) * base . _tr_fraction
cnt = int ( round ( cnt ) )
for i in a :
index = np... |
def loxodrome_inverse ( lat1 : float , lon1 : float , lat2 : float , lon2 : float , ell : Ellipsoid = None , deg : bool = True ) :
"""computes the arc length and azimuth of the loxodrome
between two points on the surface of the reference ellipsoid
Parameters
lat1 : float or numpy . ndarray of float
geodetic... | # set ellipsoid parameters
if ell is None :
ell = Ellipsoid ( )
if deg is True :
lat1 , lon1 , lat2 , lon2 = np . radians ( [ lat1 , lon1 , lat2 , lon2 ] )
# compute isometric latitude of P1 and P2
isolat1 = isometric ( lat1 , deg = False , ell = ell )
isolat2 = isometric ( lat2 , deg = False , ell = ell )
# co... |
def get_node ( guild_id : int , ignore_ready_status : bool = False ) -> Node :
"""Gets a node based on a guild ID , useful for noding separation . If the
guild ID does not already have a node association , the least used
node is returned . Skips over nodes that are not yet ready .
Parameters
guild _ id : in... | guild_count = 1e10
least_used = None
for node in _nodes :
guild_ids = node . player_manager . guild_ids
if ignore_ready_status is False and not node . ready . is_set ( ) :
continue
elif len ( guild_ids ) < guild_count :
guild_count = len ( guild_ids )
least_used = node
if guild_i... |
def token_at_cursor ( code , pos = 0 ) :
"""Find the token present at the passed position in the code buffer
: return ( tuple ) : a pair ( token , start _ position )""" | l = len ( code )
end = start = pos
# Go forwards while we get alphanumeric chars
while end < l and code [ end ] . isalpha ( ) :
end += 1
# Go backwards while we get alphanumeric chars
while start > 0 and code [ start - 1 ] . isalpha ( ) :
start -= 1
# If previous character is a % , add it ( potential magic )
if... |
def to_latex ( self , buf = None , upper_triangle = True , ** kwargs ) :
"""Render a DataFrame to a tabular environment table .
You can splice this into a LaTeX document .
Requires ` ` \\ usepackage { booktabs } ` ` .
Wrapper around the : meth : ` pandas . DataFrame . to _ latex ` method .""" | out = self . _sympy_formatter ( )
out = out . _abs_ref_formatter ( format_as = 'latex' )
if not upper_triangle :
out = out . _remove_upper_triangle ( )
return out . _frame . to_latex ( buf = buf , ** kwargs ) |
def xml_report_path ( cls , resolution_cache_dir , resolve_hash_name , conf ) :
"""The path to the xml report ivy creates after a retrieve .
: API : public
: param string cache _ dir : The path of the ivy cache dir used for resolves .
: param string resolve _ hash _ name : Hash from the Cache key from the Ver... | return os . path . join ( resolution_cache_dir , '{}-{}-{}.xml' . format ( IvyUtils . INTERNAL_ORG_NAME , resolve_hash_name , conf ) ) |
def _capture_stderr ( callable : Callable [ ... , CaptureResult ] , * args , ** kwargs ) -> CaptureResult :
"""Captures content written to standard error .
: param callable : the callable to wrap
: param args : positional arguments passed to the callable
: param kwargs : keyword arguments passed to the callab... | stream = StringIO ( )
with redirect_stderr ( stream ) :
return_value = callable ( * args , ** kwargs )
assert return_value . stderr is None , "stderr appears to have already been captured"
return CaptureResult ( return_value = return_value . return_value , stdout = return_value . stdout , stderr = stream . getvalue... |
def psd ( data , dt , ndivide = 1 , window = hanning , overlap_half = False ) :
"""Calculate power spectrum density of data .
Args :
data ( np . ndarray ) : Input data .
dt ( float ) : Time between each data .
ndivide ( int ) : Do averaging ( split data into ndivide , get psd of each , and average them ) . ... | logger = getLogger ( 'decode.utils.ndarray.psd' )
if overlap_half :
step = int ( len ( data ) / ( ndivide + 1 ) )
size = step * 2
else :
step = int ( len ( data ) / ndivide )
size = step
if bin ( len ( data ) ) . count ( '1' ) != 1 :
logger . warning ( 'warning: length of data is not power of 2: {}'... |
def pmap_by_grp ( self ) :
""": returns : dictionary " grp - XXX " - > ProbabilityMap instance""" | if hasattr ( self , '_pmap_by_grp' ) : # already called
return self . _pmap_by_grp
# populate _ pmap _ by _ grp
self . _pmap_by_grp = { }
if 'poes' in self . dstore : # build probability maps restricted to the given sids
ok_sids = set ( self . sids )
for grp , dset in self . dstore [ 'poes' ] . items ( ) :
... |
def debug_sphere_out ( self , p : Union [ Unit , Point2 , Point3 ] , r : Union [ int , float ] , color = None ) :
"""Draws a sphere at point p with radius r . Don ' t forget to add ' await self . _ client . send _ debug ' .""" | self . _debug_spheres . append ( debug_pb . DebugSphere ( p = self . to_debug_point ( p ) , r = r , color = self . to_debug_color ( color ) ) ) |
def on_error ( self , ws , error ) :
"""Todo""" | if type ( error ) . __name__ == "KeyboardInterrupt" :
sys . exit ( )
self . logger . debug ( "error" ) |
def find_open_and_close_braces ( line_index , start , brace , lines ) :
"""Take the line where we want to start and the index where we want to start
and find the first instance of matched open and close braces of the same
type as brace in file file .
: param : line ( int ) : the index of the line we want to s... | if brace in [ '[' , ']' ] :
open_brace = '['
close_brace = ']'
elif brace in [ '{' , '}' ] :
open_brace = '{'
close_brace = '}'
elif brace in [ '(' , ')' ] :
open_brace = '('
close_brace = ')'
else : # unacceptable brace type !
return ( - 1 , - 1 , - 1 , - 1 )
open_braces = [ ]
line = lines ... |
def patch_wave_header ( body ) :
"""Patch header to the given wave body .
: param body : the wave content body , it should be bytearray .""" | length = len ( body )
padded = length + length % 2
total = WAVE_HEADER_LENGTH + padded
header = copy . copy ( WAVE_HEADER )
# fill the total length position
header [ 4 : 8 ] = bytearray ( struct . pack ( '<I' , total ) )
header += bytearray ( struct . pack ( '<I' , length ) )
data = header + body
# the total length is ... |
def zeeman_energies ( fine_state , Bz ) :
r"""Return Zeeman effect energies for a given fine state and \
magnetic field .
> > > ground _ state = State ( " Rb " , 87 , 5 , 0 , 1 / Integer ( 2 ) )
> > > Bz = 200.0
> > > Bz = Bz / 10000
> > > for f _ group in zeeman _ energies ( ground _ state , Bz ) :
. .... | element = fine_state . element
isotope = fine_state . isotope
N = fine_state . n
L = fine_state . l
J = fine_state . j
energiesZeeman = [ ]
for i , F in enumerate ( fine_state . fperm ) :
gL , gS , gI , gJ , gF = lande_g_factors ( element , isotope , L , J , F )
energiesF = [ ]
hyperfine_level = State ( ele... |
def _textlist ( self , _addtail = False ) :
'''Returns a list of text strings contained within an element and its sub - elements .
Helpful for extracting text from prose - oriented XML ( such as XHTML or DocBook ) .''' | result = [ ]
if ( not _addtail ) and ( self . text is not None ) :
result . append ( self . text )
for elem in self :
result . extend ( elem . textlist ( True ) )
if _addtail and self . tail is not None :
result . append ( self . tail )
return result |
def _extract_model_params ( self , defaults , ** kwargs ) :
"""this method allows django managers use ` objects . get _ or _ create ` and
` objects . update _ or _ create ` on a hashable object .""" | obj = kwargs . pop ( self . object_property_name , None )
if obj is not None :
kwargs [ 'object_hash' ] = self . model . _compute_hash ( obj )
lookup , params = super ( ) . _extract_model_params ( defaults , ** kwargs )
if obj is not None :
params [ self . object_property_name ] = obj
del params [ 'object_h... |
def _log_band_gap_information ( bs ) :
"""Log data about the direct and indirect band gaps .
Args :
bs ( : obj : ` ~ pymatgen . electronic _ structure . bandstructure . BandStructureSymmLine ` ) :""" | bg_data = bs . get_band_gap ( )
if not bg_data [ 'direct' ] :
logging . info ( 'Indirect band gap: {:.3f} eV' . format ( bg_data [ 'energy' ] ) )
direct_data = bs . get_direct_band_gap_dict ( )
if bs . is_spin_polarized :
direct_bg = min ( ( spin_data [ 'value' ] for spin_data in direct_data . values ( ) ) )
... |
def coordinate_grad_semi_dual ( b , M , reg , beta , i ) :
'''Compute the coordinate gradient update for regularized discrete distributions for ( i , : )
The function computes the gradient of the semi dual problem :
. . math : :
\max_v \sum_i (\sum_j v_j * b_j - reg * log(\sum_j exp((v_j - M_{i,j})/reg) * b_j... | r = M [ i , : ] - beta
exp_beta = np . exp ( - r / reg ) * b
khi = exp_beta / ( np . sum ( exp_beta ) )
return b - khi |
def json2elem ( json_data , factory = ET . Element ) :
"""Convert a JSON string into an Element .
Whatever Element implementation we could import will be used by
default ; if you want to use something else , pass the Element class
as the factory parameter .""" | return internal_to_elem ( json . loads ( json_data ) , factory ) |
def remove_cookie ( self , cookie_name ) :
"""Remove cookie by its name
: param cookie _ name : cookie name
: return :""" | if self . __ro_flag :
raise RuntimeError ( 'Read-only cookie-jar changing attempt' )
if cookie_name in self . __cookies . keys ( ) :
self . __cookies . pop ( cookie_name ) |
def _find_flats_edges ( self , data , mag , direction ) :
"""Extend flats 1 square downstream
Flats on the downstream side of the flat might find a valid angle ,
but that doesn ' t mean that it ' s a correct angle . We have to find
these and then set them equal to a flat""" | i12 = np . arange ( data . size ) . reshape ( data . shape )
flat = mag == FLAT_ID_INT
flats , n = spndi . label ( flat , structure = FLATS_KERNEL3 )
objs = spndi . find_objects ( flats )
f = flat . ravel ( )
d = data . ravel ( )
for i , _obj in enumerate ( objs ) :
region = flats [ _obj ] == i + 1
I = i12 [ _o... |
def register ( self , resource = None , ** meta ) :
"""Add resource to the API .
: param resource : Resource class for registration
: param * * meta : Redefine Meta options for the resource
: return adrest . views . Resource : Generated resource .""" | if resource is None :
def wrapper ( resource ) :
return self . register ( resource , ** meta )
return wrapper
# Must be instance of ResourceView
if not issubclass ( resource , ResourceView ) :
raise AssertionError ( "%s not subclass of ResourceView" % resource )
# Cannot be abstract
if resource . _m... |
def unhash ( text , hashes ) :
"""Unhashes all hashed entites in the hashes dictionary .
The pattern for hashes is defined by re _ hash . After everything is
unhashed , < pre > blocks are " pulled out " of whatever indentation
level in which they used to be ( e . g . in a list ) .""" | def retrieve_match ( match ) :
return hashes [ match . group ( 0 ) ]
while re_hash . search ( text ) :
text = re_hash . sub ( retrieve_match , text )
text = re_pre_tag . sub ( lambda m : re . sub ( '^' + m . group ( 1 ) , '' , m . group ( 0 ) , flags = re . M ) , text )
return text |
def start ( workflow_name , data = None , object_id = None , ** kwargs ) :
"""Start a workflow by given name for specified data .
The name of the workflow to start is considered unique and it is
equal to the name of a file containing the workflow definition .
The data passed could be a list of Python standard... | from . proxies import workflow_object_class
from . worker_engine import run_worker
if data is None and object_id is None :
raise WorkflowsMissingData ( "No data or object_id passed to task.ß" )
if object_id is not None :
obj = workflow_object_class . get ( object_id )
if not obj :
raise WorkflowsMis... |
def fill_slots_headers ( self , items ) :
"""Generates the header cell for each slot . For each slot , the first
cell displays information about the parent all analyses within that
given slot have in common , such as the AR Id , SampleType , etc .
: param items : dictionary with items to be rendered in the li... | prev_position = 0
for item in items :
item_position = item [ "Pos" ]
if item_position == prev_position :
item = self . skip_item_key ( item , "Pos" )
# head slot already filled
continue
if item . get ( "disabled" , False ) : # empty slot
continue
# This is the first analy... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.