signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def each_indexed_object ( collection , index_name , ** where ) :
"""Yields each object indexed by the index with
name ` ` name ` ` with ` ` values ` ` matching on indexed
field values .""" | index = _db [ collection ] . indexes [ index_name ]
for id in index . value_map . get ( indexed_value ( index , where ) , [ ] ) :
yield get_object ( collection , id ) |
def gen_reciprocals ( self , quadrupoles ) :
"""For a given set of quadrupoles , generate and return reciprocals""" | reciprocals = quadrupoles [ : , : : - 1 ] . copy ( )
reciprocals [ : , 0 : 2 ] = np . sort ( reciprocals [ : , 0 : 2 ] , axis = 1 )
reciprocals [ : , 2 : 4 ] = np . sort ( reciprocals [ : , 2 : 4 ] , axis = 1 )
return reciprocals |
def export_xlsx ( wb , output , fn ) :
"""export as excel
wb :
output :
fn : file name""" | wb . close ( )
output . seek ( 0 )
response = HttpResponse ( output . read ( ) , content_type = "application/vnd.ms-excel" )
cd = codecs . encode ( 'attachment;filename=%s' % fn , 'utf-8' )
response [ 'Content-Disposition' ] = cd
return response |
def _set_bearer_user_vars ( allowed_client_ids , scopes ) :
"""Validate the oauth bearer token and set endpoints auth user variables .
If the bearer token is valid , this sets ENDPOINTS _ USE _ OAUTH _ SCOPE . This
provides enough information that our endpoints . get _ current _ user ( ) function
can get the ... | all_scopes , sufficient_scopes = _process_scopes ( scopes )
try :
authorized_scopes = oauth . get_authorized_scopes ( sorted ( all_scopes ) )
except oauth . Error :
_logger . debug ( 'Unable to get authorized scopes.' , exc_info = True )
return
if not _are_scopes_sufficient ( authorized_scopes , sufficient_... |
def get_content_hashes ( image_path , level = None , regexp = None , include_files = None , tag_root = True , level_filter = None , skip_files = None , version = None , include_sizes = True ) :
'''get _ content _ hashes is like get _ image _ hash , but it returns a complete dictionary
of file names ( keys ) and t... | if level_filter is not None :
file_filter = level_filter
elif level is None :
file_filter = get_level ( "REPLICATE" , version = version , skip_files = skip_files , include_files = include_files )
else :
file_filter = get_level ( level , version = version , skip_files = skip_files , include_files = include_f... |
def user_agent ( ) :
"""Return a string representing the user agent .""" | data = { "installer" : { "name" : "pip" , "version" : pipenv . patched . notpip . __version__ } , "python" : platform . python_version ( ) , "implementation" : { "name" : platform . python_implementation ( ) , } , }
if data [ "implementation" ] [ "name" ] == 'CPython' :
data [ "implementation" ] [ "version" ] = pla... |
def __waituntil ( self , stopwaiting , timeoutmsg ) :
"""Waits until stopwaiting ( ) returns True , or until the wait times out
( according to the self . _ _ timeout value ) .
This is to make a function wait until a buffer has been filled . i . e .
stopwaiting ( ) should return True when the buffer is no long... | if not stopwaiting ( ) :
if self . __timeout == 0 : # in non - blocking mode ( immediate timeout )
# push event loop to really be sure there is no data available
_macutil . looponce ( )
if not stopwaiting ( ) : # trying to perform operation now would block
raise _socket . error ( err... |
def dictify ( r , root = True ) :
"""Convert an ElementTree into a dict .""" | if root :
return { r . tag : dictify ( r , False ) }
d = { }
if r . text and r . text . strip ( ) :
try :
return int ( r . text )
except ValueError :
try :
return float ( r . text )
except ValueError :
return r . text
for x in r . findall ( "./*" ) :
if x ... |
def _set_role_variable_by_entity_key ( self ) -> Dict [ str , str ] :
'''Identify and set the good roles for the different entities''' | if self . role_variable_by_entity_key is None :
self . role_variable_by_entity_key = dict ( ( entity . key , entity . key + '_legacy_role' ) for entity in self . tax_benefit_system . entities )
return self . role_variable_by_entity_key |
def set_align_options ( p ) :
"""Used in align ( ) and batch ( )""" | p . add_option ( "--bwa" , default = "bwa" , help = "Run bwa at this path" )
p . add_option ( "--rg" , help = "Read group" )
p . add_option ( "--readtype" , choices = ( "pacbio" , "pbread" , "ont2d" , "intractg" ) , help = "Read type in bwa-mem" )
p . set_cutoff ( cutoff = 800 ) |
def _number_xpad ( self ) :
"""Get the number of the joystick .""" | js_path = self . _device_path . replace ( '-event' , '' )
js_chardev = os . path . realpath ( js_path )
try :
number_text = js_chardev . split ( 'js' ) [ 1 ]
except IndexError :
return
try :
number = int ( number_text )
except ValueError :
return
self . __device_number = number |
def handle_scheduled ( self , target ) :
"""target is a Handler or simple callable""" | if not isinstance ( target , Handler ) :
return target ( )
return self . _handle_scheduled ( target ) |
def update ( self , author = values . unset , attributes = values . unset , date_created = values . unset , date_updated = values . unset , body = values . unset ) :
"""Update the MessageInstance
: param unicode author : The identity of the message ' s author .
: param unicode attributes : A string metadata fie... | data = values . of ( { 'Author' : author , 'Attributes' : attributes , 'DateCreated' : serialize . iso8601_datetime ( date_created ) , 'DateUpdated' : serialize . iso8601_datetime ( date_updated ) , 'Body' : body , } )
payload = self . _version . update ( 'POST' , self . _uri , data = data , )
return MessageInstance ( ... |
def write_worksheets ( workbook , data_list , result_info_key , identifier_keys ) :
"""Writes rest of the worksheets to workbook .
Args :
workbook : workbook to write into
data _ list : Analytics API data as a list of dicts
result _ info _ key : the key in api _ data dicts that contains the data results
i... | # we can use the first item to figure out the worksheet keys
worksheet_keys = get_worksheet_keys ( data_list [ 0 ] , result_info_key )
for key in worksheet_keys :
title = key . split ( '/' ) [ 1 ]
title = utilities . convert_snake_to_title_case ( title )
title = KEY_TO_WORKSHEET_MAP . get ( title , title )
... |
def _resolve_base_image ( self , build_json ) :
"""If this is an auto - rebuild , adjust the base image to use the triggering build""" | spec = build_json . get ( "spec" )
try :
image_id = spec [ 'triggeredBy' ] [ 0 ] [ 'imageChangeBuild' ] [ 'imageID' ]
except ( TypeError , KeyError , IndexError ) : # build not marked for auto - rebuilds ; use regular base image
base_image = self . workflow . builder . base_image
self . log . info ( "using ... |
def copy ( self , deep = False ) :
"""Build a copy of this dictionary .
Parameters
deep : ` bool ` , optional , default : ` False `
perform a deep copy of the original dictionary with a fresh
memory address
Returns
flag2 : ` DataQualityFlag `
a copy of the original dictionary""" | if deep :
return deepcopy ( self )
return super ( DataQualityDict , self ) . copy ( ) |
def sphbear ( lat1 , lon1 , lat2 , lon2 , tol = 1e-15 ) :
"""Calculate the bearing between two locations on a sphere .
lat1
The latitude of the first location .
lon1
The longitude of the first location .
lat2
The latitude of the second location .
lon2
The longitude of the second location .
tol
T... | # cross product on outer axis :
ocross = lambda a , b : np . cross ( a , b , axisa = 0 , axisb = 0 , axisc = 0 )
# if args have shape S , this has shape ( 3 , S )
v1 = np . asarray ( [ np . cos ( lat1 ) * np . cos ( lon1 ) , np . cos ( lat1 ) * np . sin ( lon1 ) , np . sin ( lat1 ) ] )
v2 = np . asarray ( [ np . cos ( ... |
def get ( self , key , _else = None ) :
"""The method to get an assets value""" | with self . _lock :
self . expired ( )
# see if everything expired
try :
value = self . _dict [ key ] . get ( )
return value
except KeyError :
return _else
except ValueError :
return _else |
def weighted_axioms ( self , x , y , xg ) :
"""return a tuple ( sub , sup , equiv , other ) indicating estimated prior probabilities for an interpretation of a mapping
between x and y .
See kboom paper""" | # TODO : allow additional weighting
# weights are log odds w = log ( p / ( 1 - p ) )
# ( Sub , Sup , Eq , Other )
scope_pairs = [ ( 'label' , 'label' , 0.0 , 0.0 , 3.0 , - 0.8 ) , ( 'label' , 'exact' , 0.0 , 0.0 , 2.5 , - 0.5 ) , ( 'label' , 'broad' , - 1.0 , 1.0 , 0.0 , 0.0 ) , ( 'label' , 'narrow' , 1.0 , - 1.0 , 0.0... |
def to_xarray ( self ) :
"""Return an xarray object from the pandas object .
Returns
xarray . DataArray or xarray . Dataset
Data in the pandas structure converted to Dataset if the object is
a DataFrame , or a DataArray if the object is a Series .
See Also
DataFrame . to _ hdf : Write DataFrame to an HD... | try :
import xarray
except ImportError : # Give a nice error message
raise ImportError ( "the xarray library is not installed\n" "you can install via conda\n" "conda install xarray\n" "or via pip\n" "pip install xarray\n" )
if self . ndim == 1 :
return xarray . DataArray . from_series ( self )
elif self . n... |
def minimum ( attrs , inputs , proto_obj ) :
"""Elementwise minimum of arrays .""" | # MXNet minimum compares only two symbols at a time .
# ONNX can send more than two to compare .
# Breaking into multiple mxnet ops to compare two symbols at a time
if len ( inputs ) > 1 :
mxnet_op = symbol . minimum ( inputs [ 0 ] , inputs [ 1 ] )
for op_input in inputs [ 2 : ] :
mxnet_op = symbol . mi... |
def XyzToRgb ( x , y , z ) :
'''Convert the color from CIE XYZ coordinates to sRGB .
. . note : :
Compensation for sRGB gamma correction is applied before converting .
Parameters :
The X component value [ 0 . . . 1]
The Y component value [ 0 . . . 1]
The Z component value [ 0 . . . 1]
Returns :
The ... | r = ( x * 3.2406255 ) - ( y * 1.5372080 ) - ( z * 0.4986286 )
g = - ( x * 0.9689307 ) + ( y * 1.8757561 ) + ( z * 0.0415175 )
b = ( x * 0.0557101 ) - ( y * 0.2040211 ) + ( z * 1.0569959 )
return tuple ( ( ( ( v <= _srgbGammaCorrInv ) and [ v * 12.92 ] or [ ( 1.055 * ( v ** ( 1 / 2.4 ) ) ) - 0.055 ] ) [ 0 ] for v in ( r... |
def reorder_levels ( self , dim_order = None , inplace = None , ** dim_order_kwargs ) :
"""Rearrange index levels using input order .
Parameters
dim _ order : optional
Mapping from names matching dimensions and values given
by lists representing new level orders . Every given dimension
must have a multi -... | inplace = _check_inplace ( inplace )
dim_order = either_dict_or_kwargs ( dim_order , dim_order_kwargs , 'reorder_levels' )
replace_coords = { }
for dim , order in dim_order . items ( ) :
coord = self . _coords [ dim ]
index = coord . to_index ( )
if not isinstance ( index , pd . MultiIndex ) :
raise... |
def get_all_tags ( self , filters = None , max_records = None , next_token = None ) :
"""Lists the Auto Scaling group tags .
This action supports pagination by returning a token if there are more
pages to retrieve . To get the next page , call this action again with the returned token as the NextToken parameter... | params = { }
if max_records :
params [ 'MaxRecords' ] = max_records
if next_token :
params [ 'NextToken' ] = next_token
return self . get_list ( 'DescribeTags' , params , [ ( 'member' , Tag ) ] ) |
def Emulation_setPageScaleFactor ( self , pageScaleFactor ) :
"""Function path : Emulation . setPageScaleFactor
Domain : Emulation
Method name : setPageScaleFactor
WARNING : This function is marked ' Experimental ' !
Parameters :
Required arguments :
' pageScaleFactor ' ( type : number ) - > Page scale ... | assert isinstance ( pageScaleFactor , ( float , int ) ) , "Argument 'pageScaleFactor' must be of type '['float', 'int']'. Received type: '%s'" % type ( pageScaleFactor )
subdom_funcs = self . synchronous_command ( 'Emulation.setPageScaleFactor' , pageScaleFactor = pageScaleFactor )
return subdom_funcs |
def domain_search ( auth = None , ** kwargs ) :
'''Search domains
CLI Example :
. . code - block : : bash
salt ' * ' keystoneng . domain _ search
salt ' * ' keystoneng . domain _ search name = domain1''' | cloud = get_operator_cloud ( auth )
kwargs = _clean_kwargs ( ** kwargs )
return cloud . search_domains ( ** kwargs ) |
def setup_iperf_server ( self , protocol = 'TCP' , port = 5001 , window = None ) :
"""iperf - s""" | iperf = iperf_driver . IPerfDriver ( )
try :
data = iperf . start_server ( protocol = 'TCP' , port = 5001 , window = None )
return agent_utils . make_response ( code = 0 , data = data )
except :
message = 'Start iperf server failed!'
return agent_utils . make_response ( code = 1 , message = message ) |
def _purge ( dir , pattern , reason = '' ) :
"""delete files in dir that match pattern""" | for f in os . listdir ( dir ) :
if re . search ( pattern , f ) :
print "Purging file {0}. {1}" . format ( f , reason )
os . remove ( os . path . join ( dir , f ) ) |
def monitor ( args ) :
"""file monitor mode""" | filename = args . get ( 'MDFILE' )
if not filename :
print col ( 'Need file argument' , 2 )
raise SystemExit
last_err = ''
last_stat = 0
while True :
if not os . path . exists ( filename ) :
last_err = 'File %s not found. Will continue trying.' % filename
else :
try :
stat = ... |
def balance ( self ) :
"""Balance a node .
The balance is inductive and relies on all subtrees being balanced
recursively or by construction . If the subtrees are not balanced , then
this will not fix them .""" | # Always lean left with red nodes .
if self . right . red :
self = self . rotate_left ( )
# Never permit red nodes to have red children . Note that if the left - hand
# node is NULL , it will short - circuit and fail this test , so we don ' t have
# to worry about a dereference here .
if self . left . red and self ... |
def restart ( self , container , timeout = 10 ) :
"""Restart a container . Similar to the ` ` docker restart ` ` command .
Args :
container ( str or dict ) : The container to restart . If a dict , the
` ` Id ` ` key is used .
timeout ( int ) : Number of seconds to try to stop for before killing
the contai... | params = { 't' : timeout }
url = self . _url ( "/containers/{0}/restart" , container )
conn_timeout = self . timeout
if conn_timeout is not None :
conn_timeout += timeout
res = self . _post ( url , params = params , timeout = conn_timeout )
self . _raise_for_status ( res ) |
def get ( self , subset = None ) :
"""Return a dictionary object with the registered fields and their values
Optional rgument :
| ` ` subset ` ` - - a list of names to restrict the number of fields
in the result""" | if subset is None :
return dict ( ( name , attr . get ( copy = True ) ) for name , attr in self . _fields . items ( ) )
else :
return dict ( ( name , attr . get ( copy = True ) ) for name , attr in self . _fields . items ( ) if name in subset ) |
def get_mac_address_table_output_mac_address_table_mac_type ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_mac_address_table = ET . Element ( "get_mac_address_table" )
config = get_mac_address_table
output = ET . SubElement ( get_mac_address_table , "output" )
mac_address_table = ET . SubElement ( output , "mac-address-table" )
vlanid_key = ET . SubElement ( mac_address_table , "vlanid... |
def flatten_component_refs ( container : ast . Class , expression : ast . Union [ ast . ConnectClause , ast . AssignmentStatement , ast . ForStatement , ast . Symbol ] , instance_prefix : str ) -> ast . Union [ ast . ConnectClause , ast . AssignmentStatement , ast . ForStatement , ast . Symbol ] :
"""Flattens compo... | expression_copy = copy . deepcopy ( expression )
w = TreeWalker ( )
w . walk ( ComponentRefFlattener ( container , instance_prefix ) , expression_copy )
return expression_copy |
def default_input_format ( content_type = 'application/json' , apply_globally = False , api = None ) :
"""A decorator that allows you to override the default output format for an API""" | def decorator ( formatter ) :
formatter = hug . output_format . content_type ( content_type ) ( formatter )
if apply_globally :
hug . defaults . input_format [ content_type ] = formatter
else :
apply_to_api = hug . API ( api ) if api else hug . api . from_object ( formatter )
apply_t... |
def host_first ( self ) :
"""First available host in this subnet .""" | if ( self . version ( ) == 4 and self . mask > 30 ) or ( self . version ( ) == 6 and self . mask > 126 ) :
return self
else :
return IP ( self . network_long ( ) + 1 , version = self . version ( ) ) |
def watch_prefix_once ( self , key_prefix , timeout = None , ** kwargs ) :
"""Watches a range of keys with a prefix , similar to watch _ once""" | kwargs [ 'range_end' ] = _increment_last_byte ( key_prefix )
return self . watch_once ( key_prefix , timeout = timeout , ** kwargs ) |
def run_commandline ( self , argv = None ) :
"""Run the command - line interface of this experiment .
If ` ` argv ` ` is omitted it defaults to ` ` sys . argv ` ` .
Parameters
argv : list [ str ] or str , optional
Command - line as string or list of strings like ` ` sys . argv ` ` .
Returns
sacred . run... | argv = ensure_wellformed_argv ( argv )
short_usage , usage , internal_usage = self . get_usage ( )
args = docopt ( internal_usage , [ str ( a ) for a in argv [ 1 : ] ] , help = False )
cmd_name = args . get ( 'COMMAND' ) or self . default_command
config_updates , named_configs = get_config_updates ( args [ 'UPDATE' ] )... |
def _validate_disallowed ( self , disallowed , field , value ) :
"""Readonly but with a custom error .
The rule ' s arguments are validated against this schema :
{ ' type ' : ' boolean ' }""" | if disallowed :
msg = 'disallowed user provided config option'
self . _error ( field , msg ) |
def validate ( self , value ) :
"""Validate value .
Args :
value :
Returns :
A validated value .
Raises :
UnitError""" | for validate in self . validates :
value = validate ( value )
return value |
def starts ( self , layer ) :
"""Retrieve start positions of elements if given layer .""" | starts = [ ]
for data in self [ layer ] :
starts . append ( data [ START ] )
return starts |
def _parseAtPage ( self , src ) :
"""page
: PAGE _ SYM S * IDENT ? pseudo _ page ? S *
' { ' S * declaration [ ' ; ' S * declaration ] * ' } ' S *""" | ctxsrc = src
src = src [ len ( '@page' ) : ] . lstrip ( )
page , src = self . _getIdent ( src )
if src [ : 1 ] == ':' :
pseudopage , src = self . _getIdent ( src [ 1 : ] )
page = page + '_' + pseudopage
else :
pseudopage = None
# src , properties = self . _ parseDeclarationGroup ( src . lstrip ( ) )
# Conta... |
def _launch_flow ( self , client , name , args ) :
"""Create specified flow , setting KeepAlive if requested .
Args :
client : GRR Client object on which to launch the flow .
name : string containing flow name .
args : proto ( * FlowArgs ) for type of flow , as defined in GRR flow proto .
Returns :
stri... | # Start the flow and get the flow ID
flow = self . _check_approval_wrapper ( client , client . CreateFlow , name = name , args = args )
flow_id = flow . flow_id
print ( '{0:s}: Scheduled' . format ( flow_id ) )
if self . keepalive :
keepalive_flow = client . CreateFlow ( name = 'KeepAlive' , args = flows_pb2 . Keep... |
def force ( self , owner , builderNames = None , builderid = None , ** kwargs ) :
"""We check the parameters , and launch the build , if everything is correct""" | builderNames = yield self . computeBuilderNames ( builderNames , builderid )
if not builderNames :
raise KeyError ( "builderNames not specified or not supported" )
# Currently the validation code expects all kwargs to be lists
# I don ' t want to refactor that now so much sure we comply . . .
kwargs = dict ( ( k , ... |
def do_install_dependencies ( dev = False , only = False , bare = False , requirements = False , allow_global = False , ignore_hashes = False , skip_lock = False , concurrent = True , requirements_dir = None , pypi_mirror = False , ) :
"""Executes the install functionality .
If requirements is True , simply spits... | from six . moves import queue
if requirements :
bare = True
blocking = not concurrent
# Load the lockfile if it exists , or if only is being used ( e . g . lock is being used ) .
if skip_lock or only or not project . lockfile_exists :
if not bare :
click . echo ( crayons . normal ( fix_utf8 ( "Installin... |
def replace ( self , source , dest ) :
"""Replace source broker with destination broker in replica set if found .""" | for i , broker in enumerate ( self . replicas ) :
if broker == source :
self . replicas [ i ] = dest
return |
def margin ( self , axis = None , weighted = True , include_missing = False , include_transforms_for_dims = None , prune = False , include_mr_cat = False , ) :
"""Get margin for the selected axis .
the selected axis . For MR variables , this is the sum of the selected
and non - selected slices .
Args
axis (... | table = self . _counts ( weighted ) . raw_cube_array
new_axis = self . _adjust_axis ( axis )
index = tuple ( None if i in new_axis else slice ( None ) for i , _ in enumerate ( table . shape ) )
# Calculate denominator . Only include those H & S dimensions , across
# which we DON ' T sum . These H & S are needed because... |
def SdkSetup ( self ) :
"""Microsoft Windows SDK Setup""" | if self . vc_ver > 9.0 :
return [ ]
return [ os . path . join ( self . si . WindowsSdkDir , 'Setup' ) ] |
def power_chisq_from_precomputed ( corr , snr , snr_norm , bins , indices = None , return_bins = False ) :
"""Calculate the chisq timeseries from precomputed values .
This function calculates the chisq at all times by performing an
inverse FFT of each bin .
Parameters
corr : FrequencySeries
The produce of... | # Get workspace memory
global _q_l , _qtilde_l , _chisq_l
bin_snrs = [ ]
if _q_l is None or len ( _q_l ) != len ( snr ) :
q = zeros ( len ( snr ) , dtype = complex_same_precision_as ( snr ) )
qtilde = zeros ( len ( snr ) , dtype = complex_same_precision_as ( snr ) )
_q_l = q
_qtilde_l = qtilde
else :
... |
def accept ( self ) :
'''Extracts raw value from form ' s raw data and passes it to converter''' | value = self . raw_value
if not self . _check_value_type ( value ) : # XXX should this be silent or TypeError ?
value = [ ] if self . multiple else self . _null_value
self . clean_value = self . conv . accept ( value )
return { self . name : self . clean_value } |
def base_add_isoquant_data ( features , quantfeatures , acc_col , quantacc_col , quantfields ) :
"""Generic function that takes a peptide or protein table and adds
quant data from ANOTHER such table .""" | quant_map = get_quantmap ( quantfeatures , quantacc_col , quantfields )
for feature in features :
feat_acc = feature [ acc_col ]
outfeat = { k : v for k , v in feature . items ( ) }
try :
outfeat . update ( quant_map [ feat_acc ] )
except KeyError :
outfeat . update ( { field : 'NA' for ... |
def directInitialMatrix ( self ) :
"""We generate an initial sparse matrix with all the transition rates ( or probabilities ) .
We later transform this matrix into a rate or probability matrix depending on the preferred method of obtaining pi .""" | # First initialize state codes and the mapping with states .
self . setStateCodes ( )
# For each state , calculate the indices of reached states and rates using the transition function .
results = imap ( self . transitionStates , self . mapping . values ( ) )
# Simpler alternative that uses less memory .
# Would be com... |
def _move_to_desired_location ( self ) :
"""Animate movement to desired location on map .""" | self . _next_update = 100000
x_start = self . _convert_longitude ( self . _longitude )
y_start = self . _convert_latitude ( self . _latitude )
x_end = self . _convert_longitude ( self . _desired_longitude )
y_end = self . _convert_latitude ( self . _desired_latitude )
if sqrt ( ( x_end - x_start ) ** 2 + ( y_end - y_st... |
def asdict ( self ) :
"""Retrieve all attributes as a dictionary .""" | if self . cache and self . _cached_asdict is not None :
return self . _cached_asdict
d = self . _get_nosync ( )
if self . cache :
self . _cached_asdict = d
return d |
def mpoint_ ( self , col , x = None , y = None , rsum = None , rmean = None ) :
"""Splits a column into multiple series based on the column ' s
unique values . Then visualize theses series in a chart .
Parameters : column to split , x axis column , y axis column
Optional : rsum = " 1D " to resample and sum da... | return self . _multiseries ( col , x , y , "point" , rsum , rmean ) |
def add_method_model ( self , func , # type : Callable
name = None , # type : Optional [ str ]
description = None , # type : Optional [ str ]
owner = None , # type : object
) : # type : ( . . . ) - > MethodModel
"""Register a function to be added to the block""" | if name is None :
name = func . __name__
method = MethodModel . from_callable ( func , description )
self . _add_field ( owner , name , method , func )
return method |
def search ( cursor = None , expr = None , facet = None , filterQuery = None , highlight = None , partial = None , query = None , queryOptions = None , queryParser = None , returnFields = None , size = None , sort = None , start = None , stats = None ) :
"""Retrieves a list of documents that match the specified sea... | pass |
def update_rba ( self , current_extent ) : # type : ( int ) - > None
'''A method to update the current rba for the ISO hybridization .
Parameters :
current _ extent - The new extent to set the RBA to .
Returns :
Nothing .''' | if not self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'This IsoHybrid object is not yet initialized' )
self . rba = current_extent |
def load_name ( self , name ) :
"""Find and return the template with the given template name .
Arguments :
name : the name of the template .""" | locator = self . _make_locator ( )
path = locator . find_name ( name , self . search_dirs )
return self . read ( path ) |
def getAudioData ( self ) :
"""Fetch the audio data .""" | with self . preload_mutex :
cache_url = self . buildUrl ( cache_friendly = True )
if cache_url in __class__ . cache :
logging . getLogger ( ) . debug ( "Got data for URL '%s' from cache" % ( cache_url ) )
audio_data = __class__ . cache [ cache_url ]
assert ( audio_data )
else :
... |
def groupby_size ( columns , column_tys , grouping_columns , grouping_column_tys ) :
"""Groups the given columns by the corresponding grouping column
value , and aggregate by summing values .
Args :
columns ( List < WeldObject > ) : List of columns as WeldObjects
column _ tys ( List < str > ) : List of each... | weld_obj = WeldObject ( encoder_ , decoder_ )
if len ( grouping_columns ) == 1 and len ( grouping_column_tys ) == 1 :
grouping_column_var = weld_obj . update ( grouping_columns [ 0 ] )
if isinstance ( grouping_columns [ 0 ] , WeldObject ) :
grouping_column_var = grouping_columns [ 0 ] . weld_code
gr... |
def setHint ( self , hint ) :
"""Sets the hint text to the inputed value .
: param hint | < str >""" | self . _hint = self . formatText ( hint )
self . update ( )
self . hintChanged . emit ( self . hint ( ) ) |
async def create ( source_id : str , name : str , schema_id : str , payment_handle : int ) :
"""Creates a new CredentialDef object that is written to the ledger
: param source _ id : Institution ' s unique ID for the credential definition
: param name : Name of credential definition
: param schema _ id : The ... | constructor_params = ( source_id , name , schema_id )
c_source_id = c_char_p ( source_id . encode ( 'utf-8' ) )
c_schema_id = c_char_p ( schema_id . encode ( 'utf-8' ) )
c_name = c_char_p ( name . encode ( 'utf-8' ) )
# default institution _ did in config is used as issuer _ did
c_issuer_did = None
c_payment = c_uint32... |
def accounts ( self ) :
"""Ask the bank for the known : py : class : ` ofxclient . Account ` list .
: rtype : list of : py : class : ` ofxclient . Account ` objects""" | from ofxclient . account import Account
client = self . client ( )
query = client . account_list_query ( )
resp = client . post ( query )
resp_handle = StringIO ( resp )
if IS_PYTHON_2 :
parsed = OfxParser . parse ( resp_handle )
else :
parsed = OfxParser . parse ( BytesIO ( resp_handle . read ( ) . encode ( ) ... |
def _straight_line_vertices ( adjacency_mat , node_coords , directed = False ) :
"""Generate the vertices for straight lines between nodes .
If it is a directed graph , it also generates the vertices which can be
passed to an : class : ` ArrowVisual ` .
Parameters
adjacency _ mat : array
The adjacency mat... | if not issparse ( adjacency_mat ) :
adjacency_mat = np . asarray ( adjacency_mat , float )
if ( adjacency_mat . ndim != 2 or adjacency_mat . shape [ 0 ] != adjacency_mat . shape [ 1 ] ) :
raise ValueError ( "Adjacency matrix should be square." )
arrow_vertices = np . array ( [ ] )
edges = _get_edges ( adjacency... |
def samples ( self ) :
"""Yield the samples as dicts , keyed by dimensions .""" | names = self . series . dimensions
for values in zip ( * ( getattr ( self . series , name ) for name in names ) ) :
yield dict ( zip ( names , values ) ) |
def start ( self ) :
'''Startup the kafka consumer .''' | log . debug ( 'Creating the consumer using the bootstrap servers: %s and the group ID: %s' , self . bootstrap_servers , self . group_id )
try :
self . consumer = kafka . KafkaConsumer ( bootstrap_servers = self . bootstrap_servers , group_id = self . group_id )
except kafka . errors . NoBrokersAvailable as err :
... |
def add_attribute ( self , feature_id , attribute_key , attribute_value , organism = None , sequence = None ) :
"""Add an attribute to a feature
: type feature _ id : str
: param feature _ id : Feature UUID
: type attribute _ key : str
: param attribute _ key : Attribute Key
: type attribute _ value : str... | data = { 'features' : [ { 'uniquename' : feature_id , 'non_reserved_properties' : [ { 'tag' : attribute_key , 'value' : attribute_value , } ] } ] }
data = self . _update_data ( data , organism , sequence )
return self . post ( 'addAttribute' , data ) |
def generate_private_key ( self , key_size = 2048 , public_exponent = 65537 ) :
"""Generate a private ( and a corresponding public ) key
: return : None""" | self . __set_private_key ( rsa . generate_private_key ( public_exponent = public_exponent , key_size = key_size , backend = default_backend ( ) ) ) |
def flairlist ( self , r , limit = 1000 , after = None , before = None ) :
"""Login required . Gets flairlist for subreddit ` r ` . See https : / / github . com / reddit / reddit / wiki / API % 3A - flairlist .
However , the wiki docs are wrong ( as of 2012/5/4 ) . Returns : class : ` things . ListBlob ` of : cla... | params = dict ( limit = limit )
if after :
params [ 'after' ] = after
elif before :
params [ 'before' ] = before
b = self . get ( 'r' , r , 'api' , 'flairlist' , params = params )
return b . users |
def QA_util_get_trade_range ( start , end ) :
'给出交易具体时间' | start , end = QA_util_get_real_datelist ( start , end )
if start is not None :
return trade_date_sse [ trade_date_sse . index ( start ) : trade_date_sse . index ( end ) + 1 : 1 ]
else :
return None |
def has_add_permission ( self , request ) :
"""Returns True if the requesting user is allowed to add an object , False otherwise .""" | perm_string = '%s.add_%s' % ( self . model . _meta . app_label , self . model . _meta . object_name . lower ( ) )
return request . user . has_perm ( perm_string ) |
def ts_stats ( Xt , y , fs = 1.0 , class_labels = None ) :
'''Generates some helpful statistics about the data X
Parameters
X : array - like , shape [ n _ series , . . . ]
Time series data and ( optionally ) contextual data
y : array - like , shape [ n _ series ]
target data
fs : float
sampling freque... | check_ts_data ( Xt )
Xt , Xs = get_ts_data_parts ( Xt )
if Xs is not None :
S = len ( np . atleast_1d ( Xs [ 0 ] ) )
else :
S = 0
C = np . max ( y ) + 1
# number of classes
if class_labels is None :
class_labels = np . arange ( C )
N = len ( Xt )
if Xt [ 0 ] . ndim > 1 :
D = Xt [ 0 ] . shape [ 1 ]
else ... |
def apply_splice ( a , splice ) :
"mutate a * and * return it . a as list , splice as diff . Delta ." | a [ splice . a : splice . b ] = splice . text
# text isn ' t always text . See diff comments .
return a |
def parse_location ( data ) :
"""Parses given location data .
: param data : Exception .
: type data : Exception
: return : Location object .
: rtype : Location""" | tokens = data . split ( "," )
location = Location ( directories = [ ] , files = [ ] , filters_in = [ ] , filters_out = [ ] , targets = [ ] )
if not tokens :
return location
for token in tokens :
token = token . strip ( )
if not token :
continue
if foundations . common . path_exists ( token ) :
... |
def whois ( self , nick ) :
"""Runs a WHOIS on someone .
Required arguments :
* nick - Nick to whois .
Returns a dictionary :
IDENT = = The user ' s ident .
HOST = = The user ' s host .
NAME = = The user ' s real name .
SERVER = = The server the user is on .
SERVER _ INFO = = The name of the server ... | with self . lock :
self . send ( 'WHOIS %s' % nick )
whois_r = { 'CHANNELS' : [ ] }
while self . readable ( ) :
msg = self . _recv ( )
info = msg [ 2 ] . split ( None , 4 )
if msg [ 0 ] == '311' :
whois_r [ 'IDENT' ] = info [ 1 ]
whois_r [ 'HOST' ] = info [ 2 ... |
def _init_metadata ( self ) :
"""stub""" | self . _start_timestamp_metadata = { 'element_id' : Id ( self . my_osid_object_form . _authority , self . my_osid_object_form . _namespace , 'start_timestamp' ) , 'element_label' : 'start timestamp' , 'instructions' : 'enter an integer number of seconds for the start time' , 'required' : False , 'read_only' : False , '... |
def find_jar ( jar_name , root_path = None ) :
"""Look for the named jar in :
# . ` ` root _ path ` ` , if specified
# . working directory - - ` ` PWD ` `
# . ` ` $ { PWD } / build ` `
# . ` ` / usr / share / java ` `
Return the full path of the jar if found ; else return : obj : ` None ` .""" | jar_name = os . path . basename ( jar_name )
root = root_path or os . getcwd ( )
paths = ( root , os . path . join ( root , "build" ) , "/usr/share/java" )
for p in paths :
p = os . path . join ( p , jar_name )
if os . path . exists ( p ) :
return p
return None |
def _find_return_target ( self , target ) :
"""Check if the return target exists in the stack , and return the index if exists . We always search from the most
recent call stack frame since the most recent frame has a higher chance to be hit in normal CFG recovery .
: param int target : Target of the return .
... | for i , frame in enumerate ( self ) :
if frame . ret_addr == target :
return i
return None |
def __RegisterDescriptor ( self , new_descriptor ) :
"""Register the given descriptor in this registry .""" | if not isinstance ( new_descriptor , ( extended_descriptor . ExtendedMessageDescriptor , extended_descriptor . ExtendedEnumDescriptor ) ) :
raise ValueError ( 'Cannot add descriptor of type %s' % ( type ( new_descriptor ) , ) )
full_name = self . __ComputeFullName ( new_descriptor . name )
if full_name in self . __... |
def extant_file ( x ) :
"""' Type ' for argparse - checks that file exists but does not open .""" | if not os . path . exists ( x ) :
raise argparse . ArgumentError ( "{0} does not exist" . format ( x ) )
return x |
def default_targets ( self ) :
"""Default targets for ` dvc repro ` and ` dvc pipeline ` .""" | from dvc . stage import Stage
msg = "assuming default target '{}'." . format ( Stage . STAGE_FILE )
logger . warning ( msg )
return [ Stage . STAGE_FILE ] |
def log ( self , msg , * args ) :
"""Logs a message to stderr .""" | if args :
msg %= args
click . echo ( msg , file = sys . stderr ) |
def load_config ( options ) :
'''Load options , platform , colors , and icons .''' | global opts , pform
opts = options
pform = options . pform
global_ns = globals ( )
# get colors
if pform . hicolor :
global_ns [ 'dim_templ' ] = ansi . dim8t
global_ns [ 'swap_clr_templ' ] = ansi . csi8_blk % ansi . blu8
else :
global_ns [ 'dim_templ' ] = ansi . dim4t
global_ns [ 'swap_clr_templ' ] = an... |
def parse_options_header ( value , multiple = False ) :
"""Parse a ` ` Content - Type ` ` like header into a tuple with the content
type and the options :
> > > parse _ options _ header ( ' text / html ; charset = utf8 ' )
( ' text / html ' , { ' charset ' : ' utf8 ' } )
This should not be used to parse ` `... | if not value :
return "" , { }
result = [ ]
value = "," + value . replace ( "\n" , "," )
while value :
match = _option_header_start_mime_type . match ( value )
if not match :
break
result . append ( match . group ( 1 ) )
# mimetype
options = { }
# Parse options
rest = match . gro... |
def MeetsConditions ( knowledge_base , source ) :
"""Check conditions on the source .""" | source_conditions_met = True
os_conditions = ConvertSupportedOSToConditions ( source )
if os_conditions :
source . conditions . append ( os_conditions )
for condition in source . conditions :
source_conditions_met &= artifact_utils . CheckCondition ( condition , knowledge_base )
return source_conditions_met |
def model_counts_map ( self , name = None , exclude = None , use_mask = False ) :
"""Return the model expectation map for a single source , a set
of sources , or all sources in the ROI . The map will be
computed using the current model parameters .
Parameters
name : str
Parameter that defines the sources ... | if self . projtype == "WCS" :
v = pyLike . FloatVector ( self . npix ** 2 * self . enumbins )
elif self . projtype == "HPX" :
v = pyLike . FloatVector ( np . max ( self . geom . npix ) * self . enumbins )
else :
raise Exception ( "Unknown projection type %s" , self . projtype )
exclude = utils . arg_to_list... |
def to_unix_ts ( start_time ) :
"""Given a datetime object , returns its value as a unix timestamp""" | if isinstance ( start_time , datetime ) :
if is_timezone_aware ( start_time ) :
start_time = start_time . astimezone ( pytz . utc )
else :
log . warning ( "Non timezone-aware datetime object passed to IncrementalEndpoint. " "The Zendesk API expects UTC time, if this is not the case results will ... |
def run_decoder ( self , prev_word : mx . nd . NDArray , bucket_key : Tuple [ int , int ] , model_state : 'ModelState' ) -> Tuple [ mx . nd . NDArray , mx . nd . NDArray , 'ModelState' ] :
"""Runs forward pass of the single - step decoder .
: param prev _ word : Previous word ids . Shape : ( batch * beam , ) .
... | batch_beam_size = prev_word . shape [ 0 ]
batch = mx . io . DataBatch ( data = [ prev_word . as_in_context ( self . context ) ] + model_state . states , label = None , bucket_key = bucket_key , provide_data = self . _get_decoder_data_shapes ( bucket_key , batch_beam_size ) )
self . decoder_module . forward ( data_batch... |
def remover ( self , id_model ) :
"""Remove Model from by the identifier .
: param id _ model : Identifier of the Model . Integer value and greater than zero .
: return : None
: raise InvalidParameterError : The identifier of Model is null and invalid .
: raise ModeloEquipamentoNaoExisteError : Model not re... | if not is_valid_int_param ( id_model ) :
raise InvalidParameterError ( u'The identifier of Model is invalid or was not informed.' )
url = 'model/' + str ( id_model ) + '/'
code , xml = self . submit ( None , 'DELETE' , url )
return self . response ( code , xml ) |
def licenses ( self , query = None , offset = None , limit = None , sample = None , sort = None , order = None , facet = None , ** kwargs ) :
'''Search Crossref licenses
: param query : [ String ] A query string
: param offset : [ Fixnum ] Number of record to start at , from 1 to 10000
: param limit : [ Fixnu... | check_kwargs ( [ "ids" , "filter" , "works" ] , kwargs )
res = request ( self . mailto , self . base_url , "/licenses/" , None , query , None , offset , limit , None , sort , order , facet , None , None , None , None , ** kwargs )
return res |
def check_function_args ( args , signatures , function_name ) :
"""Check function args - return message if function args don ' t match function signature
Called from validate _ functions
We have following types of arguments to validate :
1 . Required , position _ dependent arguments , e . g . p ( HGNC : AKT1 ... | messages = [ ]
arg_types = [ ]
for arg in args :
arg_type = arg . __class__ . __name__
if arg_type == "Function" :
arg_types . append ( ( arg . name , "" ) )
elif arg_type == "NSArg" :
arg_types . append ( ( arg_type , f"{arg.namespace}:{arg.value}" ) )
elif arg_type == "StrArg" :
... |
def stop ( self , timeout = None ) :
"""Stop the given command""" | if not timeout :
timeout = self . timeout
self . kill_switch ( )
# Send the signal to all the process groups
self . process . kill ( )
self . thread . join ( timeout )
try :
os . killpg ( os . getpgid ( self . process . pid ) , signal . SIGTERM )
except :
pass
if self . stopped :
return True
else :
... |
def validate_branchset ( self , branchset_node , depth , number , branchset ) :
"""See superclass ' method for description and signature specification .
Checks that the following conditions are met :
* First branching level must contain exactly one branchset , which
must be of type " sourceModel " .
* All o... | if depth == 0 :
if number > 0 :
raise LogicTreeError ( branchset_node , self . filename , 'there must be only one branch set ' 'on first branching level' )
elif branchset . uncertainty_type != 'sourceModel' :
raise LogicTreeError ( branchset_node , self . filename , 'first branchset must define ... |
def map_fn_switch ( fn , elems , use_map_fn = True , ** kwargs ) :
"""Construct the graph with either tf . map _ fn or a python for loop .
This function is mainly for for benchmarking purpose .
tf . map _ fn is dynamic but is much slower than creating a static graph with
for loop . However , having a for loop... | if use_map_fn :
return tf . map_fn ( fn , elems , ** kwargs )
elems_unpacked = ( tf . unstack ( e ) for e in elems )
out_unpacked = [ fn ( e ) for e in zip ( * elems_unpacked ) ]
out = tf . stack ( out_unpacked )
return out |
def parse_noaa_line ( line ) :
"""Parse NOAA stations .
This is an old list , the format is :
NUMBER NAME & STATE / COUNTRY LAT LON ELEV ( meters )
010250 TROMSO NO 6941N 01855E 10""" | station = { }
station [ 'station_name' ] = line [ 7 : 51 ] . strip ( )
station [ 'station_code' ] = line [ 0 : 6 ]
station [ 'CC' ] = line [ 55 : 57 ]
station [ 'ELEV(m)' ] = int ( line [ 73 : 78 ] )
station [ 'LAT' ] = _mlat ( line [ 58 : 64 ] )
station [ 'LON' ] = _mlon ( line [ 65 : 71 ] )
station [ 'ST' ] = line [ ... |
def lies_under ( self , prefix ) :
"""Indicates if the ` prefix ` is a parent of this path .""" | orig_list = self . norm_case ( ) . _components ( )
pref_list = self . __class__ ( prefix ) . norm_case ( ) . _components ( )
return ( len ( orig_list ) >= len ( pref_list ) and orig_list [ : len ( pref_list ) ] == pref_list ) |
def replace_grid ( self , updated_grid ) :
"""replace all cells in current grid with updated grid""" | for col in range ( self . get_grid_width ( ) ) :
for row in range ( self . get_grid_height ( ) ) :
if updated_grid [ row ] [ col ] == EMPTY :
self . set_empty ( row , col )
else :
self . set_full ( row , col ) |
def _add_batch ( self , TX_nodes , payment ) :
"""Method to add a payment as a batch . The transaction details are already
present . Will fold the nodes accordingly and the call the
_ add _ to _ batch _ list function to store the batch .""" | TX_nodes [ 'PmtIdNode' ] . append ( TX_nodes [ 'EndToEnd_PmtId_Node' ] )
TX_nodes [ 'AmtNode' ] . append ( TX_nodes [ 'InstdAmtNode' ] )
TX_nodes [ 'CdtTrfTxInfNode' ] . append ( TX_nodes [ 'PmtIdNode' ] )
TX_nodes [ 'CdtTrfTxInfNode' ] . append ( TX_nodes [ 'AmtNode' ] )
if TX_nodes [ 'BIC_CdtrAgt_Node' ] . text is no... |
def _list_files ( root ) :
"""Lists all of the files in a directory , taking into account any . gitignore
file that is present
: param root :
A unicode filesystem path
: return :
A list of unicode strings , containing paths of all files not ignored
by . gitignore with root , using relative paths""" | dir_patterns , file_patterns = _gitignore ( root )
paths = [ ]
prefix = os . path . abspath ( root ) + os . sep
for base , dirs , files in os . walk ( root ) :
for d in dirs :
for dir_pattern in dir_patterns :
if fnmatch ( d , dir_pattern ) :
dirs . remove ( d )
b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.