INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Open proxy connection to a device's management interface. :param id: Device ID as an int. :return: :class:`devices.Connection <devices.Connection>` object :rtype: devices.Connection
def connect(self, id): # pylint: disable=invalid-name,redefined-builtin """Open proxy connection to a device's management interface. :param id: Device ID as an int. :return: :class:`devices.Connection <devices.Connection>` object :rtype: devices.Connection """ schema = C...
Close proxy connection to a device's management interface. :param id: Device ID as an int.
def disconnect(self, id): # pylint: disable=invalid-name,redefined-builtin """Close proxy connection to a device's management interface. :param id: Device ID as an int. """ return self.service.post(self.base+str(id)+'/disconnect/')
Power on a device using it's power on command. :param id: Device ID as an int. :return: :class:`devices.PowerCmd <devices.PowerCmd>` object :rtype: devices.PowerCmd
def power_on(self, id): # pylint: disable=invalid-name,redefined-builtin """Power on a device using it's power on command. :param id: Device ID as an int. :return: :class:`devices.PowerCmd <devices.PowerCmd>` object :rtype: devices.PowerCmd """ schema = PowerCmdSchema() ...
Bulk copy a set of devices. :param ids: Int list of device IDs. :return: :class:`devices.Device <devices.Device>` list
def bulk_copy(self, ids): """Bulk copy a set of devices. :param ids: Int list of device IDs. :return: :class:`devices.Device <devices.Device>` list """ schema = DeviceSchema() return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema)
Wrap value in list if it is not one.
def ensure_list(value: Union[T, Sequence[T]]) -> Sequence[T]: """Wrap value in list if it is not one.""" if value is None: return [] return value if isinstance(value, list) else [value]
Проверяет, что переданный объект - один из возможных `VALUES`
def validate(cls, cnd): "Проверяет, что переданный объект - один из возможных `VALUES`" if cnd not in cls.VALUES: raise ValueError("Value {} cannot be used in {}".format( cnd, cls )) return cls(cnd)
Highlight string for terminal color coding. Purpose: We use this utility function to insert a ANSI/win32 color code | and Bright style marker before a string, and reset the color and | style after the string. We then return the string with these | codes inserted. @param out_st...
def color(out_string, color='grn'): """ Highlight string for terminal color coding. Purpose: We use this utility function to insert a ANSI/win32 color code | and Bright style marker before a string, and reset the color and | style after the string. We then return the string with these ...
Add color ANSI codes for diff lines. Purpose: Adds the ANSI/win32 color coding for terminal output to output | produced from difflib. @param string: The string to be replacing @type string: str @returns: The new string with ANSI codes injected. @rtype: str
def color_diffs(string): """ Add color ANSI codes for diff lines. Purpose: Adds the ANSI/win32 color coding for terminal output to output | produced from difflib. @param string: The string to be replacing @type string: str @returns: The new string with ANSI codes injected. @rtype: ...
List linked accounts.
def index(): """List linked accounts.""" oauth = current_app.extensions['oauthlib.client'] services = [] service_map = {} i = 0 for appid, conf in six.iteritems( current_app.config['OAUTHCLIENT_REMOTE_APPS']): if not conf.get('hide', False): services.append(dict...
Ensure that JavaScript at a given URL is available to the browser.
def load_script(browser, url): """Ensure that JavaScript at a given URL is available to the browser.""" if browser.current_url.startswith('file:'): url = 'https:' + url browser.execute_script(""" var script_tag = document.createElement("script"); script_tag.setAttribute("type", "text/javascr...
Find HTML elements using jQuery-style selectors. Ensures that jQuery is available to the browser; if it gets a WebDriverException that looks like jQuery is not available, it attempts to include it and reexecute the script.
def find_elements_by_jquery(browser, selector): """Find HTML elements using jQuery-style selectors. Ensures that jQuery is available to the browser; if it gets a WebDriverException that looks like jQuery is not available, it attempts to include it and reexecute the script.""" try: return br...
Find a single HTML element using jQuery-style selectors.
def find_element_by_jquery(step, browser, selector): """Find a single HTML element using jQuery-style selectors.""" elements = find_elements_by_jquery(browser, selector) assert_true(step, len(elements) > 0) return elements[0]
:return: True when we can access the REST API
def can_access_api(self): """ :return: True when we can access the REST API """ try: version_dict = self.get_version() except Exception, e: msg = 'An exception was raised when connecting to REST API: "%s"' raise APIException(msg % e) el...
:return: A list with all the Scan instances available in the remote API
def get_scans(self): """ :return: A list with all the Scan instances available in the remote API """ code, data = self.send_request('/scans/', method='GET') if code != 200: msg = 'Failed to retrieve scans. Unexpected code %s' raise APIException(msg % code...
Return the id of a label's for attribute
def element_id_by_label(browser, label): """Return the id of a label's for attribute""" label = XPathSelector(browser, unicode('//label[contains(., "%s")]' % label)) if not label: return False return label.get_attribute('for')
Locate an input field of a given value This first looks for the value as the id of the element, then the name of the element, then a label for the element.
def find_field(browser, field, value): """Locate an input field of a given value This first looks for the value as the id of the element, then the name of the element, then a label for the element. """ return find_field_by_id(browser, field, value) + \ find_field_by_name(browser, field, va...
Find a field of any of the specified types.
def find_any_field(browser, field_types, field_name): """ Find a field of any of the specified types. """ return reduce( operator.add, (find_field(browser, field_type, field_name) for field_type in field_types) )
Locate the control input that has a label pointing to it This will first locate the label element that has a label of the given name. It then pulls the id out of the 'for' attribute, and uses it to locate the element by its id.
def find_field_by_label(browser, field, label): """Locate the control input that has a label pointing to it This will first locate the label element that has a label of the given name. It then pulls the id out of the 'for' attribute, and uses it to locate the element by its id. """ return XPa...
Returns the Element specified by @option or None Looks at the real <select> not the select2 widget, since that doesn't create the DOM until we click on it.
def option_in_select(browser, select_name, option): """ Returns the Element specified by @option or None Looks at the real <select> not the select2 widget, since that doesn't create the DOM until we click on it. """ select = find_field(browser, 'select', select_name) assert select try...
A decorator to invoke a function periodically until it returns a truthy value.
def wait_for(func): """ A decorator to invoke a function periodically until it returns a truthy value. """ def wrapped(*args, **kwargs): timeout = kwargs.pop('timeout', 15) start = time() result = None while time() - start < timeout: result = func(*args...
The cached list of elements.
def _elements(self): """ The cached list of elements. """ if not hasattr(self, '_elements_cached'): setattr(self, '_elements_cached', list(self._select())) return self._elements_cached
Returns a dictionary of variables and their possibly os-dependent defaults.
def get_defaults(): """ Returns a dictionary of variables and their possibly os-dependent defaults. """ DEFAULTS = {} # Determine the run-time pipe read/write buffer. if 'PC_PIPE_BUF' in os.pathconf_names: # unix x, y = os.pipe() DEFAULTS['PIPE_BUF'] = os.fpathconf(x...
Configures and starts a logger to monitor the execution of a **PaPy** pipeline. Arguments: - log_to_file(``bool``) [default: ``True``] Should we write logging messages into a file? - log_to_stream(``bool`` or ``object``) [default: ``False``] Should we print logging messages to a...
def start_logger(log_to_file=False, \ log_to_stream=False, \ log_to_file_level=logging.INFO, \ log_to_stream_level=logging.INFO, \ log_filename=None, \ log_stream=None, \ log_rotate=True, \ log_size=52...
Determine the server URL.
def site_url(url): """ Determine the server URL. """ base_url = 'http://%s' % socket.gethostname() if server.port is not 80: base_url += ':%d' % server.port return urlparse.urljoin(base_url, url)
Get external id from account info.
def _get_external_id(account_info): """Get external id from account info.""" if all(k in account_info for k in ('external_id', 'external_method')): return dict(id=account_info['external_id'], method=account_info['external_method']) return None
Retrieve user object for the given request. Uses either the access token or extracted account information to retrieve the user object. :param client_id: The client id. :param account_info: The dictionary with the account info. (Default: ``None``) :param access_token: The access token. (Def...
def oauth_get_user(client_id, account_info=None, access_token=None): """Retrieve user object for the given request. Uses either the access token or extracted account information to retrieve the user object. :param client_id: The client id. :param account_info: The dictionary with the account info....
Authenticate an oauth authorized callback. :param client_id: The client id. :param user: A user instance. :param require_existing_link: If ``True``, check if remote account exists. (Default: ``False``) :returns: ``True`` if the user is successfully authenticated.
def oauth_authenticate(client_id, user, require_existing_link=False): """Authenticate an oauth authorized callback. :param client_id: The client id. :param user: A user instance. :param require_existing_link: If ``True``, check if remote account exists. (Default: ``False``) :returns: ``True...
Register user if possible. :param form: A form instance. :returns: A :class:`invenio_accounts.models.User` instance.
def oauth_register(form): """Register user if possible. :param form: A form instance. :returns: A :class:`invenio_accounts.models.User` instance. """ if form.validate(): data = form.to_dict() if not data.get('password'): data['password'] = '' user = register_user...
Link a user to an external id. :param user: A :class:`invenio_accounts.models.User` instance. :param external_id: The external id associated with the user. (Default: ``None``) :raises invenio_oauthclient.errors.AlreadyLinkedError: Raised if already exists a link.
def oauth_link_external_id(user, external_id=None): """Link a user to an external id. :param user: A :class:`invenio_accounts.models.User` instance. :param external_id: The external id associated with the user. (Default: ``None``) :raises invenio_oauthclient.errors.AlreadyLinkedError: Raised if...
Unlink a user from an external id. :param external_id: The external id associated with the user.
def oauth_unlink_external_id(external_id): """Unlink a user from an external id. :param external_id: The external id associated with the user. """ with db.session.begin_nested(): UserIdentity.query.filter_by(id=external_id['id'], method=external_id['method']...
Get URL to redirect to and ensure that it is local. :param arg: URL argument. :returns: The redirect target or ``None``.
def get_safe_redirect_target(arg='next'): """Get URL to redirect to and ensure that it is local. :param arg: URL argument. :returns: The redirect target or ``None``. """ for target in request.args.get(arg), request.referrer: if target: redirect_uri = urisplit(target) ...
Make a registration form.
def create_registrationform(*args, **kwargs): """Make a registration form.""" class RegistrationForm(_security.confirm_register_form): password = None recaptcha = None return RegistrationForm(*args, **kwargs)
Prefill form with data. :param form: The form to fill. :param data: The data to insert in the form. :returns: A pre-filled form.
def fill_form(form, data): """Prefill form with data. :param form: The form to fill. :param data: The data to insert in the form. :returns: A pre-filled form. """ for (key, value) in data.items(): if hasattr(form, key): if isinstance(value, dict): fill_form(g...
Return the right param to disable CSRF depending on WTF-Form version. From Flask-WTF 0.14.0, `csrf_enabled` param has been deprecated in favor of `meta={csrf: True/False}`.
def _get_csrf_disabled_param(): """Return the right param to disable CSRF depending on WTF-Form version. From Flask-WTF 0.14.0, `csrf_enabled` param has been deprecated in favor of `meta={csrf: True/False}`. """ import flask_wtf from pkg_resources import parse_version supports_meta = parse_...
Find and load step definitions, and them find and load features under `base_path` specified on constructor
def run(self): """ Find and load step definitions, and them find and load features under `base_path` specified on constructor """ try: self.loader.find_and_load_step_definitions() except StepLoadingError, e: print "Error loading step definitions:\n", e ...
A recursive method to return a ``list`` of *all* **node objects** connected from this **toplogical node**.
def deep_nodes(self, allnodes=None): """ A recursive method to return a ``list`` of *all* **node objects** connected from this **toplogical node**. """ allnodes = (allnodes or []) for (node, node_) in ((node, node_) for (node, node_) in\ self.iterite...
comparison of **node objects** based on the ``"branch"`` attribute of their **topological nodes**.
def cmp_branch(self, node1, node2): """ comparison of **node objects** based on the ``"branch"`` attribute of their **topological nodes**. """ # note reverse return cmp(getattr(self[node2], "branch", None), \ getattr(self[node1], "branch", Non...
Recursive depth first search. By default ("order" = ``"append"``) this returns the **node objects** in the reverse postorder. To change this into the preorder use a ``collections.deque`` as "bucket" and ``"appendleft"`` as "order". Arguments: - bucket(``list`` ...
def dfs(self, node, bucket=None, order="append"): """ Recursive depth first search. By default ("order" = ``"append"``) this returns the **node objects** in the reverse postorder. To change this into the preorder use a ``collections.deque`` as "bucket" and ``"appendleft"`` as ...
Returns a valid postorder of the **node objects** of the ``DictGraph`` *if* the topology is a directed acyclic graph. This postorder is semi-random, because the order of elements in a dictionary is semi-random and so are the starting nodes of the depth-first search traversal, which d...
def postorder(self): """ Returns a valid postorder of the **node objects** of the ``DictGraph`` *if* the topology is a directed acyclic graph. This postorder is semi-random, because the order of elements in a dictionary is semi-random and so are the starting nodes of the depth...
Returns the maximum rank for each **topological node** in the ``DictGraph``. The rank of a node is defined as the number of edges between the node and a node which has rank 0. A **topological node** has rank 0 if it has no incoming edges.
def node_rank(self): """ Returns the maximum rank for each **topological node** in the ``DictGraph``. The rank of a node is defined as the number of edges between the node and a node which has rank 0. A **topological node** has rank 0 if it has no incoming edges. ...
Returns the width of each node in the graph. #TODO
def node_width(self): """ Returns the width of each node in the graph. #TODO """ nodes = self.postorder() node_width = {} for node in nodes: sum_width = 0 for child in self[node].nodes(): sum_width += node_width[child] ...
Returns the width of each rank in the graph. #TODO
def rank_width(self): """ Returns the width of each rank in the graph. #TODO """ rank_width = defaultdict(int) node_rank = self.node_rank() for rank in node_rank.values(): rank_width[rank] += 1 return dict(rank_width)
Adds a **node object** to the ``DictGraph``. Returns ``True`` if a new **node object** has been added. If the **node object** is already in the ``DictGraph`` returns ``False``. Arguments: - node(``object``) Node to be added. Any hashable Python ``object``. ...
def add_node(self, node, xtra=None, branch=None): """ Adds a **node object** to the ``DictGraph``. Returns ``True`` if a new **node object** has been added. If the **node object** is already in the ``DictGraph`` returns ``False``. Arguments: - node(``...
Removes a **node object** from the ``DictGraph``. Returns ``True`` if a **node object** has been removed. If the **node object** is not in the ``DictGraph`` raises a ``KeyError``. Arguments: - node(``object``) **node object** to be removed. Any hashable Python ...
def del_node(self, node): """ Removes a **node object** from the ``DictGraph``. Returns ``True`` if a **node object** has been removed. If the **node object** is not in the ``DictGraph`` raises a ``KeyError``. Arguments: - node(``object``) **node ...
Adds an edge to the ``DictGraph``. An edge is just a pair of **node objects**. If the **node objects** are not in the graph they are created. Arguments: - edge(iterable) An ordered pair of **node objects**. The edge is assumed to have a direction from t...
def add_edge(self, edge, double=False): """ Adds an edge to the ``DictGraph``. An edge is just a pair of **node objects**. If the **node objects** are not in the graph they are created. Arguments: - edge(iterable) An ordered pair of **node objects**....
Removes an edge from the ``DictGraph``. An edge is a pair of **node objects**. The **node objects** are not removed from the ``DictGraph``. Arguments: - edge(``tuple``) An ordered pair of **node objects**. The edge is assumed to have a direction from the first t...
def del_edge(self, edge, double=False): """ Removes an edge from the ``DictGraph``. An edge is a pair of **node objects**. The **node objects** are not removed from the ``DictGraph``. Arguments: - edge(``tuple``) An ordered pair of **node objects**. The edge ...
Adds **node objects** to the graph. Arguments: - nodes(iterable) Sequence of **node objects** to be added to the ``DictGraph`` - xtras(iterable) [default: ``None``] Sequence of ``Node.xtra`` dictionaries corresponding to the **node...
def add_nodes(self, nodes, xtras=None): """ Adds **node objects** to the graph. Arguments: - nodes(iterable) Sequence of **node objects** to be added to the ``DictGraph`` - xtras(iterable) [default: ``None``] Sequence of ``Node....
Adds edges to the graph. Takes optional arguments for ``DictGraph.add_edge``. Arguments: - edges(iterable) Sequence of edges to be added to the ``DictGraph``.
def add_edges(self, edges, *args, **kwargs): """ Adds edges to the graph. Takes optional arguments for ``DictGraph.add_edge``. Arguments: - edges(iterable) Sequence of edges to be added to the ``DictGraph``. """ for edg...
Removes edges from the graph. Takes optional arguments for ``DictGraph.del_edge``. Arguments: - edges(iterable) Sequence of edges to be removed from the ``DictGraph``.
def del_edges(self, edges, *args, **kwargs): """ Removes edges from the graph. Takes optional arguments for ``DictGraph.del_edge``. Arguments: - edges(iterable) Sequence of edges to be removed from the ``DictGraph``. """ ...
Returns a ``tuple`` of all edges in the ``DictGraph`` an edge is a pair of **node objects**. Arguments: - nodes(iterable) [default: ``None``] iterable of **node objects** if specified the edges will be limited to those outgoing from one of the specif...
def edges(self, nodes=None): """ Returns a ``tuple`` of all edges in the ``DictGraph`` an edge is a pair of **node objects**. Arguments: - nodes(iterable) [default: ``None``] iterable of **node objects** if specified the edges will be limited to t...
Returns a ``tuple`` of incoming edges for a **node object**. Arguments: - node(``object``) **node object** present in the graph to be queried for incoming edges.
def incoming_edges(self, node): """ Returns a ``tuple`` of incoming edges for a **node object**. Arguments: - node(``object``) **node object** present in the graph to be queried for incoming edges. """ edges = self.edges() ...
Returns a ``tuple`` of outgoing edges for a **node object**. Arguments: - node(``object``) **node object** present in the graph to be queried for outgoing edges.
def outgoing_edges(self, node): """ Returns a ``tuple`` of outgoing edges for a **node object**. Arguments: - node(``object``) **node object** present in the graph to be queried for outgoing edges. """ #TODO: pls make outgoig_ed...
Open a Jaide session with the device. To open a Jaide session to the device, and run the appropriate function against the device. Arguments for the downstream function are passed through. @param ip: String of the IP or hostname of the device to connect to. @type ip: str @param username: The st...
def open_connection(ip, username, password, function, args, write=False, conn_timeout=5, sess_timeout=300, port=22): """ Open a Jaide session with the device. To open a Jaide session to the device, and run the appropriate function against the device. Arguments for the downstream functio...
Run an operational command. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param commands: the operational commands to send to the device. @type commands: str or list @param format: The desired output format from the device, either 'text' | or 'x...
def command(jaide, commands, format="text", xpath=False): """ Run an operational command. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param commands: the operational commands to send to the device. @type commands: str or list @param format: The desired out...
Execute a commit against the device. Purpose: This function will send set commands to a device, and commit | the changes. Options exist for confirming, comments, | synchronizing, checking, blank commits, or delaying to a later | time/date. @param jaide: The jaide connection to...
def commit(jaide, commands, check, sync, comment, confirm, at_time, blank): """ Execute a commit against the device. Purpose: This function will send set commands to a device, and commit | the changes. Options exist for confirming, comments, | synchronizing, checking, blank commits, or de...
Perform a show | compare with some set commands. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param commands: The set commands to send to the device to compare with. @type commands: str or list @returns: The output from the device. @rtype str
def compare(jaide, commands): """ Perform a show | compare with some set commands. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param commands: The set commands to send to the device to compare with. @type commands: str or list @returns: The output from th...
Perform a show | compare with some set commands. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param second_host: The device IP or hostname of the second host to | compare with. @type second_host: str @param mode: How to compare the configu...
def diff_config(jaide, second_host, mode): """ Perform a show | compare with some set commands. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param second_host: The device IP or hostname of the second host to | compare with. @type second_ho...
Copy file(s) from a device to the local machine. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param source: The source filepath on the junos device to pull. @type source: str @param destination: the destination filepath on the local device for ...
def pull(jaide, source, destination, progress, multi): """ Copy file(s) from a device to the local machine. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param source: The source filepath on the junos device to pull. @type source: str @param destination: the...
Copy file(s) from the local machine to a junos device. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param source: The source filepath on the junos device to pull. @type source: str @param destination: the destination filepath on the local device for ...
def push(jaide, source, destination, progress, multi=False): """ Copy file(s) from the local machine to a junos device. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param source: The source filepath on the junos device to pull. @type source: str @param dest...
Send shell commands to a device. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param commands: The shell commands to send to the device. @type commands: str or list. @returns: The output of the commands. @rtype str
def shell(jaide, commands): """ Send shell commands to a device. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param commands: The shell commands to send to the device. @type commands: str or list. @returns: The output of the commands. @rtype str ""...
Returns all keys from etcd. :param reactor: reference to Twisted' reactor. :param etcd_address: Address with port number where etcd is running. :return: An instance of txaioetcd.Range containing all keys and their values.
def get_all_keys(reactor, key_type, value_type, etcd_address): """Returns all keys from etcd. :param reactor: reference to Twisted' reactor. :param etcd_address: Address with port number where etcd is running. :return: An instance of txaioetcd.Range containing all keys and their values....
Send the GET request required to stop the scan If timeout is not specified we just send the request and return. When it is the method will wait for (at most) :timeout: seconds until the scan changes it's status/stops. If the timeout is reached then an exception is raised. :para...
def stop(self, timeout=None): """ Send the GET request required to stop the scan If timeout is not specified we just send the request and return. When it is the method will wait for (at most) :timeout: seconds until the scan changes it's status/stops. If the timeout is reached t...
Convert an xrb address to public key in bytes >>> xrb_address_to_public_key('xrb_1e3i81r51e3i81r51e3i81r51e3i'\ '81r51e3i81r51e3i81r51e3imxssakuq') b'00000000000000000000000000000000' :param address: xrb address :type address: bytes :return: public key in bytes ...
def xrb_address_to_public_key(address): """ Convert an xrb address to public key in bytes >>> xrb_address_to_public_key('xrb_1e3i81r51e3i81r51e3i81r51e3i'\ '81r51e3i81r51e3i81r51e3imxssakuq') b'00000000000000000000000000000000' :param address: xrb address :typ...
Convert `public_key` (bytes) to an xrb address >>> public_key_to_xrb_address(b'00000000000000000000000000000000') 'xrb_1e3i81r51e3i81r51e3i81r51e3i81r51e3i81r51e3i81r51e3imxssakuq' :param public_key: public key in bytes :type public_key: bytes :return: xrb address :rtype: str
def public_key_to_xrb_address(public_key): """ Convert `public_key` (bytes) to an xrb address >>> public_key_to_xrb_address(b'00000000000000000000000000000000') 'xrb_1e3i81r51e3i81r51e3i81r51e3i81r51e3i81r51e3i81r51e3imxssakuq' :param public_key: public key in bytes :type public_key: bytes ...
Flask application initialization.
def init_app(self, app): """Flask application initialization.""" self.init_config(app) state = _OAuthClientState(app) app.extensions['invenio-oauthclient'] = state return state
Initialize configuration.
def init_config(self, app): """Initialize configuration.""" for k in dir(config): if k.startswith('OAUTHCLIENT_'): app.config.setdefault(k, getattr(config, k)) @app.before_first_request def override_template_configuration(): """Override template c...
Passes inputs with indecies in s. By default passes the whole inbox. Arguments: - s(sequence) [default: ``None``] The default translates to a range for all inputs of the "inbox" i.e. ``range(len(inbox))``
def spasser(inbox, s=None): """ Passes inputs with indecies in s. By default passes the whole inbox. Arguments: - s(sequence) [default: ``None``] The default translates to a range for all inputs of the "inbox" i.e. ``range(len(inbox))`` """ seq = (s or range(len(inbox))) ret...
Zips inputs from inbox with indicies in "s". By default zips the whole inbox (all indices). Arguments: - s(sequence) [default: ``None``]
def szipper(inbox, s=None): """ Zips inputs from inbox with indicies in "s". By default zips the whole inbox (all indices). Arguments: - s(sequence) [default: ``None``] """ #TODO: test szipper return zip(*[input_ for i, input_ in enumerate(inbox) if i in s])
String joins input with indices in s. Arguments: - s(sequence) [default: ``None``] ``tuple`` or ``list`` of indices of the elements which will be joined. - join(``str``) [default: ``""``] String which will join the elements of the inbox i.e. ``join.join()``.
def sjoiner(inbox, s=None, join=""): """ String joins input with indices in s. Arguments: - s(sequence) [default: ``None``] ``tuple`` or ``list`` of indices of the elements which will be joined. - join(``str``) [default: ``""``] String which will join the elements of the inbo...
Writes the first element of the inbox to the provided stream (file handle) delimiting the input by the optional delimiter string. Returns the name of the file being written. Note that only a single process can have access to a file handle open for writing. Therefore this function should only be ...
def dump_stream(inbox, handle, delimiter=None): """ Writes the first element of the inbox to the provided stream (file handle) delimiting the input by the optional delimiter string. Returns the name of the file being written. Note that only a single process can have access to a file handle op...
Creates a string generator from a stream (file handle) containing data delimited by the delimiter strings. This is a stand-alone function and should be used to feed external data into a pipeline. Arguments: - hande(``file``) A file handle open for reading. - delimiter(``str``) [default: ``No...
def load_stream(handle, delimiter=None): """ Creates a string generator from a stream (file handle) containing data delimited by the delimiter strings. This is a stand-alone function and should be used to feed external data into a pipeline. Arguments: - hande(``file``) A file handle open f...
Writes the first element of the inbox as a file of a specified type. The type can be 'file', 'fifo' or 'socket' corresponding to typical files, named pipes (FIFOs). FIFOs and TCP sockets and are volatile i.e. exists only as long as the Python process, which created them. FIFOs are local i.e. allow to...
def dump_item(inbox, type='file', prefix=None, suffix=None, dir=None, \ timeout=320, buffer=None): """ Writes the first element of the inbox as a file of a specified type. The type can be 'file', 'fifo' or 'socket' corresponding to typical files, named pipes (FIFOs). FIFOs and TCP socke...
Loads data from a file. Determines the file type automatically ``"file"``, ``"fifo"``, ``"socket"``, but allows to specify the representation type ``"string"`` or ``"mmap"`` for memory mapped access to the file. Returns the loaded item as a ``str`` or ``mmap`` object. Internally creates an item from ...
def load_item(inbox, type="string", remove=True, buffer=None): """ Loads data from a file. Determines the file type automatically ``"file"``, ``"fifo"``, ``"socket"``, but allows to specify the representation type ``"string"`` or ``"mmap"`` for memory mapped access to the file. Returns the loaded...
Creates a line generator from a stream (file handle) containing data in lines. Arguments: - follow(``bool``) [default: ``False``] If ``True`` follows the file after it finishes like 'tail -f'. - wait(``float``) [default: ``0.1``] time to wait in seconds between file polls.
def make_lines(handle, follow=False, wait=0.1): """ Creates a line generator from a stream (file handle) containing data in lines. Arguments: - follow(``bool``) [default: ``False``] If ``True`` follows the file after it finishes like 'tail -f'. - wait(``float``) [default: ``0.1``]...
Serializes the first element of the input using the pickle protocol using the fastes binary protocol.
def pickle_dumps(inbox): """ Serializes the first element of the input using the pickle protocol using the fastes binary protocol. """ # http://bugs.python.org/issue4074 gc.disable() str_ = cPickle.dumps(inbox[0], cPickle.HIGHEST_PROTOCOL) gc.enable() return str_
Deserializes the first element of the input using the pickle protocol.
def pickle_loads(inbox): """ Deserializes the first element of the input using the pickle protocol. """ gc.disable() obj = cPickle.loads(inbox[0]) gc.enable() return obj
Serializes the first element of the input using the JSON protocol as implemented by the ``json`` Python 2.6 library.
def json_dumps(inbox): """ Serializes the first element of the input using the JSON protocol as implemented by the ``json`` Python 2.6 library. """ gc.disable() str_ = json.dumps(inbox[0]) gc.enable() return str_
Deserializes the first element of the input using the JSON protocol as implemented by the ``json`` Python 2.6 library.
def json_loads(inbox): """ Deserializes the first element of the input using the JSON protocol as implemented by the ``json`` Python 2.6 library. """ gc.disable() obj = json.loads(inbox[0]) gc.enable() return obj
Callback validating the at_time commit option. Purpose: Validates the `at time` option for the commit command. Only the | the following two formats are supported: 'hh:mm[:ss]' or | 'yyyy-mm-dd hh:mm[:ss]' (seconds are optional). @param ctx: The click context paramter, for receiving the o...
def at_time_validate(ctx, param, value): """ Callback validating the at_time commit option. Purpose: Validates the `at time` option for the commit command. Only the | the following two formats are supported: 'hh:mm[:ss]' or | 'yyyy-mm-dd hh:mm[:ss]' (seconds are optional). @param ctx...
Validate the -w option. Purpose: Validates the `-w`|`--write` option. Two arguments are expected. | The first is the mode, which must be in ['s', 'single', 'm', | 'multiple']. The mode determins if we're writing to one file for | all device output, or to a separate file for each d...
def write_validate(ctx, param, value): """ Validate the -w option. Purpose: Validates the `-w`|`--write` option. Two arguments are expected. | The first is the mode, which must be in ['s', 'single', 'm', | 'multiple']. The mode determins if we're writing to one file for | all ...
Callback function to write the output from the script. @param input: A tuple containing two things: | 1. None or Tuple of file mode and destination filepath | 2. The output of the jaide command that will be either | written to sys.stdout or to a file, depending on...
def write_out(input): """ Callback function to write the output from the script. @param input: A tuple containing two things: | 1. None or Tuple of file mode and destination filepath | 2. The output of the jaide command that will be either | written to sys.std...
Manipulate one or more Junos devices. Purpose: The main function is the entry point for the jaide tool. Click | handles arguments, commands and options. The parameters passed to | this function are all potential options (required or not) that | must come *before* the command from t...
def main(ctx, host, password, port, quiet, session_timeout, connect_timeout, username): """ Manipulate one or more Junos devices. Purpose: The main function is the entry point for the jaide tool. Click | handles arguments, commands and options. The parameters passed to | this fun...
Execute a commit against the device. Purpose: This function will send set commands to a device, and commit | the changes. Options exist for confirming, comments, | synchronizing, checking, blank commits, or delaying to a later | time/date. @param ctx: The click context paramte...
def commit(ctx, commands, blank, check, sync, comment, confirm, at_time): """ Execute a commit against the device. Purpose: This function will send set commands to a device, and commit | the changes. Options exist for confirming, comments, | synchronizing, checking, blank commits, or dela...
Run 'show | compare' for set commands. @param ctx: The click context paramter, for receiving the object dictionary | being manipulated by other previous functions. Needed by any | function with the @click.pass_context decorator. @type ctx: click.Context @param commands: The Juno...
def compare(ctx, commands): """ Run 'show | compare' for set commands. @param ctx: The click context paramter, for receiving the object dictionary | being manipulated by other previous functions. Needed by any | function with the @click.pass_context decorator. @type ctx: click.C...
Copy file(s) from device(s) -> local machine. @param ctx: The click context paramter, for receiving the object dictionary | being manipulated by other previous functions. Needed by any | function with the @click.pass_context decorator. @type ctx: click.Context @param source: the...
def pull(ctx, source, destination, progress): """ Copy file(s) from device(s) -> local machine. @param ctx: The click context paramter, for receiving the object dictionary | being manipulated by other previous functions. Needed by any | function with the @click.pass_context decorato...
Copy file(s) from local machine -> device(s). @param ctx: The click context paramter, for receiving the object dictionary | being manipulated by other previous functions. Needed by any | function with the @click.pass_context decorator. @type ctx: click.Context @param source: the...
def push(ctx, source, destination, progress): """ Copy file(s) from local machine -> device(s). @param ctx: The click context paramter, for receiving the object dictionary | being manipulated by other previous functions. Needed by any | function with the @click.pass_context decorato...
Execute operational mode command(s). This function will send operational mode commands to a Junos device. jaide.utils.clean_lines() is used to determine how we are receiving commands, and ignore comment lines or blank lines in a command file. @param ctx: The click context paramter, for receiving t...
def operational(ctx, commands, format, xpath): """ Execute operational mode command(s). This function will send operational mode commands to a Junos device. jaide.utils.clean_lines() is used to determine how we are receiving commands, and ignore comment lines or blank lines in a command file. ...
Config comparison between two devices. @param ctx: The click context paramter, for receiving the object dictionary | being manipulated by other previous functions. Needed by any | function with the @click.pass_context decorator. @type ctx: click.Context @param second_host: The I...
def diff_config(ctx, second_host, mode): """ Config comparison between two devices. @param ctx: The click context paramter, for receiving the object dictionary | being manipulated by other previous functions. Needed by any | function with the @click.pass_context decorator. @type...
Allow for partial commands.
def get_command(self, ctx, cmd_name): """ Allow for partial commands. """ rv = click.Group.get_command(self, ctx, cmd_name) if rv is not None: return rv matches = [x for x in self.list_commands(ctx) if x.startswith(cmd_name)] if not matches: ...
Converts a value from `from_unit` units to `to_unit` units :param value: value to convert :type value: int or str or decimal.Decimal :param from_unit: unit to convert from :type from_unit: str :param to_unit: unit to convert to :type to_unit: str >>> convert(value='1.5', from_unit='xrb',...
def convert(value, from_unit, to_unit): """ Converts a value from `from_unit` units to `to_unit` units :param value: value to convert :type value: int or str or decimal.Decimal :param from_unit: unit to convert from :type from_unit: str :param to_unit: unit to convert to :type to_unit...
Get etcd status. :param timeout: Request timeout in seconds. :type timeout: int :returns: The current etcd cluster status. :rtype: instance of :class:`txaioetcd.Status`
def status(self, timeout=None): """ Get etcd status. :param timeout: Request timeout in seconds. :type timeout: int :returns: The current etcd cluster status. :rtype: instance of :class:`txaioetcd.Status` """ def run(txn): txn.execute("SELEC...
Range gets the keys in the range from the key-value store. :param key: key is the first key for the range. If range_end is not given, the request only looks up key. :type key: bytes :param range_end: range_end is the upper bound on the requested range [key, range_end). ...
def get(self, key, range_end=None, count_only=None, keys_only=None, limit=None, max_create_revision=None, min_create_revision=None, min_mod_revision=None, revision=None, serializable=None, ...
Submit a transaction. Processes multiple requests in a single transaction. A transaction increments the revision of the key-value store and generates events with the same revision for every completed request. It is not allowed to modify the same key several times within...
def submit(self, txn, timeout=None): """ Submit a transaction. Processes multiple requests in a single transaction. A transaction increments the revision of the key-value store and generates events with the same revision for every completed request. It is not al...
Endpoint that SNS accesses. Includes logic verifying request
def endpoint(request): """Endpoint that SNS accesses. Includes logic verifying request""" # pylint: disable=too-many-return-statements,too-many-branches # In order to 'hide' the endpoint, all non-POST requests should return # the site's default HTTP404 if request.method != 'POST': raise Htt...
Function to process a JSON message delivered from Amazon
def process_message(message, notification): """ Function to process a JSON message delivered from Amazon """ # Confirm that there are 'notificationType' and 'mail' fields in our # message if not set(VITAL_MESSAGE_FIELDS) <= set(message): # At this point we're sure that it's Amazon sendin...
Function to process a bounce notification
def process_bounce(message, notification): """Function to process a bounce notification""" mail = message['mail'] bounce = message['bounce'] bounces = [] for recipient in bounce['bouncedRecipients']: # Create each bounce record. Add to a list for reference later. bounces += [Bounce....
Function to process a complaint notification
def process_complaint(message, notification): """Function to process a complaint notification""" mail = message['mail'] complaint = message['complaint'] if 'arrivalDate' in complaint: arrival_date = clean_time(complaint['arrivalDate']) else: arrival_date = None complaints = [] ...
Function to process a delivery notification
def process_delivery(message, notification): """Function to process a delivery notification""" mail = message['mail'] delivery = message['delivery'] if 'timestamp' in delivery: delivered_datetime = clean_time(delivery['timestamp']) else: delivered_datetime = None deliveries = [...
Click on a label
def click_on_label(step, label): """ Click on a label """ with AssertContextManager(step): elem = world.browser.find_element_by_xpath(str( '//label[normalize-space(text()) = "%s"]' % label)) elem.click()
Check if the element is focused
def element_focused(step, id): """ Check if the element is focused """ elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) focused = world.browser.switch_to_active_element() assert_true(step, elem == focused)