signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def to_dataframe ( self ) :
"""Convert the confusion matrix to a dataframe .
Returns :
A DataFrame with " target " , " predicted " , " count " columns .""" | data = [ ]
for target_index , target_row in enumerate ( self . _cm ) :
for predicted_index , count in enumerate ( target_row ) :
data . append ( ( self . _labels [ target_index ] , self . _labels [ predicted_index ] , count ) )
return pd . DataFrame ( data , columns = [ 'target' , 'predicted' , 'count' ] ) |
def result ( self , wait = 0 ) :
"""return the full list of results from the chain when it finishes . blocks until timeout .
: param int wait : how many milliseconds to wait for a result
: return : an unsorted list of results""" | if self . started :
return result_group ( self . group , wait = wait , count = self . length ( ) , cached = self . cached ) |
async def execute ( self , query , * , dc = None , near = None , limit = None , consistency = None ) :
"""Executes a prepared query
Parameters :
query ( ObjectID ) : Query ID
dc ( str ) : Specify datacenter that will be used .
Defaults to the agent ' s local datacenter .
near ( str ) : Sort the resulting ... | query_id = extract_attr ( query , keys = [ "ID" ] )
response = await self . _api . get ( "/v1/query/%s/execute" % query_id , params = { "dc" : dc , "near" : near , "limit" : limit } , consistency = consistency )
return response . body |
def _ctype_key_value ( keys , vals ) :
"""Returns ctype arrays for the key - value args , and the whether string keys are used .
For internal use only .""" | if isinstance ( keys , ( tuple , list ) ) :
assert ( len ( keys ) == len ( vals ) )
c_keys = [ ]
c_vals = [ ]
use_str_keys = None
for key , val in zip ( keys , vals ) :
c_key_i , c_val_i , str_keys_i = _ctype_key_value ( key , val )
c_keys += c_key_i
c_vals += c_val_i
... |
def geom2shp ( geom , out_fn , fields = False ) :
"""Write out a new shapefile for input geometry""" | from pygeotools . lib import timelib
driverName = "ESRI Shapefile"
drv = ogr . GetDriverByName ( driverName )
if os . path . exists ( out_fn ) :
drv . DeleteDataSource ( out_fn )
out_ds = drv . CreateDataSource ( out_fn )
out_lyrname = os . path . splitext ( os . path . split ( out_fn ) [ 1 ] ) [ 0 ]
geom_srs = geo... |
def provision ( self , instance_id : str , service_details : ProvisionDetails , async_allowed : bool ) -> ProvisionedServiceSpec :
"""Provision the new instance
see openbrokerapi documentation
Returns :
ProvisionedServiceSpec""" | if service_details . plan_id == self . _backend . config . UUID_PLANS_EXISTING_CLUSTER : # Provision the instance on an Existing Atlas Cluster
# Find or create the instance
instance = self . _backend . find ( instance_id )
# Create the instance if needed
return self . _backend . create ( instance , service_... |
def to_iso639_1 ( key ) :
"""Find ISO 639-1 code for language specified by key .
> > > to _ iso639_1 ( " swe " )
u ' sv '
> > > to _ iso639_1 ( " English " )
u ' en '""" | item = find ( whatever = key )
if not item :
raise NonExistentLanguageError ( 'Language does not exist.' )
return item [ u'iso639_1' ] |
def dialog_open ( self , * , dialog : dict , trigger_id : str , ** kwargs ) -> SlackResponse :
"""Open a dialog with a user .
Args :
dialog ( dict ) : A dictionary of dialog arguments .
" callback _ id " : " 46eh782b0 " ,
" title " : " Request something " ,
" submit _ label " : " Request " ,
" state " :... | kwargs . update ( { "dialog" : dialog , "trigger_id" : trigger_id } )
return self . api_call ( "dialog.open" , json = kwargs ) |
def _decode_response ( response ) :
"""Strip off Gerrit ' s magic prefix and decode a response .
: returns :
Decoded JSON content as a dict , or raw text if content could not be
decoded as JSON .
: raises :
requests . HTTPError if the response contains an HTTP error status code .""" | content_type = response . headers . get ( 'content-type' , '' )
logger . debug ( "status[%s] content_type[%s] encoding[%s]" % ( response . status_code , content_type , response . encoding ) )
response . raise_for_status ( )
content = response . content . strip ( )
if response . encoding :
content = content . decode... |
def p_genvar ( self , p ) :
'genvar : ID' | p [ 0 ] = Genvar ( name = p [ 1 ] , width = Width ( msb = IntConst ( '31' , lineno = p . lineno ( 1 ) ) , lsb = IntConst ( '0' , lineno = p . lineno ( 1 ) ) , lineno = p . lineno ( 1 ) ) , lineno = p . lineno ( 1 ) )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def process ( self , input_data , topic = None ) :
"""Invokes each handler in sequence .
Publishes final output data .
Params :
input _ data : message received by stream
topic : name of plugin or stream message received from ,
if applicable""" | for handler in self . handlers :
output = handler . handle ( input_data )
input_data = output
self . publish ( input_data ) |
def setup ( self , redis_conn = None , host = 'localhost' , port = 6379 ) :
'''Set up the redis connection''' | if redis_conn is None :
if host is not None and port is not None :
self . redis_conn = redis . Redis ( host = host , port = port )
else :
raise Exception ( "Please specify some form of connection " "to Redis" )
else :
self . redis_conn = redis_conn
self . redis_conn . info ( ) |
def bump ( self , level = 'patch' , label = None ) :
"""Bump version following semantic versioning rules .""" | bump = self . _bump_pre if level == 'pre' else self . _bump
bump ( level , label ) |
def K2findCampaigns_byname_main ( args = None ) :
"""Exposes K2findCampaigns to the command line .""" | parser = argparse . ArgumentParser ( description = "Check if a target is " "(or was) observable by any past or future " "observing campaign of NASA's K2 mission." )
parser . add_argument ( 'name' , nargs = 1 , type = str , help = "Name of the object. This will be passed on " "to the CDS name resolver " "to retrieve co... |
def _verify_include_files_used ( self , file_uses , included_files ) :
"""Find all # include files that are unnecessary .""" | for include_file , use in file_uses . items ( ) :
if not use & USES_DECLARATION :
node , module = included_files [ include_file ]
if module . ast_list is not None :
msg = "'{}' does not need to be #included" . format ( node . filename )
if use & USES_REFERENCE :
... |
def set_state ( self , light_id , ** kwargs ) :
'''Sets state on the light , can be used like this :
. . code - block : : python
set _ state ( 1 , xy = [ 1,2 ] )''' | light = self . get_light ( light_id )
url = '/api/%s/lights/%s/state' % ( self . username , light . light_id )
response = self . make_request ( 'PUT' , url , kwargs )
setting_count = len ( kwargs . items ( ) )
success_count = 0
for data in response :
if 'success' in data :
success_count += 1
if success_coun... |
def _init_metadata ( self ) :
"""stub""" | self . _published_metadata = { 'element_id' : Id ( self . my_osid_object_form . _authority , self . my_osid_object_form . _namespace , 'published' ) , 'element_label' : 'Published' , 'instructions' : 'flags if item is published or not' , 'required' : False , 'read_only' : False , 'linked' : False , 'array' : False , 'd... |
def CreateSubsetFile ( in_drainage_line , river_id , out_riv_bas_id_file , file_geodatabase = None ) :
"""Creates River Basin ID subset input CSV file for RAPID
based on the Drainage Line shapefile with river ID and
next downstream ID fields
Parameters
in _ drainage _ line : str
Path to the stream network... | ogr_drainage_line_shapefile_lyr , ogr_drainage_line_shapefile = open_shapefile ( in_drainage_line , file_geodatabase )
ogr_drainage_line_definition = ogr_drainage_line_shapefile_lyr . GetLayerDefn ( )
orig_field_names = [ ]
for idx in xrange ( ogr_drainage_line_definition . GetFieldCount ( ) ) :
orig_field_names . ... |
def print_subtree ( self , fobj = sys . stdout , level = 0 ) :
"""Print this group node and the subtree rooted at it""" | fobj . write ( "{}{!r}\n" . format ( " " * ( level * 2 ) , self ) )
for child in self . get_children ( ) :
child . print_subtree ( fobj , level + 1 ) |
def get_segment_length ( linestring : LineString , p : Point , q : Optional [ Point ] = None ) -> float :
"""Given a Shapely linestring and two Shapely points ,
project the points onto the linestring , and return the distance
along the linestring between the two points .
If ` ` q is None ` ` , then return the... | # Get projected distances
d_p = linestring . project ( p )
if q is not None :
d_q = linestring . project ( q )
d = abs ( d_p - d_q )
else :
d = d_p
return d |
def _fake_closeenumeration ( self , namespace , ** params ) :
"""Implements WBEM server responder for
: meth : ` ~ pywbem . WBEMConnection . CloseEnumeration `
with data from the instance repository .
If the EnumerationContext is valid it removes it from the
context repository . Otherwise it returns an exce... | self . _validate_namespace ( namespace )
context_id = params [ 'EnumerationContext' ]
try :
context_data = self . enumeration_contexts [ context_id ]
except KeyError :
raise CIMError ( CIM_ERR_INVALID_ENUMERATION_CONTEXT , _format ( "EnumerationContext {0!A} not found in mock server " "enumeration contexts." , ... |
def copy_from_scratch ( file_mapping , dry_run = True ) :
"""Copy output files from scratch area""" | for key , value in file_mapping . items ( ) :
if dry_run :
print ( "copy %s %s" % ( value , key ) )
else :
try :
outdir = os . path . dirname ( key )
os . makedirs ( outdir )
except OSError :
pass
print ( "copy %s %s" % ( value , key ) )
... |
def set_input_focus ( self , focus , revert_to , time , onerror = None ) :
"""Set input focus to focus , which should be a window ,
X . PointerRoot or X . NONE . revert _ to specifies where the focus
reverts to if the focused window becomes not visible , and should
be X . RevertToParent , RevertToPointerRoot ... | request . SetInputFocus ( display = self . display , onerror = onerror , revert_to = revert_to , focus = focus , time = time ) |
def getApplicationsErrorNameFromEnum ( self , error ) :
"""Returns a string for an applications error""" | fn = self . function_table . getApplicationsErrorNameFromEnum
result = fn ( error )
return result |
def read_pod_security_policy ( self , name , ** kwargs ) : # noqa : E501
"""read _ pod _ security _ policy # noqa : E501
read the specified PodSecurityPolicy # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > th... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . read_pod_security_policy_with_http_info ( name , ** kwargs )
# noqa : E501
else :
( data ) = self . read_pod_security_policy_with_http_info ( name , ** kwargs )
# noqa : E501
return data |
def WriteFlowResponses ( self , responses ) :
"""Writes FlowMessages and updates corresponding requests .""" | status_available = set ( )
requests_updated = set ( )
task_ids_by_request = { }
for response in responses :
flow_key = ( response . client_id , response . flow_id )
if flow_key not in self . flows :
logging . error ( "Received response for unknown flow %s, %s." , response . client_id , response . flow_i... |
def claim_new ( self ) -> Iterable [ str ] :
"""Checks for messages in the ` ` new ` ` subdirectory , moving them to
` ` cur ` ` and returning their keys .""" | new_subdir = self . _paths [ 'new' ]
cur_subdir = self . _paths [ 'cur' ]
for name in os . listdir ( new_subdir ) :
new_path = os . path . join ( new_subdir , name )
cur_path = os . path . join ( cur_subdir , name )
try :
os . rename ( new_path , cur_path )
except FileNotFoundError :
pas... |
def overloaded ( func ) :
"""Introduces a new overloaded function and registers its first implementation .""" | fn = unwrap ( func )
ensure_function ( fn )
def dispatcher ( * args , ** kwargs ) :
resolved = None
if dispatcher . __complex_parameters :
cache_key_pos = [ ]
cache_key_kw = [ ]
for argset in ( 0 , 1 ) if kwargs else ( 0 , ) :
if argset == 0 :
arg_pairs = enum... |
def getRunningBatchJobIDs ( self ) :
"""Returns map of running jobIDs and the time they have been running .""" | # Example lines . .
# r 5410186 benedictpaten worker 1247029663 localhost
# r 5410324 benedictpaten worker 1247030076 localhost
runningJobs = { }
issuedJobs = self . getIssuedBatchJobIDs ( )
for line in self . _runParasol ( [ 'pstat2' ] ) [ 1 ] :
if line != '' :
match = self . runningPattern . match ( line ... |
def dictstr ( arg ) :
"""Parse a key = value string as a tuple ( key , value ) that can be provided as an argument to dict ( )""" | key , value = arg . split ( "=" )
if value . lower ( ) == "true" or value . lower ( ) == "false" :
value = bool ( value )
elif INT_RE . match ( value ) :
value = int ( value )
elif FLOAT_RE . match ( value ) :
value = float ( value )
return ( key , value ) |
def save ( self , eopatch , use_tmp = True ) :
"""Method which does the saving
: param eopatch : EOPatch containing the data which will be saved
: type eopatch : EOPatch
: param use _ tmp : If ` True ` data will be saved to temporary file , otherwise it will be saved to intended
( i . e . final ) location
... | filename = self . tmp_filename if use_tmp else self . final_filename
if self . feature_name is None :
data = eopatch [ self . feature_type ]
if self . feature_type . has_dict ( ) :
data = data . get_dict ( )
if self . feature_type is FeatureType . BBOX :
data = tuple ( data ) + ( int ( data ... |
def transform ( self , X ) :
"""Parameters
X : array - like , shape [ n x m ]
The mask in form of n x m array .""" | if self . mode_ == 'target' :
return np . apply_along_axis ( self . _target , 1 , np . reshape ( X , ( X . shape [ 0 ] , X . shape [ 1 ] * X . shape [ 2 ] ) ) )
if self . mode_ == 'majority' :
return np . apply_along_axis ( self . _majority , 1 , np . reshape ( X , ( X . shape [ 0 ] , X . shape [ 1 ] * X . shap... |
def run ( self ) :
"""Performs the actual FEFF run
Returns :
( subprocess . Popen ) Used for monitoring .""" | with open ( self . output_file , "w" ) as f_std , open ( self . stderr_file , "w" , buffering = 1 ) as f_err : # Use line buffering for stderr
# On TSCC , need to run shell command
p = subprocess . Popen ( self . feff_cmd , stdout = f_std , stderr = f_err , shell = True )
return p |
def key_press_event ( self , obj , event ) :
"""Listens for key press event""" | key = self . iren . GetKeySym ( )
log . debug ( 'Key %s pressed' % key )
if key == 'q' :
self . q_pressed = True
# Grab screenshot right before renderer closes
self . last_image = self . screenshot ( True , return_img = True )
elif key == 'b' :
self . observer = self . iren . AddObserver ( 'LeftButtonPr... |
def _default_node_children ( self , node , visitor , children ) :
"""Generates a key and list of children of the given : class : ` CTENode `
` node ` , intended to be used as an update to the dictionary
representation generated by the : meth : ` node _ as _ tree ` method . The key is
` ` children ` ` and the ... | return { self . model . _cte_node_children : [ self . node_as_tree ( child , visitor = visitor , children = children ) for child in node . children . all ( ) ] } |
def get_cpds ( self , node = None ) :
"""Returns the cpd of the node . If node is not specified returns all the CPDs
that have been added till now to the graph
Parameter
node : any hashable python object ( optional )
The node whose CPD we want . If node not specified returns all the
CPDs added to the mode... | if node is not None :
if node not in self . nodes ( ) :
raise ValueError ( 'Node not present in the Directed Graph' )
for cpd in self . cpds :
if cpd . variable == node :
return cpd
else :
return None
else :
return self . cpds |
def newton_refine2 ( s_vals , curve1 , curve2 ) :
"""Image for : func : ` . newton _ refine ` docstring .""" | if NO_IMAGES :
return
ax = curve1 . plot ( 256 )
ax . lines [ - 1 ] . zorder = 1
curve2 . plot ( 256 , ax = ax )
ax . lines [ - 1 ] . zorder = 1
points = curve1 . evaluate_multi ( np . asfortranarray ( s_vals ) )
colors = seaborn . dark_palette ( "blue" , 5 )
ax . scatter ( points [ 0 , : ] , points [ 1 , : ] , c =... |
def stop ( self ) :
"""Stop serving . Always call this to clean up after yourself .""" | self . _stopped = True
threads = [ self . _accept_thread ]
threads . extend ( self . _server_threads )
self . _listening_sock . close ( )
for sock in list ( self . _server_socks ) :
try :
sock . shutdown ( socket . SHUT_RDWR )
except socket . error :
pass
try :
sock . close ( )
e... |
def insert ( self , key , column_parent , column , consistency_level ) :
"""Insert a Column at the given column _ parent . column _ family and optional column _ parent . super _ column .
Parameters :
- key
- column _ parent
- column
- consistency _ level""" | self . _seqid += 1
d = self . _reqs [ self . _seqid ] = defer . Deferred ( )
self . send_insert ( key , column_parent , column , consistency_level )
return d |
def list_all_files ( self ) :
"""Utility method that yields all files on the device ' s file
systems .""" | def list_files_recursively ( directory ) :
f_gen = itertools . chain ( directory . files , * tuple ( list_files_recursively ( d ) for d in directory . directories ) )
for f in f_gen :
yield f
return list_files_recursively ( self . filesystem ) |
def _add_input_state ( self , node , input_state ) :
"""Add the input state to all successors of the given node .
: param node : The node whose successors ' input states will be touched .
: param input _ state : The state that will be added to successors of the node .
: return : None""" | successors = self . _graph_visitor . successors ( node )
for succ in successors :
if succ in self . _state_map :
self . _state_map [ succ ] = self . _merge_states ( succ , * ( [ self . _state_map [ succ ] , input_state ] ) )
else :
self . _state_map [ succ ] = input_state |
def get_online_version ( ) :
"""Download update info and parse it .""" | session = requests . session ( )
page = urlopen ( UPDATE_URL , session )
version , url = None , None
for line in page . text . splitlines ( ) :
if line . startswith ( VERSION_TAG ) :
version = line . split ( ':' , 1 ) [ 1 ] . strip ( )
elif line . startswith ( URL_TAG ) :
url = line . split ( ':... |
def gather_parsing_stats ( self ) :
"""Times parsing if - - verbose .""" | if self . verbose :
start_time = time . clock ( )
try :
yield
finally :
elapsed_time = time . clock ( ) - start_time
printerr ( "Time while parsing:" , elapsed_time , "seconds" )
if packrat_cache :
hits , misses = ParserElement . packrat_cache_stats
pr... |
def post_run ( self , outline = False , * args , ** kwargs ) :
"""Any steps that need to be taken after running the action .""" | post_destroy = self . context . config . post_destroy
if not outline and post_destroy :
util . handle_hooks ( stage = "post_destroy" , hooks = post_destroy , provider = self . provider , context = self . context ) |
def generate_module_table_header ( modules ) :
"""Generate header with module table entries for builtin modules .
: param List [ ( module _ name , obj _ module , enabled _ define ) ] modules : module defs
: return : None""" | # Print header file for all external modules .
mod_defs = [ ]
print ( "// Automatically generated by makemoduledefs.py.\n" )
for module_name , obj_module , enabled_define in modules :
mod_def = "MODULE_DEF_{}" . format ( module_name . upper ( ) )
mod_defs . append ( mod_def )
print ( ( "#if ({enabled_define... |
def approved_funds ( pronac , dt ) :
"""Verifica se o valor total de um projeto é um
outlier em relação
aos projetos do mesmo seguimento cultural
Dataframes : planilha _ orcamentaria""" | funds_df = data . approved_funds_by_projects
project = ( funds_df . loc [ funds_df [ 'PRONAC' ] == pronac ] )
project = project . to_dict ( 'records' ) [ 0 ]
info = ( data . approved_funds_agg . to_dict ( orient = "index" ) [ project [ 'idSegmento' ] ] )
mean , std = info . values ( )
outlier = gaussian_outlier . is_ou... |
def chown ( self , uid , gid ) :
"""Change the owner ( C { uid } ) and group ( C { gid } ) of this file . As with
python ' s C { os . chown } function , you must pass both arguments , so if you
only want to change one , use L { stat } first to retrieve the current
owner and group .
@ param uid : new owner '... | self . sftp . _log ( DEBUG , 'chown(%s, %r, %r)' % ( hexlify ( self . handle ) , uid , gid ) )
attr = SFTPAttributes ( )
attr . st_uid , attr . st_gid = uid , gid
self . sftp . _request ( CMD_FSETSTAT , self . handle , attr ) |
def start_kex ( self ) :
"""Start the GSS - API / SSPI Authenticated Diffie - Hellman Group Exchange""" | if self . transport . server_mode :
self . transport . _expect_packet ( MSG_KEXGSS_GROUPREQ )
return
# request a bit range : we accept ( min _ bits ) to ( max _ bits ) , but prefer
# ( preferred _ bits ) . according to the spec , we shouldn ' t pull the
# minimum up above 1024.
self . gss_host = self . transpor... |
def get_currency_symbols ( self ) -> List [ str ] :
"""Returns the used currencies ' symbols as an array""" | result = [ ]
currencies = self . currencies . get_book_currencies ( )
for cur in currencies :
result . append ( cur . mnemonic )
return result |
def Kn2Der ( nu , y , n = 0 ) :
r"""Find the derivatives of : math : ` K _ \ nu ( y ^ { 1/2 } ) ` .
Parameters
nu : float
The order of the modified Bessel function of the second kind .
y : array of float
The values to evaluate at .
n : nonnegative int , optional
The order of derivative to take .""" | n = int ( n )
y = scipy . asarray ( y , dtype = float )
sqrty = scipy . sqrt ( y )
if n == 0 :
K = scipy . special . kv ( nu , sqrty )
else :
K = scipy . zeros_like ( y )
x = scipy . asarray ( [ fixed_poch ( 1.5 - j , j ) * y ** ( 0.5 - j ) for j in scipy . arange ( 1.0 , n + 1.0 , dtype = float ) ] ) . T
... |
def __parseThunks ( self , thunkRVA , importSection ) :
"""Parses the thunks and returns a list""" | offset = to_offset ( thunkRVA , importSection )
table_offset = 0
thunks = [ ]
while True :
thunk = IMAGE_THUNK_DATA . from_buffer ( importSection . raw , offset )
offset += sizeof ( IMAGE_THUNK_DATA )
if thunk . Ordinal == 0 :
break
thunkData = ThunkData ( header = thunk , rva = table_offset + t... |
def dump ( self , obj , ** kwargs ) :
"""Take obj for later use : using class name to namespace definition .""" | self . obj = obj
return super ( JSONSchema , self ) . dump ( obj , ** kwargs ) |
def cmd_add_label ( docid , label_name , color = None ) :
"""Arguments : < document _ id > < label _ name > [ < label _ color > ]
Add a label on a document .
Color must be specified if the label doesn ' t exist yet .
Color will be ignored if the label already exists .
Color format must be given in hexadecim... | dsearch = get_docsearch ( )
doc = dsearch . get ( docid )
if doc is None :
raise Exception ( "Document {} not found. Cannot add label on it" . format ( docid ) )
label = None
for clabel in dsearch . label_list :
if clabel . name == label_name :
label = clabel
break
if not label and not color :
... |
def get_appliances ( self , location_id ) :
"""Get the appliances added for a specified location .
Args :
location _ id ( string ) : identifiying string of appliance
Returns :
list : dictionary objects containing appliances data""" | url = "https://api.neur.io/v1/appliances"
headers = self . __gen_headers ( )
headers [ "Content-Type" ] = "application/json"
params = { "locationId" : location_id , }
url = self . __append_url_params ( url , params )
r = requests . get ( url , headers = headers )
return r . json ( ) |
def get_vnetwork_vswitches_input_datacenter ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_vnetwork_vswitches = ET . Element ( "get_vnetwork_vswitches" )
config = get_vnetwork_vswitches
input = ET . SubElement ( get_vnetwork_vswitches , "input" )
datacenter = ET . SubElement ( input , "datacenter" )
datacenter . text = kwargs . pop ( 'datacenter' )
callback = kwargs . p... |
def check_constraint ( self , pkge = None , constr = None ) :
"""Checks the constraints .
: param pkge : the package to check
: type pkge : Package
: param constr : the package constraint to check
: type constr : PackageConstraint""" | if not pkge is None :
return javabridge . call ( self . jobject , "checkConstraint" , "(Lweka/core/packageManagement/Package;)Z" , pkge . jobject )
if not constr is None :
return javabridge . call ( self . jobject , "checkConstraint" , "(Lweka/core/packageManagement/PackageConstraint;)Z" , pkge . jobject )
rais... |
def _doy_to_datetimeindex ( doy , epoch_year = 2014 ) :
"""Convert a day of year scalar or array to a pd . DatetimeIndex .
Parameters
doy : numeric
Contains days of the year
Returns
pd . DatetimeIndex""" | doy = np . atleast_1d ( doy ) . astype ( 'float' )
epoch = pd . Timestamp ( '{}-12-31' . format ( epoch_year - 1 ) )
timestamps = [ epoch + dt . timedelta ( days = adoy ) for adoy in doy ]
return pd . DatetimeIndex ( timestamps ) |
def insert ( name , table = 'filter' , family = 'ipv4' , ** kwargs ) :
'''. . versionadded : : 2014.1.0
Insert a rule into a chain
name
A user - defined name to call this rule by in another part of a state or
formula . This should not be an actual rule .
table
The table that owns the chain that should b... | ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' }
if 'rules' in kwargs :
ret [ 'changes' ] [ 'locale' ] = [ ]
comments = [ ]
save = False
for rule in kwargs [ 'rules' ] :
if 'rules' in rule :
del rule [ 'rules' ]
if '__agg__' in rule :
d... |
def bulk_update ( cls , files , api = None ) :
"""This call updates the details for multiple specified files .
Use this call to set new information for the files , thus replacing
all existing information and erasing omitted parameters . For each
of the specified files , the call sets a new name , new tags and... | if not files :
raise SbgError ( 'Files are required.' )
api = api or cls . _API
data = { 'items' : [ { 'id' : file_ . id , 'name' : file_ . name , 'tags' : file_ . tags , 'metadata' : file_ . metadata , } for file_ in files ] }
logger . info ( 'Updating files in bulk.' )
response = api . post ( url = cls . _URL [ '... |
def data ( self , root ) :
'''Convert etree . Element into a dictionary''' | value = self . dict ( )
# Add attributes specific ' attributes ' key
if root . attrib :
value [ 'attributes' ] = self . dict ( )
for attr , attrval in root . attrib . items ( ) :
value [ 'attributes' ] [ unicode ( attr ) ] = self . _fromstring ( attrval )
# Add children to specific ' children ' key
chil... |
def config_put ( args ) :
'''Install a valid method configuration into a workspace , in one of several
ways : from a JSON file containing a config definition ( both file names
and objects are supported ) ; as a string representing the content of such
a JSON file ; or as a dict generated from such JSON content... | config = args . config
if os . path . isfile ( config ) :
with open ( config , 'r' ) as fp :
config = json . loads ( fp . read ( ) )
elif isinstance ( config , str ) :
config = json . loads ( config )
elif isinstance ( config , dict ) :
pass
elif hasattr ( config , "read" ) :
config = json . loa... |
def _to_spans ( x ) :
"""Convert a Candidate , Mention , or Span to a list of spans .""" | if isinstance ( x , Candidate ) :
return [ _to_span ( m ) for m in x ]
elif isinstance ( x , Mention ) :
return [ x . context ]
elif isinstance ( x , TemporarySpanMention ) :
return [ x ]
else :
raise ValueError ( f"{type(x)} is an invalid argument type" ) |
def get_publisher ( self , publisher_name , flags = None ) :
"""GetPublisher .
[ Preview API ]
: param str publisher _ name :
: param int flags :
: rtype : : class : ` < Publisher > < azure . devops . v5_0 . gallery . models . Publisher > `""" | route_values = { }
if publisher_name is not None :
route_values [ 'publisherName' ] = self . _serialize . url ( 'publisher_name' , publisher_name , 'str' )
query_parameters = { }
if flags is not None :
query_parameters [ 'flags' ] = self . _serialize . query ( 'flags' , flags , 'int' )
response = self . _send (... |
def on_update_enabled ( self , conf_evt ) :
"""Implements neighbor configuration change listener .""" | enabled = conf_evt . value
# If we do not have any protocol bound and configuration asks us to
# enable this peer , we try to establish connection again .
if enabled :
LOG . info ( '%s enabled' , self )
if self . _protocol and self . _protocol . started :
LOG . error ( 'Tried to enable neighbor that is ... |
def skip_cycles ( self ) -> int :
"""The number of cycles dedicated to skips .""" | return sum ( ( int ( re . sub ( r'\D' , '' , op ) ) for op in self . skip_tokens ) ) |
def bulk_add ( self , item_id , ref_id = None , tags = None , time = None , title = None , url = None ) :
"""Add an item to list
See : https : / / getpocket . com / developer / docs / v3 / modify
: param item _ id : int
: param ref _ id : tweet _ id
: param tags : list of tags
: param time : time of actio... | self . _add_action ( 'add' )
return self |
def ssl_proxy ( self , value ) :
"""Sets https proxy setting .
: Args :
- value : The https proxy value .""" | self . _verify_proxy_type_compatibility ( ProxyType . MANUAL )
self . proxyType = ProxyType . MANUAL
self . sslProxy = value |
def get_context_data ( self , ** kwargs ) :
"""Populate the context of the template
with all published entries and all the categories .""" | context = super ( Sitemap , self ) . get_context_data ( ** kwargs )
context . update ( { 'entries' : Entry . published . all ( ) , 'categories' : Category . published . all ( ) , 'authors' : Author . published . all ( ) } )
return context |
def set_ ( name , path ) :
'''. . versionadded : : 0.17.0
Sets alternative for < name > to < path > , if < path > is defined
as an alternative for < name > .
name
is the master name for this link group
( e . g . pager )
path
is the location of one of the alternative target files .
( e . g . / usr / ... | ret = { 'name' : name , 'path' : path , 'result' : True , 'changes' : { } , 'comment' : '' }
current = __salt__ [ 'alternatives.show_current' ] ( name )
if current == path :
ret [ 'comment' ] = 'Alternative for {0} already set to {1}' . format ( name , path )
return ret
display = __salt__ [ 'alternatives.displa... |
def pull ( collector , image , ** kwargs ) :
"""Pull an image""" | if not image . image_index :
raise BadOption ( "The chosen image does not have a image_index configuration" , wanted = image . name )
tag = kwargs [ "artifact" ]
if tag is NotSpecified :
collector . configuration [ "harpoon" ] . tag
if tag is not NotSpecified :
image . tag = tag
log . info ( "Pulling ta... |
def api_method ( self ) :
"""Returns the api method to ` send ` the current API Object type""" | if not self . _api_method :
raise NotImplementedError ( )
return getattr ( self . api , self . _api_method ) |
def _add_arg ( self , key , value , mask = False ) :
"""Add CLI Arg for the correct language .
Args :
key ( string ) : The CLI Args key ( e . g . , - - name ) .
value ( string ) : The CLI Args value ( e . g . , bob ) .
mask ( boolean , default : False ) : Indicates whether no mask value .""" | if self . lang == 'python' :
self . _add_arg_python ( key , value , mask )
elif self . lang == 'java' :
self . _add_arg_java ( key , value , mask ) |
def __write_docstring ( self , routine ) :
"""Writes the docstring for the wrapper method of a stored routine .
: param dict routine : The metadata of the stored routine .""" | self . _write_line ( '"""' )
self . __write_docstring_description ( routine )
self . _write_docstring_parameters ( routine )
self . __write_docstring_return_type ( )
self . _write_line ( '"""' ) |
def vatu0 ( self , E , Lz , u0 , R , retv2 = False ) :
"""NAME :
vatu0
PURPOSE :
calculate the velocity at u0
INPUT :
E - energy
Lz - angular momentum
u0 - u0
R - radius corresponding to u0 , pi / 2.
retv2 = ( False ) , if True return v ^ 2
OUTPUT :
velocity
HISTORY :
2012-11-29 - Written ... | v2 = ( 2. * ( E - actionAngleStaeckel . potentialStaeckel ( u0 , numpy . pi / 2. , self . _pot , self . _delta ) ) - Lz ** 2. / R ** 2. )
if retv2 :
return v2
v2 [ ( v2 < 0. ) * ( v2 > - 10. ** - 7. ) ] = 0.
return numpy . sqrt ( v2 ) |
def read ( self ) :
"""Reads enough bytes from ` ` open _ stream _ in ` ` to fill the ` ` width ` `
( if available ) and converts them to an ` ` int ` ` . Returns this ` ` int ` ` .""" | int_ = bytes_to_int ( self . open_stream_in . read ( math . ceil ( self . width / 8 ) ) , self . width )
self . repr_ . setvalue ( int_ )
return self . value . getvalue ( ) |
def list_exchanges_for_vhost ( self , vhost ) :
"""A list of all exchanges in a given virtual host .
: param vhost : The vhost name
: type vhost : str""" | return self . _api_get ( '/api/exchanges/{0}' . format ( urllib . parse . quote_plus ( vhost ) ) ) |
def retinotopy_anchors ( mesh , mdl , polar_angle = None , eccentricity = None , weight = None , weight_min = 0.1 , field_sign_weight = 0 , field_sign = None , invert_field_sign = False , radius_weight = 0 , radius_weight_source = 'Wandell2015' , radius = None , model_field_sign = None , model_hemi = Ellipsis , scale =... | if pimms . is_str ( mdl ) :
hemi = None
if pimms . is_str ( model_hemi ) :
model_hemi = model_hemi . upper ( )
hemnames = { k : h for ( h , als ) in [ ( 'LH' , [ 'LH' , 'L' , 'LEFT' , 'RHX' , 'RX' ] ) , ( 'RH' , [ 'RH' , 'R' , 'RIGHT' , 'LHX' , 'LX' ] ) ] for k in als }
if model_hemi in ... |
def setup_prometheus ( self , registry = None ) :
"""Setup Prometheus .""" | kwargs = { }
if registry :
kwargs [ "registry" ] = registry
self . metrics = PrometheusMetrics ( self . app , ** kwargs )
try :
version = pkg_resources . require ( self . app . name ) [ 0 ] . version
except pkg_resources . DistributionNotFound :
version = "unknown"
self . metrics . info ( "app_info" , "Appl... |
def projection ( self , * axes , ** kwargs ) :
"""Projection to lower - dimensional histogram .
The inheriting class should implement the _ projection _ class _ map
class attribute to suggest class for the projection . If the
arguments don ' t match any of the map keys , HistogramND is used .""" | axes , _ = self . _get_projection_axes ( * axes )
axes = tuple ( sorted ( axes ) )
if axes in self . _projection_class_map :
klass = self . _projection_class_map [ axes ]
return HistogramND . projection ( self , * axes , type = klass , ** kwargs )
else :
return HistogramND . projection ( self , * axes , ** ... |
def info ( self , msg : str ) -> None :
"""Write an info message to the Windows Application log
( ± to the Python disk log ) .""" | # noinspection PyUnresolvedReferences
servicemanager . LogInfoMsg ( str ( msg ) )
if self . debugging :
log . info ( msg ) |
def resolve_config ( self ) :
'''Resolve configuration params to native instances''' | conf = self . load_config ( self . force_default )
for k in conf [ 'hues' ] :
conf [ 'hues' ] [ k ] = getattr ( KEYWORDS , conf [ 'hues' ] [ k ] )
as_tuples = lambda name , obj : namedtuple ( name , obj . keys ( ) ) ( ** obj )
self . hues = as_tuples ( 'Hues' , conf [ 'hues' ] )
self . opts = as_tuples ( 'Options' ... |
def update ( self , template_id , assumer , template_types , template_dests , template_start_standards , template_start_fees , template_add_standards , template_add_fees , session , name = None ) :
'''taobao . delivery . template . update 修改运费模板
修改运费模板''' | request = TOPRequest ( 'taobao.delivery.template.update' )
if name != None :
request [ 'name' ] = name
request [ 'assumer' ] = assumer
request [ 'template_id' ] = template_id
request [ 'template_types' ] = template_types
request [ 'template_dests' ] = template_dests
request [ 'template_start_standards' ] = template... |
def convex_conj ( self ) :
"""Convex conjugate functional of IndicatorLpUnitBall .
Returns
convex _ conj : GroupL1Norm
The convex conjugate is the the group L1 - norm .""" | conj_exp = conj_exponent ( self . pointwise_norm . exponent )
return GroupL1Norm ( self . domain , exponent = conj_exp ) |
def get_next_input ( self ) :
"""Returns the next line of input
: return : string of input""" | # TODO : could override input if we get input coming in at the same time
all_input = Deployment . objects . get ( pk = self . id ) . input or ''
lines = all_input . splitlines ( )
first_line = lines [ 0 ] if len ( lines ) else None
lines = lines [ 1 : ] if len ( lines ) > 1 else [ ]
Deployment . objects . filter ( pk =... |
def auto ( self ) :
"""Returns the highest whole - number unit .""" | if self . _value >= 1000000000000 :
return self . tb , 'tb'
if self . _value >= 1000000000 :
return self . gb , 'gb'
if self . _value >= 1000000 :
return self . mb , 'mb'
if self . _value >= 1000 :
return self . kb , 'kb'
else :
return self . b , 'b' |
def get_unlabeled_entries ( self ) :
"""Returns list of unlabeled features , along with their entry _ ids
Returns
unlabeled _ entries : list of ( entry _ id , feature ) tuple
Labeled entries""" | return [ ( idx , entry [ 0 ] ) for idx , entry in enumerate ( self . data ) if entry [ 1 ] is None ] |
def get_path_url ( path , relative = False ) :
"""Returns an absolute or relative path url given a path""" | if relative :
return os . path . relpath ( path )
else :
return 'file://%s' % os . path . abspath ( path ) |
def delete_service ( self , stack , service ) :
"""删除服务
删除指定名称服务 , 并自动销毁服务已部署的所有容器和存储卷 。
Args :
- stack : 服务所属的服务组名称
- service : 服务名
Returns :
返回一个tuple对象 , 其格式为 ( < result > , < ResponseInfo > )
- result 成功返回空dict { } , 失败返回 { " error " : " < errMsg string > " }
- ResponseInfo 请求的Response信息""" | url = '{0}/v3/stacks/{1}/services/{2}' . format ( self . host , stack , service )
return self . __delete ( url ) |
def check_for_usable_restore_env ( self ) :
"""Check if the current env can be used to restore files .""" | self . check_for_usable_environment ( )
if not os . path . isdir ( self . mackup_folder ) :
utils . error ( "Unable to find the Mackup folder: {}\n" "You might want to back up some files or get your" " storage directory synced first." . format ( self . mackup_folder ) ) |
def set_ip_port ( self , ip , port ) :
'''set ip and port''' | self . address = ip
self . port = port
self . stop ( )
self . start ( ) |
def match_all_concepts ( self , string ) :
'''Returns sorted list of all : class : ` Concept ` s matching ` ` string ` `''' | multipliers = { 'exact' : 10 ** 5 , 'fname' : 10 ** 4 , 'fuzzy' : 10 ** 2 , 'fuzzy_fragment' : 1 }
matches = [ ]
for concept in self . vocab :
matches += concept . matches ( string , self . fuzzy , self . fname_match , self . fuzzy_fragment , self . guess )
return sort_matches ( matches ) |
def WriteClientCrashInfo ( self , client_id , crash_info ) :
"""Writes a new client crash record .""" | if client_id not in self . metadatas :
raise db . UnknownClientError ( client_id )
ts = rdfvalue . RDFDatetime . Now ( )
self . metadatas [ client_id ] [ "last_crash_timestamp" ] = ts
history = self . crash_history . setdefault ( client_id , { } )
history [ ts ] = crash_info . SerializeToString ( ) |
def compile_insert_get_id ( self , query , values , sequence = None ) :
"""Compile an insert and get ID statement into SQL .
: param query : A QueryBuilder instance
: type query : QueryBuilder
: param values : The values to insert
: type values : dict
: param sequence : The id sequence
: type sequence :... | if sequence is None :
sequence = "id"
return "%s RETURNING %s" % ( self . compile_insert ( query , values ) , self . wrap ( sequence ) , ) |
def stop ( self ) :
"""BLOCKS UNTIL ALL THREADS HAVE STOPPED
THEN RUNS sys . exit ( 0)""" | global DEBUG
self_thread = Thread . current ( )
if self_thread != MAIN_THREAD or self_thread != self :
Log . error ( "Only the main thread can call stop() on main thread" )
DEBUG = True
self . please_stop . go ( )
join_errors = [ ]
with self . child_lock :
children = copy ( self . children )
for c in reversed (... |
def symbolic_Rz_matrix ( symbolic_theta ) :
"""Matrice symbolique de rotation autour de l ' axe Z""" | return sympy . Matrix ( [ [ sympy . cos ( symbolic_theta ) , - sympy . sin ( symbolic_theta ) , 0 ] , [ sympy . sin ( symbolic_theta ) , sympy . cos ( symbolic_theta ) , 0 ] , [ 0 , 0 , 1 ] ] ) |
def set_title ( self , value : Union [ Literal , Identifier , str ] , lang : str = None ) :
"""Set the DC Title literal value
: param value : Value of the title node
: param lang : Language in which the value is""" | return self . metadata . add ( key = DC . title , value = value , lang = lang ) |
def decode ( self ) :
"Decode self . buffer , populating instance variables and return self ." | buflen = len ( self . buffer )
tftpassert ( buflen >= 4 , "malformed ERR packet, too short" )
log . debug ( "Decoding ERR packet, length %s bytes" , buflen )
if buflen == 4 :
log . debug ( "Allowing this affront to the RFC of a 4-byte packet" )
fmt = b"!HH"
log . debug ( "Decoding ERR packet with fmt: %s" ,... |
def validate_auth_mechanism ( option , value ) :
"""Validate the authMechanism URI option .""" | # CRAM - MD5 is for server testing only . Undocumented ,
# unsupported , may be removed at any time . You have
# been warned .
if value not in MECHANISMS and value != 'CRAM-MD5' :
raise ValueError ( "%s must be in %s" % ( option , tuple ( MECHANISMS ) ) )
return value |
def _create ( self , uri , body , records = None , subdomains = None , return_none = False , return_raw = False , ** kwargs ) :
"""Handles the communication with the API when creating a new
resource managed by this class .
Since DNS works completely differently for create ( ) than the other
APIs , this method... | self . run_hooks ( "modify_body_for_create" , body , ** kwargs )
resp , resp_body = self . _async_call ( uri , body = body , method = "POST" , error_class = exc . DomainCreationFailed )
response_body = resp_body [ self . response_key ] [ 0 ]
return self . resource_class ( self , response_body ) |
def tofile ( self , filepath = None ) :
"""Saves configuration into a file and returns its path .
Convenience method .
: param str | unicode filepath : Filepath to save configuration into .
If not provided a temporary file will be automatically generated .
: rtype : str | unicode""" | if filepath is None :
with NamedTemporaryFile ( prefix = '%s_' % self . alias , suffix = '.ini' , delete = False ) as f :
filepath = f . name
else :
filepath = os . path . abspath ( filepath )
if os . path . isdir ( filepath ) :
filepath = os . path . join ( filepath , '%s.ini' % self . alia... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.