signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _diff_text ( left , right , verbose = False ) :
"""Return the explanation for the diff between text or bytes
Unless - - verbose is used this will skip leading and trailing
characters which are identical to keep the diff minimal .
If the input are bytes they will be safely converted to text .""" | from difflib import ndiff
explanation = [ ]
if isinstance ( left , py . builtin . bytes ) :
left = u ( repr ( left ) [ 1 : - 1 ] ) . replace ( r'\n' , '\n' )
if isinstance ( right , py . builtin . bytes ) :
right = u ( repr ( right ) [ 1 : - 1 ] ) . replace ( r'\n' , '\n' )
if not verbose :
i = 0
# just... |
def _prepare_wsdl_objects ( self ) :
"""This is the data that will be used to create your shipment . Create
the data structure and get it ready for the WSDL request .""" | # Default behavior is to not request transit information
self . ReturnTransitAndCommit = False
# This is the primary data structure for processShipment requests .
self . RequestedShipment = self . client . factory . create ( 'RequestedShipment' )
self . RequestedShipment . ShipTimestamp = datetime . datetime . now ( )
... |
async def get_vm ( self , vm_id ) :
"""Dummy get _ vm func""" | if vm_id not in self . _vms :
raise DummyIaasVmNotFound ( )
return self . _vms [ vm_id ] |
def h6_mahe ( simulated_array , observed_array , k = 1 , replace_nan = None , replace_inf = None , remove_neg = False , remove_zero = False ) :
"""Compute the H6 mean absolute error .
. . image : : / pictures / H6 . png
. . image : : / pictures / AHE . png
* * Range : * *
* * Notes : * *
Parameters
simu... | # Treats data
simulated_array , observed_array = treat_values ( simulated_array , observed_array , replace_nan = replace_nan , replace_inf = replace_inf , remove_neg = remove_neg , remove_zero = remove_zero )
top = ( simulated_array / observed_array - 1 )
bot = np . power ( 0.5 * ( 1 + np . power ( simulated_array / ob... |
def runQuery ( statDict , query ) :
"""Filters for the given query .""" | parts = [ x . strip ( ) for x in OPERATOR . split ( query ) ]
assert len ( parts ) in ( 1 , 3 )
queryKey = parts [ 0 ]
result = { }
for key , value in six . iteritems ( statDict ) :
if key == queryKey :
if len ( parts ) == 3 :
op = OPERATORS [ parts [ 1 ] ]
try :
quer... |
def cross_product_compare ( start , candidate1 , candidate2 ) :
"""Compare two relative changes by their cross - product .
This is meant to be a way to determine which vector is more " inside "
relative to ` ` start ` ` .
. . note : :
This is a helper for : func : ` _ simple _ convex _ hull ` .
Args :
s... | delta1 = candidate1 - start
delta2 = candidate2 - start
return cross_product ( delta1 , delta2 ) |
def create ( controller_id , name ) :
"""Turn class into a kervi controller""" | def _decorator ( cls ) :
class _ControllerClass ( cls , Controller ) :
def __init__ ( self ) :
Controller . __init__ ( self , controller_id , name )
for key in cls . __dict__ . keys ( ) :
prop = cls . __dict__ [ key ]
if isinstance ( prop , KerviValue ... |
def similarity ( self , other ) :
"""Compare two objects for similarity .
@ param self : first object to compare
@ param other : second object to compare
@ return : L { Similarity } result of comparison""" | sim = self . Similarity ( )
total = 0.0
# Calculate similarity ratio for each attribute
cname = self . __class__ . __name__
for aname , weight in self . attributes . items ( ) :
attr1 = getattr ( self , aname , None )
attr2 = getattr ( other , aname , None )
self . log ( attr1 , attr2 , '%' , cname = cname ... |
def get_varied_cfg_lbls ( cfg_list , default_cfg = None , mainkey = '_cfgname' , checkname = False ) :
r"""Args :
cfg _ list ( list ) :
default _ cfg ( None ) : ( default = None )
checkname ( bool ) : if True removes names if they are all the same .
Returns :
list : cfglbl _ list
CommandLine :
python ... | import utool as ut
try :
cfgname_list = [ cfg [ mainkey ] for cfg in cfg_list ]
except KeyError :
cfgname_list = [ '' ] * len ( cfg_list )
varied_cfg_list = partition_varied_cfg_list ( cfg_list , default_cfg ) [ 1 ]
if checkname and ut . allsame ( cfgname_list ) :
cfgname_list = [ None ] * len ( cfgname_lis... |
def _parseSpecType ( self , classString ) :
"""This class attempts to parse the spectral type . It should probably use more advanced matching use regex""" | try :
classString = str ( classString )
except UnicodeEncodeError : # This is for the benefit of 1RXS1609 which currently has the spectral type K7 \ pm 1V
# TODO add unicode support and handling for this case / ammend the target
return False
# some initial cases
if classString == '' or classString == 'nan' :
... |
def process_data ( self , file_info ) :
"""expects FileInfo""" | if self . _has_reached_stop_limit ( ) :
self . log . info ( "Remaining bytes in quota (%d) has reached minimum to request stop (%d)" , self . _quota . remaining , self . _stop_on_remaining )
self . fire ( events . TransmissionQuotaReached ( ) )
elif not self . _fits_in_quota ( file_info ) :
self . log . deb... |
def vector_drive ( self , vx , vy , vw , tm_diff ) :
"""Call this from your : func : ` PhysicsEngine . update _ sim ` function .
Will update the robot ' s position on the simulation field .
This moves the robot using a velocity vector relative to the robot
instead of by speed / rotation speed .
: param vx :... | # if the robot is disabled , don ' t do anything
if not self . robot_enabled :
return
angle = vw * tm_diff
vx = vx * tm_diff
vy = vy * tm_diff
x = vx * math . sin ( angle ) + vy * math . cos ( angle )
y = vx * math . cos ( angle ) + vy * math . sin ( angle )
self . distance_drive ( x , y , angle ) |
def _search_mapred_emu ( self , index , query ) :
"""Emulates a search request via MapReduce . Used in the case
where the transport supports MapReduce but has no native
search capability .""" | phases = [ ]
if not self . phaseless_mapred ( ) :
phases . append ( { 'language' : 'erlang' , 'module' : 'riak_kv_mapreduce' , 'function' : 'reduce_identity' , 'keep' : True } )
mr_result = self . mapred ( { 'module' : 'riak_search' , 'function' : 'mapred_search' , 'arg' : [ index , query ] } , phases )
result = { ... |
def makedirs ( name , mode = 0o777 , exist_ok = False ) :
"""cheapo replacement for py3 makedirs with support for exist _ ok""" | if os . path . exists ( name ) :
if not exist_ok :
raise FileExistsError ( "File exists: " + name )
else :
os . makedirs ( name , mode ) |
def resolve_multiple_existing_paths ( paths ) :
""": param paths : A list of paths to items that need to be resolved
: type paths : list
: returns : A dictionary mapping a specified path to either its resolved
object or Nones , if the object could not be resolved
: rtype : dict
For each input given in pat... | done_objects = { }
# Return value
to_resolve_in_batch_paths = [ ]
# Paths to resolve
to_resolve_in_batch_inputs = [ ]
# Project , folderpath , and entity name
for path in paths :
project , folderpath , entity_name = resolve_path ( path , expected = 'entity' )
try :
must_resolve , project , folderpath , ... |
def layout_spring ( self , num_dims = 2 , spring_constant = None , iterations = 50 , initial_temp = 0.1 , initial_layout = None ) :
'''Position vertices using the Fruchterman - Reingold ( spring ) algorithm .
num _ dims : int ( default = 2)
Number of dimensions to embed vertices in .
spring _ constant : float... | if initial_layout is None :
X = np . random . random ( ( self . num_vertices ( ) , num_dims ) )
else :
X = np . array ( initial_layout , dtype = float , copy = True )
assert X . shape == ( self . num_vertices ( ) , num_dims )
if spring_constant is None : # default to sqrt ( area _ of _ viewport / num _ vert... |
def send_rpc_message ( self , method , request ) :
'''Sends a Hadoop RPC request to the NameNode .
The IpcConnectionContextProto , RpcPayloadHeaderProto and HadoopRpcRequestProto
should already be serialized in the right way ( delimited or not ) before
they are passed in this method .
The Hadoop RPC protoco... | log . debug ( "############## SENDING ##############" )
# 0 . RpcRequestHeaderProto
rpc_request_header = self . create_rpc_request_header ( )
# 1 . RequestHeaderProto
request_header = self . create_request_header ( method )
# 2 . Param
param = request . SerializeToString ( )
if log . getEffectiveLevel ( ) == logging . ... |
def serialize ( obj ) :
"""JSON serializer for objects not serializable by default json code""" | if isinstance ( obj , datetime . datetime ) :
serial = obj . isoformat ( sep = 'T' )
return serial
if isinstance ( obj , uuid . UUID ) :
serial = str ( obj )
return serial
try :
return obj . __dict__
except AttributeError :
return str ( obj )
except Exception as e :
strval = 'unknown obj'
... |
def update_pypsa_storage ( pypsa , storages , storages_lines ) :
"""Adds storages and their lines to pypsa representation of the edisgo graph .
This function effects the following attributes of the pypsa network :
components ( ' StorageUnit ' ) , storage _ units , storage _ units _ t ( p _ set , q _ set ) ,
b... | bus = { 'name' : [ ] , 'v_nom' : [ ] , 'x' : [ ] , 'y' : [ ] }
line = { 'name' : [ ] , 'bus0' : [ ] , 'bus1' : [ ] , 'type' : [ ] , 'x' : [ ] , 'r' : [ ] , 's_nom' : [ ] , 'length' : [ ] }
storage = { 'name' : [ ] , 'bus' : [ ] , 'p_nom' : [ ] , 'state_of_charge_initial' : [ ] , 'efficiency_store' : [ ] , 'efficiency_d... |
def check_status ( status ) :
"""Check the status of a mkl functions and raise a python exeption if
there is an error .""" | if status :
msg = lib . DftiErrorMessage ( status )
msg = ctypes . c_char_p ( msg ) . value
raise RuntimeError ( msg ) |
def get_screen_size ( self , screen_no ) :
"""Returns the size of the given screen number""" | return GetScreenSize ( display = self . display , opcode = self . display . get_extension_major ( extname ) , window = self . id , screen = screen_no , ) |
def pspawn_wrapper ( self , sh , escape , cmd , args , env ) :
"""Wrapper function for handling piped spawns .
This looks to the calling interface ( in Action . py ) like a " normal "
spawn , but associates the call with the PSPAWN variable from
the construction environment and with the streams to which we
... | return self . pspawn ( sh , escape , cmd , args , env , self . logstream , self . logstream ) |
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) :
"""See : meth : ` superclass method
< . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > `
for spec of input and result values .""" | sites . vs30 = 700 * np . ones ( len ( sites . vs30 ) )
mean , stddevs = super ( ) . get_mean_and_stddevs ( sites , rup , dists , imt , stddev_types )
C = CauzziFaccioli2008SWISS01 . COEFFS
tau_ss = 'tau'
log_phi_ss = np . log ( 10 )
mean , stddevs = _apply_adjustments ( C , self . COEFFS_FS_ROCK [ imt ] , tau_ss , mea... |
def temp_unit ( self ) :
"""Get unit of temp .""" | if CONST . UNIT_FAHRENHEIT in self . _get_status ( CONST . TEMP_STATUS_KEY ) :
return CONST . UNIT_FAHRENHEIT
elif CONST . UNIT_CELSIUS in self . _get_status ( CONST . TEMP_STATUS_KEY ) :
return CONST . UNIT_CELSIUS
return None |
def create_action ( self ) :
"""Create actions associated with Annotations .""" | actions = { }
act = QAction ( 'New Annotations' , self )
act . triggered . connect ( self . new_annot )
actions [ 'new_annot' ] = act
act = QAction ( 'Load Annotations' , self )
act . triggered . connect ( self . load_annot )
actions [ 'load_annot' ] = act
act = QAction ( 'Clear Annotations...' , self )
act . triggered... |
def pairwise ( iterable ) :
"""From itertools cookbook . [ a , b , c , . . . ] - > ( a , b ) , ( b , c ) , . . .""" | first , second = tee ( iterable )
next ( second , None )
return zip ( first , second ) |
def register ( self , schema ) :
"""Register input schema class .
When registering a schema , all inner schemas are registered as well .
: param Schema schema : schema to register .
: return : old registered schema .
: rtype : type""" | result = None
uuid = schema . uuid
if uuid in self . _schbyuuid :
result = self . _schbyuuid [ uuid ]
if result != schema :
self . _schbyuuid [ uuid ] = schema
name = schema . name
schemas = self . _schbyname . setdefault ( name , set ( ) )
schemas . add ( schema )
for innername , innerschema in... |
def get_checksum ( file ) :
"""Get SHA256 hash from the contents of a given file""" | with open ( file , 'rb' ) as FH :
contents = FH . read ( )
return hashlib . sha256 ( contents ) . hexdigest ( ) |
def fetch ( self ) :
"""Fetch & return a new ` Tag ` object representing the tag ' s current state
: rtype : Tag
: raises DOAPIError : if the API endpoint replies with an error ( e . g . , if
the tag no longer exists )""" | api = self . doapi_manager
return api . _tag ( api . request ( self . url ) [ "tag" ] ) |
async def _async_get_data ( self , resource , id = None ) :
"""Get the data from the resource .""" | if id :
url = urljoin ( self . _api_url , "spc/{}/{}" . format ( resource , id ) )
else :
url = urljoin ( self . _api_url , "spc/{}" . format ( resource ) )
data = await async_request ( self . _session . get , url )
if not data :
return False
if id and isinstance ( data [ 'data' ] [ resource ] , list ) : # ... |
def remove ( self , observableElement ) :
"""remove an obsrvable element
: param str observableElement : the name of the observable element""" | if observableElement in self . _observables :
self . _observables . remove ( observableElement ) |
def set_accuracy ( self , acc ) :
"""Sets the accuracy order of the finite difference scheme .
If the FinDiff object is not a raw partial derivative but a composition of derivatives
the accuracy order will be propagated to the child operators .""" | self . acc = acc
if self . child :
self . child . set_accuracy ( acc ) |
def type ( self ) :
"""Returns the shape of the data array associated with this file .""" | hdu = self . open ( )
_type = hdu . data . dtype . name
if not self . inmemory :
self . close ( )
del hdu
return _type |
def delete_port_binding ( self , port , host ) :
"""Enqueue port binding delete""" | if not self . get_instance_type ( port ) :
return
for pb_key in self . _get_binding_keys ( port , host ) :
pb_res = MechResource ( pb_key , a_const . PORT_BINDING_RESOURCE , a_const . DELETE )
self . provision_queue . put ( pb_res ) |
def make_bag ( bag_dir , bag_info = None , processes = 1 , checksum = None ) :
"""Convert a given directory into a bag . You can pass in arbitrary
key / value pairs to put into the bag - info . txt metadata file as
the bag _ info dictionary .""" | bag_dir = os . path . abspath ( bag_dir )
logger . info ( "creating bag for directory %s" , bag_dir )
# assume md5 checksum if not specified
if not checksum :
checksum = [ 'md5' ]
if not os . path . isdir ( bag_dir ) :
logger . error ( "no such bag directory %s" , bag_dir )
raise RuntimeError ( "no such bag... |
def discard ( self , item ) :
'''Remove * item * .''' | index = self . _index ( item )
if index >= 0 :
del self . _members [ index ] |
def ckan_extension_template ( name , target ) :
"""Create ckanext - ( name ) in target directory .""" | setupdir = '{0}/ckanext-{1}theme' . format ( target , name )
extdir = setupdir + '/ckanext/{0}theme' . format ( name )
templatedir = extdir + '/templates/'
staticdir = extdir + '/static/datacats'
makedirs ( templatedir + '/home/snippets' )
makedirs ( staticdir )
here = dirname ( __file__ )
copyfile ( here + '/images/ch... |
def AgregarCTG ( self , nro_ctg = None , nro_carta_porte = None , porcentaje_secado_humedad = None , importe_secado = None , peso_neto_merma_secado = None , tarifa_secado = None , importe_zarandeo = None , peso_neto_merma_zarandeo = None , tarifa_zarandeo = None , peso_neto_confirmado_definitivo = None , ** kwargs ) :
... | ctg = dict ( nroCTG = nro_ctg , nroCartaDePorte = nro_carta_porte , pesoNetoConfirmadoDefinitivo = peso_neto_confirmado_definitivo , porcentajeSecadoHumedad = porcentaje_secado_humedad , importeSecado = importe_secado , pesoNetoMermaSecado = peso_neto_merma_secado , tarifaSecado = tarifa_secado , importeZarandeo = impo... |
def eth_getLogs ( self , from_block = BLOCK_TAG_LATEST , to_block = BLOCK_TAG_LATEST , address = None , topics = None ) :
"""https : / / github . com / ethereum / wiki / wiki / JSON - RPC # eth _ getlogs
: param from _ block : Block tag or number ( optional )
: type from _ block : int or BLOCK _ TAGS
: param ... | obj = { 'fromBlock' : validate_block ( from_block ) , 'toBlock' : validate_block ( to_block ) , 'address' : address , 'topics' : topics }
result = yield from self . rpc_call ( 'eth_getLogs' , [ obj ] )
return result |
def gen_code_api ( self ) :
"""TODO : Docstring for gen _ code _ api .""" | # edit config file
conf_editor = Editor ( self . conf_fpath )
# insert code path for searching
conf_editor . editline_with_regex ( r'^# import os' , 'import os' )
conf_editor . editline_with_regex ( r'^# import sys' , 'import sys' )
conf_editor . editline_with_regex ( r'^# sys\.path\.insert' , 'sys.path.insert(0, "{}")... |
def run_bafRegress ( filenames , out_prefix , extract_filename , freq_filename , options ) :
"""Runs the bafRegress function .
: param filenames : the set of all sample files .
: param out _ prefix : the output prefix .
: param extract _ filename : the name of the markers to extract .
: param freq _ filenam... | # The command
command = [ "bafRegress.py" , "estimate" , "--freqfile" , freq_filename , "--freqcol" , "2,5" , "--extract" , extract_filename , "--colsample" , options . colsample , "--colmarker" , options . colmarker , "--colbaf" , options . colbaf , "--colab1" , options . colab1 , "--colab2" , options . colab2 , ]
com... |
def check_error_code ( self ) :
"""For CredSSP version of 3 or newer , the server can response with an
NtStatus error code with details of what error occurred . This method
will check if the error code exists and throws an NTStatusException
if it is no STATUS _ SUCCESS .""" | # start off with STATUS _ SUCCESS as a baseline
status = NtStatusCodes . STATUS_SUCCESS
error_code = self [ 'errorCode' ]
if error_code . isValue : # ASN . 1 Integer is stored as an signed integer , we need to
# convert it to a unsigned integer
status = ctypes . c_uint32 ( error_code ) . value
if status != NtStatus... |
def get_sigma ( database_file_name = '' , e_min = np . NaN , e_max = np . NaN , e_step = np . NaN , t_kelvin = None ) :
"""retrieve the Energy and sigma axis for the given isotope
: param database _ file _ name : path / to / file with extension
: type database _ file _ name : string
: param e _ min : left ene... | file_extension = os . path . splitext ( database_file_name ) [ 1 ]
if t_kelvin is None : # ' . csv ' files
if file_extension != '.csv' :
raise IOError ( "Cross-section File type must be '.csv'" )
else :
_df = get_database_data ( file_name = database_file_name )
_dict = get_interpolated_d... |
def del_all_host_comments ( self , host ) :
"""Delete all host comments
Format of the line that triggers function call : :
DEL _ ALL _ HOST _ COMMENTS ; < host _ name >
: param host : host to edit
: type host : alignak . objects . host . Host
: return : None""" | comments = list ( host . comments . keys ( ) )
for uuid in comments :
host . del_comment ( uuid )
self . send_an_element ( host . get_update_status_brok ( ) ) |
def mark_flags_as_required ( flag_names , flag_values = _flagvalues . FLAGS ) :
"""Ensures that flags are not None during program execution .
Recommended usage :
if _ _ name _ _ = = ' _ _ main _ _ ' :
flags . mark _ flags _ as _ required ( [ ' flag1 ' , ' flag2 ' , ' flag3 ' ] )
app . run ( )
Args :
fla... | for flag_name in flag_names :
mark_flag_as_required ( flag_name , flag_values ) |
def get_vnetwork_dvs_output_vnetwork_dvs_interface_type ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_vnetwork_dvs = ET . Element ( "get_vnetwork_dvs" )
config = get_vnetwork_dvs
output = ET . SubElement ( get_vnetwork_dvs , "output" )
vnetwork_dvs = ET . SubElement ( output , "vnetwork-dvs" )
interface_type = ET . SubElement ( vnetwork_dvs , "interface-type" )
interface_type . te... |
def create_instances_from_matrices ( x , y = None , name = "data" ) :
"""Allows the generation of an Instances object from a 2 - dimensional matrix for X and a
1 - dimensional matrix for Y ( optional ) .
All data must be numerical . Attributes can be converted to nominal with the
weka . filters . unsupervised... | if y is not None :
if len ( x ) != len ( y ) :
raise Exception ( "Dimensions of x and y differ: " + str ( len ( x ) ) + " != " + str ( len ( y ) ) )
# create header
atts = [ ]
for i in range ( len ( x [ 0 ] ) ) :
atts . append ( Attribute . create_numeric ( "x" + str ( i + 1 ) ) )
if y is not None :
... |
def confirm_login_allowed ( self , user ) :
"""Controls whether the given User may log in . This is a policy setting ,
independent of end - user authentication . This default behavior is to
allow login by active users , and reject login by inactive users .
If the given user cannot log in , this method should ... | if not user . is_active :
raise forms . ValidationError ( self . error_messages [ 'inactive' ] , code = 'inactive' , ) |
def waypoint_request_list_send ( self ) :
'''wrapper for waypoint _ request _ list _ send''' | if self . mavlink10 ( ) :
self . mav . mission_request_list_send ( self . target_system , self . target_component )
else :
self . mav . waypoint_request_list_send ( self . target_system , self . target_component ) |
def multi_h1 ( cls , a_dict : Dict [ str , Any ] , bins = None , ** kwargs ) -> "HistogramCollection" :
"""Create a collection from multiple datasets .""" | from physt . binnings import calculate_bins
mega_values = np . concatenate ( list ( a_dict . values ( ) ) )
binning = calculate_bins ( mega_values , bins , ** kwargs )
title = kwargs . pop ( "title" , None )
name = kwargs . pop ( "name" , None )
collection = HistogramCollection ( binning = binning , title = title , nam... |
def get_next_first ( intersection , intersections , to_end = True ) :
"""Gets the next node along the current ( first ) edge .
. . note : :
This is a helper used only by : func : ` get _ next ` , which in
turn is only used by : func : ` basic _ interior _ combine ` , which itself
is only used by : func : ` ... | along_edge = None
index_first = intersection . index_first
s = intersection . s
for other_int in intersections :
other_s = other_int . s
if other_int . index_first == index_first and other_s > s :
if along_edge is None or other_s < along_edge . s :
along_edge = other_int
if along_edge is Non... |
def _TerminateProcess ( self , process ) :
"""Terminate a process .
Args :
process ( MultiProcessBaseProcess ) : process to terminate .""" | pid = process . pid
logger . warning ( 'Terminating process: (PID: {0:d}).' . format ( pid ) )
process . terminate ( )
# Wait for the process to exit .
process . join ( timeout = self . _PROCESS_JOIN_TIMEOUT )
if process . is_alive ( ) :
logger . warning ( 'Killing process: (PID: {0:d}).' . format ( pid ) )
sel... |
def plot_diagram ( ax , x , y , label = "S" , title = "syntenic" , gradient = True ) :
"""Part of the diagrams that are re - used . ( x , y ) marks the center of the
diagram . Label determines the modification to the " S " graph .""" | trackgap = .06
tracklen = .12
xa , xb = x - tracklen , x + tracklen
ya , yb = y + trackgap , y - trackgap
hsps = ( ( ( 60 , 150 ) , ( 50 , 130 ) ) , ( ( 190 , 225 ) , ( 200 , 240 ) ) , ( ( 330 , 280 ) , ( 360 , 310 ) ) )
for yy in ( ya , yb ) :
ax . plot ( ( xa , xb ) , ( yy , yy ) , "-" , color = "gray" , lw = 2 ,... |
def app ( self ) :
"""Internal method that will supply the app to use internally .
Returns :
flask . Flask : The app to use within the component .
Raises :
RuntimeError : This is raised if no app was provided to the
component and the method is being called outside of an
application context .""" | app = self . _app or current_app
if not in_app_context ( app ) :
raise RuntimeError ( "This component hasn't been initialized yet " "and an app context doesn't exist." )
# If current _ app is the app , this must be used in order for their IDs
# to be the same , as current _ app will wrap the app in a proxy .
if has... |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : FaxMediaContext for this FaxMediaInstance
: rtype : twilio . rest . fax . v1 . fax . fax _ media . FaxMediaContext""" | if self . _context is None :
self . _context = FaxMediaContext ( self . _version , fax_sid = self . _solution [ 'fax_sid' ] , sid = self . _solution [ 'sid' ] , )
return self . _context |
def delete ( self , key , sort_key ) :
primary_key = key
key = self . prefixed ( '{}:{}' . format ( key , sort_key ) )
"""Delete an element in dictionary""" | self . logger . debug ( 'Storage - delete {}' . format ( key ) )
if sort_key is not None :
self . cache [ self . prefixed ( primary_key ) ] . remove ( sort_key )
for index in self . _secondary_indexes :
obj = json . loads ( self . cache [ key ] )
if index in obj . keys ( ) :
self . cache [ 'secondar... |
def _parse_create_args ( client , args ) :
"""Converts CLI arguments to args for VSManager . create _ instance .
: param dict args : CLI arguments""" | data = { "hourly" : args . get ( 'billing' , 'hourly' ) == 'hourly' , "cpus" : args . get ( 'cpu' , None ) , "ipv6" : args . get ( 'ipv6' , None ) , "disks" : args . get ( 'disk' , None ) , "os_code" : args . get ( 'os' , None ) , "memory" : args . get ( 'memory' , None ) , "flavor" : args . get ( 'flavor' , None ) , "... |
def render ( self , context , instance , placeholder ) :
'''Allows this plugin to use templates designed for a list of locations .''' | context = super ( LocationPlugin , self ) . render ( context , instance , placeholder )
context [ 'location_list' ] = [ instance . location , ]
return context |
def to_index ( self , index_type , index_name , includes = None ) :
"""Create an index field from this field""" | return IndexField ( self . name , self . data_type , index_type , index_name , includes ) |
def _initialize ( self , funs_to_tally , length ) :
"""Create a group named ` ` chain # ` ` to store all data for this chain .""" | chain = self . nchains
self . _chains [ chain ] = self . _h5file . create_group ( '/' , 'chain%d' % chain , 'chain #%d' % chain )
for name , fun in six . iteritems ( funs_to_tally ) :
arr = np . asarray ( fun ( ) )
assert arr . dtype != np . dtype ( 'object' )
array = self . _h5file . createEArray ( self . ... |
def process_parsed_coords ( coords ) :
"""Takes a set of parsed coordinates , which come as an array of strings ,
and returns a numpy array of floats .""" | geometry = np . zeros ( shape = ( len ( coords ) , 3 ) , dtype = float )
for ii , entry in enumerate ( coords ) :
for jj in range ( 3 ) :
geometry [ ii , jj ] = float ( entry [ jj ] )
return geometry |
def __fillablebox ( msg , title = "" , default = "" , mask = None , image = None , root = None ) :
"""Show a box in which a user can enter some text .
You may optionally specify some default text , which will appear in the
enterbox when it is displayed .
Returns the text that the user entered , or None if he ... | if sys . platform == 'darwin' :
_bring_to_front ( )
global boxRoot , __enterboxText , __enterboxDefaultText
global cancelButton , entryWidget , okButton
if title is None :
title = ""
if default is None :
default = ""
__enterboxDefaultText = default
__enterboxText = __enterboxDefaultText
if root :
root .... |
def generate ( env ) :
"""Add Builders and construction variables for cyglink to an Environment .""" | gnulink . generate ( env )
env [ 'LINKFLAGS' ] = SCons . Util . CLVar ( '-Wl,-no-undefined' )
env [ 'SHLINKCOM' ] = shlib_action
env [ 'LDMODULECOM' ] = ldmod_action
env . Append ( SHLIBEMITTER = [ shlib_emitter ] )
env . Append ( LDMODULEEMITTER = [ ldmod_emitter ] )
env [ 'SHLIBPREFIX' ] = 'cyg'
env [ 'SHLIBSUFFIX' ]... |
def folderitem ( self , obj , item , index ) :
"""Service triggered each time an item is iterated in folderitems .
The use of this service prevents the extra - loops in child objects .
: obj : the instance of the class to be foldered
: item : dict containing the properties of the object to be used by
the te... | title = obj . Title ( )
description = obj . Description ( )
url = obj . absolute_url ( )
item [ "replace" ] [ "Title" ] = get_link ( url , value = title )
item [ "Description" ] = description
sample_types = obj . getSampleTypes ( )
if sample_types :
links = map ( lambda st : get_link ( st . absolute_url ( ) , value... |
def add_subplot ( self , x , y , n , margin = 0.05 ) :
"""Creates a div child subplot in a matplotlib . figure . add _ subplot style .
Parameters
x : int
The number of rows in the grid .
y : int
The number of columns in the grid .
n : int
The cell number in the grid , counted from 1 to x * y .
Examp... | width = 1. / y
height = 1. / x
left = ( ( n - 1 ) % y ) * width
top = ( ( n - 1 ) // y ) * height
left = left + width * margin
top = top + height * margin
width = width * ( 1 - 2. * margin )
height = height * ( 1 - 2. * margin )
div = Div ( position = 'absolute' , width = '{}%' . format ( 100. * width ) , height = '{}%... |
def from_api_repr ( cls , resource , zone ) :
"""Factory : construct a change set given its API representation
: type resource : dict
: param resource : change set representation returned from the API .
: type zone : : class : ` google . cloud . dns . zone . ManagedZone `
: param zone : A zone which holds z... | changes = cls ( zone = zone )
changes . _set_properties ( resource )
return changes |
def get_ssl_context ( private_key , certificate ) :
"""Get ssl context from private key and certificate paths .
The return value is used when calling Flask .
i . e . app . run ( ssl _ context = get _ ssl _ context ( , , , ) )""" | if ( certificate and os . path . isfile ( certificate ) and private_key and os . path . isfile ( private_key ) ) :
context = ssl . SSLContext ( ssl . PROTOCOL_TLSv1_2 )
context . load_cert_chain ( certificate , private_key )
return context
return None |
def all_build_jobs ( self ) :
"""Similar to build _ jobs ,
but uses the default manager to return archived experiments as well .""" | from db . models . build_jobs import BuildJob
return BuildJob . all . filter ( project = self ) |
def wrap_handler ( cls , handler , protocol , ** kwargs ) :
'''Wrap a request handler with the matching protocol handler''' | def _wrapper ( request , * args , ** kwargs ) :
instance = cls ( request = request , ** kwargs )
if protocol == Resource . Protocol . http :
return instance . _wrap_http ( handler , request = request , ** kwargs )
elif protocol == Resource . Protocol . websocket :
return instance . _wrap_ws ... |
def pf_post_lopf ( network , args , extra_functionality , add_foreign_lopf ) :
"""Function that prepares and runs non - linar load flow using PyPSA pf .
If network has been extendable , a second lopf with reactances adapted to
new s _ nom is needed .
If crossborder lines are DC - links , pf is only applied on... | network_pf = network
# Update x of extended lines and transformers
if network_pf . lines . s_nom_extendable . any ( ) or network_pf . transformers . s_nom_extendable . any ( ) :
storages_extendable = network_pf . storage_units . p_nom_extendable . copy ( )
lines_extendable = network_pf . lines . s_nom_extendabl... |
def load ( filename ) :
"""Load a CameraIntrinsics object from a file .
Parameters
filename : : obj : ` str `
The . intr file to load the object from .
Returns
: obj : ` CameraIntrinsics `
The CameraIntrinsics object loaded from the file .
Raises
ValueError
If filename does not have the . intr ext... | file_root , file_ext = os . path . splitext ( filename )
if file_ext . lower ( ) != INTR_EXTENSION :
raise ValueError ( 'Extension %s not supported for CameraIntrinsics. Must be stored with extension %s' % ( file_ext , INTR_EXTENSION ) )
f = open ( filename , 'r' )
ci = json . load ( f )
f . close ( )
return Orthog... |
def _do_else ( self , rule , p_selectors , p_parents , p_children , scope , media , c_lineno , c_property , c_codestr , code , name ) :
"""Implements @ else""" | if '@if' not in rule [ OPTIONS ] :
log . error ( "@else with no @if (%s" , rule [ INDEX ] [ rule [ LINENO ] ] )
val = rule [ OPTIONS ] . pop ( '@if' , True )
if not val :
rule [ CODESTR ] = c_codestr
self . manage_children ( rule , p_selectors , p_parents , p_children , scope , media ) |
def _ensure_values ( data : Mapping [ str , Any ] ) -> Tuple [ Dict [ str , Any ] , bool ] :
"""Make sure we have appropriate keys and say if we should write""" | to_return = { }
should_write = False
for keyname , typekind , default in REQUIRED_DATA :
if keyname not in data :
LOG . debug ( f"Defaulted config value {keyname} to {default}" )
to_return [ keyname ] = default
should_write = True
elif not isinstance ( data [ keyname ] , typekind ) :
... |
def load_wc ( cls , stream ) :
"""Return a ` Wilson ` instance initialized by a WCxf file - like object""" | wc = wcxf . WC . load ( stream )
return cls . from_wc ( wc ) |
def plot ( self , wavelengths = None , ** kwargs ) : # pragma : no cover
"""Plot the spectrum .
. . note : : Uses ` ` matplotlib ` ` .
Parameters
wavelengths : array - like , ` ~ astropy . units . quantity . Quantity ` , or ` None `
Wavelength values for sampling .
If not a Quantity , assumed to be in Ang... | w , y = self . _get_arrays ( wavelengths )
self . _do_plot ( w , y , ** kwargs ) |
def set_dwelling_current ( self , settings ) :
'''Sets the amperage of each motor for when it is dwelling .
Values are initialized from the ` robot _ config . log _ current ` values ,
and can then be changed through this method by other parts of the API .
For example , ` Pipette ` setting the dwelling - curre... | self . _dwelling_current_settings [ 'now' ] . update ( settings )
# if an axis specified in the ` settings ` is currently dwelling ,
# reset it ' s current to the new dwelling - current value
dwelling_axes_to_update = { axis : amps for axis , amps in self . _dwelling_current_settings [ 'now' ] . items ( ) if self . _ac... |
def _parse_supl ( content ) :
"""Parse supplemental measurements data .
Parameters
content : str
Data to parse
Returns
: class : ` pandas . DataFrame ` containing the data""" | col_names = [ 'year' , 'month' , 'day' , 'hour' , 'minute' , 'hourly_low_pressure' , 'hourly_low_pressure_time' , 'hourly_high_wind' , 'hourly_high_wind_direction' , 'hourly_high_wind_time' ]
col_units = { 'hourly_low_pressure' : 'hPa' , 'hourly_low_pressure_time' : None , 'hourly_high_wind' : 'meters/second' , 'hourly... |
def read ( self , n ) :
"""Read * n * bytes from the subprocess ' output channel .
Args :
n ( int ) : The number of bytes to read .
Returns :
bytes : * n * bytes of output .
Raises :
EOFError : If the process exited .""" | d = b''
while n :
try :
block = self . _process . stdout . read ( n )
except ValueError :
block = None
if not block :
self . _process . poll ( )
raise EOFError ( 'Process ended' )
d += block
n -= len ( block )
return d |
def dewpoint_rh ( temperature , rh ) :
r"""Calculate the ambient dewpoint given air temperature and relative humidity .
Parameters
temperature : ` pint . Quantity `
Air temperature
rh : ` pint . Quantity `
Relative humidity expressed as a ratio in the range 0 < rh < = 1
Returns
` pint . Quantity `
T... | if np . any ( rh > 1.2 ) :
warnings . warn ( 'Relative humidity >120%, ensure proper units.' )
return dewpoint ( rh * saturation_vapor_pressure ( temperature ) ) |
def describe_tile ( self , index ) :
"""Get the registration information for the tile at the given index .""" | if index >= len ( self . tile_manager . registered_tiles ) :
tile = TileInfo . CreateInvalid ( )
else :
tile = self . tile_manager . registered_tiles [ index ]
return tile . registration_packet ( ) |
def unicast ( self , socket_id , event , data ) :
"""Sends an event to a single socket . Returns ` True ` if that
worked or ` False ` if not .""" | payload = self . _server . serialize_event ( event , data )
rv = self . _server . sockets . get ( socket_id )
if rv is not None :
rv . socket . send ( payload )
return True
return False |
def _to_datalibrary_safe ( fname , gi , folder_name , sample_info , config ) :
"""Upload with retries for intermittent JSON failures .""" | num_tries = 0
max_tries = 5
while 1 :
try :
_to_datalibrary ( fname , gi , folder_name , sample_info , config )
break
except ( simplejson . scanner . JSONDecodeError , bioblend . galaxy . client . ConnectionError ) as e :
num_tries += 1
if num_tries > max_tries :
rais... |
def _put_subject ( self , subject_id , body ) :
"""Update a subject for the given subject id . The body is not
a list but a dictionary of a single resource .""" | assert isinstance ( body , ( dict ) ) , "PUT requires body to be dict."
# subject _ id could be a path such as ' / asset / 123 ' so quote
uri = self . _get_subject_uri ( guid = subject_id )
return self . service . _put ( uri , body ) |
def complete ( self , msg ) :
"""Called to complete a transaction , usually when ProcessIO has
shipped the IOCB off to some other thread or function .""" | if _debug :
IOCB . _debug ( "complete(%d) %r" , self . ioID , msg )
if self . ioController : # pass to controller
self . ioController . complete_io ( self , msg )
else : # just fill in the data
self . ioState = COMPLETED
self . ioResponse = msg
self . trigger ( ) |
def restore ( self ) :
"""Restore the saved value for the attribute of the object .""" | if self . proxy_object is None :
if self . getter :
setattr ( self . getter_class , self . attr_name , self . getter )
elif self . is_local :
setattr ( self . orig_object , self . attr_name , self . orig_value )
else : # Was not a local , safe to delete :
delattr ( self . orig_object... |
def copy ( self , existing_inputs ) :
"""Creates a copy of self using existing input placeholders .""" | return PPOPolicyGraph ( self . observation_space , self . action_space , self . config , existing_inputs = existing_inputs ) |
def add_members ( current ) :
"""Subscribe member ( s ) to a channel
. . code - block : : python
# request :
' view ' : ' _ zops _ add _ members ' ,
' channel _ key ' : key ,
' read _ only ' : boolean , # true if this is a Broadcast channel ,
# false if it ' s a normal chat room
' members ' : [ key , ... | newly_added , existing = [ ] , [ ]
read_only = current . input [ 'read_only' ]
for member_key in current . input [ 'members' ] :
sb , new = Subscriber ( current ) . objects . get_or_create ( user_id = member_key , read_only = read_only , channel_id = current . input [ 'channel_key' ] )
if new :
newly_ad... |
def _print_fields ( self , fields ) :
"""Print the fields , padding the names as necessary to align them .""" | # Prepare a formatting string that aligns the names and types based on the longest ones
longest_name = max ( fields , key = lambda f : len ( f [ 1 ] ) ) [ 1 ]
longest_type = max ( fields , key = lambda f : len ( f [ 2 ] ) ) [ 2 ]
field_format = '%s%-{}s %-{}s %s' . format ( len ( longest_name ) + self . _padding_after_... |
def minify ( compiled ) :
"""Perform basic minifications .
Fails on non - tabideal indentation or a string with a # .""" | compiled = compiled . strip ( )
if compiled :
out = [ ]
for line in compiled . splitlines ( ) :
line = line . split ( "#" , 1 ) [ 0 ] . rstrip ( )
if line :
ind = 0
while line . startswith ( " " ) :
line = line [ 1 : ]
ind += 1
... |
def Run ( self ) :
"Execute the action" | inputs = self . GetInput ( )
return SendInput ( len ( inputs ) , ctypes . byref ( inputs ) , ctypes . sizeof ( INPUT ) ) |
def RepositoryName ( self ) :
"""FullName after removing the local path to the repository .
If we have a real absolute path name here we can try to do something smart :
detecting the root of the checkout and truncating / path / to / checkout from
the name so that we get header guards that don ' t include thin... | fullname = self . FullName ( )
if os . path . exists ( fullname ) :
project_dir = os . path . dirname ( fullname )
if os . path . exists ( os . path . join ( project_dir , ".svn" ) ) : # If there ' s a . svn file in the current directory , we recursively look
# up the directory tree for the top of the SVN c... |
def integerize ( self ) :
"""Convert co - ordinate values to integers .""" | self . x = int ( round ( self . x ) )
self . y = int ( round ( self . y ) ) |
def __get_gaas_hmac_headers ( self , method , url , date = None , body = None , secret = None , userId = None ) :
"""Note : this documentation was copied for the Java client for GP .
Generate GaaS HMAC credentials used for HTTP Authorization header .
GaaS HMAC uses HMAC SHA1 algorithm signing a message composed... | if not date :
date = self . __get_RFC1123_date ( )
message = str ( method ) + '\n' + str ( url ) + '\n' + str ( date ) + '\n'
if body :
message += str ( body )
if not secret :
secret = self . __serviceAccount . get_password ( )
secret = bytes ( secret . encode ( self . __ENCODINGFORMAT ) )
message = bytes (... |
def crop ( stream , x , y , width , height , ** kwargs ) :
"""Crop the input video .
Args :
x : The horizontal position , in the input video , of the left edge of
the output video .
y : The vertical position , in the input video , of the top edge of the
output video .
width : The width of the output vid... | return FilterNode ( stream , crop . __name__ , args = [ width , height , x , y ] , kwargs = kwargs ) . stream ( ) |
def get_prep_value ( self , value ) :
"""Return the integer value to be stored from the hex string""" | if value is None or value == "" :
return None
if isinstance ( value , six . string_types ) :
value = _hex_string_to_unsigned_integer ( value )
if _using_signed_storage ( ) :
value = _unsigned_to_signed_integer ( value )
return value |
def distance_similarity ( a , b , p , T = CLOSE_DISTANCE_THRESHOLD ) :
"""Computes the distance similarity between a line segment
and a point
Args :
a ( [ float , float ] ) : x and y coordinates . Line start
b ( [ float , float ] ) : x and y coordinates . Line end
p ( [ float , float ] ) : x and y coordin... | d = distance_to_line ( a , b , p )
r = ( - 1 / float ( T ) ) * abs ( d ) + 1
return r if r > 0 else 0 |
def query_all ( ) :
'''查询大类记录''' | recs = TabTag . select ( ) . where ( TabTag . uid . endswith ( '00' ) ) . order_by ( TabTag . uid )
return recs |
def message ( subject , message , access_token , all_members = False , project_member_ids = None , base_url = OH_BASE_URL ) :
"""Send an email to individual users or in bulk . To learn more about Open
Humans OAuth2 projects , go to :
https : / / www . openhumans . org / direct - sharing / oauth2 - features /
... | url = urlparse . urljoin ( base_url , '/api/direct-sharing/project/message/?{}' . format ( urlparse . urlencode ( { 'access_token' : access_token } ) ) )
if not ( all_members ) and not ( project_member_ids ) :
response = requests . post ( url , data = { 'subject' : subject , 'message' : message } )
handle_error... |
def _at ( self , t ) :
"""Compute the GCRS position and velocity of this Topos at time ` t ` .""" | pos , vel = terra ( self . latitude . radians , self . longitude . radians , self . elevation . au , t . gast )
pos = einsum ( 'ij...,j...->i...' , t . MT , pos )
vel = einsum ( 'ij...,j...->i...' , t . MT , vel )
if self . x :
R = rot_y ( self . x * ASEC2RAD )
pos = einsum ( 'ij...,j...->i...' , R , pos )
if s... |
def helical_turbulent_Nu_Schmidt ( Re , Pr , Di , Dc ) :
r'''Calculates Nusselt number for a fluid flowing inside a curved
pipe such as a helical coil under turbulent conditions , using the method of
Schmidt [ 1 ] _ , also shown in [ 2 ] _ , [ 3 ] _ , and [ 4 ] _ .
For : math : ` Re _ { crit } < Re < 2.2 \ ti... | D_ratio = Di / Dc
if Re <= 2.2E4 :
term = Re ** ( 0.8 - 0.22 * D_ratio ** 0.1 ) * Pr ** ( 1 / 3. )
return 0.023 * ( 1. + 14.8 * ( 1. + D_ratio ) * D_ratio ** ( 1 / 3. ) ) * term
else :
return 0.023 * ( 1. + 3.6 * ( 1. - D_ratio ) * D_ratio ** 0.8 ) * Re ** 0.8 * Pr ** ( 1 / 3. ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.