INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Setter method for esp, mapped from YANG variable /routing_system/interface/ve/ipv6/interface_ospfv3_conf/authentication/ipsec_auth_key_config/esp (algorithm-type-esp) If this variable is read-only (config: false) in the source YANG file, then _set_esp is considered as a private method. Backends looking to p...
def _set_esp(self, v, load=False): """ Setter method for esp, mapped from YANG variable /routing_system/interface/ve/ipv6/interface_ospfv3_conf/authentication/ipsec_auth_key_config/esp (algorithm-type-esp) If this variable is read-only (config: false) in the source YANG file, then _set_esp is considered...
Setter method for esp_key, mapped from YANG variable /routing_system/interface/ve/ipv6/interface_ospfv3_conf/authentication/ipsec_auth_key_config/esp_key (ipsec-authentication-hexkey-string) If this variable is read-only (config: false) in the source YANG file, then _set_esp_key is considered as a private m...
def _set_esp_key(self, v, load=False): """ Setter method for esp_key, mapped from YANG variable /routing_system/interface/ve/ipv6/interface_ospfv3_conf/authentication/ipsec_auth_key_config/esp_key (ipsec-authentication-hexkey-string) If this variable is read-only (config: false) in the source YANG file,...
Setter method for esp_auth, mapped from YANG variable /routing_system/interface/ve/ipv6/interface_ospfv3_conf/authentication/ipsec_auth_key_config/esp_auth (algorithm-type-ah) If this variable is read-only (config: false) in the source YANG file, then _set_esp_auth is considered as a private method. Backend...
def _set_esp_auth(self, v, load=False): """ Setter method for esp_auth, mapped from YANG variable /routing_system/interface/ve/ipv6/interface_ospfv3_conf/authentication/ipsec_auth_key_config/esp_auth (algorithm-type-ah) If this variable is read-only (config: false) in the source YANG file, then _set_esp...
Setter method for ospf_route_map, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/ospf/ospf_route_map (rmap-type) If this variable is read-only (config: false) in the source YANG file, then _se...
def _set_ospf_route_map(self, v, load=False): """ Setter method for ospf_route_map, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/ospf/ospf_route_map (rmap-type) If this variable is read-...
Setter method for ospf_level1, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/ospf/ospf_level1 (empty) If this variable is read-only (config: false) in the source YANG file, then _set_ospf_lev...
def _set_ospf_level1(self, v, load=False): """ Setter method for ospf_level1, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/ospf/ospf_level1 (empty) If this variable is read-only (config:...
Setter method for ospf_level2, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/ospf/ospf_level2 (empty) If this variable is read-only (config: false) in the source YANG file, then _set_ospf_lev...
def _set_ospf_level2(self, v, load=False): """ Setter method for ospf_level2, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/ospf/ospf_level2 (empty) If this variable is read-only (config:...
Setter method for ospf_level12, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/ospf/ospf_level12 (empty) If this variable is read-only (config: false) in the source YANG file, then _set_ospf_l...
def _set_ospf_level12(self, v, load=False): """ Setter method for ospf_level12, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/ospf/ospf_level12 (empty) If this variable is read-only (conf...
Setter method for show_clock, mapped from YANG variable /brocade_clock_rpc/show_clock (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_show_clock is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_show...
def _set_show_clock(self, v, load=False): """ Setter method for show_clock, mapped from YANG variable /brocade_clock_rpc/show_clock (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_show_clock is considered as a private method. Backends looking to populate this v...
Check the ownership of a domain by going thru a serie of strategies. If at least one strategy succeed, the domain is considered verified, and this methods returns true. The prefix is a fixed DNS safe string like "yourservice-domain-verification" and the code is a random value associated to this domain....
def check(domain, prefix, code, strategies='*'): """ Check the ownership of a domain by going thru a serie of strategies. If at least one strategy succeed, the domain is considered verified, and this methods returns true. The prefix is a fixed DNS safe string like "yourservice-domain-verification" ...
:param filepath: :return: True or False
def __is_file_to_be_busted(self, filepath): """ :param filepath: :return: True or False """ if not self.extensions: return True return Path(filepath).suffix in self.extensions if filepath else False
Register `app` in cache buster so that `url_for` adds a unique prefix to URLs generated for the `'static'` endpoint. Also make the app able to serve cache-busted static files. This allows setting long cache expiration values on static resources because whenever the resource changes, so ...
def register_cache_buster(self, app, config=None): """ Register `app` in cache buster so that `url_for` adds a unique prefix to URLs generated for the `'static'` endpoint. Also make the app able to serve cache-busted static files. This allows setting long cache expiration values...
Get environment variable or provide default. Args: var (str): environment variable to search for default (optional(str)): default to return
def env_or_default(var, default=None): """Get environment variable or provide default. Args: var (str): environment variable to search for default (optional(str)): default to return """ if var in os.environ: return os.environ[var] return default
Encrypt and value with KMS key. Args: value (str): value to encrypt key (str): key id or alias aws_config (optional[dict]): aws credentials dict of arguments passed into boto3 session example: aws_creds = {'aws_access_key_id': aws_access_key_id, ...
def kms_encrypt(value, key, aws_config=None): """Encrypt and value with KMS key. Args: value (str): value to encrypt key (str): key id or alias aws_config (optional[dict]): aws credentials dict of arguments passed into boto3 session example: aws_c...
Get from config object by exposing Config.get_value method. dict.get() method on Config.values
def get_value(*args, **kwargs): """Get from config object by exposing Config.get_value method. dict.get() method on Config.values """ global _config if _config is None: raise ValueError('configuration not set; must run figgypy.set_config first') return _config.get_value(*args, **kwargs)
Set value in the global Config object.
def set_value(*args, **kwargs): """Set value in the global Config object.""" global _config if _config is None: raise ValueError('configuration not set; must run figgypy.set_config first') return _config.set_value(*args, **kwargs)
encode(msg) -> SLIP-encoded message. Encodes a message (a byte sequence) into a SLIP-encoded packet. :param bytes msg: The message that must be encoded :return: The SLIP-encoded message :rtype: bytes
def encode(msg): """encode(msg) -> SLIP-encoded message. Encodes a message (a byte sequence) into a SLIP-encoded packet. :param bytes msg: The message that must be encoded :return: The SLIP-encoded message :rtype: bytes """ msg = bytes(msg) return END + msg.replace(ESC, ...
decode(packet) -> message from SLIP-encoded packet Retrieves the message from the SLIP-encoded packet. :param bytes packet: The SLIP-encoded message. Note that this must be exactly one complete packet. The :func:`decode` function does not provide any buffering for incom...
def decode(packet): """decode(packet) -> message from SLIP-encoded packet Retrieves the message from the SLIP-encoded packet. :param bytes packet: The SLIP-encoded message. Note that this must be exactly one complete packet. The :func:`decode` function does not provide any buf...
is_valid(packet) -> indicates if the packet's contents conform to the SLIP specification. A packet is valid if: * It contains no :const:`END` bytes other than leading and/or trailing :const:`END` bytes, and * Each :const:`ESC` byte is followed by either an :const:`ESC_END` or an :const:`ESC_ESC` ...
def is_valid(packet): """is_valid(packet) -> indicates if the packet's contents conform to the SLIP specification. A packet is valid if: * It contains no :const:`END` bytes other than leading and/or trailing :const:`END` bytes, and * Each :const:`ESC` byte is followed by either an :const:`ES...
receive(data) -> List of decoded messages. Processes :obj:`data`, which must be a bytes-like object, and returns a (possibly empty) list with :class:`bytes` objects, each containing a decoded message. Any non-terminated SLIP packets in :obj:`data` are buffered, and process...
def receive(self, data): """receive(data) -> List of decoded messages. Processes :obj:`data`, which must be a bytes-like object, and returns a (possibly empty) list with :class:`bytes` objects, each containing a decoded message. Any non-terminated SLIP packets in :obj:`dat...
flush() -> List of decoded messages. Decodes the packets in the internal buffer. This enables the continuation of the processing of received packets after a :exc:`ProtocolError` has been handled. :return: A (possibly empty) list of decoded messages from the buffered pack...
def flush(self): """flush() -> List of decoded messages. Decodes the packets in the internal buffer. This enables the continuation of the processing of received packets after a :exc:`ProtocolError` has been handled. :return: A (possibly empty) list of decoded me...
Unescape libconfig string literals
def decode_escapes(s): '''Unescape libconfig string literals''' def decode_match(match): return codecs.decode(match.group(0), 'unicode-escape') return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
Load the contents of ``f`` (a file-like object) to a Python object The returned object is a subclass of ``dict`` that exposes string keys as attributes as well. Example: >>> with open('test/example.cfg') as f: ... config = libconf.load(f) >>> config['window']['title'] ...
def load(f, filename=None, includedir=''): '''Load the contents of ``f`` (a file-like object) to a Python object The returned object is a subclass of ``dict`` that exposes string keys as attributes as well. Example: >>> with open('test/example.cfg') as f: ... config = libconf.load...
Load the contents of ``string`` to a Python object The returned object is a subclass of ``dict`` that exposes string keys as attributes as well. Example: >>> config = libconf.loads('window: { title: "libconfig example"; };') >>> config['window']['title'] 'libconfig example' ...
def loads(string, filename=None, includedir=''): '''Load the contents of ``string`` to a Python object The returned object is a subclass of ``dict`` that exposes string keys as attributes as well. Example: >>> config = libconf.loads('window: { title: "libconfig example"; };') >>> conf...
Stringize ``s``, adding double quotes and escaping as necessary Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and ``\t``. Escape all remaining unprintable characters in ``\xFF``-style. The returned string will be surrounded by double quotes.
def dump_string(s): '''Stringize ``s``, adding double quotes and escaping as necessary Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and ``\t``. Escape all remaining unprintable characters in ``\xFF``-style. The returned string will be surrounded by double quotes. ''' s ...
Get the libconfig datatype of a value Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array), ``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool), ``'f'`` (float), or ``'s'`` (string). Produces the proper type for LibconfList, LibconfArray, LibconfInt64 instances.
def get_dump_type(value): '''Get the libconfig datatype of a value Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array), ``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool), ``'f'`` (float), or ``'s'`` (string). Produces the proper type for LibconfList, LibconfArray, LibconfInt64...
Return array value type, raise ConfigSerializeError for invalid arrays Libconfig arrays must only contain scalar values and all elements must be of the same libconfig data type. Raises ConfigSerializeError if these invariants are not met. Returns the value type of the array. If an array contains both ...
def get_array_value_dtype(lst): '''Return array value type, raise ConfigSerializeError for invalid arrays Libconfig arrays must only contain scalar values and all elements must be of the same libconfig data type. Raises ConfigSerializeError if these invariants are not met. Returns the value type o...
Save a value of any libconfig type This function serializes takes ``key`` and ``value`` and serializes them into ``f``. If ``key`` is ``None``, a list-style output is produced. Otherwise, output has ``key = value`` format.
def dump_value(key, value, f, indent=0): '''Save a value of any libconfig type This function serializes takes ``key`` and ``value`` and serializes them into ``f``. If ``key`` is ``None``, a list-style output is produced. Otherwise, output has ``key = value`` format. ''' spaces = ' ' * indent ...
Save a collection of attributes
def dump_collection(cfg, f, indent=0): '''Save a collection of attributes''' for i, value in enumerate(cfg): dump_value(None, value, f, indent) if i < len(cfg) - 1: f.write(u',\n')
Save a dictionary of attributes
def dump_dict(cfg, f, indent=0): '''Save a dictionary of attributes''' for key in cfg: if not isstr(key): raise ConfigSerializeError("Dict keys must be strings: %r" % (key,)) dump_value(key, cfg[key], f, indent) f.write(u';\n')
Serialize ``cfg`` into a libconfig-formatted ``str`` ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values (numbers, strings, booleans, possibly nested dicts, lists, and tuples). Returns the formatted string.
def dumps(cfg): '''Serialize ``cfg`` into a libconfig-formatted ``str`` ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values (numbers, strings, booleans, possibly nested dicts, lists, and tuples). Returns the formatted string. ''' str_file = io.StringIO() dump(cfg, st...
Serialize ``cfg`` as a libconfig-formatted stream into ``f`` ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values (numbers, strings, booleans, possibly nested dicts, lists, and tuples). ``f`` must be a ``file``-like object with a ``write()`` method.
def dump(cfg, f): '''Serialize ``cfg`` as a libconfig-formatted stream into ``f`` ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values (numbers, strings, booleans, possibly nested dicts, lists, and tuples). ``f`` must be a ``file``-like object with a ``write()`` method. ''' ...
Open the libconfig file specified by sys.argv[1] and pretty-print it
def main(): '''Open the libconfig file specified by sys.argv[1] and pretty-print it''' global output if len(sys.argv[1:]) == 1: with io.open(sys.argv[1], 'r', encoding='utf-8') as f: output = load(f) else: output = load(sys.stdin) dump(output, sys.stdout)
Yield tokens from the input string or throw ConfigParseError
def tokenize(self, string): '''Yield tokens from the input string or throw ConfigParseError''' pos = 0 while pos < len(string): m = SKIP_RE.match(string, pos=pos) if m: skip_lines = m.group(0).split('\n') if len(skip_lines) > 1: ...
Create a token stream by reading an input file Read tokens from `f`. If an include directive ('@include "file.cfg"') is found, read its contents as well. The `filename` argument is used for error messages and to detect circular imports. ``includedir`` sets the lookup directory for incl...
def from_file(cls, f, filename=None, includedir='', seenfiles=None): '''Create a token stream by reading an input file Read tokens from `f`. If an include directive ('@include "file.cfg"') is found, read its contents as well. The `filename` argument is used for error messages and to de...
Return (but do not consume) the next token At the end of input, ``None`` is returned.
def peek(self): '''Return (but do not consume) the next token At the end of input, ``None`` is returned. ''' if self.position >= len(self.tokens): return None return self.tokens[self.position]
Consume and return the next token if it has the correct type Multiple token types (as strings, e.g. 'integer64') can be given as arguments. If the next token is one of them, consume and return it. If the token type doesn't match, return None.
def accept(self, *args): '''Consume and return the next token if it has the correct type Multiple token types (as strings, e.g. 'integer64') can be given as arguments. If the next token is one of them, consume and return it. If the token type doesn't match, return None. ''' ...
Consume and return the next token if it has the correct type Multiple token types (as strings, e.g. 'integer64') can be given as arguments. If the next token is one of them, consume and return it. If the token type doesn't match, raise a ConfigParseError.
def expect(self, *args): '''Consume and return the next token if it has the correct type Multiple token types (as strings, e.g. 'integer64') can be given as arguments. If the next token is one of them, consume and return it. If the token type doesn't match, raise a ConfigParseError. ...
Raise a ConfigParseError at the current input position
def error(self, msg): '''Raise a ConfigParseError at the current input position''' if self.finished(): raise ConfigParseError("Unexpected end of input; %s" % (msg,)) else: t = self.peek() raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
Load variables from environment variables.
def load_variables(): """Load variables from environment variables.""" if (not os.environ.get("PYCONFLUENCE_TOKEN") or not os.environ.get("PYCONFLUENCE_USER") or not os.environ.get("PYCONFLUENCE_ORG")): print ("One or more pyconfluence environment variables are not set. " ...
Main function to be called from this module. send a request using method 'req' and to the url. the _rest() function will add the base_url to this, so 'url' should be something like '/ips'.
def rest(url, req="GET", data=None): """Main function to be called from this module. send a request using method 'req' and to the url. the _rest() function will add the base_url to this, so 'url' should be something like '/ips'. """ load_variables() return _rest(base_url + url, req, data)
Send a rest rest request to the server.
def _rest(url, req, data=None): """Send a rest rest request to the server.""" if url.upper().startswith("HTTPS"): print("Secure connection required: Please use HTTPS or https") return "" req = req.upper() if req != "GET" and req != "PUT" and req != "POST" and req != "DELETE": re...
Take action based on what kind of request is needed.
def _api_action(url, req, data=None): """Take action based on what kind of request is needed.""" requisite_headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} auth = (user, token) if req == "GET": response = requests.get(url, headers=requisite_h...
See: https://core.telegram.org/bots/api#sendanimation :param animation: Same as ``photo`` in :meth:`amanobot.aio.Bot.sendPhoto`
async def sendAnimation(self, chat_id, animation, duration=None, width=None, height=None, thumb=None, caption=None, parse_mode=None, ...
See: https://core.telegram.org/bots/api#sendvenue
async def sendVenue(self, chat_id, latitude, longitude, title, address, foursquare_id=None, foursquare_type=None, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ S...
See: https://core.telegram.org/bots/api#sendcontact
async def sendContact(self, chat_id, phone_number, first_name, last_name=None, vcard=None, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ See: https://c...
See: https://core.telegram.org/bots/api#sendpoll
async def sendPoll(self, chat_id, question, options, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ See: https://core.telegram.org/bots/api#sendpoll """ p = _strip(locals()) return await self._api_...
See: https://core.telegram.org/bots/api#editmessagemedia :param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.aio.Bot.editMessageText`
async def editMessageMedia(self, msg_identifier, media, reply_markup=None): """ See: https://core.telegram.org/bots/api#editmessagemedia :param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.aio.Bot.editMessageText` """ p = _strip(lo...
Return two dictionaries: compiled and text prompts.
def _prepare_patterns(self, pattern_dict): """Return two dictionaries: compiled and text prompts.""" dict_compiled = {} dict_text = {} dict_dscr = {} for platform, patterns in pattern_dict.items(): dict_text[platform] = {} dict_compiled[platform] = {} ...
Return all the patterns for specific platform.
def _platform_patterns(self, platform='generic', compiled=False): """Return all the patterns for specific platform.""" patterns = self._dict_compiled.get(platform, None) if compiled else self._dict_text.get(platform, None) if patterns is None: raise KeyError("Unknown platform: {}".fo...
Return the pattern defined by the key string specific to the platform. :param platform: :param key: :param compiled: :return: Pattern string or RE object.
def pattern(self, platform, key, compiled=True): """Return the pattern defined by the key string specific to the platform. :param platform: :param key: :param compiled: :return: Pattern string or RE object. """ patterns = self._platform_patterns(platform, compile...
Return the patter description.
def description(self, platform, key): """Return the patter description.""" patterns = self._dict_dscr.get(platform, None) description = patterns.get(key, None) return description
Return the platform name based on the prompt matching.
def platform(self, with_prompt, platforms=None): """Return the platform name based on the prompt matching.""" if platforms is None: platforms = self._dict['generic']['prompt_detection'] for platform in platforms: pattern = self.pattern(platform, 'prompt') res...
Execute after connect.
def after_connect(self): """Execute after connect.""" # TODO: check if this works. show_users = self.device.send("show users", timeout=120) result = re.search(pattern_manager.pattern(self.platform, 'connected_locally'), show_users) if result: self.log('Locally connect...
Return the version information from Unix host.
def get_version_text(self): """Return the version information from Unix host.""" try: version_text = self.device.send('uname -sr', timeout=10) except CommandError: self.log("Non Unix jumphost type detected") return None raise ConnectionError("Non U...
Return hostname information from the Unix host.
def get_hostname_text(self): """Return hostname information from the Unix host.""" # FIXME: fix it, too complex logic try: hostname_text = self.device.send('hostname', timeout=10) if hostname_text: self.device.hostname = hostname_text.splitlines()[0] ...
Extend prompt with flexible mode handling regexp.
def make_dynamic_prompt(self, prompt): """Extend prompt with flexible mode handling regexp.""" patterns = ["[\r\n]" + pattern_manager.pattern( self.platform, pattern_name, compiled=False) for pattern_name in self.target_prompt_components] patterns_re = "|".join(patterns).format(host...
Find a config file if possible.
def _find_file(f): """Find a config file if possible.""" if os.path.isabs(f): return f else: for d in Config._dirs: _f = os.path.join(d, f) if os.path.isfile(_f): return _f raise FiggypyError( ...
Get values from config file
def _load_file(self, f): """Get values from config file""" try: with open(f, 'r') as _fo: _seria_in = seria.load(_fo) _y = _seria_in.dump('yaml') except IOError: raise FiggypyError("could not open configuration file") self.values.up...
Make setup easier by providing a constructor method. Move to config_file File can be located with a filename only, relative path, or absolute path. If only name or relative path is provided, look in this order: 1. current directory 2. `~/.config/<file_name>` 3. `/etc/<f...
def setup(self, config_file=None, aws_config=None, gpg_config=None, decrypt_gpg=True, decrypt_kms=True): """Make setup easier by providing a constructor method. Move to config_file File can be located with a filename only, relative path, or absolute path. If only name or r...
Authenticate using the Console Server protocol specific FSM.
def authenticate(self, driver): """Authenticate using the Console Server protocol specific FSM.""" # 0 1 2 3 events = [driver.username_re, driver.password_re, self.device.prompt_re, driver.rommon_re, ...
Disconnect using protocol specific method.
def disconnect(self, device): """Disconnect using protocol specific method.""" self.device.ctrl.sendcontrol('d') self.device.ctrl.send("c.") self.log("CONSOLE SERVER disconnect") try: self.device.ctrl.send(chr(4)) except OSError: self.log("Protocol...
Pass the call to the attribute called attribute_name for every method listed in method_names.
def delegate(attribute_name, method_names): """Pass the call to the attribute called attribute_name for every method listed in method_names.""" # hack for python 2.7 as nonlocal is not available info = { 'attribute': attribute_name, 'methods': method_names } def decorator(cls): ...
Convert regex pattern to string. If pattern is string it returns itself, if pattern is SRE_Pattern then return pattern attribute :param pattern: pattern object or string :return: str: pattern sttring
def pattern_to_str(pattern): """Convert regex pattern to string. If pattern is string it returns itself, if pattern is SRE_Pattern then return pattern attribute :param pattern: pattern object or string :return: str: pattern sttring """ if isinstance(pattern, str): return repr(patter...
Check reachability for specified hostname/port. It tries to open TCP socket. It supports IPv6. :param host: hostname or ip address string :rtype: str :param port: tcp port number :rtype: number :return: True if host is reachable else false
def is_reachable(host, port=23): """Check reachability for specified hostname/port. It tries to open TCP socket. It supports IPv6. :param host: hostname or ip address string :rtype: str :param port: tcp port number :rtype: number :return: True if host is reachable else false """ ...
Calculate the Levenshtein distance between string a and b. :param str_a: String - input string a :param str_b: String - input string b :return: Number - Levenshtein Distance between string a and b
def levenshtein_distance(str_a, str_b): """Calculate the Levenshtein distance between string a and b. :param str_a: String - input string a :param str_b: String - input string b :return: Number - Levenshtein Distance between string a and b """ len_a, len_b = len(str_a), len(str_b) if len_a ...
Parse the inventory text and return udi dict.
def parse_inventory(inventory_output=None): """Parse the inventory text and return udi dict.""" udi = { "name": "", "description": "", "pid": "", "vid": "", "sn": "" } if inventory_output is None: return udi # find the record with chassis text in name...
Overload urls and make list of lists of urls.
def normalize_urls(urls): """Overload urls and make list of lists of urls.""" _urls = [] if isinstance(urls, list): if urls: if isinstance(urls[0], list): # multiple connections (list of the lists) _urls = urls elif isinstance(urls[0], str): ...
Read yaml file and return the dict. It assumes the module file exists with the defaults. If the CONDOOR_{SCRIPT_NAME} env is set then the user file from the env is loaded and merged with the default There can be user file located in ~/.condoor directory with the {script_name}.yaml filename. If exists ...
def yaml_file_to_dict(script_name, path=None): """Read yaml file and return the dict. It assumes the module file exists with the defaults. If the CONDOOR_{SCRIPT_NAME} env is set then the user file from the env is loaded and merged with the default There can be user file located in ~/.condoor director...
Override the standard write method to filter the content.
def write(self, text): """Override the standard write method to filter the content.""" index = text.find('\n') if index == -1: self._buffer = self._buffer + text else: self._buffer = self._buffer + text[:index + 1] if self._pattern: # p...
Converts the internal stat type of yappi(which is returned by a call to YFuncStats.get()) as pstats object.
def convert2pstats(stats): """ Converts the internal stat type of yappi(which is returned by a call to YFuncStats.get()) as pstats object. """ if not isinstance(stats, YFuncStats): raise YappiError("Source stats must be derived from YFuncStats.") import pstats class _PStatHolder...
Start profiler.
def start(builtins=False, profile_threads=True): """ Start profiler. """ if profile_threads: threading.setprofile(_callback) _yappi.start(builtins, profile_threads)
Sets the internal clock type for timing. Profiler shall not have any previous stats. Otherwise an exception is thrown.
def set_clock_type(type): """ Sets the internal clock type for timing. Profiler shall not have any previous stats. Otherwise an exception is thrown. """ type = type.upper() if type not in CLOCK_TYPES: raise YappiError("Invalid clock type:%s" % (type)) _yappi.set_clock_type(C...
Check for basic sanity errors in stats. e.g: Check for duplicate stats.
def _debug_check_sanity(self): """ Check for basic sanity errors in stats. e.g: Check for duplicate stats. """ for x in self: if self._stats.count(x) > 1: return False return True
Prints all of the child function profiler results to a given file. (stdout by default)
def print_all(self, out=sys.stdout): """ Prints all of the child function profiler results to a given file. (stdout by default) """ if self.empty(): return FUNC_NAME_LEN = 38 CALLCOUNT_LEN = 9 out.write(CRLF) out.write("name ...
Writes all the function stats in a callgrind-style format to the given file. (stdout by default)
def _save_as_CALLGRIND(self, path): """ Writes all the function stats in a callgrind-style format to the given file. (stdout by default) """ header = """version: 1\ncreator: %s\npid: %d\ncmd: %s\npart: 1\n\nevents: Ticks""" % \ ('yappi', os.getpid(), ' '...
Prints all of the thread profiler results to a given file. (stdout by default)
def print_all(self, out=sys.stdout): """ Prints all of the thread profiler results to a given file. (stdout by default) """ THREAD_FUNC_NAME_LEN = 25 THREAD_NAME_LEN = 13 THREAD_ID_LEN = 15 THREAD_SCHED_CNT_LEN = 10 out.write(CRLF) out.write("name...
Reads a reply from the server. Raises: ConnectionResetError: If the connection with the server is lost (we can't read any response anymore). Or if the server replies without a proper return code. Returns: (int, str): A (code, full_message) 2-tupl...
async def read_reply(self): """ Reads a reply from the server. Raises: ConnectionResetError: If the connection with the server is lost (we can't read any response anymore). Or if the server replies without a proper return code. Returns: ...
Sends the given command to the server. Args: command (str): Command to send to the server. Raises: ConnectionResetError: If the connection with the server is lost. (Shouldn't it raise BrokenPipeError too ?)
async def send_command(self, command): """ Sends the given command to the server. Args: command (str): Command to send to the server. Raises: ConnectionResetError: If the connection with the server is lost. (Shouldn't it raise BrokenPipeError too ?) ...
Build HopInfo object from url. It allows only telnet and ssh as a valid protocols. Args: url (str): The url string describing the node. i.e. telnet://username@1.1.1.1. The protocol, username and address portion of url is mandatory. Port and password is optional. If ...
def make_hop_info_from_url(url, verify_reachability=None): """Build HopInfo object from url. It allows only telnet and ssh as a valid protocols. Args: url (str): The url string describing the node. i.e. telnet://username@1.1.1.1. The protocol, username and address portion o...
Return if host is reachable.
def is_reachable(self): """Return if host is reachable.""" if self.verify_reachability and \ hasattr(self.verify_reachability, '__call__'): return self.verify_reachability(host=self.hostname, port=self.port) # assume is reachable if can't verify return True
Returns (ts, rvs), where ts is a list of arrays of observation times (one array for each observatory), and rvs is a corresponding list of total radial velocity measurements.
def generate(self): """Returns (ts, rvs), where ts is a list of arrays of observation times (one array for each observatory), and rvs is a corresponding list of total radial velocity measurements.""" ts=self.generate_tobs() noise=self.generate_noise(ts) rvs=[] ...
Change to the privilege mode.
def enable(self, enable_password): """Change to the privilege mode.""" if self.device.prompt[-1] == '#': self.log("Device is already in privileged mode") return events = [self.password_re, self.device.prompt_re, pexpect.TIMEOUT, pexpect.EOF] transitions = [ ...
Reload the device. CSM_DUT#reload System configuration has been modified. Save? [yes/no]: yes Building configuration... [OK] Proceed with reload? [confirm]
def reload(self, reload_timeout=300, save_config=True): """Reload the device. CSM_DUT#reload System configuration has been modified. Save? [yes/no]: yes Building configuration... [OK] Proceed with reload? [confirm] """ response = "yes" if save_config els...
Apply config.
def config(self, config_text, plane): """Apply config.""" nol = config_text.count('\n') config_lines = iter(config_text.splitlines()) events = [self.prompt_re, self.syntax_error_re] transitions = [ (self.prompt_re, [0], 0, partial(a_send_line, config_lines), 10), ...
Get the types of a subtag string (excludes redundant and grandfathered). :param str subtag: subtag. :return: list of types. The return list can be empty.
def types(subtag): """ Get the types of a subtag string (excludes redundant and grandfathered). :param str subtag: subtag. :return: list of types. The return list can be empty. """ if subtag in index: types = index[subtag] return [type for type i...
Get a list of existing :class:`language_tags.Subtag.Subtag` objects given the input subtag(s). :param subtags: string subtag or list of string subtags. :return: a list of existing :class:`language_tags.Subtag.Subtag` objects. The return list can be empty.
def subtags(subtags): """ Get a list of existing :class:`language_tags.Subtag.Subtag` objects given the input subtag(s). :param subtags: string subtag or list of string subtags. :return: a list of existing :class:`language_tags.Subtag.Subtag` objects. The return list can be empty. ...
Get a list of non-existing string subtag(s) given the input string subtag(s). :param subtags: string subtag or a list of string subtags. :return: list of non-existing string subtags. The return list can be empty.
def filter(subtags): """ Get a list of non-existing string subtag(s) given the input string subtag(s). :param subtags: string subtag or a list of string subtags. :return: list of non-existing string subtags. The return list can be empty. """ if not isinstance(subtags, li...
Gets a list of :class:`language_tags.Subtag.Subtag` objects where the description matches. :param description: a string or compiled regular expression. For example: ``search(re.compile('\d{4}'))`` if the description of the returned subtag must contain four contiguous numerical digits. :type...
def search(description, all=False): """ Gets a list of :class:`language_tags.Subtag.Subtag` objects where the description matches. :param description: a string or compiled regular expression. For example: ``search(re.compile('\d{4}'))`` if the description of the returned subtag must...
Gets a list of descriptions given the tag. :param str tag: (hyphen-separated) tag. :return: list of string descriptions. The return list can be empty.
def description(tag): """ Gets a list of descriptions given the tag. :param str tag: (hyphen-separated) tag. :return: list of string descriptions. The return list can be empty. """ tag_object = Tag(tag) results = [] results.extend(tag_object.descriptions)...
Get a list of :class:`language_tags.Subtag.Subtag` objects given the string macrolanguage. :param string macrolanguage: subtag macrolanguage. :return: a list of the macrolanguage :class:`language_tags.Subtag.Subtag` objects. :raise Exception: if the macrolanguage does not exists.
def languages(macrolanguage): """ Get a list of :class:`language_tags.Subtag.Subtag` objects given the string macrolanguage. :param string macrolanguage: subtag macrolanguage. :return: a list of the macrolanguage :class:`language_tags.Subtag.Subtag` objects. :raise Exception: if...
Get a :class:`language_tags.Subtag.Subtag` by subtag and type. Can be None if not exists. :param str subtag: subtag. :param str type: type of the subtag. :return: :class:`language_tags.Subtag.Subtag` if exists, otherwise None.
def type(subtag, type): """ Get a :class:`language_tags.Subtag.Subtag` by subtag and type. Can be None if not exists. :param str subtag: subtag. :param str type: type of the subtag. :return: :class:`language_tags.Subtag.Subtag` if exists, otherwise None. """ subt...
Draw ``N`` samples from the prior.
def prior_draw(self, N=1): """ Draw ``N`` samples from the prior. """ p = np.random.ranf(size=(N, self.ndim)) p = (self._upper_right - self._lower_left) * p + self._lower_left return p
Use a uniform, bounded prior.
def lnprior(self, X): """ Use a uniform, bounded prior. """ if np.any(X < self._lower_left) or np.any(X > self._upper_right): return -np.inf else: return 0.0
Use a softened version of the interpolant as a likelihood.
def lnlike(self, X): """ Use a softened version of the interpolant as a likelihood. """ return -3.5*np.log(self._interpolant(X[0], X[1], grid=False))
Print detected information.
def echo_info(conn): """Print detected information.""" click.echo("General information:") click.echo(" Hostname: {}".format(conn.hostname)) click.echo(" HW Family: {}".format(conn.family)) click.echo(" HW Platform: {}".format(conn.platform)) click.echo(" SW Type: {}".format(conn.os_type)) cl...
Run the main function.
def run(url, cmd, log_path, log_level, log_session, force_discovery, print_info): """Run the main function.""" log_level = log_levels[log_level] conn = condoor.Connection("host", list(url), log_session=log_session, log_level=log_level, log_dir=log_path) try: conn.connect(force_discovery=force_di...
Convert to URL scheme.
def convert(self, value, param, ctx): """Convert to URL scheme.""" if not isinstance(value, tuple): parsed = urlparse.urlparse(value) if parsed.scheme not in ('telnet', 'ssh'): self.fail('invalid URL scheme (%s). Only telnet and ssh URLs are ' ...
Send text line to the controller followed by `os.linesep`.
def a_send_line(text, ctx): """Send text line to the controller followed by `os.linesep`.""" if hasattr(text, '__iter__'): try: ctx.ctrl.sendline(text.next()) except StopIteration: ctx.finished = True else: ctx.ctrl.sendline(text) return True
Sent the username text.
def a_send_username(username, ctx): """Sent the username text.""" if username: ctx.ctrl.sendline(username) return True else: ctx.ctrl.disconnect() raise ConnectionAuthenticationError("Username not provided", ctx.ctrl.hostname)
Send the password text. Before sending the password local echo is disabled. If password not provided it disconnects from the device and raises ConnectionAuthenticationError exception.
def a_send_password(password, ctx): """Send the password text. Before sending the password local echo is disabled. If password not provided it disconnects from the device and raises ConnectionAuthenticationError exception. """ if password: ctx.ctrl.send_command(password, password=True) ...