sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def reference(self): """Return the Reference object for this Key. This is a entity_pb.Reference instance -- a protocol buffer class used by the lower-level API to the datastore. NOTE: The caller should not mutate the return value. """ if self.__reference is None: self.__reference = _Cons...
Return the Reference object for this Key. This is a entity_pb.Reference instance -- a protocol buffer class used by the lower-level API to the datastore. NOTE: The caller should not mutate the return value.
entailment
def urlsafe(self): """Return a url-safe string encoding this Key's Reference. This string is compatible with other APIs and languages and with the strings used to represent Keys in GQL and in the App Engine Admin Console. """ # This is 3-4x faster than urlsafe_b64decode() urlsafe = base64.b...
Return a url-safe string encoding this Key's Reference. This string is compatible with other APIs and languages and with the strings used to represent Keys in GQL and in the App Engine Admin Console.
entailment
def get_async(self, **ctx_options): """Return a Future whose result is the entity for this Key. If no such entity exists, a Future is still returned, and the Future's eventual return result be None. """ from . import model, tasklets ctx = tasklets.get_context() cls = model.Model._kind_map.g...
Return a Future whose result is the entity for this Key. If no such entity exists, a Future is still returned, and the Future's eventual return result be None.
entailment
def delete_async(self, **ctx_options): """Schedule deletion of the entity for this Key. This returns a Future, whose result becomes available once the deletion is complete. If no such entity exists, a Future is still returned. In all cases the Future's result is None (i.e. there is no way to tell...
Schedule deletion of the entity for this Key. This returns a Future, whose result becomes available once the deletion is complete. If no such entity exists, a Future is still returned. In all cases the Future's result is None (i.e. there is no way to tell whether the entity existed or not).
entailment
def add_flow_exception(exc): """Add an exception that should not be logged. The argument must be a subclass of Exception. """ global _flow_exceptions if not isinstance(exc, type) or not issubclass(exc, Exception): raise TypeError('Expected an Exception subclass, got %r' % (exc,)) as_set = set(_flow_exc...
Add an exception that should not be logged. The argument must be a subclass of Exception.
entailment
def _init_flow_exceptions(): """Internal helper to initialize _flow_exceptions. This automatically adds webob.exc.HTTPException, if it can be imported. """ global _flow_exceptions _flow_exceptions = () add_flow_exception(datastore_errors.Rollback) try: from webob import exc except ImportError: ...
Internal helper to initialize _flow_exceptions. This automatically adds webob.exc.HTTPException, if it can be imported.
entailment
def sleep(dt): """Public function to sleep some time. Example: yield tasklets.sleep(0.5) # Sleep for half a sec. """ fut = Future('sleep(%.3f)' % dt) eventloop.queue_call(dt, fut.set_result, None) return fut
Public function to sleep some time. Example: yield tasklets.sleep(0.5) # Sleep for half a sec.
entailment
def _transfer_result(fut1, fut2): """Helper to transfer result or errors from one Future to another.""" exc = fut1.get_exception() if exc is not None: tb = fut1.get_traceback() fut2.set_exception(exc, tb) else: val = fut1.get_result() fut2.set_result(val)
Helper to transfer result or errors from one Future to another.
entailment
def synctasklet(func): """Decorator to run a function as a tasklet when called. Use this to wrap a request handler function that will be called by some web application framework (e.g. a Django view function or a webapp.RequestHandler.get method). """ taskletfunc = tasklet(func) # wrap at declaration time....
Decorator to run a function as a tasklet when called. Use this to wrap a request handler function that will be called by some web application framework (e.g. a Django view function or a webapp.RequestHandler.get method).
entailment
def toplevel(func): """A sync tasklet that sets a fresh default Context. Use this for toplevel view functions such as webapp.RequestHandler.get() or Django view functions. """ synctaskletfunc = synctasklet(func) # wrap at declaration time. @utils.wrapping(func) def add_context_wrapper(*args, **kwds): ...
A sync tasklet that sets a fresh default Context. Use this for toplevel view functions such as webapp.RequestHandler.get() or Django view functions.
entailment
def _make_cloud_datastore_context(app_id, external_app_ids=()): """Creates a new context to connect to a remote Cloud Datastore instance. This should only be used outside of Google App Engine. Args: app_id: The application id to connect to. This differs from the project id as it may have an additional...
Creates a new context to connect to a remote Cloud Datastore instance. This should only be used outside of Google App Engine. Args: app_id: The application id to connect to. This differs from the project id as it may have an additional prefix, e.g. "s~" or "e~". external_app_ids: A list of apps that...
entailment
def _analyze_indexed_fields(indexed_fields): """Internal helper to check a list of indexed fields. Args: indexed_fields: A list of names, possibly dotted names. (A dotted name is a string containing names separated by dots, e.g. 'foo.bar.baz'. An undotted name is a string containing no dots, e.g. 'foo'...
Internal helper to check a list of indexed fields. Args: indexed_fields: A list of names, possibly dotted names. (A dotted name is a string containing names separated by dots, e.g. 'foo.bar.baz'. An undotted name is a string containing no dots, e.g. 'foo'.) Returns: A dict whose keys are undotted ...
entailment
def _make_model_class(message_type, indexed_fields, **props): """Construct a Model subclass corresponding to a Message subclass. Args: message_type: A Message subclass. indexed_fields: A list of dotted and undotted field names. **props: Additional properties with which to seed the class. Returns: ...
Construct a Model subclass corresponding to a Message subclass. Args: message_type: A Message subclass. indexed_fields: A list of dotted and undotted field names. **props: Additional properties with which to seed the class. Returns: A Model subclass whose properties correspond to those fields of ...
entailment
def _message_to_entity(msg, modelclass): """Recursive helper for _to_base_type() to convert a message to an entity. Args: msg: A Message instance. modelclass: A Model subclass. Returns: An instance of modelclass. """ ent = modelclass() for prop_name, prop in modelclass._properties.iteritems():...
Recursive helper for _to_base_type() to convert a message to an entity. Args: msg: A Message instance. modelclass: A Model subclass. Returns: An instance of modelclass.
entailment
def _projected_entity_to_message(ent, message_type): """Recursive helper for _from_base_type() to convert an entity to a message. Args: ent: A Model instance. message_type: A Message subclass. Returns: An instance of message_type. """ msg = message_type() analyzed = _analyze_indexed_fields(ent...
Recursive helper for _from_base_type() to convert an entity to a message. Args: ent: A Model instance. message_type: A Message subclass. Returns: An instance of message_type.
entailment
def _validate(self, value): """Validate an Enum value. Raises: TypeError if the value is not an instance of self._enum_type. """ if not isinstance(value, self._enum_type): raise TypeError('Expected a %s instance, got %r instead' % (self._enum_type.__name__, value))
Validate an Enum value. Raises: TypeError if the value is not an instance of self._enum_type.
entailment
def _validate(self, msg): """Validate an Enum value. Raises: TypeError if the value is not an instance of self._message_type. """ if not isinstance(msg, self._message_type): raise TypeError('Expected a %s instance for %s property', self._message_type.__name__, ...
Validate an Enum value. Raises: TypeError if the value is not an instance of self._message_type.
entailment
def _to_base_type(self, msg): """Convert a Message value to a Model instance (entity).""" ent = _message_to_entity(msg, self._modelclass) ent.blob_ = self._protocol_impl.encode_message(msg) return ent
Convert a Message value to a Model instance (entity).
entailment
def _from_base_type(self, ent): """Convert a Model instance (entity) to a Message value.""" if ent._projection: # Projection query result. Reconstitute the message from the fields. return _projected_entity_to_message(ent, self._message_type) blob = ent.blob_ if blob is not None: prot...
Convert a Model instance (entity) to a Message value.
entailment
def _get_value(self, entity): """Compute and store a default value if necessary.""" value = super(_ClassKeyProperty, self)._get_value(entity) if not value: value = entity._class_key() self._store_value(entity, value) return value
Compute and store a default value if necessary.
entailment
def _update_kind_map(cls): """Override; called by Model._fix_up_properties(). Update the kind map as well as the class map, except for PolyModel itself (its class key is empty). Note that the kind map will contain entries for all classes in a PolyModel hierarchy; they all have the same kind, but d...
Override; called by Model._fix_up_properties(). Update the kind map as well as the class map, except for PolyModel itself (its class key is empty). Note that the kind map will contain entries for all classes in a PolyModel hierarchy; they all have the same kind, but different class names. PolyModel c...
entailment
def _from_pb(cls, pb, set_key=True, ent=None, key=None): """Override. Use the class map to give the entity the correct subclass. """ prop_name = cls.class_._name class_name = [] for plist in [pb.property_list(), pb.raw_property_list()]: for p in plist: if p.name() == prop_name: ...
Override. Use the class map to give the entity the correct subclass.
entailment
def _get_kind(cls): """Override. Make sure that the kind returned is the root class of the polymorphic hierarchy. """ bases = cls._get_hierarchy() if not bases: # We have to jump through some hoops to call the superclass' # _get_kind() method. First, this is called by the metaclass...
Override. Make sure that the kind returned is the root class of the polymorphic hierarchy.
entailment
def _get_hierarchy(cls): """Internal helper to return the list of polymorphic base classes. This returns a list of class objects, e.g. [Animal, Feline, Cat]. """ bases = [] for base in cls.mro(): # pragma: no branch if hasattr(base, '_get_hierarchy'): bases.append(base) del bases...
Internal helper to return the list of polymorphic base classes. This returns a list of class objects, e.g. [Animal, Feline, Cat].
entailment
def find_env_paths_in_basedirs(base_dirs): """Returns all potential envs in a basedir""" # get potential env path in the base_dirs env_path = [] for base_dir in base_dirs: env_path.extend(glob.glob(os.path.join( os.path.expanduser(base_dir), '*', ''))) # self.log.info("Found the ...
Returns all potential envs in a basedir
entailment
def convert_to_env_data(mgr, env_paths, validator_func, activate_func, name_template, display_name_template, name_prefix): """Converts a list of paths to environments to env_data. env_data is a structure {name -> (ressourcedir, kernel spec)} """ env_data = {} for venv_dir in...
Converts a list of paths to environments to env_data. env_data is a structure {name -> (ressourcedir, kernel spec)}
entailment
def validate_IPykernel(venv_dir): """Validates that this env contains an IPython kernel and returns info to start it Returns: tuple (ARGV, language, resource_dir) """ python_exe_name = find_exe(venv_dir, "python") if python_exe_name is None: python_exe_name = find_exe(venv_dir, "py...
Validates that this env contains an IPython kernel and returns info to start it Returns: tuple (ARGV, language, resource_dir)
entailment
def validate_IRkernel(venv_dir): """Validates that this env contains an IRkernel kernel and returns info to start it Returns: tuple (ARGV, language, resource_dir) """ r_exe_name = find_exe(venv_dir, "R") if r_exe_name is None: return [], None, None # check if this is really an...
Validates that this env contains an IRkernel kernel and returns info to start it Returns: tuple (ARGV, language, resource_dir)
entailment
def find_exe(env_dir, name): """Finds a exe with that name in the environment path""" if platform.system() == "Windows": name = name + ".exe" # find the binary exe_name = os.path.join(env_dir, name) if not os.path.exists(exe_name): exe_name = os.path.join(env_dir, "bin", name) ...
Finds a exe with that name in the environment path
entailment
def get_virtualenv_env_data(mgr): """Finds kernel specs from virtualenv environments env_data is a structure {name -> (resourcedir, kernel spec)} """ if not mgr.find_virtualenv_envs: return {} mgr.log.debug("Looking for virtualenv environments in %s...", mgr.virtualenv_env_dirs) # fi...
Finds kernel specs from virtualenv environments env_data is a structure {name -> (resourcedir, kernel spec)}
entailment
def source_bash(args, stdin=None): """Simply bash-specific wrapper around source-foreign Returns a dict to be used as a new environment""" args = list(args) new_args = ['bash', '--sourcer=source'] new_args.extend(args) return source_foreign(new_args, stdin=stdin)
Simply bash-specific wrapper around source-foreign Returns a dict to be used as a new environment
entailment
def source_zsh(args, stdin=None): """Simply zsh-specific wrapper around source-foreign Returns a dict to be used as a new environment""" args = list(args) new_args = ['zsh', '--sourcer=source'] new_args.extend(args) return source_foreign(new_args, stdin=stdin)
Simply zsh-specific wrapper around source-foreign Returns a dict to be used as a new environment
entailment
def source_cmd(args, stdin=None): """Simple cmd.exe-specific wrapper around source-foreign. returns a dict to be used as a new environment """ args = list(args) fpath = locate_binary(args[0]) args[0] = fpath if fpath else args[0] if not os.path.isfile(args[0]): raise RuntimeError("C...
Simple cmd.exe-specific wrapper around source-foreign. returns a dict to be used as a new environment
entailment
def argvquote(arg, force=False): """ Returns an argument quoted in such a way that that CommandLineToArgvW on Windows will return the argument string unchanged. This is the same thing Popen does when supplied with an list of arguments. Arguments in a command line should be separated by spaces; this ...
Returns an argument quoted in such a way that that CommandLineToArgvW on Windows will return the argument string unchanged. This is the same thing Popen does when supplied with an list of arguments. Arguments in a command line should be separated by spaces; this function does not add these spaces. This ...
entailment
def escape_windows_cmd_string(s): """Returns a string that is usable by the Windows cmd.exe. The escaping is based on details here and emperical testing: http://www.robvanderwoude.com/escapechars.php """ for c in '()%!^<>&|"': s = s.replace(c, '^' + c) s = s.replace('/?', '/.') retur...
Returns a string that is usable by the Windows cmd.exe. The escaping is based on details here and emperical testing: http://www.robvanderwoude.com/escapechars.php
entailment
def source_foreign(args, stdin=None): """Sources a file written in a foreign shell language.""" parser = _ensure_source_foreign_parser() ns = parser.parse_args(args) if ns.prevcmd is not None: pass # don't change prevcmd if given explicitly elif os.path.isfile(ns.files_or_code[0]): ...
Sources a file written in a foreign shell language.
entailment
def _is_executable_file(path): """Checks that path is an executable regular file, or a symlink towards one. This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``. This function was forked from pexpect originally: Copyright (c) 2013-2014, Pexpect development team Copyright (c) 2012,...
Checks that path is an executable regular file, or a symlink towards one. This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``. This function was forked from pexpect originally: Copyright (c) 2013-2014, Pexpect development team Copyright (c) 2012, Noah Spurrier <noah@noah.org> PE...
entailment
def foreign_shell_data(shell, interactive=True, login=False, envcmd=None, aliascmd=None, extra_args=(), currenv=None, safe=False, prevcmd='', postcmd='', funcscmd=None, sourcer=None, use_tmpfile=False, tmpfile_ext=None, runcmd=N...
Extracts data from a foreign (non-xonsh) shells. Currently this gets the environment, aliases, and functions but may be extended in the future. Parameters ---------- shell : str The name of the shell, such as 'bash' or '/bin/sh'. interactive : bool, optional Whether the shell should...
entailment
def to_bool(x): """"Converts to a boolean in a semantically meaningful way.""" if isinstance(x, bool): return x elif isinstance(x, str): return False if x.lower() in _FALSES else True else: return bool(x)
Converts to a boolean in a semantically meaningful way.
entailment
def parse_env(s): """Parses the environment portion of string into a dict.""" m = ENV_RE.search(s) if m is None: return {} g1 = m.group(1) env = dict(ENV_SPLIT_RE.findall(g1)) return env
Parses the environment portion of string into a dict.
entailment
def get_conda_env_data(mgr): """Finds kernel specs from conda environments env_data is a structure {name -> (resourcedir, kernel spec)} """ if not mgr.find_conda_envs: return {} mgr.log.debug("Looking for conda environments in %s...", mgr.conda_env_dirs) # find all potential env paths...
Finds kernel specs from conda environments env_data is a structure {name -> (resourcedir, kernel spec)}
entailment
def _find_conda_env_paths_from_conda(mgr): """Returns a list of path as given by `conda env list --json`. Returns empty list, if conda couldn't be called. """ # this is expensive, so make it configureable... if not mgr.use_conda_directly: return [] mgr.log.debug("Looking for conda envir...
Returns a list of path as given by `conda env list --json`. Returns empty list, if conda couldn't be called.
entailment
def validate_env(self, envname): """ Check the name of the environment against the black list and the whitelist. If a whitelist is specified only it is checked. """ if self.whitelist_envs and envname in self.whitelist_envs: return True elif self.whitelist_envs...
Check the name of the environment against the black list and the whitelist. If a whitelist is specified only it is checked.
entailment
def _get_env_data(self, reload=False): """Get the data about the available environments. env_data is a structure {name -> (resourcedir, kernel spec)} """ # This is called much too often and finding-process is really expensive :-( if not reload and getattr(self, "_env_data_cache...
Get the data about the available environments. env_data is a structure {name -> (resourcedir, kernel spec)}
entailment
def find_kernel_specs_for_envs(self): """Returns a dict mapping kernel names to resource directories.""" data = self._get_env_data() return {name: data[name][0] for name in data}
Returns a dict mapping kernel names to resource directories.
entailment
def get_all_kernel_specs_for_envs(self): """Returns the dict of name -> kernel_spec for all environments""" data = self._get_env_data() return {name: data[name][1] for name in data}
Returns the dict of name -> kernel_spec for all environments
entailment
def find_kernel_specs(self): """Returns a dict mapping kernel names to resource directories.""" # let real installed kernels overwrite envs with the same name: # this is the same order as the get_kernel_spec way, which also prefers # kernels from the jupyter dir over env kernels. ...
Returns a dict mapping kernel names to resource directories.
entailment
def get_all_specs(self): """Returns a dict mapping kernel names and resource directories. """ # This is new in 4.1 -> https://github.com/jupyter/jupyter_client/pull/93 specs = self.get_all_kernel_specs_for_envs() specs.update(super(EnvironmentKernelSpecManager, self).get_all_spec...
Returns a dict mapping kernel names and resource directories.
entailment
def get_kernel_spec(self, kernel_name): """Returns a :class:`KernelSpec` instance for the given kernel_name. Raises :exc:`NoSuchKernel` if the given kernel name is not found. """ try: return super(EnvironmentKernelSpecManager, self).get_kernel_spec(k...
Returns a :class:`KernelSpec` instance for the given kernel_name. Raises :exc:`NoSuchKernel` if the given kernel name is not found.
entailment
def to_latin(string_to_transliterate, lang_code='sr'): ''' Transliterate serbian cyrillic string of characters to latin string of characters. :param string_to_transliterate: The cyrillic string to transliterate into latin characters. :param lang_code: Indicates the cyrillic language code we are translating ...
Transliterate serbian cyrillic string of characters to latin string of characters. :param string_to_transliterate: The cyrillic string to transliterate into latin characters. :param lang_code: Indicates the cyrillic language code we are translating from. Defaults to Serbian (sr). :return: A string of latin ...
entailment
def to_cyrillic(string_to_transliterate, lang_code='sr'): ''' Transliterate serbian latin string of characters to cyrillic string of characters. :param string_to_transliterate: The latin string to transliterate into cyrillic characters. :param lang_code: Indicates the cyrillic language code we are translati...
Transliterate serbian latin string of characters to cyrillic string of characters. :param string_to_transliterate: The latin string to transliterate into cyrillic characters. :param lang_code: Indicates the cyrillic language code we are translating to. Defaults to Serbian (sr). :return: A string of cyrillic...
entailment
def parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as XML and returns the resulting data. """ assert etree, 'XMLParser requires defusedxml to be installed' parser_context = parser_context or {} encoding = parser_context.get(...
Parses the incoming bytestream as XML and returns the resulting data.
entailment
def _xml_convert(self, element): """ convert the xml `element` into the corresponding python object """ children = list(element) if len(children) == 0: return self._type_convert(element.text) else: # if the fist child tag is list-item means all c...
convert the xml `element` into the corresponding python object
entailment
def _type_convert(self, value): """ Converts the value returned by the XMl parse into the equivalent Python type """ if value is None: return value try: return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S') except ValueError: ...
Converts the value returned by the XMl parse into the equivalent Python type
entailment
def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders `data` into serialized XML. """ if data is None: return '' stream = StringIO() xml = SimplerXMLGenerator(stream, self.charset) xml.startDocument() xml.startE...
Renders `data` into serialized XML.
entailment
def open(self): """Open a connection to the device.""" device_type = 'cisco_ios' if self.transport == 'telnet': device_type = 'cisco_ios_telnet' self.device = ConnectHandler(device_type=device_type, host=self.hostname, ...
Open a connection to the device.
entailment
def _create_tmp_file(config): """Write temp file and for use with inline config and SCP.""" tmp_dir = tempfile.gettempdir() rand_fname = py23_compat.text_type(uuid.uuid4()) filename = os.path.join(tmp_dir, rand_fname) with open(filename, 'wt') as fobj: fobj.write(conf...
Write temp file and for use with inline config and SCP.
entailment
def _load_candidate_wrapper(self, source_file=None, source_config=None, dest_file=None, file_system=None): """ Transfer file to remote device for either merge or replace operations Returns (return_status, msg) """ return_status = False msg...
Transfer file to remote device for either merge or replace operations Returns (return_status, msg)
entailment
def load_replace_candidate(self, filename=None, config=None): """ SCP file to device filesystem, defaults to candidate_config. Return None or raise exception """ self.config_replace = True return_status, msg = self._load_candidate_wrapper(source_file=filename, ...
SCP file to device filesystem, defaults to candidate_config. Return None or raise exception
entailment
def load_merge_candidate(self, filename=None, config=None): """ SCP file to remote device. Merge configuration in: copy <file> running-config """ self.config_replace = False return_status, msg = self._load_candidate_wrapper(source_file=filename, ...
SCP file to remote device. Merge configuration in: copy <file> running-config
entailment
def _commit_hostname_handler(self, cmd): """Special handler for hostname change on commit operation.""" current_prompt = self.device.find_prompt().strip() terminating_char = current_prompt[-1] pattern = r"[>#{}]\s*$".format(terminating_char) # Look exclusively for trailing patter...
Special handler for hostname change on commit operation.
entailment
def commit_config(self): """ If replacement operation, perform 'configure replace' for the entire config. If merge operation, perform copy <file> running-config. """ # Always generate a rollback config on commit self._gen_rollback_cfg() if self.config_replace: ...
If replacement operation, perform 'configure replace' for the entire config. If merge operation, perform copy <file> running-config.
entailment
def discard_config(self): """Set candidate_cfg to current running-config. Erase the merge_cfg file.""" discard_candidate = 'copy running-config {}'.format(self._gen_full_path(self.candidate_cfg)) discard_merge = 'copy null: {}'.format(self._gen_full_path(self.merge_cfg)) self._disable_co...
Set candidate_cfg to current running-config. Erase the merge_cfg file.
entailment
def _xfer_file(self, source_file=None, source_config=None, dest_file=None, file_system=None, TransferClass=FileTransfer): """Transfer file to remote device. By default, this will use Secure Copy if self.inline_transfer is set, then will use Netmiko InlineTransfer method to tr...
Transfer file to remote device. By default, this will use Secure Copy if self.inline_transfer is set, then will use Netmiko InlineTransfer method to transfer inline using either SSH or telnet (plus TCL onbox). Return (status, msg) status = boolean msg = details on what ...
entailment
def _gen_full_path(self, filename, file_system=None): """Generate full file path on remote device.""" if file_system is None: return '{}/{}'.format(self.dest_file_system, filename) else: if ":" not in file_system: raise ValueError("Invalid file_system spec...
Generate full file path on remote device.
entailment
def _gen_rollback_cfg(self): """Save a configuration that can be used for rollback.""" cfg_file = self._gen_full_path(self.rollback_cfg) cmd = 'copy running-config {}'.format(cfg_file) self._disable_confirm() self.device.send_command_expect(cmd) self._enable_confirm()
Save a configuration that can be used for rollback.
entailment
def _check_file_exists(self, cfg_file): """ Check that the file exists on remote device using full path. cfg_file is full path i.e. flash:/file_name For example # dir flash:/candidate_config.txt Directory of flash:/candidate_config.txt 33 -rw- 5592 Dec...
Check that the file exists on remote device using full path. cfg_file is full path i.e. flash:/file_name For example # dir flash:/candidate_config.txt Directory of flash:/candidate_config.txt 33 -rw- 5592 Dec 18 2015 10:50:22 -08:00 candidate_config.txt retu...
entailment
def _expand_interface_name(self, interface_brief): """ Obtain the full interface name from the abbreviated name. Cache mappings in self.interface_map. """ if self.interface_map.get(interface_brief): return self.interface_map.get(interface_brief) command = 'sh...
Obtain the full interface name from the abbreviated name. Cache mappings in self.interface_map.
entailment
def get_lldp_neighbors(self): """IOS implementation of get_lldp_neighbors.""" lldp = {} command = 'show lldp neighbors' output = self._send_command(command) # Check if router supports the command if '% Invalid input' in output: return {} # Process th...
IOS implementation of get_lldp_neighbors.
entailment
def get_lldp_neighbors_detail(self, interface=''): """ IOS implementation of get_lldp_neighbors_detail. Calls get_lldp_neighbors. """ lldp = {} lldp_neighbors = self.get_lldp_neighbors() # Filter to specific interface if interface: lldp_data ...
IOS implementation of get_lldp_neighbors_detail. Calls get_lldp_neighbors.
entailment
def get_facts(self): """Return a set of facts from the devices.""" # default values. vendor = u'Cisco' uptime = -1 serial_number, fqdn, os_version, hostname, domain_name = ('Unknown',) * 5 # obtain output from device show_ver = self._send_command('show version') ...
Return a set of facts from the devices.
entailment
def get_interfaces(self): """ Get interface details. last_flapped is not implemented Example Output: { u'Vlan1': { 'description': u'N/A', 'is_enabled': True, 'is_up': True, 'last_flapped': -1.0, ...
Get interface details. last_flapped is not implemented Example Output: { u'Vlan1': { 'description': u'N/A', 'is_enabled': True, 'is_up': True, 'last_flapped': -1.0, 'mac_address': u'a493.4cc1.67a7', ...
entailment
def get_interfaces_ip(self): """ Get interface ip details. Returns a dict of dicts Example Output: { u'FastEthernet8': { 'ipv4': { u'10.66.43.169': { 'prefix_length': 22}}}, u'Loopback555': { 'ipv4': { u'192.168.1.1': { 'prefix_length': 24}}, ...
Get interface ip details. Returns a dict of dicts Example Output: { u'FastEthernet8': { 'ipv4': { u'10.66.43.169': { 'prefix_length': 22}}}, u'Loopback555': { 'ipv4': { u'192.168.1.1': { 'prefix_length': 24}}, 'ipv6': { u'1::1': { ...
entailment
def bgp_time_conversion(bgp_uptime): """ Convert string time to seconds. Examples 00:14:23 00:13:40 00:00:21 00:00:13 00:00:49 1d11h 1d17h 1w0d 8w5d 1y28w never """ bgp_uptime = bgp_uptime.st...
Convert string time to seconds. Examples 00:14:23 00:13:40 00:00:21 00:00:13 00:00:49 1d11h 1d17h 1w0d 8w5d 1y28w never
entailment
def get_bgp_neighbors(self): """BGP neighbor information. Currently no VRF support. Supports both IPv4 and IPv6. """ supported_afi = ['ipv4', 'ipv6'] bgp_neighbor_data = dict() bgp_neighbor_data['global'] = {} # get summary output from device cmd_bgp_al...
BGP neighbor information. Currently no VRF support. Supports both IPv4 and IPv6.
entailment
def get_environment(self): """ Get environment facts. power and fan are currently not implemented cpu is using 1-minute average cpu hard-coded to cpu0 (i.e. only a single CPU) """ environment = {} cpu_cmd = 'show proc cpu' mem_cmd = 'show memory s...
Get environment facts. power and fan are currently not implemented cpu is using 1-minute average cpu hard-coded to cpu0 (i.e. only a single CPU)
entailment
def get_arp_table(self): """ Get arp table information. Return a list of dictionaries having the following set of keys: * interface (string) * mac (string) * ip (string) * age (float) For example:: [ { ...
Get arp table information. Return a list of dictionaries having the following set of keys: * interface (string) * mac (string) * ip (string) * age (float) For example:: [ { 'interface' : 'MgmtEth0/RSP0/CPU0...
entailment
def cli(self, commands): """ Execute a list of commands and return the output in a dictionary format using the command as the key. Example input: ['show clock', 'show calendar'] Output example: { 'show calendar': u'22:02:01 UTC Thu Feb 18 2016', 's...
Execute a list of commands and return the output in a dictionary format using the command as the key. Example input: ['show clock', 'show calendar'] Output example: { 'show calendar': u'22:02:01 UTC Thu Feb 18 2016', 'show clock': u'*22:01:51.165 UTC Thu Feb 18 20...
entailment
def get_mac_address_table(self): """ Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table, having the following keys * mac (string) * interface (string) * vlan (int) * active (boolean) * static (...
Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table, having the following keys * mac (string) * interface (string) * vlan (int) * active (boolean) * static (boolean) * moves (int) * last...
entailment
def traceroute(self, destination, source=C.TRACEROUTE_SOURCE, ttl=C.TRACEROUTE_TTL, timeout=C.TRACEROUTE_TIMEOUT, vrf=C.TRACEROUTE_VRF): """ Executes traceroute on the device and returns a dictionary with the result. :param destination: Host or IP Address of the destination ...
Executes traceroute on the device and returns a dictionary with the result. :param destination: Host or IP Address of the destination :param source (optional): Use a specific IP Address to execute the traceroute :param ttl (optional): Maimum number of hops -> int (0-255) :param timeout ...
entailment
def get_config(self, retrieve='all'): """Implementation of get_config for IOS. Returns the startup or/and running configuration as dictionary. The keys of the dictionary represent the type of configuration (startup or running). The candidate is always empty string, since IOS doe...
Implementation of get_config for IOS. Returns the startup or/and running configuration as dictionary. The keys of the dictionary represent the type of configuration (startup or running). The candidate is always empty string, since IOS does not support candidate configuration.
entailment
def set_range(self, value): """Set the range of the accelerometer to the provided value. Range value should be one of these constants: - ADXL345_RANGE_2_G = +/-2G - ADXL345_RANGE_4_G = +/-4G - ADXL345_RANGE_8_G = +/-8G - ADXL345_RANGE_16_G = +/-16G ...
Set the range of the accelerometer to the provided value. Range value should be one of these constants: - ADXL345_RANGE_2_G = +/-2G - ADXL345_RANGE_4_G = +/-4G - ADXL345_RANGE_8_G = +/-8G - ADXL345_RANGE_16_G = +/-16G
entailment
def read(self): """Read the current value of the accelerometer and return it as a tuple of signed 16-bit X, Y, Z axis values. """ raw = self._device.readList(ADXL345_REG_DATAX0, 6) return struct.unpack('<hhh', raw)
Read the current value of the accelerometer and return it as a tuple of signed 16-bit X, Y, Z axis values.
entailment
def deinit(bus=DEFAULT_SPI_BUS, chip_select=DEFAULT_SPI_CHIP_SELECT): """Stops interrupts on all boards. Only required when using :func:`digital_read` and :func:`digital_write`. :param bus: SPI bus /dev/spidev<bus>.<chipselect> (default: {bus}) :type bus: int :param chip_select: SPI chip...
Stops interrupts on all boards. Only required when using :func:`digital_read` and :func:`digital_write`. :param bus: SPI bus /dev/spidev<bus>.<chipselect> (default: {bus}) :type bus: int :param chip_select: SPI chip select /dev/spidev<bus>.<chipselect> (default: {chip}) :type chip_select: i...
entailment
def digital_write(pin_num, value, hardware_addr=0): """Writes the value to the input pin specified. .. note:: This function is for familiarality with users of other types of IO board. Consider accessing the ``output_pins`` attribute of a PiFaceDigital object: >>> pfd = PiFaceDigital(hardw...
Writes the value to the input pin specified. .. note:: This function is for familiarality with users of other types of IO board. Consider accessing the ``output_pins`` attribute of a PiFaceDigital object: >>> pfd = PiFaceDigital(hardware_addr) >>> pfd.output_pins[pin_num].value = 1 ...
entailment
def digital_write_pullup(pin_num, value, hardware_addr=0): """Writes the value to the input pullup specified. .. note:: This function is for familiarality with users of other types of IO board. Consider accessing the ``gppub`` attribute of a PiFaceDigital object: >>> pfd = PiFaceDigital(h...
Writes the value to the input pullup specified. .. note:: This function is for familiarality with users of other types of IO board. Consider accessing the ``gppub`` attribute of a PiFaceDigital object: >>> pfd = PiFaceDigital(hardware_addr) >>> hex(pfd.gppub.value) 0xff >...
entailment
def get_my_ip(): """Returns this computers IP address as a string.""" ip = subprocess.check_output(GET_IP_CMD, shell=True).decode('utf-8')[:-1] return ip.strip()
Returns this computers IP address as a string.
entailment
def set_output_port(self, new_value, old_value=0): """Sets the output port value to new_value, defaults to old_value.""" print("Setting output port to {}.".format(new_value)) port_value = old_value try: port_value = int(new_value) # dec except ValueError: ...
Sets the output port value to new_value, defaults to old_value.
entailment
def _request_api(self, **kwargs): """Wrap the calls the url, with the given arguments. :param str url: Url to call with the given arguments :param str method: [POST | GET] Method to use on the request :param int status: Expected status code """ _url = kwargs.get('url') ...
Wrap the calls the url, with the given arguments. :param str url: Url to call with the given arguments :param str method: [POST | GET] Method to use on the request :param int status: Expected status code
entailment
def get_infos_with_id(self, uid): """Get info about a user based on his id. :return: JSON """ _logid = uid _user_info_url = USER_INFO_URL.format(logid=_logid) return self._request_api(url=_user_info_url).json()
Get info about a user based on his id. :return: JSON
entailment
def get_current_activities(self, login=None, **kwargs): """Get the current activities of user. Either use the `login` param, or the client's login if unset. :return: JSON """ _login = kwargs.get( 'login', login or self._login ) _activity_...
Get the current activities of user. Either use the `login` param, or the client's login if unset. :return: JSON
entailment
def get_notifications(self, login=None, **kwargs): """Get the current notifications of a user. :return: JSON """ _login = kwargs.get( 'login', login or self._login ) _notif_url = NOTIF_URL.format(login=_login) return self._request_api(url...
Get the current notifications of a user. :return: JSON
entailment
def get_grades(self, login=None, promotion=None, **kwargs): """Get a user's grades on a single promotion based on his login. Either use the `login` param, or the client's login if unset. :return: JSON """ _login = kwargs.get( 'login', login or self._logi...
Get a user's grades on a single promotion based on his login. Either use the `login` param, or the client's login if unset. :return: JSON
entailment
def get_picture(self, login=None, **kwargs): """Get a user's picture. :param str login: Login of the user to check :return: JSON """ _login = kwargs.get( 'login', login or self._login ) _activities_url = PICTURE_URL.format(login=_login) ...
Get a user's picture. :param str login: Login of the user to check :return: JSON
entailment
def get_projects(self, **kwargs): """Get a user's project. :param str login: User's login (Default: self._login) :return: JSON """ _login = kwargs.get('login', self._login) search_url = SEARCH_URL.format(login=_login) return self._request_api(url=search_url).jso...
Get a user's project. :param str login: User's login (Default: self._login) :return: JSON
entailment
def get_activities_for_project(self, module=None, **kwargs): """Get the related activities of a project. :param str module: Stages of a given module :return: JSON """ _module_id = kwargs.get('module', module) _activities_url = ACTIVITIES_URL.format(module_id=_module_id)...
Get the related activities of a project. :param str module: Stages of a given module :return: JSON
entailment
def get_group_for_activity(self, module=None, project=None, **kwargs): """Get groups for activity. :param str module: Base module :param str module: Project which contains the group requested :return: JSON """ _module_id = kwargs.get('module', module) _project_i...
Get groups for activity. :param str module: Base module :param str module: Project which contains the group requested :return: JSON
entailment
def get_students(self, **kwargs): """Get users by promotion id. :param int promotion: Promotion ID :return: JSON """ _promotion_id = kwargs.get('promotion') _url = PROMOTION_URL.format(promo_id=_promotion_id) return self._request_api(url=_url).json()
Get users by promotion id. :param int promotion: Promotion ID :return: JSON
entailment
def get_log_events(self, login=None, **kwargs): """Get a user's log events. :param str login: User's login (Default: self._login) :return: JSON """ _login = kwargs.get( 'login', login ) log_events_url = GSA_EVENTS_URL.format(login=_login)...
Get a user's log events. :param str login: User's login (Default: self._login) :return: JSON
entailment
def get_events(self, login=None, start_date=None, end_date=None, **kwargs): """Get a user's events. :param str login: User's login (Default: self._login) :param str start_date: Start date :param str end_date: To date :return: JSON """ _login = kwargs.get( ...
Get a user's events. :param str login: User's login (Default: self._login) :param str start_date: Start date :param str end_date: To date :return: JSON
entailment