signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _audit_request ( options , func , request_context , * args , ** kwargs ) : # noqa : C901
"""Run a request function under audit .""" | logger = getLogger ( "audit" )
request_info = RequestInfo ( options , func , request_context )
response = None
request_info . capture_request ( )
try : # process the request
with elapsed_time ( request_info . timing ) :
response = func ( * args , ** kwargs )
except Exception as error :
request_info . ca... |
def setNumberRange ( key , keyType , start , end ) :
'''check number range''' | return And ( And ( keyType , error = SCHEMA_TYPE_ERROR % ( key , keyType . __name__ ) ) , And ( lambda n : start <= n <= end , error = SCHEMA_RANGE_ERROR % ( key , '(%s,%s)' % ( start , end ) ) ) , ) |
def set_files ( self , files_downloaded , files_failed ) :
"""set _ files : records progress from downloading files
Args :
files _ downloaded ( [ str ] ) : list of files that have been downloaded
files _ failed ( [ str ] ) : list of files that failed to download
Returns : None""" | self . files_downloaded = files_downloaded
self . files_failed = files_failed
self . __record_progress ( Status . GET_FILE_DIFF ) |
def to_dict ( self ) :
"""Convert current Stage into a dictionary
: return : python dictionary""" | stage_desc_as_dict = { 'uid' : self . _uid , 'name' : self . _name , 'state' : self . _state , 'state_history' : self . _state_history , 'parent_pipeline' : self . _p_pipeline }
return stage_desc_as_dict |
def add_aacgm_coordinates ( inst , glat_label = 'glat' , glong_label = 'glong' , alt_label = 'alt' ) :
"""Uses AACGMV2 package to add AACGM coordinates to instrument object .
The Altitude Adjusted Corrected Geomagnetic Coordinates library is used
to calculate the latitude , longitude , and local time
of the s... | import aacgmv2
aalat = [ ] ;
aalon = [ ] ;
mlt = [ ]
for lat , lon , alt , time in zip ( inst [ glat_label ] , inst [ glong_label ] , inst [ alt_label ] , inst . data . index ) : # aacgmv2 latitude and longitude from geodetic coords
tlat , tlon , tmlt = aacgmv2 . get_aacgm_coord ( lat , lon , alt , time )
aalat... |
def x_select_cb ( self , w , index ) :
"""Callback to set X - axis column .""" | try :
self . x_col = self . cols [ index ]
except IndexError as e :
self . logger . error ( str ( e ) )
else :
self . plot_two_columns ( reset_xlimits = True ) |
def f ( self , v , t ) :
"""Aburn2012 equations right hand side , noise free term
Args :
v : ( 8 , ) array
state vector
t : number
scalar time
Returns :
(8 , ) array""" | ret = np . zeros ( 8 )
ret [ 0 ] = v [ 4 ]
ret [ 4 ] = ( self . He1 * self . ke1 * ( self . g1 * self . S ( v [ 1 ] - v [ 2 ] ) + self . u_mean ) - 2 * self . ke1 * v [ 4 ] - self . ke1 * self . ke1 * v [ 0 ] )
ret [ 1 ] = v [ 5 ]
ret [ 5 ] = ( self . He2 * self . ke2 * ( self . g2 * self . S ( v [ 0 ] ) + self . p_mea... |
def fulfill ( self , agreement_id , reward_address , amount , account ) :
"""Fulfill the lock reward condition .
: param agreement _ id : id of the agreement , hex str
: param reward _ address : ethereum account address , hex str
: param amount : Amount of tokens , int
: param account : Account instance
:... | return self . _fulfill ( agreement_id , reward_address , amount , transact = { 'from' : account . address , 'passphrase' : account . password } ) |
def get_DID_subdomain ( did , db_path = None , zonefiles_dir = None , atlasdb_path = None , check_pending = False ) :
"""Static method for resolving a DID to a subdomain
Return the subdomain record on success
Return None on error""" | opts = get_blockstack_opts ( )
if not is_subdomains_enabled ( opts ) :
log . warn ( "Subdomain support is disabled" )
return None
if db_path is None :
db_path = opts [ 'subdomaindb_path' ]
if zonefiles_dir is None :
zonefiles_dir = opts [ 'zonefiles' ]
if atlasdb_path is None :
atlasdb_path = opts [... |
def action_filter ( method_name , * args , ** kwargs ) :
"""Creates an effect that will call the action ' s method with the current
value and specified arguments and keywords .
@ param method _ name : the name of method belonging to the action .
@ type method _ name : str""" | def action_filter ( value , context , ** _params ) :
method = getattr ( context [ "action" ] , method_name )
return _filter ( method , value , args , kwargs )
return action_filter |
def split ( self , cutting_points , track_relative = False , overlap = 0.0 ) :
"""Split the utterance into x parts ( sub - utterances ) and
return them as new utterances . x is defined by cutting _ points
( ` ` x = len ( cutting _ points ) + 1 ` ` ) .
By default cutting - points are relative to the start of t... | if not track_relative :
cutting_points = [ c + self . start for c in cutting_points ]
if len ( cutting_points ) == 0 :
raise ValueError ( 'At least 1 cutting point is needed!' )
splitted_label_lists = collections . defaultdict ( list )
for idx , label_list in self . label_lists . items ( ) :
label_cutting_p... |
def read_rows ( self , read_position , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) :
"""Reads rows from the table in the format prescribed by the read
session . Each response contains one or more table rows , up to a
m... | gapic_client = super ( BigQueryStorageClient , self )
stream = gapic_client . read_rows ( read_position , retry = retry , timeout = timeout , metadata = metadata )
return reader . ReadRowsStream ( stream , gapic_client , read_position , { "retry" : retry , "timeout" : timeout , "metadata" : metadata } , ) |
def silhouette_n_clusters ( data , k_min , k_max , distance = 'euclidean' ) :
"""Computes and plot the silhouette score vs number of clusters graph to help selecting the number of clusters visually
: param data : The data object
: param k _ min : lowerbound of the cluster range
: param k _ max : upperbound of... | k_range = range ( k_min , k_max )
k_means_var = [ Clustering . kmeans ( k ) . fit ( data ) for k in k_range ]
silhouette_scores = [ obj . silhouette_score ( data = data , metric = distance ) for obj in k_means_var ]
fig = plt . figure ( )
ax = fig . add_subplot ( 111 )
ax . plot ( k_range , silhouette_scores , 'b*-' )
... |
def returner ( ret ) :
'''Send a slack message with the data through a webhook
: param ret : The Salt return
: return : The result of the post''' | _options = _get_options ( ret )
webhook = _options . get ( 'webhook' , None )
show_tasks = _options . get ( 'show_tasks' )
author_icon = _options . get ( 'author_icon' )
if not webhook or webhook is '' :
log . error ( '%s.webhook not defined in salt config' , __virtualname__ )
return
report = _generate_report (... |
def is_free ( self ) :
"""returns True if any of the spectral model parameters is set to free , else False""" | return bool ( np . array ( [ int ( value . get ( "free" , False ) ) for key , value in self . spectral_pars . items ( ) ] ) . sum ( ) ) |
def _interval_to_double_bound_points ( xarray , yarray ) :
"""Helper function to deal with a xarray consisting of pd . Intervals . Each
interval is replaced with both boundaries . I . e . the length of xarray
doubles . yarray is modified so it matches the new shape of xarray .""" | xarray1 = np . array ( [ x . left for x in xarray ] )
xarray2 = np . array ( [ x . right for x in xarray ] )
xarray = list ( itertools . chain . from_iterable ( zip ( xarray1 , xarray2 ) ) )
yarray = list ( itertools . chain . from_iterable ( zip ( yarray , yarray ) ) )
return xarray , yarray |
def incremental ( self , start_time , include = None ) :
"""Retrieve bulk data from the incremental API .
: param include : list of objects to sideload . ` Side - loading API Docs
< https : / / developer . zendesk . com / rest _ api / docs / core / side _ loading > ` _ _ .
: param start _ time : The time of t... | return self . _query_zendesk ( self . endpoint . incremental , self . object_type , start_time = start_time , include = include ) |
def angle_to_speed_percentage ( angle ) :
"""The following graphic illustrates the * * motor power outputs * * for the
left and right motors based on where the joystick is pointing , of the
form ` ` ( left power , right power ) ` ` : :
(1 , 1)
(0 , 1 ) . | . ( 1 , 0)
. | x - axis .
( - 1 , 1 ) . - - - -... | if 0 <= angle <= 45 : # left motor stays at 1
left_speed_percentage = 1
# right motor transitions from - 1 to 0
right_speed_percentage = - 1 + ( angle / 45.0 )
elif 45 < angle <= 90 : # left motor stays at 1
left_speed_percentage = 1
# right motor transitions from 0 to 1
percentage_from_45_to_90... |
def complete_multipart_upload ( self , key_name , upload_id , xml_body , headers = None ) :
"""Complete a multipart upload operation .""" | query_args = 'uploadId=%s' % upload_id
if headers is None :
headers = { }
headers [ 'Content-Type' ] = 'text/xml'
response = self . connection . make_request ( 'POST' , self . name , key_name , query_args = query_args , headers = headers , data = xml_body )
contains_error = False
body = response . read ( )
# Some e... |
def draw_sample ( self , Xstar , n = 0 , num_samp = 1 , rand_vars = None , rand_type = 'standard normal' , diag_factor = 1e3 , method = 'cholesky' , num_eig = None , mean = None , cov = None , modify_sign = None , ** kwargs ) :
"""Draw a sample evaluated at the given points ` Xstar ` .
Note that this function dra... | # All of the input processing for Xstar and n will be done in here :
if mean is None or cov is None :
out = self . predict ( Xstar , n = n , full_output = True , ** kwargs )
mean = out [ 'mean' ]
cov = out [ 'cov' ]
if rand_vars is None and method != 'eig' :
try :
return numpy . random . multiva... |
def xor ( a , b ) :
"""Bitwise xor on equal length bytearrays .""" | return bytearray ( i ^ j for i , j in zip ( a , b ) ) |
def check_height ( self , dataset ) :
'''float z ( time ) ; / / . . . . . Depending on the precision used for the variable , the data type could be int or double instead of float . Also the variable " z " could be substituted with a more descriptive name like " depth " , " altitude " , " pressure " , etc .
z : lo... | results = [ ]
exists_ctx = TestCtx ( BaseCheck . HIGH , 'Variable for height must exist' )
var = util . get_z_variable ( dataset )
exists_ctx . assert_true ( var is not None , "A variable for height must exist" )
if var is None :
return exists_ctx . to_result ( )
# Check Height Name
required_ctx = TestCtx ( BaseChe... |
def refactor_extract_method ( self , start , end , name , make_global ) :
"""Extract region as a method .""" | refactor = ExtractMethod ( self . project , self . resource , start , end )
return self . _get_changes ( refactor , name , similar = True , global_ = make_global ) |
def apply ( self , spectrum , plot = False ) :
"""Apply the filter to the given [ W , F ] , or [ W , F , E ] spectrum
Parameters
spectrum : array - like
The wavelength [ um ] and flux of the spectrum
to apply the filter to
plot : bool
Plot the original and filtered spectrum
Returns
np . ndarray
Th... | # Convert to filter units if possible
f_units = 1.
if hasattr ( spectrum [ 0 ] , 'unit' ) :
spectrum [ 0 ] = spectrum [ 0 ] . to ( self . wave_units )
if hasattr ( spectrum [ 1 ] , 'unit' ) :
spectrum [ 1 ] = spectrum [ 1 ] . to ( self . flux_units )
f_units = self . flux_units
if len ( spectrum ) >= 3 and ... |
def axis ( origin_size = 0.04 , transform = None , origin_color = None , axis_radius = None , axis_length = None ) :
"""Return an XYZ axis marker as a Trimesh , which represents position
and orientation . If you set the origin size the other parameters
will be set relative to it .
Parameters
transform : ( 4... | # the size of the ball representing the origin
origin_size = float ( origin_size )
# set the transform and use origin - relative
# sized for other parameters if not specified
if transform is None :
transform = np . eye ( 4 )
if origin_color is None :
origin_color = [ 255 , 255 , 255 , 255 ]
if axis_radius is No... |
def steps ( current , target , max_steps ) :
"""Steps between two values .
: param current : Current value ( 0.0-1.0 ) .
: param target : Target value ( 0.0-1.0 ) .
: param max _ steps : Maximum number of steps .""" | if current < 0 or current > 1.0 :
raise ValueError ( "current value %s is out of bounds (0.0-1.0)" , current )
if target < 0 or target > 1.0 :
raise ValueError ( "target value %s is out of bounds (0.0-1.0)" , target )
return int ( abs ( ( current * max_steps ) - ( target * max_steps ) ) ) |
def date ( self , field = None , val = None ) :
"""Like datetime , but truncated to be a date only""" | return self . datetime ( field = field , val = val ) . date ( ) |
def get_constructor_attributes_types ( item_type ) -> Dict [ str , Tuple [ Type [ Any ] , bool ] ] :
"""Utility method to return a dictionary of attribute name > attribute type from the constructor of a given type
It supports PEP484 and ' attrs ' declaration , see https : / / github . com / python - attrs / attrs... | res = dict ( )
try : # - - Try to read an ' attr ' declaration and to extract types and optionality
from parsyfiles . plugins_optional . support_for_attrs import get_attrs_declarations
decls = get_attrs_declarations ( item_type )
# check that types are correct
for attr_name , v in decls . items ( ) :
... |
def use_in ( ContentHandler ) :
"""Modify ContentHandler , a sub - class of
pycbc _ glue . ligolw . LIGOLWContentHandler , to cause it to use the Array and
ArrayStream classes defined in this module when parsing XML
documents .
Example :
> > > from pycbc _ glue . ligolw import ligolw
> > > class MyConte... | def startStream ( self , parent , attrs , __orig_startStream = ContentHandler . startStream ) :
if parent . tagName == ligolw . Array . tagName :
return ArrayStream ( attrs ) . config ( parent )
return __orig_startStream ( self , parent , attrs )
def startArray ( self , parent , attrs ) :
return Arr... |
def _try_assign_utc_time ( self , raw_time , time_base ) :
"""Try to assign a UTC time to this reading .""" | # Check if the raw time is encoded UTC since y2k or just uptime
if raw_time != IOTileEvent . InvalidRawTime and ( raw_time & ( 1 << 31 ) ) :
y2k_offset = self . raw_time ^ ( 1 << 31 )
return self . _Y2KReference + datetime . timedelta ( seconds = y2k_offset )
if time_base is not None :
return time_base + da... |
def _sim_WA ( trace , PAZ , seedresp , water_level , velocity = False ) :
"""Remove the instrument response from a trace and simulate a Wood - Anderson .
Returns a de - meaned , de - trended , Wood Anderson simulated trace in
its place .
Works in - place on data and will destroy your original data , copy the ... | # Note Wood anderson sensitivity is 2080 as per Uhrhammer & Collins 1990
PAZ_WA = { 'poles' : [ - 6.283 + 4.7124j , - 6.283 - 4.7124j ] , 'zeros' : [ 0 + 0j ] , 'gain' : 1.0 , 'sensitivity' : 2080 }
if velocity :
PAZ_WA [ 'zeros' ] = [ 0 + 0j , 0 + 0j ]
# De - trend data
trace . detrend ( 'simple' )
# Simulate Wood... |
def max_rigid_id ( self ) :
"""Returns the maximum rigid body ID contained in the Compound .
This is usually used by compound . root to determine the maximum
rigid _ id in the containment hierarchy .
Returns
int or None
The maximum rigid body ID contained in the Compound . If no
rigid body IDs are found... | try :
return max ( [ particle . rigid_id for particle in self . particles ( ) if particle . rigid_id is not None ] )
except ValueError :
return |
def topic_detail ( request , slug ) :
"""A detail view of a Topic
Templates :
: template : ` faq / topic _ detail . html `
Context :
topic
An : model : ` faq . Topic ` object .
question _ list
A list of all published : model : ` faq . Question ` objects that relate
to the given : model : ` faq . Top... | extra_context = { 'question_list' : Question . objects . published ( ) . filter ( topic__slug = slug ) , }
return object_detail ( request , queryset = Topic . objects . published ( ) , extra_context = extra_context , template_object_name = 'topic' , slug = slug ) |
def angular_errors ( hyp_axes ) :
"""Minimum and maximum angular errors
corresponding to 1st and 2nd axes
of PCA distribution .
Ordered as [ minimum , maximum ] angular error .""" | # Not quite sure why this is sqrt but it is empirically correct
ax = N . sqrt ( hyp_axes )
return tuple ( N . arctan2 ( ax [ - 1 ] , ax [ : - 1 ] ) ) |
def load ( filenames , prepare_data_iterator = True , batch_size = None , exclude_parameter = False , parameter_only = False ) :
'''load
Load network information from files .
Args :
filenames ( list ) : List of filenames .
Returns :
dict : Network information .''' | class Info :
pass
info = Info ( )
proto = nnabla_pb2 . NNablaProtoBuf ( )
for filename in filenames :
_ , ext = os . path . splitext ( filename )
# TODO : Here is some known problems .
# - Even when protobuf file includes network structure ,
# it will not loaded .
# - Even when prototxt file inc... |
def pre_factor_kkt ( Q , G , A ) :
"""Perform all one - time factorizations and cache relevant matrix products""" | nineq , nz , neq , _ = get_sizes ( G , A )
# S = [ A Q ^ { - 1 } A ^ T A Q ^ { - 1 } G ^ T ]
# [ G Q ^ { - 1 } A ^ T G Q ^ { - 1 } G ^ T + D ^ { - 1 } ]
U_Q = torch . potrf ( Q )
# partial cholesky of S matrix
U_S = torch . zeros ( neq + nineq , neq + nineq ) . type_as ( Q )
G_invQ_GT = torch . mm ( G , torch . potrs (... |
def copy_keywords ( self , shapefile_path ) :
"""Copy keywords from the OSM resource directory to the output path .
. . versionadded : 3.3
In addition to copying the template , tokens within the template will
be replaced with new values for the date token and title token .
: param shapefile _ path : Path to... | source_xml_path = resources_path ( 'petabencana' , 'flood-keywords.xml' )
output_xml_path = shapefile_path . replace ( 'shp' , 'xml' )
LOGGER . info ( 'Copying xml to: %s' % output_xml_path )
title_token = '[TITLE]'
new_title = self . tr ( 'Jakarta Floods - %s' % self . time_stamp )
date_token = '[DATE]'
new_date = sel... |
def _set_index ( self , key , index ) :
"""Set a new index array for this series""" | axis = key [ 0 ]
origin = "{}0" . format ( axis )
delta = "d{}" . format ( axis )
if index is None :
return delattr ( self , key )
if not isinstance ( index , Index ) :
try :
unit = index . unit
except AttributeError :
unit = getattr ( self , "_default_{}unit" . format ( axis ) )
index =... |
def set_sort ( self , request ) :
"""Take the sort parameter from the get parameters and split it into
the field and the prefix""" | # Look for ' sort ' in get request . If not available use default .
sort_request = request . GET . get ( self . sort_parameter , self . default_sort )
if sort_request . startswith ( '-' ) :
sort_order = '-'
sort_field = sort_request . split ( '-' ) [ 1 ]
else :
sort_order = ''
sort_field = sort_request
... |
def exists_locked ( filepath : str ) -> Tuple [ bool , bool ] :
"""Checks if a file is locked by opening it in append mode .
( If no exception is thrown in that situation , then the file is not locked . )
Args :
filepath : file to check
Returns :
tuple : ` ` ( exists , locked ) ` `
See https : / / www .... | exists = False
locked = None
file_object = None
if os . path . exists ( filepath ) :
exists = True
locked = True
try :
buffer_size = 8
# Opening file in append mode and read the first 8 characters .
file_object = open ( filepath , 'a' , buffer_size )
if file_object :
... |
def get ( self , request , * args , ** kwargs ) :
"""Catch protected relations and show to user .""" | self . object = self . get_object ( )
can_delete = True
protected_objects = [ ]
collector_message = None
collector = Collector ( using = "default" )
try :
collector . collect ( [ self . object ] )
except ProtectedError as e :
collector_message = ( "Cannot delete %s because it has relations " "that depends on it... |
def CCNOT ( control1 , control2 , target ) :
"""Produces a doubly - controlled NOT gate : :
CCNOT = [ [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] ,
[0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 ] ,
[0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 ] ,
[0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 ] ,
[0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 ] ,
[0 , 0 , 0 , 0 , 0 , 1 , 0... | qubits = [ unpack_qubit ( q ) for q in ( control1 , control2 , target ) ]
return Gate ( name = "CCNOT" , params = [ ] , qubits = qubits ) |
def write ( self , * args , ** kwargs ) :
""": param args : tuple ( value , style ) , tuple ( value , style )
: param kwargs : header = tuple ( value , style ) , header = tuple ( value , style )
: param args : value , value
: param kwargs : header = value , header = value""" | if args :
kwargs = dict ( zip ( self . header , args ) )
for header in kwargs :
cell = kwargs [ header ]
if not isinstance ( cell , tuple ) :
cell = ( cell , )
self . write_cell ( self . _row , self . header . index ( header ) , * cell )
self . _row += 1 |
def cn ( shape , dtype = None , impl = 'numpy' , ** kwargs ) :
"""Return a space of complex tensors .
Parameters
shape : positive int or sequence of positive ints
Number of entries per axis for elements in this space . A
single integer results in a space with 1 axis .
dtype : optional
Data type of each ... | cn_cls = tensor_space_impl ( impl )
if dtype is None :
dtype = cn_cls . default_dtype ( ComplexNumbers ( ) )
# Use args by keyword since the constructor may take other arguments
# by position
cn = cn_cls ( shape = shape , dtype = dtype , ** kwargs )
if not cn . is_complex :
raise ValueError ( 'data type {!r} no... |
def _get_sensor ( self ) :
"""Determine the sensor for this file .""" | # sometimes Himawari - 8 ( or 9 ) data is stored in SCMI format
is_h8 = 'H8' in self . platform_name
is_h9 = 'H9' in self . platform_name
is_ahi = is_h8 or is_h9
return 'ahi' if is_ahi else 'abi' |
def parse_csv ( file_path : str , entrez_id_header , log_fold_change_header , adjusted_p_value_header , entrez_delimiter , base_mean_header = None , sep = "," ) -> List [ Gene ] :
"""Read a csv file on differential expression values as Gene objects .
: param str file _ path : The path to the differential expressi... | logger . info ( "In parse_csv()" )
df = pd . read_csv ( file_path , sep = sep )
return handle_dataframe ( df , entrez_id_name = entrez_id_header , log2_fold_change_name = log_fold_change_header , adjusted_p_value_name = adjusted_p_value_header , entrez_delimiter = entrez_delimiter , base_mean = base_mean_header , ) |
def evaluate_stop_condition ( errdata , stop_condition ) :
"""Call the user - defined function : stop _ condition ( errdata )
If the function returns - 1 , do nothing . Otherwise , sys . exit .""" | if stop_condition :
return_code = stop_condition ( list ( errdata ) )
if return_code != - 1 :
log . info ( 'Stop condition triggered! Relay is terminating.' , extra = dict ( return_code = return_code ) )
sys . exit ( return_code ) |
def get_position ( directory , identifier ) :
"""Extracts the position of a paragraph from the identifier , and the parent directory of the
paragraph .
Parameters
directory : Path
A parent directory of a paragraph .
identifier : str
An identifier of a paragraph .
Returns
float
The estimated positi... | paragraph_number = get_paragraph_number ( identifier )
paragraph_total = max ( # Not all paragraphs are stored , e . g . because of processing errors .
get_paragraph_number ( get_identifier ( document ) ) + 1 for document in directory . iterdir ( ) )
assert paragraph_total > paragraph_number and paragraph_total > 0
pos... |
def update ( self , sample_sid = values . unset , status = values . unset ) :
"""Update the QueryInstance
: param unicode sample _ sid : The SID of an optional reference to the Sample created from the query
: param unicode status : The new status of the resource
: returns : Updated QueryInstance
: rtype : t... | return self . _proxy . update ( sample_sid = sample_sid , status = status , ) |
def set_vectors ( self , stoi , vectors , dim , unk_init = torch . Tensor . zero_ ) :
"""Set the vectors for the Vocab instance from a collection of Tensors .
Arguments :
stoi : A dictionary of string to the index of the associated vector
in the ` vectors ` input argument .
vectors : An indexed iterable ( o... | self . vectors = torch . Tensor ( len ( self ) , dim )
for i , token in enumerate ( self . itos ) :
wv_index = stoi . get ( token , None )
if wv_index is not None :
self . vectors [ i ] = vectors [ wv_index ]
else :
self . vectors [ i ] = unk_init ( self . vectors [ i ] ) |
def flatten_if ( cond : Callable [ [ Union [ T , ActualIterable [ T ] ] ] , bool ] ) :
"""> > > from Redy . Collections import Traversal , Flow
> > > lst : Iterable [ int ] = [ [ 1 , 2 , 3 ] ]
> > > x = Flow ( lst ) [ Traversal . flatten _ if ( lambda _ : isinstance ( _ , list ) ) ]
> > > assert isinstance ( ... | def inner ( nested : ActualIterable [ Union [ T , ActualIterable [ T ] ] ] ) -> ActualIterable [ T ] :
for each in nested :
if cond ( each ) :
yield from inner ( each )
else :
yield each
return inner |
def do_ls ( argdict ) :
'''List pages .''' | site = make_site_obj ( argdict )
if not site . tree_ready :
print "Cannot list pages. You are not within a simplystatic \
tree and you didn't specify a directory."
sys . exit ( )
drafts = argdict [ 'drafts' ]
recent = argdict [ 'recent' ]
dir = site . dirs [ 'source' ]
r = site . get_page_names ( )
if drafts :
... |
def getresponse ( self , _ = False , ** kwargs ) :
'''Retrieve the response''' | # Check to see if the cassette has a response for this request . If so ,
# then return it
if self . cassette . can_play_response_for ( self . _vcr_request ) :
log . info ( "Playing response for {} from cassette" . format ( self . _vcr_request ) )
response = self . cassette . play_response ( self . _vcr_request ... |
def peptides_to_network_input ( self , peptides ) :
"""Encode peptides to the fixed - length encoding expected by the neural
network ( which depends on the architecture ) .
Parameters
peptides : EncodableSequences or list of string
Returns
numpy . array""" | encoder = EncodableSequences . create ( peptides )
if ( self . hyperparameters [ 'peptide_amino_acid_encoding' ] == "embedding" ) :
encoded = encoder . variable_length_to_fixed_length_categorical ( max_length = self . hyperparameters [ 'kmer_size' ] , ** self . input_encoding_hyperparameter_defaults . subselect ( s... |
def adjustEndingReservationForJob ( reservation , jobShape , wallTime ) :
"""Add a job to an ending reservation that ends at wallTime , splitting
the reservation if the job doesn ' t fill the entire timeslice .""" | if jobShape . wallTime - wallTime < reservation . shape . wallTime : # This job only partially fills one of the slices . Create a new slice .
reservation . shape , nS = split ( reservation . shape , jobShape , jobShape . wallTime - wallTime )
nS . nReservation = reservation . nReservation
reservation . nRes... |
def register_writer ( klass ) :
"""Add engine to the excel writer registry . io . excel .
You must use this method to integrate with ` ` to _ excel ` ` .
Parameters
klass : ExcelWriter""" | if not callable ( klass ) :
raise ValueError ( "Can only register callables as engines" )
engine_name = klass . engine
_writers [ engine_name ] = klass |
def _chi_lr ( self , r , phi , nl , nr , beta ) :
"""computes the generalized polar basis function in the convention of Massey & Refregier eqn 8
: param nl : left basis
: type nl : int
: param nr : right basis
: type nr : int
: param beta : beta - - the characteristic scale typically choosen to be close t... | m = int ( ( nr - nl ) . real )
n = int ( ( nr + nl ) . real )
p = int ( ( n - abs ( m ) ) / 2 )
p2 = int ( ( n + abs ( m ) ) / 2 )
q = int ( abs ( m ) )
if p % 2 == 0 : # if p is even
prefac = 1
else :
prefac = - 1
prefactor = prefac / beta ** ( abs ( m ) + 1 ) * np . sqrt ( math . factorial ( p ) / ( np . pi *... |
def _dataset_merge_filestore_newresource ( self , new_resource , ignore_fields , filestore_resources ) : # type : ( hdx . data . Resource , List [ str ] , List [ hdx . data . Resource ] ) - > None
"""Helper method to add new resource from dataset including filestore .
Args :
new _ resource ( hdx . data . Resour... | new_resource . check_required_fields ( ignore_fields = ignore_fields )
self . resources . append ( new_resource )
if new_resource . get_file_to_upload ( ) :
filestore_resources . append ( new_resource )
new_resource [ 'url' ] = Dataset . temporary_url |
def build_health_endpoint ( version_dict : Mapping [ str , str ] ) -> Callable [ [ web . Request ] , Coroutine [ None , None , web . Response ] ] :
"""Build a coroutine to serve / health that captures version info""" | async def health ( request : web . Request ) -> web . Response :
return web . json_response ( { 'name' : request . app [ DEVICE_NAME_VARNAME ] , 'updateServerVersion' : version_dict . get ( 'update_server_version' , 'unknown' ) , 'serialNumber' : get_serial ( ) , 'apiServerVersion' : version_dict . get ( 'opentrons... |
def raw_datastream_old ( request , pid , dsid , type = None , repo = None , headers = None , accept_range_request = False , as_of_date = None , streaming = False ) :
'''. . NOTE : :
This version of : meth : ` raw _ datastream ` is deprecated , and you
should update to the new : meth : ` raw _ datastream ` . Thi... | if repo is None :
repo = Repository ( )
if headers is None :
headers = { }
get_obj_opts = { }
if type is not None :
get_obj_opts [ 'type' ] = type
obj = repo . get_object ( pid , ** get_obj_opts )
range_request = False
partial_request = False
try : # NOTE : we could test that pid is actually the requested
#... |
def with_ ( self , * relations ) :
"""Set the relationships that should be eager loaded .
: return : The current Builder instance
: rtype : Builder""" | if not relations :
return self
eagers = self . _parse_with_relations ( list ( relations ) )
self . _eager_load . update ( eagers )
return self |
def apply_shortcuts ( self ) :
"""Apply shortcuts settings to all widgets / plugins""" | toberemoved = [ ]
for index , ( qobject , context , name , add_sc_to_tip ) in enumerate ( self . shortcut_data ) :
keyseq = QKeySequence ( get_shortcut ( context , name ) )
try :
if isinstance ( qobject , QAction ) :
if sys . platform == 'darwin' and qobject . _shown_shortcut == 'missing' :
... |
def _read ( self , directory , filename , session , path , name , extension , spatial , spatialReferenceID , replaceParamFile ) :
"""Channel Input File Read from File Method""" | # Set file extension property
self . fileExtension = extension
# Dictionary of keywords / cards and parse function names
KEYWORDS = { 'ALPHA' : cic . cardChunk , 'BETA' : cic . cardChunk , 'THETA' : cic . cardChunk , 'LINKS' : cic . cardChunk , 'MAXNODES' : cic . cardChunk , 'CONNECT' : cic . connectChunk , 'LINK' : ci... |
def extrude ( self , input_entity , translation_axis = None , rotation_axis = None , point_on_axis = None , angle = None , num_layers = None , recombine = False , ) :
"""Extrusion ( translation + rotation ) of any entity along a given
translation _ axis , around a given rotation _ axis , about a given angle . If ... | self . _EXTRUDE_ID += 1
if _is_string ( input_entity ) :
entity = Dummy ( input_entity )
elif isinstance ( input_entity , PointBase ) :
entity = Dummy ( "Point{{{}}}" . format ( input_entity . id ) )
elif isinstance ( input_entity , SurfaceBase ) :
entity = Dummy ( "Surface{{{}}}" . format ( input_entity . ... |
def _prt_txt_desc2nts ( self , prt , desc2nts , prtfmt = None ) :
"""Print grouped and sorted GO IDs .""" | if prtfmt is None :
prtfmt = self . get_prtfmt ( "fmta" )
if self . ver_list is not None :
prt . write ( "# Versions:\n# {VER}\n" . format ( VER = "\n# " . join ( self . ver_list ) ) )
self . prt_txt_desc2nts ( prt , desc2nts , prtfmt ) |
def mmodule ( saltenv , fun , * args , ** kwargs ) :
'''Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example :
. . code - block : : bash
salt ' * ' saltutil . mmodule base test . ping''' | mminion = _MMinion ( saltenv )
return mminion . functions [ fun ] ( * args , ** kwargs ) |
def get_string ( self , sort_keys = False , pretty = False ) :
"""Returns a string representation of the Tags . The reason why this
method is different from the _ _ str _ _ method is to provide options
for pretty printing .
Args :
sort _ keys : Set to True to sort the Feff parameters alphabetically .
Defa... | keys = self . keys ( )
if sort_keys :
keys = sorted ( keys )
lines = [ ]
for k in keys :
if isinstance ( self [ k ] , dict ) :
if k in [ "ELNES" , "EXELFS" ] :
lines . append ( [ k , self . _stringify_val ( self [ k ] [ "ENERGY" ] ) ] )
beam_energy = self . _stringify_val ( self ... |
def allocateFees ( self ) :
'''Fees are allocated across invoice items based on their discounted
total price net of adjustments as a proportion of the overall
invoice ' s total price''' | items = list ( self . invoiceitem_set . all ( ) )
# Check that totals and adjusments match . If they do not , raise an error .
if self . total != sum ( [ x . total for x in items ] ) :
msg = _ ( 'Invoice item totals do not match invoice total. Unable to allocate fees.' )
logger . error ( str ( msg ) )
rais... |
def before_after_apply ( self , before_fn , after_fn , leaf_fn = None ) :
"""Applies the functions to each node in a subtree using an traversal in which
encountered twice : once right before its descendants , and once right
after its last descendant""" | stack = [ self ]
while stack :
node = stack . pop ( )
if node . is_leaf :
if leaf_fn :
leaf_fn ( node )
while node . is_last_child_of_parent :
node = node . _parent
if node :
after_fn ( node )
else :
break
else :... |
def angular_distance ( ra1 , dec1 , ra2 , dec2 ) :
"""Returns the angular distance between two points , two sets of points , or a set of points and one point .
: param ra1 : array or float , longitude of first point ( s )
: param dec1 : array or float , latitude of first point ( s )
: param ra2 : array or flo... | # Vincenty formula , slower than the Haversine formula in some cases , but stable also at antipodes
lon1 = np . deg2rad ( ra1 )
lat1 = np . deg2rad ( dec1 )
lon2 = np . deg2rad ( ra2 )
lat2 = np . deg2rad ( dec2 )
sdlon = np . sin ( lon2 - lon1 )
cdlon = np . cos ( lon2 - lon1 )
slat1 = np . sin ( lat1 )
slat2 = np . s... |
def _needs_base64_encoding ( self , attr_type , attr_value ) :
"""Return True if attr _ value has to be base - 64 encoded .
This is the case because of special chars or because attr _ type is in
self . _ base64 _ attrs""" | return attr_type . lower ( ) in self . _base64_attrs or isinstance ( attr_value , bytes ) or UNSAFE_STRING_RE . search ( attr_value ) is not None |
def _make_defaults_exposure_table ( ) :
"""Build headers for a table related to exposure classes .
: return : A table with headers .
: rtype : m . Table""" | table = m . Table ( style_class = 'table table-condensed table-striped' )
row = m . Row ( )
row . add ( m . Cell ( tr ( 'Name' ) , header = True ) )
row . add ( m . Cell ( tr ( 'Default values' ) , header = True ) )
table . add ( row )
return table |
def qeuler ( yaw , pitch , roll ) :
"""Convert Euler angle to quaternion .
Parameters
yaw : number
pitch : number
roll : number
Returns
np . array""" | yaw = np . radians ( yaw )
pitch = np . radians ( pitch )
roll = np . radians ( roll )
cy = np . cos ( yaw * 0.5 )
sy = np . sin ( yaw * 0.5 )
cr = np . cos ( roll * 0.5 )
sr = np . sin ( roll * 0.5 )
cp = np . cos ( pitch * 0.5 )
sp = np . sin ( pitch * 0.5 )
q = np . array ( ( cy * cr * cp + sy * sr * sp , cy * sr * ... |
def rename_to ( self , destination_name ) :
"""Moves this directory to the given destination . Returns a Folder object
that represents the moved directory .""" | target = self . parent . child_folder ( destination_name )
logger . info ( "Rename %s to %s" % ( self , target ) )
shutil . move ( self . path , unicode ( target ) )
return target |
def get_tag ( self , tagname , tagidx ) :
""": returns : the tag associated to the given tagname and tag index""" | return '%s=%s' % ( tagname , decode ( getattr ( self , tagname ) [ tagidx ] ) ) |
def detect_envlist ( ini ) :
"""Default envlist automatically based on the Travis environment .""" | # Find the envs that tox knows about
declared_envs = get_declared_envs ( ini )
# Find all the envs for all the desired factors given
desired_factors = get_desired_factors ( ini )
# Reduce desired factors
desired_envs = [ '-' . join ( env ) for env in product ( * desired_factors ) ]
# Find matching envs
return match_env... |
def set_trace ( frame = None , skip = 0 , server = None , port = None ) :
"""Set trace on current line , or on given frame""" | frame = frame or sys . _getframe ( ) . f_back
for i in range ( skip ) :
if not frame . f_back :
break
frame = frame . f_back
wdb = Wdb . get ( server = server , port = port )
wdb . set_trace ( frame )
return wdb |
def _set_metric ( self , metric_name , metric_type , value , tags = None ) :
"""Set a metric""" | if tags is None :
tags = [ ]
if metric_type == GAUGE :
self . gauge ( metric_name , value , tags = tags )
elif metric_type == COUNT :
self . count ( metric_name , value , tags = tags )
elif metric_type == MONOTONIC_COUNT :
self . monotonic_count ( metric_name , value , tags = tags )
else :
self . lo... |
def get_all ( self , collection_name , since = None ) :
"""method returns all job records from a particular collection that are older than < since >""" | if since is None :
query = { }
else :
query = { job . TIMEPERIOD : { '$gte' : since } }
collection = self . ds . connection ( collection_name )
cursor = collection . find ( query )
if cursor . count ( ) == 0 :
raise LookupError ( 'MongoDB has no job records in collection {0} since {1}' . format ( collection... |
def assume_role ( role_arn , session_name = None , duration_seconds = None , region = 'us-east-1' , env_vars = None ) :
"""Assume IAM role .""" | if session_name is None :
session_name = 'runway'
assume_role_opts = { 'RoleArn' : role_arn , 'RoleSessionName' : session_name }
if duration_seconds :
assume_role_opts [ 'DurationSeconds' ] = int ( duration_seconds )
boto_args = { }
if env_vars :
for i in [ 'aws_access_key_id' , 'aws_secret_access_key' , 'a... |
def _get_vars ( self , stack , scopes ) :
"""Get specifically scoped variables from a list of stack frames .
Parameters
stack : list
A list of stack frames as returned by ` ` inspect . stack ( ) ` `
scopes : sequence of strings
A sequence containing valid stack frame attribute names that
evaluate to a d... | variables = itertools . product ( scopes , stack )
for scope , ( frame , _ , _ , _ , _ , _ ) in variables :
try :
d = getattr ( frame , 'f_' + scope )
self . scope = self . scope . new_child ( d )
finally : # won ' t remove it , but DECREF it
# in Py3 this probably isn ' t necessary since fr... |
def _search_show_id ( self , series , year = None ) :
"""Search the show id from the ` series ` and ` year ` .
: param str series : series of the episode .
: param year : year of the series , if any .
: type year : int
: return : the show id , if found .
: rtype : int""" | # addic7ed doesn ' t support search with quotes
series = series . replace ( '\'' , ' ' )
# build the params
series_year = '%s %d' % ( series , year ) if year is not None else series
params = { 'search' : series_year , 'Submit' : 'Search' }
# make the search
logger . info ( 'Searching show ids with %r' , params )
r = se... |
def bd09togcj02 ( bd_lon , bd_lat ) :
"""百度坐标系 ( BD - 09 ) 转火星坐标系 ( GCJ - 02)
百度 — — > 谷歌 、 高德
: param bd _ lat : 百度坐标纬度
: param bd _ lon : 百度坐标经度
: return : 转换后的坐标列表形式""" | x = bd_lon - 0.0065
y = bd_lat - 0.006
z = math . sqrt ( x * x + y * y ) - 0.00002 * math . sin ( y * x_pi )
theta = math . atan2 ( y , x ) - 0.000003 * math . cos ( x * x_pi )
gg_lng = z * math . cos ( theta )
gg_lat = z * math . sin ( theta )
return [ gg_lng , gg_lat ] |
def gen_source_models ( self , gsim_lt ) :
"""Yield the underlying LtSourceModel , multiple times if there is sampling""" | num_gsim_paths = 1 if self . num_samples else gsim_lt . get_num_paths ( )
for i , rlz in enumerate ( self ) :
yield LtSourceModel ( rlz . value , rlz . weight , ( 'b1' , ) , [ ] , num_gsim_paths , i , 1 ) |
def _check_final_md5 ( self , key , etag ) :
"""Checks that etag from server agrees with md5 computed before upload .
This is important , since the upload could have spanned a number of
hours and multiple processes ( e . g . , gsutil runs ) , and the user could
change some of the file and not realize they hav... | if key . bucket . connection . debug >= 1 :
print 'Checking md5 against etag.'
if key . md5 != etag . strip ( '"\'' ) : # Call key . open _ read ( ) before attempting to delete the
# ( incorrect - content ) key , so we perform that request on a
# different HTTP connection . This is neededb because httplib
# will re... |
def build_info ( self ) :
"""Get the build info of this Android device , including build id and
build type .
This is not available if the device is in bootloader mode .
Returns :
A dict with the build info of this Android device , or None if the
device is in bootloader mode .""" | if self . is_bootloader :
self . log . error ( 'Device is in fastboot mode, could not get build ' 'info.' )
return
info = { }
info [ 'build_id' ] = self . adb . getprop ( 'ro.build.id' )
info [ 'build_type' ] = self . adb . getprop ( 'ro.build.type' )
return info |
def execute_sql ( self , result_type = constants . MULTI , chunked_fetch = False , chunk_size = constants . GET_ITERATOR_CHUNK_SIZE ) :
"""Run the query against the database and returns the result ( s ) . The
return value is a single data item if result _ type is SINGLE , or an
iterator over the results if the ... | try :
sql , params = self . as_sql ( )
if not sql :
raise EmptyResultSet
except EmptyResultSet :
if result_type == constants . MULTI :
return iter ( [ ] )
else :
return
cursor = self . connection . cursor ( )
cursor . prepare_query ( self . query )
cursor . execute ( sql , params... |
def format ( self , response_data ) :
"""Make Flask ` Response ` object , with data returned as a generator for the CSV content
The CSV is built from JSON - like object ( Python ` dict ` or list of ` dicts ` )""" | if "items" in response_data :
list_response_data = response_data [ "items" ]
else :
list_response_data = [ response_data ]
write_column_names = type ( list_response_data [ 0 ] ) not in ( tuple , list )
output = StringIO ( )
csv_writer = writer ( output , quoting = QUOTE_MINIMAL )
if write_column_names :
col... |
def parametrized_unbottleneck ( x , hidden_size , hparams ) :
"""Meta - function calling all the above un - bottlenecks with hparams .""" | if hparams . bottleneck_kind == "tanh_discrete" :
return tanh_discrete_unbottleneck ( x , hidden_size )
if hparams . bottleneck_kind == "isemhash" :
return isemhash_unbottleneck ( x , hidden_size , hparams . isemhash_filter_size_multiplier )
if hparams . bottleneck_kind in [ "vq" , "em" , "gumbel_softmax" ] :
... |
def update_or_create ( self , model , ** kwargs ) :
'''Update or create a new instance of ` ` model ` ` .
This method can raise an exception if the ` ` kwargs ` ` dictionary
contains field data that does not validate .
: param model : a : class : ` StdModel `
: param kwargs : dictionary of parameters .
: ... | backend = self . model ( model ) . backend
return backend . execute ( self . _update_or_create ( model , ** kwargs ) ) |
def is_none ( value , allow_empty = False , ** kwargs ) :
"""Indicate whether ` ` value ` ` is : obj : ` None < python : None > ` .
: param value : The value to evaluate .
: param allow _ empty : If ` ` True ` ` , accepts falsey values as equivalent to
: obj : ` None < python : None > ` . Defaults to ` ` Fals... | try :
validators . none ( value , allow_empty = allow_empty , ** kwargs )
except SyntaxError as error :
raise error
except Exception :
return False
return True |
def dict_contents ( self , use_dict = None , as_class = dict ) :
"""Return the contents of an object as a dict .""" | if _debug :
PDUData . _debug ( "dict_contents use_dict=%r as_class=%r" , use_dict , as_class )
return self . pdudata_contents ( use_dict = use_dict , as_class = as_class ) |
def save_config ( self , cmd = "save config" , confirm = False , confirm_response = "" ) :
"""Save Config""" | return super ( ExtremeErsSSH , self ) . save_config ( cmd = cmd , confirm = confirm , confirm_response = confirm_response ) |
def split_line ( what , indent = '' , cols = 79 ) :
"""Split a line on the closest space , or break the last word with ' - ' .
Args :
what ( str ) : text to spli one line of .
indent ( str ) : will prepend this indent to the split line , taking it into
account in the column count .
cols ( int ) : maximum ... | if len ( indent ) > cols :
raise ValueError ( "The indent can't be longer than cols." )
if cols < 2 :
raise ValueError ( "The cols can't be smaller than 2 (a char plus a possible '-')" )
what = indent + what . lstrip ( )
if len ( what ) <= cols :
what , new_line = '' , what
else :
try :
closest_... |
def disassemble_instruction ( self , instruction ) :
"""Disassembles and returns the assembly instruction string .
Args :
self ( JLink ) : the ` ` JLink ` ` instance .
instruction ( int ) : the instruction address .
Returns :
A string corresponding to the assembly instruction string at the
given instruc... | if not util . is_integer ( instruction ) :
raise TypeError ( 'Expected instruction to be an integer.' )
buf_size = self . MAX_BUF_SIZE
buf = ( ctypes . c_char * buf_size ) ( )
res = self . _dll . JLINKARM_DisassembleInst ( ctypes . byref ( buf ) , buf_size , instruction )
if res < 0 :
raise errors . JLinkExcept... |
def load_config ( self , path ) :
"""( Re - ) load the configuration file""" | self . config_path = path
self . config . read ( self . config_path ) |
def run ( ident ) :
'''Launch or resume an harvesting for a given source if none is running''' | source = get_source ( ident )
cls = backends . get ( current_app , source . backend )
backend = cls ( source )
backend . harvest ( ) |
def _process_pth ( path , base , file_name ) :
"""Process a ` ` . pth ` ` file similar to site . addpackage ( . . . ) .""" | pth_path = os . path . abspath ( os . path . join ( base , file_name ) )
# This is for ` exec ` below , as some packages ( e . g . virtualenvwrapper )
# assume that ` site . addpackage ` is running them .
sitedir = os . path . dirname ( base )
# Only process this once .
if pth_path in _processed_pths :
return
_proc... |
def connect_get_node_proxy_with_path ( self , name , path , ** kwargs ) : # noqa : E501
"""connect _ get _ node _ proxy _ with _ path # noqa : E501
connect GET requests to proxy of Node # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass a... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . connect_get_node_proxy_with_path_with_http_info ( name , path , ** kwargs )
# noqa : E501
else :
( data ) = self . connect_get_node_proxy_with_path_with_http_info ( name , path , ** kwargs )
# noqa : E501
retu... |
def upsert ( self , document , cond ) :
"""Update a document , if it exist - insert it otherwise .
Note : this will update * all * documents matching the query .
: param document : the document to insert or the fields to update
: param cond : which document to look for
: returns : a list containing the upda... | updated_docs = self . update ( document , cond )
if updated_docs :
return updated_docs
else :
return [ self . insert ( document ) ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.