_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q58100 | a_expected_prompt | train | 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 | python | {
"resource": ""
} |
q58101 | a_return_and_reconnect | train | def a_return_and_reconnect(ctx):
"""Send new line and reconnect."""
ctx.ctrl.send("\r")
ctx.device.connect(ctx.ctrl)
return True | python | {
"resource": ""
} |
q58102 | a_store_cmd_result | train | 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:
#... | python | {
"resource": ""
} |
q58103 | a_message_callback | train | 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 | python | {
"resource": ""
} |
q58104 | a_capture_show_configuration_failed | train | 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... | python | {
"resource": ""
} |
q58105 | a_configuration_inconsistency | train | 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' " \
... | python | {
"resource": ""
} |
q58106 | SMTP.fqdn | train | 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:
... | python | {
"resource": ""
} |
q58107 | SMTP.reset_state | train | 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.
... | python | {
"resource": ""
} |
q58108 | SMTP.helo | train | 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 ... | python | {
"resource": ""
} |
q58109 | SMTP.ehlo | train | 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... | python | {
"resource": ""
} |
q58110 | SMTP.help | train | 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 ... | python | {
"resource": ""
} |
q58111 | SMTP.mail | train | 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 ... | python | {
"resource": ""
} |
q58112 | SMTP.rcpt | train | 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... | python | {
"resource": ""
} |
q58113 | SMTP.quit | train | 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... | python | {
"resource": ""
} |
q58114 | SMTP.data | train | 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... | python | {
"resource": ""
} |
q58115 | SMTP.auth | train | 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... | python | {
"resource": ""
} |
q58116 | SMTP.starttls | train | 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
... | python | {
"resource": ""
} |
q58117 | SMTP.sendmail | train | 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... | python | {
"resource": ""
} |
q58118 | SMTP._auth_cram_md5 | train | 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 ... | python | {
"resource": ""
} |
q58119 | SMTP._auth_login | train | 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 ... | python | {
"resource": ""
} |
q58120 | SMTP._auth_plain | train | 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 ... | python | {
"resource": ""
} |
q58121 | Tag.format | train | 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]
... | python | {
"resource": ""
} |
q58122 | ObjectEnum | train | 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... | python | {
"resource": ""
} |
q58123 | GameTypeEnum | train | 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
) | python | {
"resource": ""
} |
q58124 | ObjectTypeEnum | train | 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
) | python | {
"resource": ""
} |
q58125 | PlayerTypeEnum | train | def PlayerTypeEnum(ctx):
"""Player Type Enumeration."""
return Enum(
ctx,
absent=0,
closed=1,
human=2,
eliminated=3,
computer=4,
cyborg=5,
spectator=6
) | python | {
"resource": ""
} |
q58126 | ResourceEnum | train | 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
) | python | {
"resource": ""
} |
q58127 | VictoryEnum | train | 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... | python | {
"resource": ""
} |
q58128 | StartingAgeEnum | train | 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
) | python | {
"resource": ""
} |
q58129 | GameActionModeEnum | train | 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,
... | python | {
"resource": ""
} |
q58130 | ReleaseTypeEnum | train | def ReleaseTypeEnum(ctx):
"""Types of Releases."""
return Enum(
ctx,
all=0,
selected=3,
sametype=4,
notselected=5,
inversetype=6,
default=Pass
) | python | {
"resource": ""
} |
q58131 | MyDiplomacyEnum | train | def MyDiplomacyEnum(ctx):
"""Player's Diplomacy Enumeration."""
return Enum(
ctx,
gaia=0,
self=1,
ally=2,
neutral=3,
enemy=4,
invalid_player=-1
) | python | {
"resource": ""
} |
q58132 | ActionEnum | train | 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,... | python | {
"resource": ""
} |
q58133 | NosebookThree.newKernel | train | def newKernel(self, nb):
"""
generate a new kernel
"""
manager, kernel = utils.start_new_kernel(
kernel_name=nb.metadata.kernelspec.name
)
return kernel | python | {
"resource": ""
} |
q58134 | Nosebook.configure | train | 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 = []
... | python | {
"resource": ""
} |
q58135 | Nosebook.wantFile | train | 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... | python | {
"resource": ""
} |
q58136 | SlipSocket.create_connection | train | 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... | python | {
"resource": ""
} |
q58137 | SlipWrapper.send_msg | train | 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) | python | {
"resource": ""
} |
q58138 | SlipWrapper.recv_msg | train | 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... | python | {
"resource": ""
} |
q58139 | Connection.finalize | train | 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... | python | {
"resource": ""
} |
q58140 | Connection._chain_indices | train | 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 | python | {
"resource": ""
} |
q58141 | Connection.resume_session_logging | train | def resume_session_logging(self):
"""Resume session logging."""
self._chain.ctrl.set_session_log(self.session_fd)
self.log("Session logging resumed") | python | {
"resource": ""
} |
q58142 | Connection.rollback | train | 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... | python | {
"resource": ""
} |
q58143 | Connection.discovery | train | 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... | python | {
"resource": ""
} |
q58144 | Connection.reload | train | 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:
... | python | {
"resource": ""
} |
q58145 | Connection.run_fsm | train | 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... | python | {
"resource": ""
} |
q58146 | Connection.emit_message | train | 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... | python | {
"resource": ""
} |
q58147 | Connection.msg_callback | train | def msg_callback(self, callback):
"""Set the message callback."""
if callable(callback):
self._msg_callback = callback
else:
self._msg_callback = None | python | {
"resource": ""
} |
q58148 | Connection.error_msg_callback | train | 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 | python | {
"resource": ""
} |
q58149 | Connection.warning_msg_callback | train | 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 | python | {
"resource": ""
} |
q58150 | Connection.info_msg_callback | train | 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 | python | {
"resource": ""
} |
q58151 | Extractor._get_view_details | train | 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... | python | {
"resource": ""
} |
q58152 | for_each_child | train | 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... | python | {
"resource": ""
} |
q58153 | resolve_frompath | train | 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) | python | {
"resource": ""
} |
q58154 | find_module | train | 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)... | python | {
"resource": ""
} |
q58155 | ImportMap.add | train | 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) | python | {
"resource": ""
} |
q58156 | ImportMap.add_package_origins | train | 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
... | python | {
"resource": ""
} |
q58157 | ImportMap.scan_module | train | 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... | python | {
"resource": ""
} |
q58158 | ImportMap.get_origins | train | 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()) | python | {
"resource": ""
} |
q58159 | ImportMap.dump | train | 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 ->... | python | {
"resource": ""
} |
q58160 | UsageMap.scan_module | train | 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 ... | python | {
"resource": ""
} |
q58161 | UsageMap.dump | train | def dump(self):
"""Prints out the contents of the usage map."""
for modpath in sorted(self.map):
title = 'Used by %s' % modpath
print('\n' + title + '\n' + '-'*len(title))
for origin in sorted(self.get_used_origins(modpath)):
print(' %s' % origin) | python | {
"resource": ""
} |
q58162 | convert_to_timestamp | train | 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) | python | {
"resource": ""
} |
q58163 | MgzPrefixed._parse | train | 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) | python | {
"resource": ""
} |
q58164 | Find._parse | train | 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... | python | {
"resource": ""
} |
q58165 | RepeatUpTo._parse | train | 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:... | python | {
"resource": ""
} |
q58166 | GotoObjectsEnd._parse | train | 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... | python | {
"resource": ""
} |
q58167 | Driver.rollback | train | def rollback(self, label, plane):
"""Rollback config."""
cm_label = 'condoor-{}'.format(int(time.time()))
self.device.send(self.rollback_cmd.format(label), timeout=120)
return cm_label | python | {
"resource": ""
} |
q58168 | start | train | def start(builtins=False, profile_threads=True):
"""Starts profiling all threads and all greenlets.
This function can be called from any thread at any time.
Resumes profiling if stop() was called previously.
* `builtins`: Profile builtin functions used by standart Python modules.
* `profile_thread... | python | {
"resource": ""
} |
q58169 | Telnet.connect | train | def connect(self, driver):
"""Connect using the Telnet protocol specific FSM."""
# 0 1 2 3
events = [ESCAPE_CHAR, driver.press_return_re, driver.standby_re, driver.username_re,
# 4 ... | python | {
"resource": ""
} |
q58170 | TelnetConsole.disconnect | train | def disconnect(self, driver):
"""Disconnect from the console."""
self.log("TELNETCONSOLE disconnect")
try:
while self.device.mode != 'global':
self.device.send('exit', timeout=10)
except OSError:
self.log("TELNETCONSOLE already disconnected")
... | python | {
"resource": ""
} |
q58171 | _calculate_apm | train | def _calculate_apm(index, player_actions, other_actions, duration):
"""Calculate player's rAPM."""
apm_per_player = {}
for player_index, histogram in player_actions.items():
apm_per_player[player_index] = sum(histogram.values())
total_unattributed = sum(other_actions.values())
total_attribut... | python | {
"resource": ""
} |
q58172 | guess_finished | train | def guess_finished(summary, postgame):
"""Sometimes a game is finished, but not recorded as such."""
if postgame and postgame.complete:
return True
for player in summary['players']:
if 'resign' in player['action_histogram']:
return True
return False | python | {
"resource": ""
} |
q58173 | RecordedGame._num_players | train | def _num_players(self):
"""Compute number of players, both human and computer."""
self._player_num = 0
self._computer_num = 0
for player in self._header.scenario.game_settings.player_info:
if player.type == 'human':
self._player_num += 1
elif playe... | python | {
"resource": ""
} |
q58174 | RecordedGame._parse_lobby_chat | train | def _parse_lobby_chat(self, messages, source, timestamp):
"""Parse a lobby chat message."""
for message in messages:
if message.message_length == 0:
continue
chat = ChatMessage(message.message, timestamp, self._players(), source=source)
self._parse_cha... | python | {
"resource": ""
} |
q58175 | RecordedGame._parse_action | train | def _parse_action(self, action, current_time):
"""Parse a player action.
TODO: handle cancels
"""
if action.action_type == 'research':
name = mgz.const.TECHNOLOGIES[action.data.technology_type]
self._research[action.data.player_id].append({
'techn... | python | {
"resource": ""
} |
q58176 | RecordedGame.operations | train | def operations(self, op_types=None):
"""Process operation stream."""
if not op_types:
op_types = ['message', 'action', 'sync', 'viewlock', 'savedchapter']
while self._handle.tell() < self._eof:
current_time = mgz.util.convert_to_timestamp(self._time / 1000)
tr... | python | {
"resource": ""
} |
q58177 | RecordedGame.summarize | train | def summarize(self):
"""Summarize game."""
if not self._achievements_summarized:
for _ in self.operations():
pass
self._summarize()
return self._summary | python | {
"resource": ""
} |
q58178 | RecordedGame.is_nomad | train | def is_nomad(self):
"""Is this game nomad.
TODO: Can we get from UP 1.4 achievements?
"""
nomad = self._header.initial.restore_time == 0 or None
for i in range(1, self._header.replay.num_players):
for obj in self._header.initial.players[i].objects:
if... | python | {
"resource": ""
} |
q58179 | RecordedGame.is_regicide | train | def is_regicide(self):
"""Is this game regicide."""
for i in range(1, self._header.replay.num_players):
for obj in self._header.initial.players[i].objects:
if obj.type == 'unit' and obj.object_type == 'king':
return True
return False | python | {
"resource": ""
} |
q58180 | RecordedGame._parse_chat | train | def _parse_chat(self, chat):
"""Parse a chat message."""
if chat.data['type'] == 'chat':
if chat.data['player'] in [p.player_name for i, p in self._players()]:
self._chat.append(chat.data)
elif chat.data['type'] == 'ladder':
self._ladder = chat.data['ladde... | python | {
"resource": ""
} |
q58181 | RecordedGame._compass_position | train | def _compass_position(self, player_x, player_y):
"""Get compass position of player."""
map_dim = self._map.size_x
third = map_dim * (1/3.0)
for direction in mgz.const.COMPASS:
point = mgz.const.COMPASS[direction]
xlower = point[0] * map_dim
xupper = (p... | python | {
"resource": ""
} |
q58182 | RecordedGame._players | train | def _players(self):
"""Get player attributes with index. No Gaia."""
for i in range(1, self._header.replay.num_players):
yield i, self._header.initial.players[i].attributes | python | {
"resource": ""
} |
q58183 | RecordedGame.players | train | def players(self, postgame, game_type):
"""Return parsed players."""
for i, attributes in self._players():
yield self._parse_player(i, attributes, postgame, game_type) | python | {
"resource": ""
} |
q58184 | RecordedGame._won_in | train | def _won_in(self):
"""Get age the game was won in."""
if not self._summary['finished']:
return
starting_age = self._summary['settings']['starting_age'].lower()
if starting_age == 'post imperial':
starting_age = 'imperial'
ages_reached = set([starting_age])... | python | {
"resource": ""
} |
q58185 | RecordedGame._rec_owner_number | train | def _rec_owner_number(self):
"""Get rec owner number."""
player = self._header.initial.players[self._header.replay.rec_player]
return player.attributes.player_color + 1 | python | {
"resource": ""
} |
q58186 | RecordedGame._get_timestamp | train | def _get_timestamp(self):
"""Get modification timestamp from rec file."""
filename_date = _find_date(os.path.basename(self._path))
if filename_date:
return filename_date | python | {
"resource": ""
} |
q58187 | RecordedGame._set_winning_team | train | def _set_winning_team(self):
"""Mark the winning team."""
if not self._summary['finished']:
return
for team in self._summary['diplomacy']['teams']:
team['winner'] = False
for player_number in team['player_numbers']:
for player in self._summary[... | python | {
"resource": ""
} |
q58188 | RecordedGame._map_hash | train | def _map_hash(self):
"""Compute a map hash based on a combination of map attributes.
- Elevation
- Map name
- Player names, colors, and civilizations
"""
elevation_bytes = bytes([tile.elevation for tile in self._header.map_info.tile])
map_name_bytes = self._map.n... | python | {
"resource": ""
} |
q58189 | Device.device_info | train | def device_info(self):
"""Return device info dict."""
return {
'family': self.family,
'platform': self.platform,
'os_type': self.os_type,
'os_version': self.os_version,
'udi': self.udi,
# TODO(klstanie): add property to make driver ... | python | {
"resource": ""
} |
q58190 | Device.clear_info | train | def clear_info(self):
"""Clear the device info."""
self._version_text = None
self._inventory_text = None
self._users_text = None
self.os_version = None
self.os_type = None
self.family = None
self.platform = None
self.udi = None
# self.is_co... | python | {
"resource": ""
} |
q58191 | Device.disconnect | train | def disconnect(self):
"""Disconnect the device."""
self.chain.connection.log("Disconnecting: {}".format(self))
if self.connected:
if self.protocol:
if self.is_console:
while self.mode != 'global':
try:
... | python | {
"resource": ""
} |
q58192 | Device.make_driver | train | def make_driver(self, driver_name='generic'):
"""Make driver factory function."""
module_str = 'condoor.drivers.%s' % driver_name
try:
__import__(module_str)
module = sys.modules[module_str]
driver_class = getattr(module, 'Driver')
except ImportError a... | python | {
"resource": ""
} |
q58193 | Device.version_text | train | def version_text(self):
"""Return version text and collect if not collected."""
if self._version_text is None:
self.chain.connection.log("Collecting version information")
self._version_text = self.driver.get_version_text()
if self._version_text:
self.c... | python | {
"resource": ""
} |
q58194 | Device.hostname_text | train | def hostname_text(self):
"""Return hostname text and collect if not collected."""
if self._hostname_text is None:
self.chain.connection.log("Collecting hostname information")
self._hostname_text = self.driver.get_hostname_text()
if self._hostname_text:
... | python | {
"resource": ""
} |
q58195 | Device.inventory_text | train | def inventory_text(self):
"""Return inventory information and collect if not available."""
if self._inventory_text is None:
self.chain.connection.log("Collecting inventory information")
self._inventory_text = self.driver.get_inventory_text()
if self._inventory_text:
... | python | {
"resource": ""
} |
q58196 | Device.users_text | train | def users_text(self):
"""Return connected users information and collect if not available."""
if self._users_text is None:
self.chain.connection.log("Getting connected users text")
self._users_text = self.driver.get_users_text()
if self._users_text:
sel... | python | {
"resource": ""
} |
q58197 | Device.get_protocol_name | train | def get_protocol_name(self):
"""Provide protocol name based on node_info."""
protocol_name = self.node_info.protocol
if self.is_console:
protocol_name += '_console'
return protocol_name | python | {
"resource": ""
} |
q58198 | Device.update_udi | train | def update_udi(self):
"""Update udi."""
self.chain.connection.log("Parsing inventory")
# TODO: Maybe validate if udi is complete
self.udi = parse_inventory(self.inventory_text) | python | {
"resource": ""
} |
q58199 | Device.update_config_mode | train | def update_config_mode(self, prompt=None):
"""Update config mode."""
# TODO: Fix the conflict with config mode attribute at connection
if prompt:
self.mode = self.driver.update_config_mode(prompt)
else:
self.mode = self.driver.update_config_mode(self.prompt) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.