signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _set_xfpe ( self , v , load = False ) :
"""Setter method for xfpe , mapped from YANG variable / brocade _ interface _ ext _ rpc / get _ media _ detail / output / interface / xfpe ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ xfpe is considered as a p... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = xfpe . xfpe , is_container = 'container' , presence = False , yang_name = "xfpe" , rest_name = "xfpe" , parent = self , choice = ( u'interface-identifier' , u'xfpe' ) , path_helper = self . _path_helper , extmethods = self . ... |
def _diff ( self , cursor , tokenizer , output_fh ) :
"""Returns output _ fh with diff results that have been reduced .
Uses a temporary file to store the results from ` cursor `
before being reduced , in order to not have the results stored
in memory twice .
: param cursor : database cursor containing raw ... | temp_path = self . _csv_temp ( cursor , constants . QUERY_FIELDNAMES )
output_fh = self . _reduce_diff_results ( temp_path , tokenizer , output_fh )
try :
os . remove ( temp_path )
except OSError as e :
self . _logger . error ( 'Failed to remove temporary file containing ' 'unreduced results: {}' . format ( e )... |
def _fill_diagonals ( m , diag_indices ) :
"""Fills diagonals of ` nsites ` matrices in ` m ` so rows sum to 0.""" | assert m . ndim == 3 , "M must have 3 dimensions"
assert m . shape [ 1 ] == m . shape [ 2 ] , "M must contain square matrices"
for r in range ( m . shape [ 0 ] ) :
scipy . fill_diagonal ( m [ r ] , 0 )
m [ r ] [ diag_indices ] -= scipy . sum ( m [ r ] , axis = 1 ) |
def from_memdb_file ( path ) :
"""Creates a sourcemap view from MemDB at a given file .""" | path = to_bytes ( path )
return View . _from_ptr ( rustcall ( _lib . lsm_view_from_memdb_file , path ) ) |
def get_current_state ( self ) :
"""Get current state for user session or None if session doesn ' t exist""" | try :
session_id = session . sessionId
return self . session_machines . current_state ( session_id )
except UninitializedStateMachine as e :
logger . error ( e ) |
def load ( source , ** kwargs ) :
"""Deserialize and load a model .
Example :
end _ model = EndModel . load ( " my _ end _ model . pkl " )
end _ model . score ( . . . )""" | with open ( source , "rb" ) as f :
return torch . load ( f , ** kwargs ) |
def run ( self , node ) :
"""Apply transformation and dependencies and fix new node location .""" | n = super ( Transformation , self ) . run ( node )
if self . update :
ast . fix_missing_locations ( n )
self . passmanager . _cache . clear ( )
return n |
def transactions ( self , cursor = None , order = 'asc' , limit = 10 , sse = False ) :
"""Retrieve the transactions JSON from this instance ' s Horizon server .
Retrieve the transactions JSON response for the account associated with
this : class : ` Address ` .
: param cursor : A paging token , specifying whe... | return self . horizon . account_transactions ( self . address , cursor = cursor , order = order , limit = limit , sse = sse ) |
async def close_interface ( self , conn_id , interface ) :
"""Close an interface on this IOTile device .
See : meth : ` AbstractDeviceAdapter . close _ interface ` .""" | self . _ensure_connection ( conn_id , True )
connection_string = self . _get_property ( conn_id , "connection_string" )
msg = dict ( interface = interface , connection_string = connection_string )
await self . _send_command ( OPERATIONS . CLOSE_INTERFACE , msg , COMMANDS . CloseInterfaceResponse ) |
def estimate_entropy ( X , epsilon = None ) :
r"""Estimate a dataset ' s Shannon entropy .
This function can take datasets of mixed discrete and continuous
features , and uses a set of heuristics to determine which functions
to apply to each .
Because this function is a subroutine in a mutual information es... | X = asarray2d ( X )
n_samples , n_features = X . shape
if n_features < 1 :
return 0
disc_mask = _get_discrete_columns ( X )
cont_mask = ~ disc_mask
# If our dataset is fully discrete / continuous , do something easier
if np . all ( disc_mask ) :
return calculate_disc_entropy ( X )
elif np . all ( cont_mask ) :
... |
def delete_refund ( self , refund_id ) :
"""Deletes an existing refund transaction .""" | request = self . _delete ( 'transactions/refunds/' + str ( refund_id ) )
return self . responder ( request ) |
def is_zip_file ( models ) :
r'''Ensure that a path is a zip file by :
- checking length is 1
- checking extension is ' . zip ' ''' | ext = os . path . splitext ( models [ 0 ] ) [ 1 ]
return ( len ( models ) == 1 ) and ( ext == '.zip' ) |
def is_feature_enabled ( self , feature_key , user_id , attributes = None ) :
"""Returns true if the feature is enabled for the given user .
Args :
feature _ key : The key of the feature for which we are determining if it is enabled or not for the given user .
user _ id : ID for user .
attributes : Dict rep... | if not self . is_valid :
self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'is_feature_enabled' ) )
return False
if not validator . is_non_empty_string ( feature_key ) :
self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'feature_key' ) )
return False
if not isins... |
def header ( args ) :
"""% prog header map conversion _ table
Rename lines in the map header . The mapping of old names to new names are
stored in two - column ` conversion _ table ` .""" | from jcvi . formats . base import DictFile
p = OptionParser ( header . __doc__ )
p . add_option ( "--prefix" , default = "" , help = "Prepend text to line number [default: %default]" )
p . add_option ( "--ids" , help = "Write ids to file [default: %default]" )
opts , args = p . parse_args ( args )
if len ( args ) != 2 ... |
def query_clients ( self ) :
"""查询clients
Returns :
[ type ] - - [ description ]""" | try :
data = self . call ( "clients" , { 'client' : 'None' } )
if len ( data ) > 0 :
return pd . DataFrame ( data ) . drop ( [ 'commandLine' , 'processId' ] , axis = 1 )
else :
return pd . DataFrame ( None , columns = [ 'id' , 'name' , 'windowsTitle' , 'accountInfo' , 'status' ] )
except Exc... |
def descriptions ( self ) :
"""Human readable word descriptions .""" | descs = [ ]
for postag , form in zip ( self . postags , self . forms ) :
desc = VERB_TYPES . get ( form , '' )
if len ( desc ) == 0 :
toks = form . split ( ' ' )
if len ( toks ) == 2 :
plur_desc = PLURALITY . get ( toks [ 0 ] , None )
case_desc = CASES . get ( toks [ 1 ] ... |
def update_plot_limits ( ax , white_space ) :
"""Sets the limit options of a matplotlib plot .
Args :
ax : matplotlib axes
white _ space ( float ) : whitespace added to surround the tight limit of the data
Note : This relies on ax . dataLim ( in 2d ) and ax . [ xy , zz ] _ dataLim being set in 3d""" | if hasattr ( ax , 'zz_dataLim' ) :
bounds = ax . xy_dataLim . bounds
ax . set_xlim ( bounds [ 0 ] - white_space , bounds [ 0 ] + bounds [ 2 ] + white_space )
ax . set_ylim ( bounds [ 1 ] - white_space , bounds [ 1 ] + bounds [ 3 ] + white_space )
bounds = ax . zz_dataLim . bounds
ax . set_zlim ( bou... |
def convert_data_element_to_data_and_metadata_1 ( data_element ) -> DataAndMetadata . DataAndMetadata :
"""Convert a data element to xdata . No data copying occurs .
The data element can have the following keys :
data ( required )
is _ sequence , collection _ dimension _ count , datum _ dimension _ count ( op... | # data . takes ownership .
data = data_element [ "data" ]
dimensional_shape = Image . dimensional_shape_from_data ( data )
is_sequence = data_element . get ( "is_sequence" , False )
dimension_count = len ( Image . dimensional_shape_from_data ( data ) )
adjusted_dimension_count = dimension_count - ( 1 if is_sequence els... |
def parse_mapping ( value ) :
"""Parse the given VCF header line mapping
Such a mapping consists of " key = value " pairs , separated by commas and
wrapped into angular brackets ( " < . . . > " ) . Strings are usually quoted ,
for certain known keys , exceptions are made , depending on the tag key .
this , ... | if not value . startswith ( "<" ) or not value . endswith ( ">" ) :
raise exceptions . InvalidHeaderException ( "Header mapping value was not wrapped in angular brackets" )
# split the comma - separated list into pairs , ignoring commas in quotes
pairs = split_quoted_string ( value [ 1 : - 1 ] , delim = "," , quote... |
def get_all_templates ( self , params = None ) :
"""Get all templates
This will iterate over all pages until it gets all elements .
So if the rate limit exceeded it will throw an Exception and you will get nothing
: param params : search params
: return : list""" | if not params :
params = { }
return self . _iterate_through_pages ( self . get_templates_per_page , resource = TEMPLATES , ** { 'params' : params } ) |
def load_class ( alias ) :
"""Finds the class registered to the alias .
The search is done in order :
1 . Checks if the class name has been registered via L { register _ class }
or L { register _ package } .
2 . Checks all functions registered via L { register _ class _ loader } .
3 . Attempts to load the... | # Try the CLASS _ CACHE first
try :
return CLASS_CACHE [ alias ]
except KeyError :
pass
for loader in CLASS_LOADERS :
klass = loader ( alias )
if klass is None :
continue
if isinstance ( klass , python . class_types ) :
return register_class ( klass , alias )
elif isinstance ( kl... |
def load_stdlib ( ) :
'''Scans sys . path for standard library modules .''' | if _stdlib :
return _stdlib
prefixes = tuple ( { os . path . abspath ( p ) for p in ( sys . prefix , getattr ( sys , 'real_prefix' , sys . prefix ) , getattr ( sys , 'base_prefix' , sys . prefix ) , ) } )
for sp in sys . path :
if not sp :
continue
_import_paths . append ( os . path . abspath ( sp )... |
def _generate_list_skippers ( self ) :
"""Generate the list of skippers of page .
: return : The list of skippers of page .
: rtype : hatemile . util . html . htmldomelement . HTMLDOMElement""" | container = self . parser . find ( '#' + AccessibleNavigationImplementation . ID_CONTAINER_SKIPPERS ) . first_result ( )
html_list = None
if container is None :
local = self . parser . find ( 'body' ) . first_result ( )
if local is not None :
container = self . parser . create_element ( 'div' )
... |
def by_credentials ( cls , session , login , password ) :
"""Get a user from given credentials
: param session : SQLAlchemy session
: type session : : class : ` sqlalchemy . Session `
: param login : username
: type login : unicode
: param password : user password
: type password : unicode
: return : ... | user = cls . by_login ( session , login , local = True )
if not user :
return None
if crypt . check ( user . password , password ) :
return user |
def parse_args ( options = { } , * args , ** kwds ) :
"""Parser of arguments .
dict options {
int min _ items : Min of required items to fold one tuple . ( default : 1)
int max _ items : Count of items in one tuple . Last ` max _ items - min _ items `
items is by default set to None . ( default : 1)
bool ... | parser_options = ParserOptions ( options )
parser_input = ParserInput ( args , kwds )
parser = Parser ( parser_options , parser_input )
parser . parse ( )
return parser . output_data |
def request ( self , method , url , body = None , headers = None , * args , ** kwargs ) :
'''Persist the request metadata in self . _ vcr _ request''' | self . _vcr_request = Request ( method = method , uri = self . _uri ( url ) , body = body , headers = headers or { } )
log . debug ( 'Got {}' . format ( self . _vcr_request ) )
# Note : The request may not actually be finished at this point , so
# I ' m not sending the actual request until getresponse ( ) . This
# allo... |
def setViewMode ( self , state = True ) :
"""Starts the view mode for moving around the scene .""" | if self . _viewMode == state :
return
self . _viewMode = state
if state :
self . _mainView . setDragMode ( self . _mainView . ScrollHandDrag )
else :
self . _mainView . setDragMode ( self . _mainView . RubberBandDrag )
self . emitViewModeChanged ( ) |
def _insert_breathe_configs ( c , * , project_name , doxygen_xml_dirname ) :
"""Add breathe extension configurations to the state .""" | if doxygen_xml_dirname is not None :
c [ 'breathe_projects' ] = { project_name : doxygen_xml_dirname }
c [ 'breathe_default_project' ] = project_name
return c |
def _or_join ( self , terms ) :
"""Joins terms using OR operator .
Args :
terms ( list ) : terms to join
Examples :
self . _ or _ join ( [ ' term1 ' , ' term2 ' ] ) - > ' term1 | term2'
Returns :
str""" | from six import text_type
if isinstance ( terms , ( tuple , list ) ) :
if len ( terms ) > 1 :
return ' | ' . join ( text_type ( t ) for t in terms )
else :
return terms [ 0 ]
else :
return terms |
def _set_fcoeport ( self , v , load = False ) :
"""Setter method for fcoeport , mapped from YANG variable / interface / port _ channel / fcoeport ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ fcoeport is considered as a private
method . Backends lookin... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = fcoeport . fcoeport , is_container = 'container' , presence = False , yang_name = "fcoeport" , rest_name = "fcoeport" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = Tr... |
def info ( name ) :
'''Get information about a service on the system
Args :
name ( str ) : The name of the service . This is not the display name . Use
` ` get _ service _ name ` ` to find the service name .
Returns :
dict : A dictionary containing information about the service .
CLI Example :
. . cod... | try :
handle_scm = win32service . OpenSCManager ( None , None , win32service . SC_MANAGER_CONNECT )
except pywintypes . error as exc :
raise CommandExecutionError ( 'Failed to connect to the SCM: {0}' . format ( exc . strerror ) )
try :
handle_svc = win32service . OpenService ( handle_scm , name , win32serv... |
def conv_to_json ( obj , fields = None ) :
"""return cdx as json dictionary string
if ` ` fields ` ` is ` ` None ` ` , output will include all fields
in order stored , otherwise only specified fields will be
included
: param fields : list of field names to output""" | if fields is None :
return json_encode ( OrderedDict ( ( ( x , obj [ x ] ) for x in obj if not x . startswith ( '_' ) ) ) ) + '\n'
result = json_encode ( OrderedDict ( [ ( x , obj [ x ] ) for x in fields if x in obj ] ) ) + '\n'
return result |
def login ( self , usr , pwd ) :
"""Use login ( ) to Log in with a username and password .""" | self . _usr = usr
self . _pwd = pwd |
def _bselect ( self , selection , start_bindex , end_bindex ) :
"""add the given buffer indices to the given QItemSelection , both byte and char panes""" | selection . select ( self . _model . index2qindexb ( start_bindex ) , self . _model . index2qindexb ( end_bindex ) )
selection . select ( self . _model . index2qindexc ( start_bindex ) , self . _model . index2qindexc ( end_bindex ) ) |
def process_update ( self , update ) :
"""Process an incoming update from a remote NetworkTables""" | data = json . loads ( update )
NetworkTables . getEntry ( data [ "k" ] ) . setValue ( data [ "v" ] ) |
def has_attribute ( module_name , attribute_name ) :
"""Is this attribute present ?""" | init_file = '%s/__init__.py' % module_name
return any ( [ attribute_name in init_line for init_line in open ( init_file ) . readlines ( ) ] ) |
def select_one ( select , tag , namespaces = None , flags = 0 , ** kwargs ) :
"""Select a single tag .""" | return compile ( select , namespaces , flags , ** kwargs ) . select_one ( tag ) |
def plat_specific_errors ( * errnames ) :
"""Return error numbers for all errors in errnames on this platform .
The ' errno ' module contains different global constants depending on
the specific platform ( OS ) . This function will return the list of
numeric values for a given list of potential names .""" | errno_names = dir ( errno )
nums = [ getattr ( errno , k ) for k in errnames if k in errno_names ]
# de - dupe the list
return dict . fromkeys ( nums ) . keys ( ) |
def get_current ( self , channel , unit = 'A' ) :
'''Reading current''' | kwargs = self . _ch_map [ channel ] [ 'ADCI' ]
current_raw = self . _get_adc_value ( ** kwargs )
voltage = self . get_voltage ( channel )
current_raw_iq = current_raw - ( self . _ch_cal [ channel ] [ 'ADCI' ] [ 'iq_offset' ] + self . _ch_cal [ channel ] [ 'ADCI' ] [ 'iq_gain' ] * voltage )
# quiescent current ( IQ ) co... |
def register_download_command ( self , download_func ) :
"""Add ' download ' command for downloading a project to a directory .
For non empty directories it will download remote files replacing local files .
: param download _ func : function to run when user choses this option""" | description = "Download the contents of a remote remote project to a local folder."
download_parser = self . subparsers . add_parser ( 'download' , description = description )
add_project_name_or_id_arg ( download_parser , help_text_suffix = "download" )
_add_folder_positional_arg ( download_parser )
include_or_exclude... |
def _cast ( self , value ) :
"""Cast the specifief value to the type of this setting .""" | if self . type != 'text' :
value = utils . cast ( self . TYPES . get ( self . type ) [ 'cast' ] , value )
return value |
def write_Bar ( file , bar , bpm = 120 , repeat = 0 , verbose = False ) :
"""Write a mingus . Bar to a MIDI file .
Both the key and the meter are written to the file as well .""" | m = MidiFile ( )
t = MidiTrack ( bpm )
m . tracks = [ t ]
while repeat >= 0 :
t . play_Bar ( bar )
repeat -= 1
return m . write_file ( file , verbose ) |
def _get_valid_mount_strings ( self ) :
"""Return a tuple of potential mount strings .
Casper Admin seems to mount in a number of ways :
- hostname / share
- fqdn / share
Plus , there ' s the possibility of :
- IPAddress / share
Then factor in the possibility that the port is included too !
This gives... | results = set ( )
join = os . path . join
url = self . connection [ "url" ]
share_name = urllib . quote ( self . connection [ "share_name" ] , safe = "~()*!.'" )
port = self . connection [ "port" ]
# URL from python - jss form :
results . add ( join ( url , share_name ) )
results . add ( join ( "%s:%s" % ( url , port )... |
def firmware_download_input_protocol_type_sftp_protocol_sftp_host ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
firmware_download = ET . Element ( "firmware_download" )
config = firmware_download
input = ET . SubElement ( firmware_download , "input" )
protocol_type = ET . SubElement ( input , "protocol-type" )
sftp_protocol = ET . SubElement ( protocol_type , "sftp-protocol" )
sftp = ET . SubEl... |
def graph_from_dot_file ( path ) :
"""Load graph as defined by a DOT file .
The file is assumed to be in DOT format . It will
be loaded , parsed and a Dot class will be returned ,
representing the graph .""" | fd = file ( path , 'rb' )
data = fd . read ( )
fd . close ( )
return graph_from_dot_data ( data ) |
def empbayes_fit ( z0 , fitargs , ** minargs ) :
"""Return fit and ` ` z ` ` corresponding to the fit
` ` lsqfit . nonlinear _ fit ( * * fitargs ( z ) ) ` ` that maximizes ` ` logGBF ` ` .
This function maximizes the logarithm of the Bayes Factor from
fit ` ` lsqfit . nonlinear _ fit ( * * fitargs ( z ) ) ` `... | save = dict ( lastz = None , lastp0 = None )
if hasattr ( z0 , 'keys' ) : # z is a dictionary
if not isinstance ( z0 , gvar . BufferDict ) :
z0 = gvar . BufferDict ( z0 )
z0buf = z0 . buf
def convert ( zbuf ) :
return gvar . BufferDict ( z0 , buf = zbuf )
elif numpy . shape ( z0 ) == ( ) : #... |
def remove ( self , vehID , reason = tc . REMOVE_VAPORIZED ) :
'''Remove vehicle with the given ID for the give reason .
Reasons are defined in module constants and start with REMOVE _''' | self . _connection . _sendByteCmd ( tc . CMD_SET_VEHICLE_VARIABLE , tc . REMOVE , vehID , reason ) |
def remove_update_callback ( self , callback , device ) :
"""Remove a registered update callback .""" | if [ callback , device ] in self . _update_callbacks :
self . _update_callbacks . remove ( [ callback , device ] )
_LOGGER . debug ( 'Removed update callback %s for %s' , callback , device ) |
def list_devices ( connection : ForestConnection = None ) :
"""Query the Forest 2.0 server for a list of underlying QPU devices .
NOTE : These can ' t directly be used to manufacture pyQuil Device objects , but this gives a list
of legal values that can be supplied to list _ lattices to filter its ( potentially... | # For the record , the dictionary stored in " devices " that we ' re getting back is keyed on device
# names and has this structure in its values :
# " is _ online " : a boolean indicating the availability of the device ,
# " is _ retuning " : a boolean indicating whether the device is busy retuning ,
# " specs " : a S... |
def check_positive_integer ( name , value ) :
"""Check a value is a positive integer .
Returns the value if so , raises ValueError otherwise .""" | try :
value = int ( value )
is_positive = ( value > 0 )
except ValueError :
raise ValueError ( '%s should be an integer; got %r' % ( name , value ) )
if is_positive :
return value
else :
raise ValueError ( '%s should be positive; got %r' % ( name , value ) ) |
def _set_default_key ( mapping ) :
"""Replace the field with the most features with a ' default ' field .""" | key_longest = sorted ( [ ( len ( v ) , k ) for k , v in mapping . items ( ) ] , reverse = True ) [ 0 ] [ 1 ]
mapping [ 'default' ] = key_longest
del ( mapping [ key_longest ] ) |
def data ( self ) :
"""Get the data , after performing post - processing if necessary .""" | data = super ( DynamicListSerializer , self ) . data
processed_data = ReturnDict ( SideloadingProcessor ( self , data ) . data , serializer = self ) if self . child . envelope else ReturnList ( data , serializer = self )
processed_data = post_process ( processed_data )
return processed_data |
def is_deb_package_installed ( pkg ) :
"""checks if a particular deb package is installed""" | with settings ( hide ( 'warnings' , 'running' , 'stdout' , 'stderr' ) , warn_only = True , capture = True ) :
result = sudo ( 'dpkg-query -l "%s" | grep -q ^.i' % pkg )
return not bool ( result . return_code ) |
def remove_ignore ( path , use_sudo = False , force = False ) :
"""Recursively removes a file or directory , ignoring any errors that may occur . Should only be used for temporary
files that can be assumed to be cleaned up at a later point .
: param path : Path to file or directory to remove .
: type path : u... | which = sudo if use_sudo else run
which ( rm ( path , recursive = True , force = force ) , warn_only = True ) |
def fill_rawq ( self ) :
"""Fill raw queue from exactly one recv ( ) system call .
Block if no data is immediately available . Set self . eof when
connection is closed .""" | if self . irawq >= len ( self . rawq ) :
self . rawq = b''
self . irawq = 0
# The buffer size should be fairly small so as to avoid quadratic
# behavior in process _ rawq ( ) above .
buf = self . sock . recv ( 64 )
self . msg ( "recv %s" , repr ( buf ) )
self . eof = ( not buf )
self . rawq = self . rawq + buf |
def get_forecast ( self ) :
'''If configured to do so , make an API request to retrieve the forecast
data for the configured / queried weather station , and return the low and
high temperatures . Otherwise , return two empty strings .''' | no_data = ( '' , '' )
if self . forecast :
query_url = STATION_QUERY_URL % ( self . api_key , 'forecast' , self . station_id )
try :
response = self . api_request ( query_url ) [ 'forecast' ]
response = response [ 'simpleforecast' ] [ 'forecastday' ] [ 0 ]
except ( KeyError , IndexError , Ty... |
def _writeWMSDatasets ( self , session , directory , wmsDatasetCards , name = None ) :
"""GSSHAPY Project Write WMS Datasets to File Method""" | if self . mapType in self . MAP_TYPES_SUPPORTED :
for card in self . projectCards :
if ( card . name in wmsDatasetCards ) and self . _noneOrNumValue ( card . value ) :
filename = card . value . strip ( '"' )
# Determine new filename
filename = self . _replaceNewFilename (... |
def reconnect ( self ) :
"""Reconnect to rabbitmq server""" | parsed = urlparse . urlparse ( self . amqp_url )
port = parsed . port or 5672
self . connection = amqp . Connection ( host = "%s:%s" % ( parsed . hostname , port ) , userid = parsed . username or 'guest' , password = parsed . password or 'guest' , virtual_host = unquote ( parsed . path . lstrip ( '/' ) or '%2F' ) )
sel... |
def delete ( self , tag , params = { } , ** options ) :
"""A specific , existing tag can be deleted by making a DELETE request
on the URL for that tag .
Returns an empty data record .
Parameters
tag : { Id } The tag to delete .""" | path = "/tags/%s" % ( tag )
return self . client . delete ( path , params , ** options ) |
def configure_alias ( self , ns , definition ) :
"""Register an alias endpoint which will redirect to a resource ' s retrieve endpoint .
Note that the retrieve endpoint MUST be registered prior to the alias endpoint .
The definition ' s func should be a retrieve function , which must :
- accept kwargs for pat... | @ self . add_route ( ns . alias_path , Operation . Alias , ns )
@ qs ( definition . request_schema )
@ wraps ( definition . func )
def retrieve ( ** path_data ) : # request _ schema is optional for Alias
request_data = ( load_query_string_data ( definition . request_schema ) if definition . request_schema else dict... |
def angle ( self ) :
"""Get the angle ( in radians ) describing the magnitude of the quaternion rotation about its rotation axis .
This is guaranteed to be within the range ( - pi : pi ) with the direction of
rotation indicated by the sign .
When a particular rotation describes a 180 degree rotation about an ... | self . _normalise ( )
norm = np . linalg . norm ( self . vector )
return self . _wrap_angle ( 2.0 * atan2 ( norm , self . scalar ) ) |
def add_inote ( self , msg , idx , off = None ) :
"""Add a message to a specific instruction by using ( default ) the index of the address if specified
: param msg : the message
: type msg : string
: param idx : index of the instruction ( the position in the list of the instruction )
: type idx : int
: pa... | if off is not None :
idx = self . off_to_pos ( off )
if idx not in self . notes :
self . notes [ idx ] = [ ]
self . notes [ idx ] . append ( msg ) |
def apply_deduct ( self , body , total_fee , contract_id , notify_url , out_trade_no = None , detail = None , attach = None , fee_type = 'CNY' , goods_tag = None , clientip = None , deviceid = None , mobile = None , email = None , qq = None , openid = None , creid = None , outerid = None ) :
"""申请扣款 api
: param b... | trade_type = 'PAP'
# 交易类型 交易类型PAP - 微信委托代扣支付
timestamp = int ( time . time ( ) )
# 10位时间戳
spbill_create_ip = get_external_ip ( )
# 终端IP 调用微信支付API的机器IP
if not out_trade_no :
now = datetime . fromtimestamp ( time . time ( ) , tz = timezone ( 'Asia/Shanghai' ) )
out_trade_no = '{0}{1}{2}' . format ( self . mch_id ... |
def clean_with_zeros ( self , x ) :
"""set nan and inf rows from x to zero""" | x [ ~ np . any ( np . isnan ( x ) | np . isinf ( x ) , axis = 1 ) ] = 0
return x |
def normalize_package_path ( cls , package_path ) :
"""Returns a normalized version of the given package path .
The root package might by denoted by ' ' or ' . ' and is normalized to ' ' .
All other packages are of the form ' path ' or ' path / subpath ' , etc .
If the given path is either absolute or relativ... | if package_path . startswith ( os . pardir + os . sep ) :
raise ValueError ( 'Relative package paths are not allowed. Given: {!r}' . format ( package_path ) )
if os . path . isabs ( package_path ) :
raise ValueError ( 'Absolute package paths are not allowed. Given: {!r}' . format ( package_path ) )
return '' if... |
def next ( self ) :
'''Never return StopIteration''' | if self . started is False :
self . started = True
now_ = datetime . now ( )
if self . hour : # Fixed hour in a day
# Next run will be the next day
scheduled = now_ . replace ( hour = self . hour , minute = self . minute , second = self . second , microsecond = 0 )
if scheduled == now_ :... |
def complete ( self ) :
"""Return True if the limit has been reached""" | if self . scan_limit is not None and self . scan_limit == 0 :
return True
if self . item_limit is not None and self . item_limit == 0 :
return True
return False |
def get_document ( self , doc_id ) :
'''Download the document given the id .''' | conn = self . agency . _database . get_connection ( )
return conn . get_document ( doc_id ) |
def started ( self ) :
"""Datetime at which the job was started .
: rtype : ` ` datetime . datetime ` ` , or ` ` NoneType ` `
: returns : the start time ( None until set from the server ) .""" | statistics = self . _properties . get ( "statistics" )
if statistics is not None :
millis = statistics . get ( "startTime" )
if millis is not None :
return _helpers . _datetime_from_microseconds ( millis * 1000.0 ) |
def update_note ( self , note_id , revision , content ) :
'''Updates the note with the given ID to have the given content''' | return notes_endpoint . update_note ( self , note_id , revision , content ) |
def spi_configure_mode ( self , spi_mode ) :
"""Configure the SPI interface by the well known SPI modes .""" | if spi_mode == SPI_MODE_0 :
self . spi_configure ( SPI_POL_RISING_FALLING , SPI_PHASE_SAMPLE_SETUP , SPI_BITORDER_MSB )
elif spi_mode == SPI_MODE_3 :
self . spi_configure ( SPI_POL_FALLING_RISING , SPI_PHASE_SETUP_SAMPLE , SPI_BITORDER_MSB )
else :
raise RuntimeError ( 'SPI Mode not supported' ) |
def generate_jid ( name , append_date = None ) :
"""Generates a v alid JID based on the room name .
: param append _ date : appends the given date to the JID""" | if not append_date :
return sanitize_jid ( name )
return '{}-{}' . format ( sanitize_jid ( name ) , append_date . strftime ( '%Y-%m-%d' ) ) |
def ip_hide_as_path_holder_as_path_access_list_ip_action ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
ip = ET . SubElement ( config , "ip" , xmlns = "urn:brocade.com:mgmt:brocade-common-def" )
hide_as_path_holder = ET . SubElement ( ip , "hide-as-path-holder" , xmlns = "urn:brocade.com:mgmt:brocade-ip-policy" )
as_path = ET . SubElement ( hide_as_path_holder , "as-path" )
access_list ... |
def new_request_session ( config , cookies ) :
"""Create a new request session .""" | session = requests . Session ( )
if cookies :
session . cookies = cookies
session . max_redirects = config [ "maxhttpredirects" ]
session . headers . update ( { "User-Agent" : config [ "useragent" ] , } )
if config [ "cookiefile" ] :
for cookie in cookies . from_file ( config [ "cookiefile" ] ) :
sessio... |
def get_key ( self , compressed = None ) :
"""Get the hex - encoded key .
: param compressed : False if you want a standard 65 Byte key ( the most
standard option ) . True if you want the compressed 33 Byte form .
Defaults to None , which in turn uses the self . compressed attribute .
: type compressed : bo... | if compressed is None :
compressed = self . compressed
if compressed :
parity = 2 + ( self . y & 1 )
# 0x02 even , 0x03 odd
return ensure_bytes ( long_to_hex ( parity , 2 ) + long_to_hex ( self . x , 64 ) )
else :
return ensure_bytes ( b'04' + long_to_hex ( self . x , 64 ) + long_to_hex ( self . y ,... |
def _key_to_pb ( self , pb ) :
"""Internal helper to copy the key into a protobuf .""" | key = self . _key
if key is None :
pairs = [ ( self . _get_kind ( ) , None ) ]
ref = key_module . _ReferenceFromPairs ( pairs , reference = pb . mutable_key ( ) )
else :
ref = key . reference ( )
pb . mutable_key ( ) . CopyFrom ( ref )
group = pb . mutable_entity_group ( )
# Must initialize this .
# To ... |
def compute ( self ) :
"""Compute and return the signature according to the given data .""" | if "Signature" in self . params :
raise RuntimeError ( "Existing signature in parameters" )
if self . signature_version is not None :
version = self . signature_version
else :
version = self . params [ "SignatureVersion" ]
if str ( version ) == "1" :
bytes = self . old_signing_text ( )
hash_type = "... |
def compile_regex ( self , fmt , query ) :
"""Turn glob ( graphite ) queries into compiled regex
* becomes . *
. becomes \ .
fmt argument is so that caller can control anchoring ( must contain exactly 1 { 0 } !""" | return re . compile ( fmt . format ( query . pattern . replace ( '.' , '\.' ) . replace ( '*' , '[^\.]*' ) . replace ( '{' , '(' ) . replace ( ',' , '|' ) . replace ( '}' , ')' ) ) ) |
def calculate_size ( name , expected , updated ) :
"""Calculates the request payload size""" | data_size = 0
data_size += calculate_size_str ( name )
data_size += LONG_SIZE_IN_BYTES
data_size += LONG_SIZE_IN_BYTES
return data_size |
def check_str ( obj ) :
"""Returns a string for various input types""" | if isinstance ( obj , str ) :
return obj
if isinstance ( obj , float ) :
return str ( int ( obj ) )
else :
return str ( obj ) |
def full_name ( self ) :
"""Returns the full name of this element by visiting every
non - None parent in its ancestor chain .""" | if self . _full_name is None :
ancestors = [ self . name ]
current = self . parent
while current is not None and type ( current ) . __name__ != "CodeParser" :
ancestors . append ( current . name )
current = current . parent
self . _full_name = "." . join ( reversed ( ancestors ) )
return... |
def add_plugin ( self , plugin , call ) :
"""Add plugin to list of plugins .
Will be added if it has the attribute I ' m bound to .""" | meth = getattr ( plugin , call , None )
if meth is not None :
self . plugins . append ( ( plugin , meth ) ) |
def getBothEdges ( self , label = None ) :
"""Gets all the edges of the node . If label
parameter is provided , it only returns the edges of
the given label
@ params label : Optional parameter to filter the edges
@ returns A generator function with the incoming edges""" | if label :
for edge in self . neoelement . relationships . all ( types = [ label ] ) :
yield Edge ( edge )
else :
for edge in self . neoelement . relationships . all ( ) :
yield Edge ( edge ) |
def build_parser ( ) :
"""Build the script ' s argument parser .""" | parser = argparse . ArgumentParser ( description = "The IOTile task supervisor" )
parser . add_argument ( '-c' , '--config' , help = "config json with options" )
parser . add_argument ( '-v' , '--verbose' , action = "count" , default = 0 , help = "Increase logging verbosity" )
return parser |
def loadFromString ( self , body ) :
"""Load config data ( i . e . JSON text ) from the given string
: param str body : config data in JSON format""" | try :
self . _data = json . loads ( body )
except Exception as e :
raise ConfigException ( '%s: invalid config body: %s' % ( self . _path , e . message ) )
self . _doDefaults ( ) |
def import_setting ( self ) :
"""Import setting to a file .""" | LOGGER . debug ( 'Import button clicked' )
home_directory = os . path . expanduser ( '~' )
file_path , __ = QFileDialog . getOpenFileName ( self , self . tr ( 'Import InaSAFE settings' ) , home_directory , self . tr ( 'JSON File (*.json)' ) )
if file_path :
title = tr ( 'Import InaSAFE Settings.' )
question = t... |
def replace_git_url ( generator ) :
"""Replace gist tags in the article content .""" | template = g_jinja2 . get_template ( GIT_TEMPLATE )
should_cache = generator . context . get ( 'GIT_CACHE_ENABLED' )
cache_location = generator . context . get ( 'GIT_CACHE_LOCATION' )
for article in generator . articles :
for match in git_regex . findall ( article . _content ) :
params = collections . defa... |
async def _workaround_1695335 ( self , delta , old , new , model ) :
"""This is a ( hacky ) temporary work around for a bug in Juju where the
instance status and agent version fields don ' t get updated properly
by the AllWatcher .
Deltas never contain a value for ` data [ ' agent - status ' ] [ ' version ' ]... | if delta . data . get ( 'synthetic' , False ) : # prevent infinite loops re - processing already processed deltas
return
full_status = await utils . run_with_interrupt ( model . get_status ( ) , model . _watch_stopping , loop = model . loop )
if model . _watch_stopping . is_set ( ) :
return
if self . id not in ... |
def do_output ( self , * args ) :
"""Pass a command directly to the current output processor""" | if args :
action , params = args [ 0 ] , args [ 1 : ]
log . debug ( "Pass %s directly to output with %s" , action , params )
function = getattr ( self . output , "do_" + action , None )
if function :
function ( * params ) |
def _standard_frame_length ( header ) :
"""Calculates the length of a standard ciphertext frame , given a complete header .
: param header : Complete message header object
: type header : aws _ encryption _ sdk . structures . MessageHeader
: rtype : int""" | frame_length = 4
# Sequence Number
frame_length += header . algorithm . iv_len
# IV
frame_length += header . frame_length
# Encrypted Content
frame_length += header . algorithm . auth_len
# Authentication Tag
return frame_length |
def compute_integrated_acquisition ( acquisition , x ) :
'''Used to compute the acquisition function when samples of the hyper - parameters have been generated ( used in GP _ MCMC model ) .
: param acquisition : acquisition function with GpyOpt model type GP _ MCMC .
: param x : location where the acquisition i... | acqu_x = 0
for i in range ( acquisition . model . num_hmc_samples ) :
acquisition . model . model . kern [ : ] = acquisition . model . hmc_samples [ i , : ]
acqu_x += acquisition . acquisition_function ( x )
acqu_x = acqu_x / acquisition . model . num_hmc_samples
return acqu_x |
def __import_vars ( self , env_file ) :
"""Actual importing function .""" | with open ( env_file , "r" ) as f : # pylint : disable = invalid - name
for line in f :
try :
line = line . lstrip ( )
if line . startswith ( 'export' ) :
line = line . replace ( 'export' , '' , 1 )
key , val = line . strip ( ) . split ( '=' , 1 )
... |
def get_event_tags ( self , id , ** kwargs ) : # noqa : E501
"""Get all tags associated with a specific event # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . get _ event _ tags ( ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . get_event_tags_with_http_info ( id , ** kwargs )
# noqa : E501
else :
( data ) = self . get_event_tags_with_http_info ( id , ** kwargs )
# noqa : E501
return data |
def get_relationship_admin_session_for_family ( self , family_id = None ) :
"""Gets the ` ` OsidSession ` ` associated with the relationship administration service for the given family .
arg : family _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Family ` `
return : ( osid . relationship . RelationshipAdmi... | if not family_id :
raise NullArgument
if not self . supports_relationship_admin ( ) :
raise Unimplemented ( )
# Need to include check to see if the familyId is found otherwise raise NotFound
try :
from . import sessions
except ImportError :
raise OperationFailed ( )
try :
session = sessions . Relati... |
def actionAngleTorus_xvFreqs_c ( pot , jr , jphi , jz , angler , anglephi , anglez , tol = 0.003 ) :
"""NAME :
actionAngleTorus _ xvFreqs _ c
PURPOSE :
compute configuration ( x , v ) and frequencies of a set of angles on a single torus
INPUT :
pot - Potential object or list thereof
jr - radial action (... | # Parse the potential
from galpy . orbit . integrateFullOrbit import _parse_pot
npot , pot_type , pot_args = _parse_pot ( pot , potfortorus = True )
# Set up result arrays
R = numpy . empty ( len ( angler ) )
vR = numpy . empty ( len ( angler ) )
vT = numpy . empty ( len ( angler ) )
z = numpy . empty ( len ( angler ) ... |
def devices ( self , value ) :
"""{ " PathOnHost " : " / dev / deviceName " , " PathInContainer " : " / dev / deviceName " , " CgroupPermissions " : " mrw " }""" | if value is None :
self . _devices = None
elif isinstance ( value , list ) :
results = [ ]
delimiter = ':'
for device in value :
if not isinstance ( device , six . string_types ) :
raise TypeError ( "each device must be a str. {0} was passed" . format ( device ) )
occurrences... |
def get_address_reachability ( self , address : Address ) -> AddressReachability :
"""Return the current reachability state for ` ` address ` ` .""" | return self . _address_to_reachability . get ( address , AddressReachability . UNKNOWN ) |
def remove_page_boundary_lines ( docbody ) :
"""Try to locate page breaks , headers and footers within a document body ,
and remove the array cells at which they are found .
@ param docbody : ( list ) of strings , each string being a line in the
document ' s body .
@ return : ( list ) of strings . The docum... | number_head_lines = number_foot_lines = 0
# Make sure document not just full of whitespace :
if not document_contains_text ( docbody ) : # document contains only whitespace - cannot safely
# strip headers / footers
return docbody
# Get list of index posns of pagebreaks in document :
page_break_posns = get_page_brea... |
def get_help ( self , about , help_type = 'Operation' ) :
"""Return information about the Mechanical Turk Service
operations and response group NOTE - this is basically useless
as it just returns the URL of the documentation
help _ type : either ' Operation ' or ' ResponseGroup '""" | params = { 'About' : about , 'HelpType' : help_type , }
return self . _process_request ( 'Help' , params ) |
def update ( callback = None , path = None , method = Method . PUT , resource = None , tags = None , summary = "Update specified resource." , middleware = None ) : # type : ( Callable , Path , Methods , Resource , Tags , str , List [ Any ] ) - > Operation
"""Decorator to configure an operation that updates a resour... | def inner ( c ) :
op = ResourceOperation ( c , path or PathParam ( '{key_field}' ) , method , resource , tags , summary , middleware )
op . responses . add ( Response ( HTTPStatus . NO_CONTENT , "{name} has been updated." ) )
op . responses . add ( Response ( HTTPStatus . BAD_REQUEST , "Validation failed." ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.