signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def populate_tabs ( self ) :
"""Populating tabs based on layer metadata .""" | self . delete_tabs ( )
layer_purpose = self . metadata . get ( 'layer_purpose' )
if not layer_purpose :
message = tr ( 'Key layer_purpose is not found in the layer {layer_name}' ) . format ( layer_name = self . layer . name ( ) )
raise KeywordNotFoundError ( message )
if layer_purpose == layer_purpose_exposure ... |
def wait_until_queue_empty ( self , channels , report = True , clear_end = True ) :
"""Waits until all queues of channels are empty .""" | state = { 'message' : '' }
self . logger . debug ( "wait_until_queue_empty: report=%s %s" % ( str ( report ) , str ( [ channel + ':' + str ( len ( self . queues [ channel ] ) ) for channel in channels ] ) , ) )
queues = [ ]
for channel in channels :
queues += self . queues [ channel ] [ : ]
def print_progress ( ) :... |
def list_tags ( self ) :
"""List Tags and return JSON encoded result .""" | try :
tags = Tags . list ( )
except NipapError , e :
return json . dumps ( { 'error' : 1 , 'message' : e . args , 'type' : type ( e ) . __name__ } )
return json . dumps ( tags , cls = NipapJSONEncoder ) |
def _load ( contract_name ) :
"""Retrieve the contract instance for ` contract _ name ` that represent the smart
contract in the keeper network .
: param contract _ name : str name of the solidity keeper contract without the network name .
: return : web3 . eth . Contract instance""" | contract_definition = ContractHandler . get_contract_dict_by_name ( contract_name )
address = Web3Provider . get_web3 ( ) . toChecksumAddress ( contract_definition [ 'address' ] )
abi = contract_definition [ 'abi' ]
contract = Web3Provider . get_web3 ( ) . eth . contract ( address = address , abi = abi )
ContractHandle... |
def send ( self , command ) :
"""Sends commands to this hypervisor .
: param command : a uBridge hypervisor command
: returns : results as a list""" | # uBridge responses are of the form :
# 1xx yyyyy \ r \ n
# 1xx yyyyy \ r \ n
# 100 - yyyy \ r \ n
# or
# 2xx - yyyy \ r \ n
# Where 1xx is a code from 100-199 for a success or 200-299 for an error
# The result might be multiple lines and might be less than the buffer size
# but still have more data . The only thing we... |
def _spawn_minions ( self , timeout = 60 ) :
'''Spawn all the coroutines which will sign in to masters''' | # Run masters discovery over SSDP . This may modify the whole configuration ,
# depending of the networking and sets of masters . If match is ' any ' we let
# eval _ master handle the discovery instead so disconnections can also handle
# discovery
if isinstance ( self . opts [ 'discovery' ] , dict ) and self . opts [ '... |
def resources_preparing_factory ( app , wrapper ) :
"""Factory which wrap all resources in settings .""" | settings = app . app . registry . settings
config = settings . get ( CONFIG_RESOURCES , None )
if not config :
return
resources = [ ( k , [ wrapper ( r , GroupResource ( k , v ) ) for r in v ] ) for k , v in config ]
settings [ CONFIG_RESOURCES ] = resources |
def check_recipe_choices ( self ) :
'''Checks what recipes are being built to see which of the alternative
and optional dependencies are being used ,
and returns a list of these .''' | recipes = [ ]
built_recipes = self . ctx . recipe_build_order
for recipe in self . depends :
if isinstance ( recipe , ( tuple , list ) ) :
for alternative in recipe :
if alternative in built_recipes :
recipes . append ( alternative )
break
for recipe in self . opt... |
def on_valid ( valid_content_type , on_invalid = json ) :
"""Renders as the specified content type only if no errors are found in the provided data object""" | invalid_kwargs = introspect . generate_accepted_kwargs ( on_invalid , 'request' , 'response' )
invalid_takes_response = introspect . takes_all_arguments ( on_invalid , 'response' )
def wrapper ( function ) :
valid_kwargs = introspect . generate_accepted_kwargs ( function , 'request' , 'response' )
valid_takes_r... |
def run ( self ) :
"""Build package and fix ordelist per checksum""" | self . files_exist ( )
self . info_file ( )
sources = self . sources
if len ( sources ) > 1 and self . sbo_sources != sources :
sources = self . sbo_sources
# If the list does not have the same order use from . info
# order .
BuildPackage ( self . script , sources , self . path , auto = True ) . build ( )
raise Sys... |
def use_active_assessment_part_view ( self ) :
"""Pass through to provider AssessmentPartLookupSession . use _ active _ assessment _ part _ view""" | self . _operable_views [ 'assessment_part' ] = ACTIVE
# self . _ get _ provider _ session ( ' assessment _ part _ lookup _ session ' ) # To make sure the session is tracked
for session in self . _get_provider_sessions ( ) :
try :
session . use_active_assessment_part_view ( )
except AttributeError :
... |
def definitiondir ( self , filetype , ** kwargs ) :
"""Returns definition subdirectory in : envvar : ` PLATELIST _ DIR ` of the form : ` ` NNNNXX ` ` .
Parameters
filetype : str
File type parameter .
designid : int or str
Design ID number . Will be converted to int internally .
Returns
definitiondir :... | designid = int ( kwargs [ 'designid' ] )
designid100 = designid // 100
subdir = "{:0>4d}" . format ( designid100 ) + "XX"
return subdir |
def getCiphertextLen ( self , ciphertext ) :
"""Given a ` ` ciphertext ` ` with a valid header , returns the length of the ciphertext inclusive of ciphertext expansion .""" | plaintext_length = self . getPlaintextLen ( ciphertext )
ciphertext_length = plaintext_length + Encrypter . _CTXT_EXPANSION
return ciphertext_length |
def get_combined_dim ( combination : str , tensor_dims : List [ int ] ) -> int :
"""For use with : func : ` combine _ tensors ` . This function computes the resultant dimension when
calling ` ` combine _ tensors ( combination , tensors ) ` ` , when the tensor dimension is known . This is
necessary for knowing t... | if len ( tensor_dims ) > 9 :
raise ConfigurationError ( "Double-digit tensor lists not currently supported" )
combination = combination . replace ( 'x' , '1' ) . replace ( 'y' , '2' )
return sum ( [ _get_combination_dim ( piece , tensor_dims ) for piece in combination . split ( ',' ) ] ) |
def _vis_calibrate ( self , data , key ) :
"""VIS channel calibration .""" | # radiance to reflectance taken as in mipp / xrit / MSG . py
# again FCI User Guide is not clear on how to do this
sirr = self . nc [ '/data/{}/measured/channel_effective_solar_irradiance' . format ( key . name ) ] [ ... ]
# reflectance = radiance / sirr * 100
data . data [ : ] /= sirr
data . data [ : ] *= 100 |
def wrap ( self , methodName , types , skip = 2 ) :
"""Create a message handler that invokes a wrapper method
with the in - order message fields as parameters , skipping over
the first ` ` skip ` ` fields , and parsed according to the ` ` types ` ` list .""" | def handler ( fields ) :
try :
args = [ field if typ is str else int ( field or 0 ) if typ is int else float ( field or 0 ) if typ is float else bool ( int ( field or 0 ) ) for ( typ , field ) in zip ( types , fields [ skip : ] ) ]
method ( * args )
except Exception :
self . logger . exc... |
def load_uri ( uri , base_uri = None , loader = None , jsonschema = False , load_on_repr = True ) :
"""Load JSON data from ` ` uri ` ` with JSON references proxied to their referent
data .
: param uri : URI to fetch the JSON from
: param kwargs : This function takes any of the keyword arguments from
: meth ... | if loader is None :
loader = jsonloader
if base_uri is None :
base_uri = uri
return JsonRef . replace_refs ( loader ( uri ) , base_uri = base_uri , loader = loader , jsonschema = jsonschema , load_on_repr = load_on_repr , ) |
def read_blitzorg_csv ( f = None ) :
"""Function to read csv data downloaded from Blitzorgs historical data
section . Time is in POSIX timestamps ( x100000 ) . An eg is kept in
stormstats / egdata / archive _ 2 _ raw . txt . If no data file is specified
the function will assume you want to read this example d... | factor = 1000000000
# don ' t change this magic number ! Its from Bzorg .
if f :
tmp = pd . read_csv ( f )
else :
f = pkg . resource_filename ( 'stormstats' , "egdata/archive_2_raw.txt" )
tmp = pd . read_csv ( f )
dt_list = [ dt . datetime . fromtimestamp ( ts / factor ) . strftime ( '%Y-%m-%d %H:%M:%S:%f' ... |
def deserialize_namespace ( data ) :
'''Deserialize a Namespace object .
: param data : bytes or str
: return : namespace''' | if isinstance ( data , bytes ) :
data = data . decode ( 'utf-8' )
kvs = data . split ( )
uri_to_prefix = { }
for kv in kvs :
i = kv . rfind ( ':' )
if i == - 1 :
raise ValueError ( 'no colon in namespace ' 'field {}' . format ( repr ( kv ) ) )
uri , prefix = kv [ 0 : i ] , kv [ i + 1 : ]
if ... |
def browse_clicked ( self , widget , data = None ) :
"""Function sets the directory to entry""" | text = self . gui_helper . create_file_chooser_dialog ( "Please select directory" , self . path_window )
if text is not None :
data . set_text ( text ) |
async def async_set_qs_value ( self , qsid , val , success_cb = None ) :
"""Push state to QSUSB , retry with backoff .""" | set_url = URL_SET . format ( self . _url , qsid , val )
for _repeat in range ( 1 , 6 ) :
set_result = await self . get_json ( set_url , 2 )
if set_result and set_result . get ( 'data' , 'NO REPLY' ) != 'NO REPLY' :
if success_cb :
success_cb ( )
return True
await asyncio . sleep ... |
def normalize ( dt , tz ) :
"""Given a object with a timezone return a datetime object
normalized to the proper timezone .
This means take the give localized datetime and returns the
datetime normalized to match the specificed timezone .""" | if not isinstance ( tz , tzinfo ) :
tz = pytz . timezone ( tz )
dt = tz . normalize ( dt )
return dt |
def delayed_assattr ( self , node ) :
"""Visit a AssAttr node
This adds name to locals and handle members definition .""" | try :
frame = node . frame ( )
for inferred in node . expr . infer ( ) :
if inferred is util . Uninferable :
continue
try :
if inferred . __class__ is bases . Instance :
inferred = inferred . _proxied
iattrs = inferred . instance_attrs
... |
def data ( self , value ) :
"""Setter for the _ data attribute . Should be set from response . read ( )
: param value : The body of the response object for the LRSResponse
: type value : unicode""" | if value is not None and not isinstance ( value , unicode ) :
value = value . decode ( 'utf-8' )
self . _data = value |
def get_type_data ( name ) :
"""Return dictionary representation of type .
Can be used to initialize primordium . type . primitives . Type""" | name = name . upper ( )
if name in CELESTIAL_TIME_TYPES :
namespace = 'time'
domain = 'Celestial Time Systems'
time_name = CELESTIAL_TIME_TYPES [ name ]
elif name in EARTH_TIME_TYPES :
namespace = 'time'
domain = 'Earth Time Systems'
time_name = EARTH_TIME_TYPES [ name ]
elif name in SUPER_FUN_T... |
def predict ( model_dir , images ) :
"""Local instant prediction .""" | results = _tf_predict ( model_dir , images )
predicted_and_scores = [ ( predicted , label_scores [ list ( labels ) . index ( predicted ) ] ) for predicted , labels , label_scores in results ]
return predicted_and_scores |
def copy ( self , name : str ) -> 'Selection' :
"""Return a new | Selection | object with the given name and copies
of the handles | Nodes | and | Elements | objects based on method
| Devices . copy | .""" | return type ( self ) ( name , copy . copy ( self . nodes ) , copy . copy ( self . elements ) ) |
def management_command ( self , command , * args , ** kwargs ) :
"""Runs a Django management command""" | self . setup_django ( )
if 'verbosity' not in kwargs :
kwargs [ 'verbosity' ] = self . verbosity
if not self . use_colour :
kwargs [ 'no_color' ] = False
self . debug ( self . yellow_style ( '$ manage.py %s' % command ) )
return call_command ( command , * args , ** kwargs ) |
def cache_request_user ( user_cls , request , user_id ) :
"""Helper function to cache currently logged in user .
User is cached at ` request . _ user ` . Caching happens only only
if user is not already cached or if cached user ' s pk does not
match ` user _ id ` .
: param user _ cls : User model class to u... | pk_field = user_cls . pk_field ( )
user = getattr ( request , '_user' , None )
if user is None or getattr ( user , pk_field , None ) != user_id :
request . _user = user_cls . get_item ( ** { pk_field : user_id } ) |
def build_messages_metrics ( messages ) :
"""Build reports ' s metrics""" | count_types = collections . Counter ( line . get ( 'type' ) or None for line in messages )
count_modules = collections . Counter ( line . get ( 'module' ) or None for line in messages )
count_symbols = collections . Counter ( line . get ( 'symbol' ) or None for line in messages )
count_paths = collections . Counter ( l... |
def fit ( self , X , y = None , groups = None , ** fit_params ) :
"""Run fit with all sets of parameters .
Parameters
X : array - like , shape = [ n _ samples , n _ features ]
Training vector , where n _ samples is the number of samples and
n _ features is the number of features .
y : array - like , shape... | estimator = self . estimator
from sklearn . metrics . scorer import _check_multimetric_scoring
scorer , multimetric = _check_multimetric_scoring ( estimator , scoring = self . scoring )
if not multimetric :
scorer = scorer [ "score" ]
self . multimetric_ = multimetric
if self . multimetric_ :
if self . refit is... |
def query ( query_string , secure = False , container = 'namedtuple' , verbose = False , user_agent = api . USER_AGENT , no_redirect = False , no_html = False , skip_disambig = False ) :
"""Generates and sends a query to DuckDuckGo API .
Args :
query _ string : Query to be passed to DuckDuckGo API .
secure : ... | if container not in Hook . containers :
raise exc . DuckDuckArgumentError ( "Argument 'container' must be one of the values: " "{0}" . format ( ', ' . join ( Hook . containers ) ) )
headers = { "User-Agent" : user_agent }
url = url_assembler ( query_string , no_redirect = no_redirect , no_html = no_html , skip_disa... |
def gen_lines_from_textfiles ( files : Iterable [ TextIO ] ) -> Generator [ str , None , None ] :
"""Generates lines from file - like objects .
Args :
files : iterable of : class : ` TextIO ` objects
Yields :
each line of all the files""" | for file in files :
for line in file :
yield line |
def addUsage_Label ( self , usage_label ) :
'''Appends one Usage _ Label to usage _ labels''' | if isinstance ( usage_label , Usage_Label ) :
self . usage_labels . append ( usage_label )
else :
raise ( Usage_LabelError , 'usage_label Type should be Usage_Label, not %s' % type ( usage_label ) ) |
def tupleize ( element , ignore_types = ( str , bytes ) ) :
"""Cast a single element to a tuple .""" | if hasattr ( element , '__iter__' ) and not isinstance ( element , ignore_types ) :
return element
else :
return tuple ( ( element , ) ) |
def get_editor_style_by_name ( name ) :
"""Get Style class .
This raises ` pygments . util . ClassNotFound ` when there is no style with this
name .""" | if name == 'vim' :
vim_style = Style . from_dict ( default_vim_style )
else :
vim_style = style_from_pygments_cls ( get_style_by_name ( name ) )
return merge_styles ( [ vim_style , Style . from_dict ( style_extensions ) , ] ) |
def pack ( self ) :
"""Pack the frame into a string according to the following scheme :
| F | R | R | R | opcode | M | Payload len | Extended payload length |
| I | S | S | S | ( 4 ) | A | ( 7 ) | ( 16/64 ) |
| N | V | V | V | | S | | ( if payload len = = 126/127 ) |
| | 1 | 2 | 3 | | K | | |
| Extended p... | header = struct . pack ( '!B' , ( self . final << 7 ) | ( self . rsv1 << 6 ) | ( self . rsv2 << 5 ) | ( self . rsv3 << 4 ) | ( self . opcode & 0xf ) )
mask = bool ( self . masking_key ) << 7
payload_len = len ( self . payload )
if payload_len <= 125 :
header += struct . pack ( '!B' , mask | payload_len )
elif paylo... |
def Handle ( self , args , token = None ) :
"""Renders list of descriptors for all the flows .""" | if data_store . RelationalDBEnabled ( ) :
flow_iterator = iteritems ( registry . FlowRegistry . FLOW_REGISTRY )
else :
flow_iterator = iteritems ( registry . AFF4FlowRegistry . FLOW_REGISTRY )
result = [ ]
for name , cls in sorted ( flow_iterator ) : # Flows without a category do not show up in the GUI .
if... |
def group_with ( self , to_user , project , bypass_limit = False ) :
"""Join the users in a group .""" | from_user = self
from_assoc = from_user . fetch_group_assoc ( project )
to_assoc = to_user . fetch_group_assoc ( project )
if from_user == to_user or from_assoc == to_assoc and from_assoc :
raise GroupWithException ( 'You are already part of that group.' )
if not from_assoc and not to_assoc :
to_assoc = UserToG... |
def add_transition_view_for_model ( self , transition_m , parent_state_m ) :
"""Creates a ` TransitionView ` and adds it to the canvas
The method creates a ` TransitionView ` from the given ` TransitionModel ` transition _ m ` and adds it to the canvas .
: param TransitionModel transition _ m : The transition f... | parent_state_v = self . canvas . get_view_for_model ( parent_state_m )
hierarchy_level = parent_state_v . hierarchy_level
transition_v = TransitionView ( transition_m , hierarchy_level )
# Draw transition above all other state elements
self . canvas . add ( transition_v , parent_state_v , index = None )
self . _connect... |
def InitAgeCheck ( self ) :
"""make an interactive grid in which users can edit ages""" | age_df = self . contribution . tables [ 'ages' ] . df
self . panel = wx . Panel ( self , style = wx . SIMPLE_BORDER )
self . grid_frame = grid_frame3 . GridFrame ( self . contribution , self . WD , 'ages' , 'ages' , self . panel , main_frame = self . main_frame )
self . grid_frame . exitButton . SetLabel ( 'Save and co... |
def find_good ( control_board , actuation_steps , resistor_index , start_index , end_index ) :
'''Use a binary search over the range of provided actuation _ steps to find the
maximum actuation voltage that is measured by the board feedback circuit
using the specified feedback resistor .''' | lower = start_index
upper = end_index
while lower < upper - 1 :
index = lower + ( upper - lower ) / 2
v = actuation_steps [ index ]
control_board . set_waveform_voltage ( v )
data = measure_board_rms ( control_board )
valid_data = data [ data [ 'divider resistor index' ] >= 0 ]
if ( valid_data [... |
def walk_dict ( data ) :
"""Generates pairs ` ` ( keys , value ) ` ` for each item in given dictionary ,
including nested dictionaries . Each pair contains :
` keys `
a tuple of 1 . . n keys , e . g . ` ` ( ' foo ' , ) ` ` for a key on root level or
` ` ( ' foo ' , ' bar ' ) ` ` for a key in a nested dictio... | assert hasattr ( data , '__getitem__' )
for key , value in data . items ( ) :
if isinstance ( value , dict ) :
yield ( key , ) , None
for keys , value in walk_dict ( value ) :
path = ( key , ) + keys
yield path , value
else :
yield ( key , ) , value |
def register_ops_if_needed ( graph_ops ) :
"""Register graph ops absent in op _ def _ registry , if present in c + + registry .
Args :
graph _ ops : set with graph op names to register .
Raises :
RuntimeError : if ` graph _ ops ` contains ops that are not in either python or
c + + registry .""" | missing_ops = graph_ops - set ( op_def_registry . get_registered_ops ( ) . keys ( ) )
if not missing_ops :
return
p_buffer = c_api . TF_GetAllOpList ( )
cpp_op_list = op_def_pb2 . OpList ( )
cpp_op_list . ParseFromString ( c_api . TF_GetBuffer ( p_buffer ) )
cpp_registry_ops = { op . name : op for op in cpp_op_list... |
def freeze_extensions ( self ) :
"""Freeze the set of extensions into a single file .
Freezing extensions can speed up the extension loading process on
machines with slow file systems since it requires only a single file
to store all of the extensions .
Calling this method will save a file into the current ... | output_path = os . path . join ( _registry_folder ( ) , 'frozen_extensions.json' )
with open ( output_path , "w" ) as outfile :
json . dump ( self . _dump_extensions ( ) , outfile ) |
def _MergeDifferentId ( self ) :
"""Tries to merge all possible combinations of entities .
This tries to merge every entity in the old schedule with every entity in
the new schedule . Unlike _ MergeSameId , the ids do not need to match .
However , _ MergeDifferentId is much slower than _ MergeSameId .
This ... | # TODO : The same entity from A could merge with multiple from B .
# This should either generate an error or should be prevented from
# happening .
for a in self . _GetIter ( self . feed_merger . a_schedule ) :
for b in self . _GetIter ( self . feed_merger . b_schedule ) :
try :
self . _Add ( a ... |
def is_a_valid_coordination_geometry ( self , mp_symbol = None , IUPAC_symbol = None , IUCr_symbol = None , name = None , cn = None ) :
"""Checks whether a given coordination geometry is valid ( exists ) and whether the parameters are coherent with
each other .
: param IUPAC _ symbol :
: param IUCr _ symbol :... | if name is not None :
raise NotImplementedError ( 'is_a_valid_coordination_geometry not implemented for the name' )
if mp_symbol is None and IUPAC_symbol is None and IUCr_symbol is None :
raise SyntaxError ( 'missing argument for is_a_valid_coordination_geometry : at least one of mp_symbol, ' 'IUPAC_symbol and ... |
def get_form ( self , request , obj = None , ** kwargs ) :
"""Returns a Form class for use in the admin add view . This is used by
add _ view and change _ view .""" | parent_id = request . REQUEST . get ( 'parent_id' , None )
if parent_id :
return FolderForm
else :
folder_form = super ( FolderAdmin , self ) . get_form ( request , obj = None , ** kwargs )
def folder_form_clean ( form_obj ) :
cleaned_data = form_obj . cleaned_data
folders_with_same_name = F... |
def validate_count_api ( rule_payload , endpoint ) :
"""Ensures that the counts api is set correctly in a payload .""" | rule = ( rule_payload if isinstance ( rule_payload , dict ) else json . loads ( rule_payload ) )
bucket = rule . get ( 'bucket' )
counts = set ( endpoint . split ( "/" ) ) & { "counts.json" }
if len ( counts ) == 0 :
if bucket is not None :
msg = ( """There is a count bucket present in your payload,
... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'key' ) and self . key is not None :
_dict [ 'key' ] = self . key . _to_dict ( )
if hasattr ( self , 'value' ) and self . value is not None :
_dict [ 'value' ] = self . value . _to_dict ( )
return _dict |
def CreateFromDocument ( xml_text , default_namespace = None , location_base = None ) :
"""Parse the given XML and use the document element to create a Python instance .
@ param xml _ text An XML document . This should be data ( Python 2
str or Python 3 bytes ) , or a text ( Python 2 unicode or Python 3
str )... | if pyxb . XMLStyle_saxer != pyxb . _XMLStyle :
dom = pyxb . utils . domutils . StringToDOM ( xml_text )
return CreateFromDOM ( dom . documentElement , default_namespace = default_namespace )
if default_namespace is None :
default_namespace = Namespace . fallbackNamespace ( )
saxer = pyxb . binding . saxer .... |
def update_label ( self , old_label , new_label ) :
"""Update a label
Replace ' old _ label ' by ' new _ label '""" | logger . info ( "%s : Updating label ([%s] -> [%s])" % ( str ( self ) , old_label . name , new_label . name ) )
labels = self . labels
try :
labels . remove ( old_label )
except ValueError : # this document doesn ' t have this label
return
logger . info ( "%s : Updating label ([%s] -> [%s])" % ( str ( self ) , ... |
def _check_area_bbox ( self ) :
"""The method checks if the area bounding box is completely inside the OSM grid . That means that its latitudes
must be contained in the interval ( - 85.0511 , 85.0511)
: raises : ValueError""" | for coord in self . area_bbox :
if abs ( coord ) > self . POP_WEB_MAX :
raise ValueError ( 'OsmTileSplitter only works for areas which have latitude in interval ' '(-85.0511, 85.0511)' ) |
def chassis_name ( self , ** kwargs ) :
"""Get device ' s chassis name / Model .
Args :
rbridge _ id ( str ) : The rbridge ID of the device
callback ( function ) : A function executed upon completion of the
method . The only parameter passed to ` callback ` will be the
` ` ElementTree ` ` ` config ` .
R... | namespace = "urn:brocade.com:mgmt:brocade-rbridge"
rbridge_id = kwargs . pop ( 'rbridge_id' , '1' )
chassis_name = ' '
callback = kwargs . pop ( 'callback' , self . _callback )
rid_args = dict ( rbridge_id = rbridge_id , chassis_name = chassis_name )
rid = getattr ( self . _rbridge , 'rbridge_id_switch_attributes_chass... |
def create_packet ( self , primary_ip_address , vlan_id = None ) :
"""Prepare a VRRP packet .
Returns a newly created ryu . lib . packet . packet . Packet object
with appropriate protocol header objects added by add _ protocol ( ) .
It ' s caller ' s responsibility to serialize ( ) .
The serialized packet w... | if self . is_ipv6 :
traffic_class = 0xc0
# set tos to internetwork control
flow_label = 0
payload_length = ipv6 . ipv6 . _MIN_LEN + len ( self )
# XXX _ MIN _ LEN
e = ethernet . ethernet ( VRRP_IPV6_DST_MAC_ADDRESS , vrrp_ipv6_src_mac_address ( self . vrid ) , ether . ETH_TYPE_IPV6 )
ip = ip... |
def _getCurrentj9Dict ( ) :
"""Downloads and parses all the webpages
For Backend""" | urls = j9urlGenerator ( )
j9Dict = { }
for url in urls :
d = _getDict ( urllib . request . urlopen ( url ) )
if len ( d ) == 0 :
raise RuntimeError ( "Parsing failed, this is could require an update of the parser." )
j9Dict . update ( d )
return j9Dict |
def generate_models ( config , raml_resources ) :
"""Generate model for each resource in : raml _ resources :
The DB model name is generated using singular titled version of current
resource ' s url . E . g . for resource under url ' / stories ' , model with
name ' Story ' will be generated .
: param config... | from . models import handle_model_generation
if not raml_resources :
return
for raml_resource in raml_resources : # No need to generate models for dynamic resource
if is_dynamic_uri ( raml_resource . path ) :
continue
# Since POST resource must define schema use only POST
# resources to generate... |
def discover_system_effect ( self , pedalboard_info ) :
"""Generate the system effect based in pedalboard _ info
: param dict pedalboard _ info : For obtain this , see
: meth : ` ~ pluginsmanager . util . mod _ pedalboard _ converter . ModPedalboardConvert . get _ pedalboard _ info ( ) `
: return SystemEffect... | # MOD swap ins and outs ! ! !
hardware = pedalboard_info [ 'hardware' ]
total_audio_outs = hardware [ 'audio_ins' ]
total_audio_ins = hardware [ 'audio_outs' ]
outputs = [ 'capture_{}' . format ( i ) for i in range ( 1 , total_audio_outs + 1 ) ]
inputs = [ 'playback_{}' . format ( i ) for i in range ( 1 , total_audio_i... |
def endpoint_class ( collection ) :
"""Return the : class : ` sandman . model . Model ` associated with the endpoint
* collection * .
: param string collection : a : class : ` sandman . model . Model ` endpoint
: rtype : : class : ` sandman . model . Model `""" | with app . app_context ( ) :
try :
cls = current_app . class_references [ collection ]
except KeyError :
raise InvalidAPIUsage ( 404 )
return cls |
def set_zones_device_assignment ( self , internal_devices , external_devices ) -> dict :
"""sets the devices for the security zones
Args :
internal _ devices ( List [ Device ] ) : the devices which should be used for the internal zone
external _ devices ( List [ Device ] ) : the devices which should be used f... | internal = [ x . id for x in internal_devices ]
external = [ x . id for x in external_devices ]
data = { "zonesDeviceAssignment" : { "INTERNAL" : internal , "EXTERNAL" : external } }
return self . _restCall ( "home/security/setZonesDeviceAssignment" , body = json . dumps ( data ) ) |
def simple_returns ( prices ) :
"""Compute simple returns from a timeseries of prices .
Parameters
prices : pd . Series , pd . DataFrame or np . ndarray
Prices of assets in wide - format , with assets as columns ,
and indexed by datetimes .
Returns
returns : array - like
Returns of assets in wide - fo... | if isinstance ( prices , ( pd . DataFrame , pd . Series ) ) :
out = prices . pct_change ( ) . iloc [ 1 : ]
else : # Assume np . ndarray
out = np . diff ( prices , axis = 0 )
np . divide ( out , prices [ : - 1 ] , out = out )
return out |
def get_or_create ( self , login ) :
"""Get the qid of the item by its external id or create if doesn ' t exist
: param login : WDLogin item
: return : tuple of ( qid , list of warnings ( strings ) , success ( True if success , returns the Exception otherwise ) )""" | if self . p :
try :
return self . p . get_or_create ( login )
except Exception as e :
return None , self . p . warnings , e
else :
return None , [ ] , self . e |
def expires_at ( self ) :
"""A : py : obj : ` ~ datetime . datetime ` of when this signature expires , if a signature expiration date is specified .
Otherwise , ` ` None ` `""" | if 'SignatureExpirationTime' in self . _signature . subpackets :
expd = next ( iter ( self . _signature . subpackets [ 'SignatureExpirationTime' ] ) ) . expires
return self . created + expd
return None |
def run_validators ( self , value ) :
"""Test the given value against all the validators on the field ,
and either raise a ` ValidationError ` or simply return .""" | errors = [ ]
for validator in self . validators :
if hasattr ( validator , 'set_context' ) :
validator . set_context ( self )
try :
validator ( value )
except ValidationError as exc : # If the validation error contains a mapping of fields to
# errors then simply raise it immediately rath... |
def safe_date ( self , x ) :
"""Transform x [ self . col _ name ] into a date string .
Args :
x ( dict like / pandas . Series ) : Row containing data to cast safely .
Returns :
str""" | t = x [ self . col_name ]
if np . isnan ( t ) :
return t
elif np . isposinf ( t ) :
t = sys . maxsize
elif np . isneginf ( t ) :
t = - sys . maxsize
tmp = time . localtime ( float ( t ) / 1e9 )
return time . strftime ( self . date_format , tmp ) |
def check_xlim_change ( self ) :
'''check for new X bounds''' | if self . xlim_pipe is None :
return None
xlim = None
while self . xlim_pipe [ 0 ] . poll ( ) :
try :
xlim = self . xlim_pipe [ 0 ] . recv ( )
except EOFError :
return None
if xlim != self . xlim :
return xlim
return None |
def get_mode ( path , follow_symlinks = True ) :
'''Return the mode of a file
path
file or directory of which to get the mode
follow _ symlinks
indicated if symlinks should be followed
CLI Example :
. . code - block : : bash
salt ' * ' file . get _ mode / etc / passwd
. . versionchanged : : 2014.1.0... | return stats ( os . path . expanduser ( path ) , follow_symlinks = follow_symlinks ) . get ( 'mode' , '' ) |
def setup_and_get_default_path ( self , jar_base_filename ) :
"""Determine the user - specific install path for the Stanford
Dependencies jar if the jar _ url is not specified and ensure that
it is writable ( that is , make sure the directory exists ) . Returns
the full path for where the jar file should be i... | import os
import errno
install_dir = os . path . expanduser ( INSTALL_DIR )
try :
os . makedirs ( install_dir )
except OSError as ose :
if ose . errno != errno . EEXIST :
raise ose
jar_filename = os . path . join ( install_dir , jar_base_filename )
return jar_filename |
def merge_figure ( fig , subfig ) :
"""Merge a sub - figure into a parent figure
Note : This function mutates the input fig dict , but it does not mutate
the subfig dict
Parameters
fig : dict
The plotly figure dict into which the sub figure will be merged
subfig : dict
The plotly figure dict that will... | # traces
data = fig . setdefault ( 'data' , [ ] )
data . extend ( copy . deepcopy ( subfig . get ( 'data' , [ ] ) ) )
# layout
layout = fig . setdefault ( 'layout' , { } )
_merge_layout_objs ( layout , subfig . get ( 'layout' , { } ) ) |
def _open_response ( self , objects , namespace , pull_type , ** params ) :
"""Build an open . . . response once the objects have been extracted from
the repository .""" | max_obj_cnt = params [ 'MaxObjectCount' ]
if max_obj_cnt is None :
max_obj_cnt = _DEFAULT_MAX_OBJECT_COUNT
default_server_timeout = 40
timeout = default_server_timeout if params [ 'OperationTimeout' ] is None else params [ 'OperationTimeout' ]
if len ( objects ) <= max_obj_cnt :
eos = u'TRUE'
context_id = "... |
def withdraw ( self , amount ) :
"""Withdraws specified neopoints from the user ' s account , returns result
Parameters :
amount ( int ) - - Amount of neopoints to withdraw
Returns
bool - True if successful , False otherwise
Raises
notEnoughBalance""" | pg = self . usr . getPage ( "http://www.neopets.com/bank.phtml" )
try :
results = pg . find ( text = "Account Type:" ) . parent . parent . parent . find_all ( "td" , align = "center" )
self . balance = results [ 1 ] . text . replace ( " NP" , "" )
except Exception :
logging . getLogger ( "neolib.user" ) . e... |
def getcompress ( self ) :
"""Retrieves info about dataset compression type and mode .
Args : :
no argument
Returns : :
tuple holding :
- compression type ( one of the SDC . COMP _ xxx constants )
- optional values , depending on the compression type
COMP _ NONE 0 value no additional value
COMP _ SK... | status , comp_type , value , v2 , v3 , v4 , v5 = _C . _SDgetcompress ( self . _id )
_checkErr ( 'getcompress' , status , 'no compression' )
if comp_type == SDC . COMP_NONE :
return ( comp_type , )
elif comp_type == SDC . COMP_SZIP :
return comp_type , value , v2 , v3 , v4 , v5
else :
return comp_type , valu... |
def search ( self ) :
"""Return list of cells to be removed .""" | matches = [ ]
for index , cell in enumerate ( self . cells ) :
for pattern in Config . patterns :
if ismatch ( cell , pattern ) :
matches . append ( index )
break
return matches |
def add_permission ( self , topic , label , account_ids , actions ) :
"""Adds a statement to a topic ' s access control policy , granting
access for the specified AWS accounts to the specified actions .
: type topic : string
: param topic : The ARN of the topic .
: type label : string
: param label : A un... | params = { 'ContentType' : 'JSON' , 'TopicArn' : topic , 'Label' : label }
self . build_list_params ( params , account_ids , 'AWSAccountId' )
self . build_list_params ( params , actions , 'ActionName' )
response = self . make_request ( 'AddPermission' , params , '/' , 'GET' )
body = response . read ( )
if response . st... |
def get_css_classes ( cls , instance ) :
"""Returns a list of CSS classes to be added as class = " . . . " to the current HTML tag .""" | css_classes = [ ]
if hasattr ( cls , 'default_css_class' ) :
css_classes . append ( cls . default_css_class )
for attr in getattr ( cls , 'default_css_attributes' , [ ] ) :
css_class = instance . glossary . get ( attr )
if isinstance ( css_class , six . string_types ) :
css_classes . append ( css_cl... |
def item_afdeling_adapter ( obj , request ) :
"""Adapter for rendering an object of
: class : ` crabpy . gateway . capakey . Afdeling ` to json .""" | return { 'id' : obj . id , 'naam' : obj . naam , 'gemeente' : { 'id' : obj . gemeente . id , 'naam' : obj . gemeente . naam } , 'centroid' : obj . centroid , 'bounding_box' : obj . bounding_box } |
def destroy_all_models_in_dict ( target_dict ) :
"""Method runs the prepare destruction method of models
which are assumed in list or tuple as values within a dict""" | if target_dict :
for model_list in target_dict . values ( ) :
if isinstance ( model_list , ( list , tuple ) ) :
for model in model_list :
model . prepare_destruction ( )
if model . _parent :
model . _parent = None
else :
rai... |
def replace_country_by_id ( cls , country_id , country , ** kwargs ) :
"""Replace Country
Replace all attributes of Country
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . replace _ country _ by _ id ( country _ i... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _replace_country_by_id_with_http_info ( country_id , country , ** kwargs )
else :
( data ) = cls . _replace_country_by_id_with_http_info ( country_id , country , ** kwargs )
return data |
def get_games ( ctx ) :
"""Prints out games owned by a Steam user .""" | username = ctx . obj [ 'username' ]
games = User ( username ) . get_games_owned ( )
for game in sorted ( games . values ( ) , key = itemgetter ( 'title' ) ) :
click . echo ( '%s [appid: %s]' % ( game [ 'title' ] , game [ 'appid' ] ) )
click . secho ( 'Total gems owned by `%s`: %d' % ( username , len ( games ) ) , f... |
def exit_with_error ( self , error , ** kwargs ) :
"""Report an error and exit .
This raises a SystemExit exception to ask the interpreter to quit .
Parameters
error : string
The error to report before quitting .""" | self . error ( error , ** kwargs )
raise SystemExit ( error ) |
def unit_tophat_ee ( x ) :
"""Tophat function on the unit interval , left - exclusive and right - exclusive .
Returns 1 if 0 < x < 1 , 0 otherwise .""" | x = np . asarray ( x )
x1 = np . atleast_1d ( x )
r = ( ( 0 < x1 ) & ( x1 < 1 ) ) . astype ( x . dtype )
if x . ndim == 0 :
return np . asscalar ( r )
return r |
def dicttoxml ( obj , root = True , custom_root = 'root' , ids = False , attr_type = True , item_func = default_item_func , cdata = False ) :
"""Converts a python object into XML .
Arguments :
- root specifies whether the output is wrapped in an XML root element
Default is True
- custom _ root allows you to... | LOG . info ( 'Inside dicttoxml(): type(obj) is: "%s", obj="%s"' % ( type ( obj ) . __name__ , unicode_me ( obj ) ) )
output = [ ]
addline = output . append
if root == True :
addline ( '<?xml version="1.0" encoding="UTF-8" ?>' )
addline ( '<%s>%s</%s>' % ( custom_root , convert ( obj , ids , attr_type , item_fun... |
def _remove ( self , args ) :
'''Remove a package''' | if len ( args ) < 2 :
raise SPMInvocationError ( 'A package must be specified' )
packages = args [ 1 : ]
msg = 'Removing packages:\n\t{0}' . format ( '\n\t' . join ( packages ) )
if not self . opts [ 'assume_yes' ] :
self . ui . confirm ( msg )
for package in packages :
self . ui . status ( '... removing {0... |
def create ( self , name , ** kwargs ) :
"""Create a new node""" | # These arguments are required
self . required ( 'create' , kwargs , [ 'hostname' , 'port' , 'storage_hostname' , 'volume_type_name' , 'size' ] )
kwargs [ 'name' ] = name
return self . http_post ( '/nodes' , params = kwargs ) |
def save_colormap ( self , name = None ) :
"""Saves the colormap with the specified name . None means use internal
name . ( See get _ name ( ) )""" | if name == None :
name = self . get_name ( )
if name == "" or not type ( name ) == str :
return "Error: invalid name."
# get the colormaps directory
colormaps = _os . path . join ( _settings . path_home , 'colormaps' )
# make sure we have the colormaps directory
_settings . MakeDir ( colormaps )
# assemble the ... |
def getCitiesDrawingXML ( points ) :
'''Build an XML string that contains a square for each city''' | xml = ""
for p in points :
x = str ( p . x )
z = str ( p . y )
xml += '<DrawBlock x="' + x + '" y="7" z="' + z + '" type="beacon"/>'
xml += '<DrawItem x="' + x + '" y="10" z="' + z + '" type="ender_pearl"/>'
return xml |
def spawn_uwsgi ( self , only = None ) :
"""Spawns uWSGI process ( es ) which will use configuration ( s ) from the module .
Returns list of tuples :
( configuration _ alias , uwsgi _ process _ id )
If only one configuration found current process ( uwsgiconf ) is replaced with a new one ( uWSGI ) ,
otherwis... | spawned = [ ]
configs = self . configurations
if len ( configs ) == 1 :
alias = configs [ 0 ] . alias
UwsgiRunner ( ) . spawn ( self . fpath , alias , replace = True )
spawned . append ( ( alias , os . getpid ( ) ) )
else :
for config in configs : # type : Configuration
alias = config . alias
... |
def write ( self , string ) :
"""Write string to file .""" | self . make_dir ( )
with open ( self . path , "w" ) as f :
if not string . endswith ( "\n" ) :
return f . write ( string + "\n" )
else :
return f . write ( string ) |
def insert ( self , val ) :
"""Inserts a value and returns a : class : ` Pair < Pair > ` .
If the generated key exists or memcache cannot store it , a
: class : ` KeyInsertError < shorten . KeyInsertError > ` is raised ( or a
: class : ` TokenInsertError < shorten . TokenInsertError > ` if a token
exists or... | key , token , formatted_key , formatted_token = self . next_formatted_pair ( )
if self . has_key ( key ) :
raise KeyInsertError ( key )
if self . has_token ( token ) :
raise TokenInsertError ( token )
# Memcache is down or read - only
if not self . _mc . add ( formatted_key , ( val , token ) ) :
raise KeyIn... |
def data ( self ) :
"""Data for packet creation .""" | header = struct . pack ( '>BLB' , 4 , # version
self . created , # creation
self . algo_id )
# public key algorithm ID
oid = util . prefix_len ( '>B' , self . curve_info [ 'oid' ] )
blob = self . curve_info [ 'serialize' ] ( self . verifying_key )
return header + oid + blob + self . ecdh_packet |
def filter ( self , table , column_slice = None ) :
"""Use the current Query object to create a mask ( a boolean array )
for ` table ` .
Parameters
table : NumPy structured array , astropy Table , etc .
column _ slice : Column to return . Default is None ( return all columns ) .
Returns
table : filtered... | if self . _operator is None and self . _operands is None :
return table if column_slice is None else self . _get_table_column ( table , column_slice )
if self . _operator == 'AND' and column_slice is None :
for op in self . _operands :
table = op . filter ( table )
return table
return self . _mask_t... |
def usage ( self , subcommand ) :
"""Return a brief description of how to use this command , by
default from the attribute ` ` self . help ` ` .""" | if len ( self . option_list ) > 0 :
usage = '%%prog %s [options] %s' % ( subcommand , self . args )
else :
usage = '%%prog %s %s' % ( subcommand , self . args )
if self . help :
return '%s\n\n%s' % ( usage , self . help )
else :
return usage |
def itemtypes ( cls , mapped_types , coll_type , visitor ) :
"""Like : py : meth : ` normalize . visitor . VisitorPattern . aggregate ` , but
returns . This will normally only get called with a single type .""" | rv = list ( v for k , v in mapped_types )
return rv [ 0 ] if len ( rv ) == 1 else rv |
def read_hypergraph ( string ) :
"""Read a hypergraph from a string in dot format . Nodes and edges specified in the input will be
added to the current hypergraph .
@ type string : string
@ param string : Input string in dot format specifying a graph .
@ rtype : hypergraph
@ return : Hypergraph""" | hgr = hypergraph ( )
dotG = pydot . graph_from_dot_data ( string )
# Read the hypernode nodes . . .
# Note 1 : We need to assume that all of the nodes are listed since we need to know if they
# are a hyperedge or a normal node
# Note 2 : We should read in all of the nodes before putting in the links
for each_node in do... |
def result ( self , timeout = None ) :
"""Return the result of the call that the future represents .
Args :
timeout : The number of seconds to wait for the result if the future
isn ' t done . If None , then there is no limit on the wait time .
Returns :
The result of the call that the future represents . ... | if self . _state == self . RUNNING :
self . _context . wait_all_futures ( [ self ] , timeout )
return self . __get_result ( ) |
def tell ( self ) :
"""Returns the current position of write head .
Examples
> > > record = mx . recordio . MXIndexedRecordIO ( ' tmp . idx ' , ' tmp . rec ' , ' w ' )
> > > print ( record . tell ( ) )
> > > for i in range ( 5 ) :
. . . record . write _ idx ( i , ' record _ % d ' % i )
. . . print ( rec... | assert self . writable
pos = ctypes . c_size_t ( )
check_call ( _LIB . MXRecordIOWriterTell ( self . handle , ctypes . byref ( pos ) ) )
return pos . value |
def shell ( commands , splitlines = False , ignore_errors = False ) :
'''Subprocess based implementation of pyinfra / api / ssh . py ' s ` ` run _ shell _ command ` ` .
Args :
commands ( string , list ) : command or list of commands to execute
spltlines ( bool ) : optionally have the output split by lines
i... | if isinstance ( commands , six . string_types ) :
commands = [ commands ]
all_stdout = [ ]
# Checking for pseudo _ state means this function works outside a deploy
# eg the vagrant connector .
print_output = ( pseudo_state . print_output if pseudo_state . isset ( ) else False )
for command in commands :
print_p... |
def insert ( self , index , text ) :
"""Insert line to the document""" | if index < 0 or index > self . _doc . blockCount ( ) :
raise IndexError ( 'Invalid block index' , index )
if index == 0 : # first
cursor = QTextCursor ( self . _doc . firstBlock ( ) )
cursor . insertText ( text )
cursor . insertBlock ( )
elif index != self . _doc . blockCount ( ) : # not the last
cu... |
def close ( self ) :
"""in write mode , closing the handle adds the sentinel value into the
queue and joins the thread executing the HTTP request . in read mode ,
this clears out the read response object so there are no references
to it , and the resources can be reclaimed .""" | if self . _mode . find ( 'w' ) >= 0 :
self . _queue . put ( self . _sentinel )
self . _thread . join ( timeout = self . _timeout )
if self . _thread . is_alive ( ) :
raise RemoteFileException ( "Closing file timed out." )
response = self . _response_queue . get_nowait ( )
try :
respo... |
def countries ( self ) :
"""Return the a dictionary of countries , modified by any overriding
options .
The result is cached so future lookups are less work intensive .""" | if not hasattr ( self , "_countries" ) :
only = self . get_option ( "only" )
if only :
only_choices = True
if not isinstance ( only , dict ) :
for item in only :
if isinstance ( item , six . string_types ) :
only_choices = False
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.