INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Provide detailed information about the session (before, after) when unable to connect.
The state machine finishes without exception | def a_unable_to_connect(ctx):
"""Provide detailed information about the session (before, after) when unable to connect.
The state machine finishes without exception
"""
message = "{}{}".format(ctx.ctrl.before, ctx.ctrl.after)
ctx.msg = message.strip().splitlines()[-1]
ctx.device.last_error_msg ... |
Raise ConnectionError exception when connected to standby console. | def a_standby_console(ctx):
"""Raise ConnectionError exception when connected to standby console."""
ctx.device.is_console = True
ctx.ctrl.disconnect()
raise ConnectionError("Standby console", ctx.ctrl.hostname) |
Provide the message that current software is not committed and reload is not possible. | def a_not_committed(ctx):
"""Provide the message that current software is not committed and reload is not possible."""
ctx.ctrl.sendline('n')
ctx.msg = "Some active software packages are not yet committed. Reload may cause software rollback."
ctx.device.chain.connection.emit_message(ctx.msg, log_level=l... |
Stay connected. | def a_stays_connected(ctx):
"""Stay connected."""
ctx.ctrl.connected = True
ctx.device.connected = False
return True |
Provide message when received humphost prompt. | def a_unexpected_prompt(ctx):
"""Provide message when received humphost prompt."""
prompt = ctx.ctrl.match.group(0)
ctx.msg = "Received the jump host prompt: '{}'".format(prompt)
ctx.device.connected = False
ctx.finished = True
raise ConnectionError("Unable to connect to the device.", ctx.ctrl.h... |
Check the prompt and update the drivers. | def a_connection_timeout(ctx):
"""Check the prompt and update the drivers."""
prompt = ctx.ctrl.after
ctx.msg = "Received the jump host prompt: '{}'".format(prompt)
ctx.device.connected = False
ctx.finished = True
raise ConnectionTimeoutError("Unable to connect to the device.", ctx.ctrl.hostname... |
Update driver, config mode and hostname when received an expected prompt. | def a_expected_prompt(ctx):
"""Update driver, config mode and hostname when received an expected prompt."""
prompt = ctx.ctrl.match.group(0)
ctx.device.update_driver(prompt)
ctx.device.update_config_mode()
ctx.device.update_hostname()
ctx.finished = True
return True |
Send new line and reconnect. | def a_return_and_reconnect(ctx):
"""Send new line and reconnect."""
ctx.ctrl.send("\r")
ctx.device.connect(ctx.ctrl)
return True |
Store the command result for complex state machines.
It is useful when exact command output is embedded in another commands, i.e. admin show inventory in eXR. | def a_store_cmd_result(ctx):
"""Store the command result for complex state machines.
It is useful when exact command output is embedded in another commands, i.e. admin show inventory in eXR.
"""
result = ctx.ctrl.before
# check if multi line
index = result.find('\n')
if index > 0:
#... |
Message the captured pattern. | def a_message_callback(ctx):
"""Message the captured pattern."""
message = ctx.ctrl.after.strip().splitlines()[-1]
ctx.device.chain.connection.emit_message(message, log_level=logging.INFO)
return True |
Capture the show configuration failed result. | def a_capture_show_configuration_failed(ctx):
"""Capture the show configuration failed result."""
result = ctx.device.send("show configuration failed")
ctx.device.last_command_result = result
index = result.find("SEMANTIC ERRORS")
ctx.device.chain.connection.emit_message(result, log_level=logging.ER... |
Raise the configuration inconsistency error. | def a_configuration_inconsistency(ctx):
"""Raise the configuration inconsistency error."""
ctx.msg = "This SDR's running configuration is inconsistent with persistent configuration. " \
"No configuration commits for this SDR will be allowed until a 'clear configuration inconsistency' " \
... |
Return XHTML content of a page.
Parameters:
- id: id of a Confluence page. | def get_page_content(id):
"""Return XHTML content of a page.
Parameters:
- id: id of a Confluence page.
"""
data = _json.loads(_api.rest("/" + str(id) + "?expand=body.storage"))
return data["body"]["storage"]["value"] |
Return name of a page based on passed page id.
Parameters:
- id: id of a Confluence page. | def get_page_name(id):
"""Return name of a page based on passed page id.
Parameters:
- id: id of a Confluence page.
"""
data = _json.loads(_api.rest("/" + str(id) + "?expand=body.storage"))
return data["title"] |
Return id of a page based on passed page name and space.
Parameters:
- name: name of a Confluence page.
- space: space the Confluence page is in. | def get_page_id(name, space):
"""Return id of a page based on passed page name and space.
Parameters:
- name: name of a Confluence page.
- space: space the Confluence page is in.
"""
data = _json.loads(_api.rest("?title=" + name.replace(" ", "%20") + "&"
"spaceKey=" + spac... |
Create a page in Confluence.
Parameters:
- name: name of the Confluence page to create.
- parent_id: ID of the intended parent of the page.
- space: key of the space where the page will be created.
- content: XHTML content to be written to the page.
Notes: the page id can be obtained by getting ... | def create_page(name, parent_id, space, content):
"""Create a page in Confluence.
Parameters:
- name: name of the Confluence page to create.
- parent_id: ID of the intended parent of the page.
- space: key of the space where the page will be created.
- content: XHTML content to be written to the... |
Update a page in Confluence.
Parameters:
- id: ID of the page you wish to edit.
- name: name you would like to give to the page (usually the same name).
- space: space where the page lives.
- content: XHTML content to be written to the page.
Notes: it is required to try an initial update to find... | def edit_page(id, name, space, content):
"""Update a page in Confluence.
Parameters:
- id: ID of the page you wish to edit.
- name: name you would like to give to the page (usually the same name).
- space: space where the page lives.
- content: XHTML content to be written to the page.
Notes:... |
Delete a page from Confluence, along with its children.
Parameters:
- id: id of a Confluence page.
Notes:
- Getting a 204 error is expected! It means the page can no longer be found. | def delete_page_full(id):
"""Delete a page from Confluence, along with its children.
Parameters:
- id: id of a Confluence page.
Notes:
- Getting a 204 error is expected! It means the page can no longer be found.
"""
children = _json.loads(get_page_children(id))
for i in children["resul... |
Returns the string used to identify the client when initiating a SMTP
session.
RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do:
- Use the client FQDN ;
- If it isn't available, we SHOULD fall back to an address literal.
Returns:
str: The value that should b... | def fqdn(self):
"""
Returns the string used to identify the client when initiating a SMTP
session.
RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do:
- Use the client FQDN ;
- If it isn't available, we SHOULD fall back to an address literal.
Returns:
... |
Resets some attributes to their default values.
This is especially useful when initializing a newly created
:class:`SMTP` instance and when closing an existing SMTP session.
It allows us to use the same SMTP instance and connect several times. | def reset_state(self):
"""
Resets some attributes to their default values.
This is especially useful when initializing a newly created
:class:`SMTP` instance and when closing an existing SMTP session.
It allows us to use the same SMTP instance and connect several times.
... |
Connects to the server.
.. note:: This method is automatically invoked by
:meth:`SMTP.__aenter__`. The code is mostly borrowed from the
:func:`asyncio.streams.open_connection` source code.
Raises:
ConnectionError subclass: If the connection between client and
... | async def connect(self):
"""
Connects to the server.
.. note:: This method is automatically invoked by
:meth:`SMTP.__aenter__`. The code is mostly borrowed from the
:func:`asyncio.streams.open_connection` source code.
Raises:
ConnectionError subclass... |
Sends the given command to the server.
Args:
*args: Command and arguments to be sent to the server.
Raises:
ConnectionResetError: If the connection with the server is
unexpectedely lost.
SMTPCommandFailedError: If the command fails.
Returns:... | async def do_cmd(self, *args, success=None):
"""
Sends the given command to the server.
Args:
*args: Command and arguments to be sent to the server.
Raises:
ConnectionResetError: If the connection with the server is
unexpectedely lost.
... |
Sends a SMTP 'HELO' command. - Identifies the client and starts the
session.
If given ``from_host`` is None, defaults to the client FQDN.
For further details, please check out `RFC 5321 § 4.1.1.1`_.
Args:
from_host (str or None): Name to use to identify the client.
... | async def helo(self, from_host=None):
"""
Sends a SMTP 'HELO' command. - Identifies the client and starts the
session.
If given ``from_host`` is None, defaults to the client FQDN.
For further details, please check out `RFC 5321 § 4.1.1.1`_.
Args:
from_host ... |
Sends a SMTP 'EHLO' command. - Identifies the client and starts the
session.
If given ``from`_host`` is None, defaults to the client FQDN.
For further details, please check out `RFC 5321 § 4.1.1.1`_.
Args:
from_host (str or None): Name to use to identify the client.
... | async def ehlo(self, from_host=None):
"""
Sends a SMTP 'EHLO' command. - Identifies the client and starts the
session.
If given ``from`_host`` is None, defaults to the client FQDN.
For further details, please check out `RFC 5321 § 4.1.1.1`_.
Args:
from_host... |
Sends a SMTP 'HELP' command.
For further details please check out `RFC 5321 § 4.1.1.8`_.
Args:
command_name (str or None, optional): Name of a command for which
you want help. For example, if you want to get help about the
'*RSET*' command, you'd call ``help... | async def help(self, command_name=None):
"""
Sends a SMTP 'HELP' command.
For further details please check out `RFC 5321 § 4.1.1.8`_.
Args:
command_name (str or None, optional): Name of a command for which
you want help. For example, if you want to get help ... |
Sends a SMTP 'MAIL' command. - Starts the mail transfer session.
For further details, please check out `RFC 5321 § 4.1.1.2`_ and
`§ 3.3`_.
Args:
sender (str): Sender mailbox (used as reverse-path).
options (list of str or None, optional): Additional options to send
... | async def mail(self, sender, options=None):
"""
Sends a SMTP 'MAIL' command. - Starts the mail transfer session.
For further details, please check out `RFC 5321 § 4.1.1.2`_ and
`§ 3.3`_.
Args:
sender (str): Sender mailbox (used as reverse-path).
options ... |
Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail.
For further details, please check out `RFC 5321 § 4.1.1.3`_ and
`§ 3.3`_.
Args:
recipient (str): E-mail address of one recipient.
options (list of str or None, optional): Additional options to send
... | async def rcpt(self, recipient, options=None):
"""
Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail.
For further details, please check out `RFC 5321 § 4.1.1.3`_ and
`§ 3.3`_.
Args:
recipient (str): E-mail address of one recipient.
opti... |
Sends a SMTP 'QUIT' command. - Ends the session.
For further details, please check out `RFC 5321 § 4.1.1.10`_.
Returns:
(int, str): A (code, message) 2-tuple containing the server
response. If the connection is already closed when calling this
method, return... | async def quit(self):
"""
Sends a SMTP 'QUIT' command. - Ends the session.
For further details, please check out `RFC 5321 § 4.1.1.10`_.
Returns:
(int, str): A (code, message) 2-tuple containing the server
response. If the connection is already closed when c... |
Sends a SMTP 'DATA' command. - Transmits the message to the server.
If ``email_message`` is a bytes object, sends it as it is. Else,
makes all the required changes so it can be safely trasmitted to the
SMTP server.`
For further details, please check out `RFC 5321 § 4.1.1.4`_.
... | async def data(self, email_message):
"""
Sends a SMTP 'DATA' command. - Transmits the message to the server.
If ``email_message`` is a bytes object, sends it as it is. Else,
makes all the required changes so it can be safely trasmitted to the
SMTP server.`
For further d... |
Tries to authenticate user against the SMTP server.
Args:
username (str): Username to authenticate with.
password (str): Password to use along with the given ``username``.
Raises:
ConnectionResetError: If the connection with the server is
unexpectede... | async def auth(self, username, password):
"""
Tries to authenticate user against the SMTP server.
Args:
username (str): Username to authenticate with.
password (str): Password to use along with the given ``username``.
Raises:
ConnectionResetError: If... |
Upgrades the connection to the SMTP server into TLS mode.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
If the server supports SSL/TLS, this will encrypt the rest of the SMTP
session.
Raises:
SMTPCommandNotSupp... | async def starttls(self, context=None):
"""
Upgrades the connection to the SMTP server into TLS mode.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
If the server supports SSL/TLS, this will encrypt the rest of the SMTP
... |
Performs an entire e-mail transaction.
Example:
>>> try:
>>> with SMTP() as client:
>>> try:
>>> r = client.sendmail(sender, recipients, message)
>>> except SMTPException:
>>> print("Error while... | async def sendmail(
self, sender, recipients, message, mail_options=None, rcpt_options=None
):
"""
Performs an entire e-mail transaction.
Example:
>>> try:
>>> with SMTP() as client:
>>> try:
>>> r = client.sen... |
Alias for :meth:`SMTP.sendmail`. | async def send_mail(
self, sender, recipients, message, mail_options=None, rcpt_options=None
):
"""
Alias for :meth:`SMTP.sendmail`.
"""
return await self.sendmail(
sender, recipients, message, mail_options, rcpt_options
) |
Calls :meth:`SMTP.ehlo` and/or :meth:`SMTP.helo` if needed.
If there hasn't been any previous *EHLO* or *HELO* command this
session, tries to initiate the session. *EHLO* is tried first.
Raises:
ConnectionResetError: If the connection with the server is
unexpectedel... | async def ehlo_or_helo_if_needed(self):
"""
Calls :meth:`SMTP.ehlo` and/or :meth:`SMTP.helo` if needed.
If there hasn't been any previous *EHLO* or *HELO* command this
session, tries to initiate the session. *EHLO* is tried first.
Raises:
ConnectionResetError: If th... |
Cleans up after the connection to the SMTP server has been closed
(voluntarily or not). | async def close(self):
"""
Cleans up after the connection to the SMTP server has been closed
(voluntarily or not).
"""
if self.writer is not None:
# Close the transport:
try:
self.writer.close()
except OSError as exc:
... |
Performs an authentication attemps using the CRAM-MD5 mechanism.
Protocol:
1. Send 'AUTH CRAM-MD5' to server ;
2. If the server replies with a 334 return code, we can go on:
1) The challenge (sent by the server) is base64-decoded ;
2) The decoded challe... | async def _auth_cram_md5(self, username, password):
"""
Performs an authentication attemps using the CRAM-MD5 mechanism.
Protocol:
1. Send 'AUTH CRAM-MD5' to server ;
2. If the server replies with a 334 return code, we can go on:
1) The challenge (sent ... |
Performs an authentication attempt using the LOGIN mechanism.
Protocol:
1. The username is base64-encoded ;
2. The string 'AUTH LOGIN' and a space character are prepended to
the base64-encoded username and sent to the server ;
3. If the server replies with a ... | async def _auth_login(self, username, password):
"""
Performs an authentication attempt using the LOGIN mechanism.
Protocol:
1. The username is base64-encoded ;
2. The string 'AUTH LOGIN' and a space character are prepended to
the base64-encoded username ... |
Performs an authentication attempt using the PLAIN mechanism.
Protocol:
1. Format the username and password in a suitable way ;
2. The formatted string is base64-encoded ;
3. The string 'AUTH PLAIN' and a space character are prepended to
the base64-encoded us... | async def _auth_plain(self, username, password):
"""
Performs an authentication attempt using the PLAIN mechanism.
Protocol:
1. Format the username and password in a suitable way ;
2. The formatted string is base64-encoded ;
3. The string 'AUTH PLAIN' and a ... |
Parses the response given by an ESMTP server after a *EHLO* command.
The response is parsed to build:
- A dict of supported ESMTP extensions (with parameters, if any).
- A list of supported authentication methods.
Returns:
(dict, list): A (extensions, auth_mechanisms) 2-tu... | def parse_esmtp_extensions(message):
"""
Parses the response given by an ESMTP server after a *EHLO* command.
The response is parsed to build:
- A dict of supported ESMTP extensions (with parameters, if any).
- A list of supported authentication methods.
Returns:
... |
Returns the given message encoded in ascii with a format suitable for
SMTP transmission:
- Makes sure the message is ASCII encoded ;
- Normalizes line endings to '\r\n' ;
- Adds a (second) period at the beginning of lines that start
with a period ;
- Makes sure the mes... | def prepare_message(message):
"""
Returns the given message encoded in ascii with a format suitable for
SMTP transmission:
- Makes sure the message is ASCII encoded ;
- Normalizes line endings to '\r\n' ;
- Adds a (second) period at the beginning of lines that start
... |
Get format according to algorithm defined in RFC 5646 section 2.1.1.
:return: formatted tag string. | def format(self):
"""
Get format according to algorithm defined in RFC 5646 section 2.1.1.
:return: formatted tag string.
"""
tag = self.data['tag']
subtags = tag.split('-')
if len(subtags) == 1:
return subtags[0]
formatted_tag = subtags[0]
... |
Get the :class:`language_tags.Subtag.Subtag` objects of the tag.
:return: list of :class:`language_tags.Subtag.Subtag` objects that are part of the tag.
The return list can be empty. | def subtags(self):
"""
Get the :class:`language_tags.Subtag.Subtag` objects of the tag.
:return: list of :class:`language_tags.Subtag.Subtag` objects that are part of the tag.
The return list can be empty.
"""
data = self.data
subtags = []
# if tag i... |
Get the language :class:`language_tags.Subtag.Subtag` of the tag.
:return: language :class:`language_tags.Subtag.Subtag` that is part of the tag.
The return can be None. | def language(self):
"""
Get the language :class:`language_tags.Subtag.Subtag` of the tag.
:return: language :class:`language_tags.Subtag.Subtag` that is part of the tag.
The return can be None.
"""
language_item = [subtag for subtag in self.subtags if subtag.type ==... |
Get the region :class:`language_tags.Subtag.Subtag` of the tag.
:return: region :class:`language_tags.Subtag.Subtag` that is part of the tag.
The return can be None. | def region(self):
"""
Get the region :class:`language_tags.Subtag.Subtag` of the tag.
:return: region :class:`language_tags.Subtag.Subtag` that is part of the tag.
The return can be None.
"""
region_item = [subtag for subtag in self.subtags if subtag.type == 'region... |
Get the script :class:`language_tags.Subtag.Subtag` of the tag.
:return: script :class:`language_tags.Subtag.Subtag` that is part of the tag.
The return can be None. | def script(self):
"""
Get the script :class:`language_tags.Subtag.Subtag` of the tag.
:return: script :class:`language_tags.Subtag.Subtag` that is part of the tag.
The return can be None.
"""
script_item = [subtag for subtag in self.subtags if subtag.type == 'script'... |
Get the errors of the tag.
If invalid then the list will consist of errors containing each a code and message explaining the error.
Each error also refers to the respective (sub)tag(s).
:return: list of errors of the tag. If the tag is valid, it returns an empty list. | def errors(self):
"""
Get the errors of the tag.
If invalid then the list will consist of errors containing each a code and message explaining the error.
Each error also refers to the respective (sub)tag(s).
:return: list of errors of the tag. If the tag is valid, it returns an ... |
Get the :class:`language_tags.Tag.Tag.Error` of a specific Tag error code.
The error creates a message explaining the error.
It also refers to the respective (sub)tag(s).
:param int code: a Tag error error:
* 1 = Tag.ERR_DEPRECATED
* 2 = Tag.ERR_NO_LANGUAGE
... | def error(self, code, subtag=None):
"""
Get the :class:`language_tags.Tag.Tag.Error` of a specific Tag error code.
The error creates a message explaining the error.
It also refers to the respective (sub)tag(s).
:param int code: a Tag error error:
* 1 = Tag.ERR_DEPRE... |
Object Enumeration.
Should export the whole list from the game for the best accuracy. | def ObjectEnum(ctx):
"""Object Enumeration.
Should export the whole list from the game for the best accuracy.
"""
return Enum(
ctx,
villager_male=83,
villager_female=293,
scout_cavalry=448,
eagle_warrior=751,
king=434,
flare=332,
relic=285... |
Game Type Enumeration. | def GameTypeEnum(ctx):
"""Game Type Enumeration."""
return Enum(
ctx,
RM=0,
Regicide=1,
DM=2,
Scenario=3,
Campaign=4,
KingOfTheHill=5,
WonderRace=6,
DefendTheWonder=7,
TurboRandom=8
) |
Object Type Enumeration. | def ObjectTypeEnum(ctx):
"""Object Type Enumeration."""
return Enum(
ctx,
static=10,
animated=20,
doppelganger=25,
moving=30,
action=40,
base=50,
missile=60,
combat=70,
building=80,
tree=90,
default=Pass
) |
Player Type Enumeration. | def PlayerTypeEnum(ctx):
"""Player Type Enumeration."""
return Enum(
ctx,
absent=0,
closed=1,
human=2,
eliminated=3,
computer=4,
cyborg=5,
spectator=6
) |
Resource Type Enumeration. | def ResourceEnum(ctx):
"""Resource Type Enumeration."""
return Enum(
ctx,
food=0,
wood=1,
stone=2,
gold=3,
decay=12,
fish=17,
default=Pass # lots of resource types exist
) |
Victory Type Enumeration. | def VictoryEnum(ctx):
"""Victory Type Enumeration."""
return Enum(
ctx,
standard=0,
conquest=1,
exploration=2,
ruins=3,
artifacts=4,
discoveries=5,
gold=6,
time_limit=7,
score=8,
standard2=9,
regicide=10,
las... |
Starting Age Enumeration. | def StartingAgeEnum(ctx):
"""Starting Age Enumeration."""
return Enum(
ctx,
what=-2,
unset=-1,
dark=0,
feudal=1,
castle=2,
imperial=3,
postimperial=4,
dmpostimperial=6
) |
Game Action Modes. | def GameActionModeEnum(ctx):
"""Game Action Modes."""
return Enum(
ctx,
diplomacy=0,
speed=1,
instant_build=2,
quick_build=4,
allied_victory=5,
cheat=6,
unk0=9,
spy=10,
unk1=11,
farm_queue=13,
farm_unqueue=14,
... |
Types of Releases. | def ReleaseTypeEnum(ctx):
"""Types of Releases."""
return Enum(
ctx,
all=0,
selected=3,
sametype=4,
notselected=5,
inversetype=6,
default=Pass
) |
Player's Diplomacy Enumeration. | def MyDiplomacyEnum(ctx):
"""Player's Diplomacy Enumeration."""
return Enum(
ctx,
gaia=0,
self=1,
ally=2,
neutral=3,
enemy=4,
invalid_player=-1
) |
Action Enumeration. | def ActionEnum(ctx):
"""Action Enumeration."""
return Enum(
ctx,
interact=0,
stop=1,
ai_interact=2,
move=3,
add_attribute=5,
give_attribute=6,
ai_move=10,
resign=11,
spec=15,
waypoint=16,
stance=18,
guard=19,... |
generate a new kernel | def newKernel(self, nb):
"""
generate a new kernel
"""
manager, kernel = utils.start_new_kernel(
kernel_name=nb.metadata.kernelspec.name
)
return kernel |
advertise options | def options(self, parser, env=os.environ):
"""
advertise options
"""
self.testMatchPat = env.get('NOSEBOOK_TESTMATCH',
r'.*[Tt]est.*\.ipynb$')
self.testMatchCellPat = env.get('NOSEBOOK_CELLMATCH',
r'.*'... |
apply configured options | def configure(self, options, conf):
"""
apply configured options
"""
super(Nosebook, self).configure(options, conf)
self.testMatch = re.compile(options.nosebookTestMatch).match
self.testMatchCell = re.compile(options.nosebookTestMatchCell).match
scrubs = []
... |
filter files to those that match nosebook-match | def wantFile(self, filename):
"""
filter files to those that match nosebook-match
"""
log.info("considering %s", filename)
if self.testMatch(filename) is None:
return False
nb = self.readnb(filename)
for cell in self.codeCells(nb):
retu... |
Create a SlipSocket connection.
This convenience method creates a connection to the the specified address
using the :func:`socket.create_connection` function.
The socket that is returned from that call is automatically wrapped in
a :class:`SlipSocket` object.
.. note::
... | def create_connection(cls, address, timeout=None, source_address=None):
"""Create a SlipSocket connection.
This convenience method creates a connection to the the specified address
using the :func:`socket.create_connection` function.
The socket that is returned from that call is automat... |
Receive a single message from the stream.
:return: A SLIP-decoded message
:rtype: bytes
:raises ProtocolError: when a SLIP protocol error has been encountered.
A subsequent call to :meth:`recv_msg` (after handling the exception)
will return the message from the next packet... | def recv_msg(self):
"""Receive a single message from the stream.
:return: A SLIP-decoded message
:rtype: bytes
:raises ProtocolError: when a SLIP protocol error has been encountered.
A subsequent call to :meth:`recv_msg` (after handling the exception)
will return t... |
Send a SLIP-encoded message over the stream.
:param bytes message: The message to encode and send | def send_msg(self, message):
"""Send a SLIP-encoded message over the stream.
:param bytes message: The message to encode and send
"""
packet = self.driver.send(message)
self.send_bytes(packet) |
Reload the device.
!!!WARNING! there is unsaved configuration!!!
This command will reboot the system. (y/n)? [n] | def reload(self, save_config=True):
"""Reload the device.
!!!WARNING! there is unsaved configuration!!!
This command will reboot the system. (y/n)? [n]
"""
if save_config:
self.device.send("copy running-config startup-config")
self.device("reload", wait_for_... |
Clean up the object.
After calling this method the object can't be used anymore.
This will be reworked when changing the logging model. | def finalize(self):
"""Clean up the object.
After calling this method the object can't be used anymore.
This will be reworked when changing the logging model.
"""
self.pause_session_logging()
self._disable_logging()
self._msg_callback = None
self._error_m... |
Get the deque of chain indices starting with last successful index. | def _chain_indices(self):
"""Get the deque of chain indices starting with last successful index."""
chain_indices = deque(range(len(self.connection_chains)))
chain_indices.rotate(self._last_chain_index)
return chain_indices |
Connect to the device.
Args:
logfile (file): Optional file descriptor for session logging. The file must be open for write.
The session is logged only if ``log_session=True`` was passed to the constructor.
If *None* then the default *session.log* file is created in `... | def connect(self, logfile=None, force_discovery=False, tracefile=None):
"""Connect to the device.
Args:
logfile (file): Optional file descriptor for session logging. The file must be open for write.
The session is logged only if ``log_session=True`` was passed to the constru... |
Reconnect to the device.
It can be called when after device reloads or the session was
disconnected either by device or jumphost. If multiple jumphosts are used then `reconnect` starts from
the last valid connection.
Args:
logfile (file): Optional file descriptor for sessio... | def reconnect(self, logfile=None, max_timeout=360, force_discovery=False, tracefile=None, retry=True):
"""Reconnect to the device.
It can be called when after device reloads or the session was
disconnected either by device or jumphost. If multiple jumphosts are used then `reconnect` starts from... |
Resume session logging. | def resume_session_logging(self):
"""Resume session logging."""
self._chain.ctrl.set_session_log(self.session_fd)
self.log("Session logging resumed") |
Send the command to the device and return the output.
Args:
cmd (str): Command string for execution. Defaults to empty string.
timeout (int): Timeout in seconds. Defaults to 300 sec (5 min)
wait_for_string (str): This is optional string that driver
waits for afte... | def send(self, cmd="", timeout=300, wait_for_string=None, password=False):
"""Send the command to the device and return the output.
Args:
cmd (str): Command string for execution. Defaults to empty string.
timeout (int): Timeout in seconds. Defaults to 300 sec (5 min)
... |
Configure the device.
This method applies configuration to the device.
Args:
configlet (text): The configuration template.
plane (text): sdr or admin
attributes (dict): The dictionary of attributes used in template.
Returns:
A string with commit... | def config(self, configlet=None, plane='sdr', **attributes):
"""Configure the device.
This method applies configuration to the device.
Args:
configlet (text): The configuration template.
plane (text): sdr or admin
attributes (dict): The dictionary of attribu... |
Rollback the configuration.
This method rolls back the configuration on the device.
Args:
label (text): The configuration label ID
plane: (text): sdr or admin
Returns:
A string with commit label or None | def rollback(self, label=None, plane='sdr'):
"""Rollback the configuration.
This method rolls back the configuration on the device.
Args:
label (text): The configuration label ID
plane: (text): sdr or admin
Returns:
A string with commit label or Non... |
Discover the device details.
This method discover several device attributes.
Args:
logfile (file): Optional file descriptor for session logging. The file must be open for write.
The session is logged only if ``log_session=True`` was passed to the constructor.
... | def discovery(self, logfile=None, tracefile=None):
"""Discover the device details.
This method discover several device attributes.
Args:
logfile (file): Optional file descriptor for session logging. The file must be open for write.
The session is logged only if ``lo... |
Reload the device and wait for device to boot up.
Returns False if reload was not successful. | def reload(self, reload_timeout=300, save_config=True, no_reload_cmd=False):
"""Reload the device and wait for device to boot up.
Returns False if reload was not successful.
"""
begin = time.time()
self._chain.target_device.clear_info()
result = False
try:
... |
Instantiate and run the Finite State Machine for the current device connection.
Here is the example of usage::
test_dir = "rw_test"
dir = "disk0:" + test_dir
REMOVE_DIR = re.compile(re.escape("Remove directory filename [{}]?".format(test_dir)))
DELETE_CONFIRM = ... | def run_fsm(self, name, command, events, transitions, timeout, max_transitions=20):
"""Instantiate and run the Finite State Machine for the current device connection.
Here is the example of usage::
test_dir = "rw_test"
dir = "disk0:" + test_dir
REMOVE_DIR = re.compi... |
Call the msg callback function with the message. | def emit_message(self, message, log_level):
"""Call the msg callback function with the message."""
self.log(message)
if log_level == logging.ERROR:
if self._error_msg_callback:
self._error_msg_callback(message)
return
if log_level == logging.W... |
Set the message callback. | def msg_callback(self, callback):
"""Set the message callback."""
if callable(callback):
self._msg_callback = callback
else:
self._msg_callback = None |
Set the error message callback. | def error_msg_callback(self, callback):
"""Set the error message callback."""
if callable(callback):
self._error_msg_callback = callback
else:
self._error_msg_callback = None |
Set the warning message callback. | def warning_msg_callback(self, callback):
"""Set the warning message callback."""
if callable(callback):
self._warning_msg_callback = callback
else:
self._warning_msg_callback = None |
Set the info message callback. | def info_msg_callback(self, callback):
"""Set the info message callback."""
if callable(callback):
self._info_msg_callback = callback
else:
self._info_msg_callback = None |
Return dict describing :class:`condoor.Connection` object.
Example::
{'connections': [{'chain': [{'driver_name': 'eXR',
'family': 'ASR9K',
'hostname': 'vkg3',
'is_console': True,
'is... | def description_record(self):
"""Return dict describing :class:`condoor.Connection` object.
Example::
{'connections': [{'chain': [{'driver_name': 'eXR',
'family': 'ASR9K',
'hostname': 'vkg3',
'is_console... |
Recursive function to extract all url details | def _get_view_details(self, urlpatterns, parent=''):
"""Recursive function to extract all url details"""
for pattern in urlpatterns:
if isinstance(pattern, (URLPattern, RegexURLPattern)):
try:
d = describe_pattern(pattern)
docstr = patt... |
Calls the callback for each AST node that's a child of the given node. | def for_each_child(node, callback):
"""Calls the callback for each AST node that's a child of the given node."""
for name in node._fields:
value = getattr(node, name)
if isinstance(value, list):
for item in value:
if isinstance(item, ast.AST):
call... |
Resolves the path of the module referred to by 'from ..x import y'. | def resolve_frompath(pkgpath, relpath, level=0):
"""Resolves the path of the module referred to by 'from ..x import y'."""
if level == 0:
return relpath
parts = pkgpath.split('.') + ['_']
parts = parts[:-level] + (relpath.split('.') if relpath else [])
return '.'.join(parts) |
Determines whether a module exists with the given modpath. | def find_module(modpath):
"""Determines whether a module exists with the given modpath."""
module_path = modpath.replace('.', '/') + '.py'
init_path = modpath.replace('.', '/') + '/__init__.py'
for root_path in sys.path:
path = os.path.join(root_path, module_path)
if os.path.isfile(path)... |
Gets (pkgpath, modpath, path, ast) for all modules in a file tree. | def get_modules(root_path):
"""Gets (pkgpath, modpath, path, ast) for all modules in a file tree."""
for dir_path, dir_names, file_names in os.walk(root_path):
assert dir_path[:len(root_path)] == root_path
subdir_path = dir_path[len(root_path):]
package_parts = list(filter(lambda x: x, s... |
Returns all the names imported by 'import *' from a given module. | def get_star_names(self, modpath):
"""Returns all the names imported by 'import *' from a given module."""
if modpath not in self.star_names:
print('Importing %s to resolve import *' % modpath, file=sys.stderr)
try:
module = self.import_module(modpath)
... |
Adds a possible origin for the given name in the given module. | def add(self, modpath, name, origin):
"""Adds a possible origin for the given name in the given module."""
self.map.setdefault(modpath, {}).setdefault(name, set()).add(origin) |
Whenever you 'import a.b.c', Python automatically binds 'b' in a to
the a.b module and binds 'c' in a.b to the a.b.c module. | def add_package_origins(self, modpath):
"""Whenever you 'import a.b.c', Python automatically binds 'b' in a to
the a.b module and binds 'c' in a.b to the a.b.c module."""
parts = modpath.split('.')
parent = parts[0]
for part in parts[1:]:
child = parent + '.' + part
... |
Scans a module, collecting possible origins for all names, assuming
names can only become bound to values in other modules by import. | def scan_module(self, pkgpath, modpath, node):
"""Scans a module, collecting possible origins for all names, assuming
names can only become bound to values in other modules by import."""
def scan_imports(node):
if node_type(node) == 'Import':
for binding in node.name... |
Returns the set of possible origins for a name in a module. | def get_origins(self, modpath, name):
"""Returns the set of possible origins for a name in a module."""
return self.map.get(modpath, {}).get(name, set()) |
Prints out the contents of the import map. | def dump(self):
"""Prints out the contents of the import map."""
for modpath in sorted(self.map):
title = 'Imports in %s' % modpath
print('\n' + title + '\n' + '-'*len(title))
for name, value in sorted(self.map.get(modpath, {}).items()):
print(' %s ->... |
Scans a module, collecting all used origins, assuming that modules
are obtained only by dotted paths and no other kinds of expressions. | def scan_module(self, modpath, node):
"""Scans a module, collecting all used origins, assuming that modules
are obtained only by dotted paths and no other kinds of expressions."""
used_origins = self.map.setdefault(modpath, set())
def get_origins(modpath, name):
"""Returns ... |
Convert int to timestamp string. | def convert_to_timestamp(time):
"""Convert int to timestamp string."""
if time == -1:
return None
time = int(time*1000)
hour = time//1000//3600
minute = (time//1000//60) % 60
second = (time//1000) % 60
return str(hour).zfill(2)+":"+str(minute).zfill(2)+":"+str(second).zfill(2) |
Parse tunnel. | def _parse(self, stream, context, path):
"""Parse tunnel."""
length = self.length(context)
new_stream = BytesIO(construct.core._read_stream(stream, length))
return self.subcon._parse(new_stream, context, path) |
Parse stream to find a given byte string. | def _parse(self, stream, context, path):
"""Parse stream to find a given byte string."""
start = stream.tell()
read_bytes = ""
if self.max_length:
read_bytes = stream.read(self.max_length)
else:
read_bytes = stream.read()
skip = read_bytes.find(sel... |
Parse until a given byte string is found. | def _parse(self, stream, context, path):
"""Parse until a given byte string is found."""
objs = []
while True:
start = stream.tell()
test = stream.read(len(self.find))
stream.seek(start)
if test == self.find:
break
else:... |
Parse until the end of objects data. | def _parse(self, stream, context, path):
"""Parse until the end of objects data."""
num_players = context._._._.replay.num_players
start = stream.tell()
# Have to read everything to be able to use find()
read_bytes = stream.read()
# Try to find the first marker, a portion... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.