text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_jump_target_maps(code, opc):
"""Returns a dictionary where the key is an offset and the values are a list of instruction offsets which can get run before... |
offset2prev = {}
prev_offset = -1
for offset, op, arg in unpack_opargs_bytecode(code, opc):
if prev_offset >= 0:
prev_list = offset2prev.get(offset, [])
prev_list.append(prev_offset)
offset2prev[offset] = prev_list
if op in opc.NOFOLLOW:
prev_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_const_info(const_index, const_list):
"""Helper to get optional details about const references Returns the dereferenced constant and its repr if the cons... |
argval = const_index
if const_list is not None:
argval = const_list[const_index]
# float values nan and inf are not directly representable in Python at least
# before 3.5 and even there it is via a library constant.
# So we will canonicalize their representation as float('nan') and float('... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_name_info(name_index, name_list):
"""Helper to get optional details about named references Returns the dereferenced name as both value and repr if the n... |
argval = name_index
if (name_list is not None
# PyPY seems to "optimize" out constant names,
# so we need for that:
and name_index < len(name_list)):
argval = name_list[name_index]
argrepr = argval
else:
argrepr = repr(argval)
return argval, argrepr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_size(op, opc):
"""For a given opcode, `op`, in opcode module `opc`, return the size, in bytes, of an `op` instruction. This is the size of the op... |
if op < opc.HAVE_ARGUMENT:
return 2 if opc.version >= 3.6 else 1
else:
return 2 if opc.version >= 3.6 else 3 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disassemble(self, lineno_width=3, mark_as_current=False, asm_format=False, show_bytes=False):
"""Format instruction details for inclusion in disassembly outp... |
fields = []
if asm_format:
indexed_operand = set(['name', 'local', 'compare', 'free'])
# Column: Source code line number
if lineno_width:
if self.starts_line is not None:
if asm_format:
lineno_fmt = "%%%dd:\n" % lineno_width
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_traceback(cls, tb):
""" Construct a Bytecode from the given traceback """ |
while tb.tb_next:
tb = tb.tb_next
return cls(tb.tb_frame.f_code, current_offset=tb.tb_lasti) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dis(self, asm_format=False, show_bytes=False):
"""Return a formatted view of the bytecode operations.""" |
co = self.codeobj
if self.current_offset is not None:
offset = self.current_offset
else:
offset = -1
output = StringIO()
self.disassemble_bytes(co.co_code, varnames=co.co_varnames,
names=co.co_names, constants=co.co_consts,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_jump_target_maps(code, opc):
"""Returns a dictionary where the key is an offset and the values are a list of instruction offsets which can get run before... |
offset2prev = {}
prev_offset = -1
for offset, op, arg in unpack_opargs_wordcode(code, opc):
if prev_offset >= 0:
prev_list = offset2prev.get(offset, [])
prev_list.append(prev_offset)
offset2prev[offset] = prev_list
prev_offset = offset
if op in op... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dis(self, x=None, file=None):
"""Disassemble classes, methods, functions, generators, or code. With no argument, disassemble the last traceback. """ |
self._print(self.Bytecode(x).dis(), file) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_protocol_from_name(name):
""" Returns the protocol class for the protocol with the given name. :type name: str :param name: The name of the protocol. :rt... |
cls = protocol_map.get(name)
if not cls:
raise ValueError('Unsupported protocol "%s".' % name)
return cls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_protocol(name, **kwargs):
""" Returns an instance of the protocol with the given name. :type name: str :param name: The name of the protocol. :rtype: ... |
cls = protocol_map.get(name)
if not cls:
raise ValueError('Unsupported protocol "%s".' % name)
return cls(**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _long_from_raw(thehash):
"""Fold to a long, a digest supplied as a string.""" |
hashnum = 0
for h in thehash:
hashnum <<= 8
hashnum |= ord(bytes([h]))
return hashnum |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aborted(self, exc_info):
""" Called by a logger to log an exception. """ |
self.exc_info = exc_info
self.did_end = True
self.write(format_exception(*self.exc_info)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_file(filename, password='', keytype=None):
""" Returns a new PrivateKey instance with the given attributes. If keytype is None, we attempt to automatica... |
if keytype is None:
try:
key = RSAKey.from_private_key_file(filename)
keytype = 'rsa'
except SSHException as e:
try:
key = DSSKey.from_private_key_file(filename)
keytype = 'dss'
excep... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_uri(self):
""" Returns a URI formatted representation of the host, including all of it's attributes except for the name. Uses the address, not the name o... |
url = Url()
url.protocol = self.get_protocol()
url.hostname = self.get_address()
url.port = self.get_tcp_port()
url.vars = dict((k, to_list(v))
for (k, v) in list(self.get_all().items())
if isinstance(v, str) or isinstance(v, list)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_address(self, address):
""" Set the address of the remote host the is contacted, without changing hostname, username, password, protocol, and TCP port nu... |
if is_ip(address):
self.address = clean_ip(address)
else:
self.address = address |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_option(self, name, default=None):
""" Returns the value of the given option if it is defined, returns the given default value otherwise. :type name: str ... |
if self.options is None:
return default
return self.options.get(name, default) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_tcp_port(self, tcp_port):
""" Defines the TCP port number. :type tcp_port: int :param tcp_port: The TCP port number. """ |
if tcp_port is None:
self.tcp_port = None
return
self.tcp_port = int(tcp_port) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, name, value):
""" Appends the given value to the list variable with the given name. :type name: string :param name: The name of the variable. :t... |
if self.vars is None:
self.vars = {}
if name in self.vars:
self.vars[name].append(value)
else:
self.vars[name] = [value] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, name, default=None):
""" Returns the value of the given variable, or the given default value if the variable is not defined. :type name: string :pa... |
if self.vars is None:
return default
return self.vars.get(name, default) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_labels(src, dst):
""" Copies all labels of one object to another object. :type src: object :param src: The object to check read the labels from. :type d... |
labels = src.__dict__.get('_labels')
if labels is None:
return
dst.__dict__['_labels'] = labels.copy() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serializeable_exc_info(thetype, ex, tb):
""" Since traceback objects can not be pickled, this function manipulates exception info tuples before they are pass... |
return thetype, ex, ''.join(traceback.format_exception(thetype, ex, tb)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deprecated(func):
""" A decorator for marking functions as deprecated. Results in a printed warning message when the function is used. """ |
def decorated(*args, **kwargs):
warnings.warn('Call to deprecated function %s.' % func.__name__,
category=DeprecationWarning,
stacklevel=2)
return func(*args, **kwargs)
decorated.__name__ = func.__name__
decorated.__doc__ = func.__doc__
decora... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def synchronized(func):
""" Decorator for synchronizing method access. """ |
@wraps(func)
def wrapped(self, *args, **kwargs):
try:
rlock = self._sync_lock
except AttributeError:
from multiprocessing import RLock
rlock = self.__dict__.setdefault('_sync_lock', RLock())
with rlock:
return func(self, *args, **kwargs)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def debug(func):
""" Decorator that prints a message whenever a function is entered or left. """ |
@wraps(func)
def wrapped(*args, **kwargs):
arg = repr(args) + ' ' + repr(kwargs)
sys.stdout.write('Entering ' + func.__name__ + arg + '\n')
try:
result = func(*args, **kwargs)
except:
sys.stdout.write('Traceback caught:\n')
sys.stdout.write(fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eval(conn, string, strip_command=True, **kwargs):
""" Compiles the given template and executes it on the given connection. Raises an exception if the compila... |
parser_args = {'strip_command': strip_command}
return _run(conn, None, string, parser_args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _urlparse_qs(url):
""" Parse a URL query string and return the components as a dictionary. Based on the cgi.parse_qs method.This is a utility function provid... |
# Extract the query part from the URL.
querystring = urlparse(url)[4]
# Split the query into name/value pairs.
pairs = [s2 for s1 in querystring.split('&') for s2 in s1.split(';')]
# Split the name/value pairs.
result = OrderedDefaultDict(list)
for name_value in pairs:
pair = name... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_debug(self, debug=1):
""" Set the debug level. :type debug: int :param debug: The debug level. """ |
self._check_if_ready()
self.debug = debug
self.main_loop.debug = debug |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_max_threads(self, max_threads):
""" Set the maximum number of concurrent threads. :type max_threads: int :param max_threads: The number of threads. """ |
if max_threads is None:
raise TypeError('max_threads must not be None.')
self._check_if_ready()
self.collection.set_max_working(max_threads) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authorize(scope, password=[None]):
""" Looks for a password prompt on the current connection and enters the given password. If a password is not given, the f... |
conn = scope.get('__connection__')
password = password[0]
if password is None:
conn.app_authorize()
else:
account = Account('', password)
conn.app_authorize(account)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(scope):
""" Closes the existing connection with the remote host. This function is rarely used, as normally Exscript closes the connection automatically... |
conn = scope.get('__connection__')
conn.close(1)
scope.define(__response__=conn.response)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exec_(scope, data):
""" Sends the given data to the remote host and waits until the host has responded with a prompt. If the given data is a list of strings,... |
conn = scope.get('__connection__')
response = []
for line in data:
conn.send(line)
conn.expect_prompt()
response += conn.response.split('\n')[1:]
scope.define(__response__=response)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait_for(scope, prompt):
""" Waits until the response of the remote host contains the given pattern. :type prompt: regex :param prompt: The prompt pattern. "... |
conn = scope.get('__connection__')
conn.expect(prompt)
scope.define(__response__=conn.response)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_prompt(scope, prompt=None):
""" Defines the pattern that is recognized at any future time when Exscript needs to wait for a prompt. In other words, whene... |
conn = scope.get('__connection__')
conn.set_prompt(prompt)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_error(scope, error_re=None):
""" Defines a pattern that, whenever detected in the response of the remote host, causes an error to be raised. In other wor... |
conn = scope.get('__connection__')
conn.set_error_prompt(error_re)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_timeout(scope, timeout):
""" Defines the time after which Exscript fails if it does not receive a prompt from the remote host. :type timeout: int :param ... |
conn = scope.get('__connection__')
conn.set_timeout(int(timeout[0]))
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_command(self, command, handler, prompt=True):
""" Registers a command. The command may be either a string (which is then automatically compiled into a re... |
if prompt:
thehandler = self._create_autoprompt_handler(handler)
else:
thehandler = handler
self.commands.add(command, thehandler) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_commands_from_file(self, filename, autoprompt=True):
""" Wrapper around add_command_handler that reads the handlers from the file with the given name. Th... |
if autoprompt:
deco = self._create_autoprompt_handler
else:
deco = None
self.commands.add_from_file(filename, deco) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init(self):
""" Init or reset the virtual device. :rtype: str :return: The initial response of the virtual device. """ |
self.logged_in = False
if self.login_type == self.LOGIN_TYPE_PASSWORDONLY:
self.prompt_stage = self.PROMPT_STAGE_PASSWORD
elif self.login_type == self.LOGIN_TYPE_NONE:
self.prompt_stage = self.PROMPT_STAGE_CUSTOM
else:
self.prompt_stage = self.PROMPT... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do(self, command):
""" "Executes" the given command on the virtual device, and returns the response. :type command: str :param command: The command to be exe... |
echo = self.echo and command or ''
if not self.logged_in:
return echo + '\n' + self._get_prompt()
response = self.commands.eval(command)
if response is None:
return echo + '\n' + self._get_prompt()
return echo + response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user(prompt=None):
""" Prompts the user for his login name, defaulting to the USER environment variable. Returns a string containing the username. May th... |
# Read username and password.
try:
env_user = getpass.getuser()
except KeyError:
env_user = ''
if prompt is None:
prompt = "Please enter your user name"
if env_user is None or env_user == '':
user = input('%s: ' % prompt)
else:
user = input('%s [%s]: ' % ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, key, default=None):
""" Returns the input with the given key from the section that was passed to the constructor. If either the section or the key ... |
if not self.parser:
return default
try:
return self.parser.get(self.section, key)
except (configparser.NoSectionError, configparser.NoOptionError):
return default |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, key, value):
""" Saves the input with the given key in the section that was passed to the constructor. If either the section or the key are not fou... |
if value is None:
return None
self.parser.set(self.section, key, value)
# Unfortunately ConfigParser attempts to write a string to the file
# object, and NamedTemporaryFile uses binary mode. So we nee to create
# the tempfile, and then re-open it.
with Name... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acquire(self, signal=True):
""" Locks the account. Method has no effect if the constructor argument `needs_lock` wsa set to False. :type signal: bool :param ... |
if not self.needs_lock:
return
with self.synclock:
while not self.lock.acquire(False):
self.synclock.wait()
if signal:
self.acquired_event(self)
self.synclock.notify_all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def release(self, signal=True):
""" Unlocks the account. Method has no effect if the constructor argument `needs_lock` wsa set to False. :type signal: bool :para... |
if not self.needs_lock:
return
with self.synclock:
self.lock.release()
if signal:
self.released_event(self)
self.synclock.notify_all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_name(self, name):
""" Changes the name of the account. :type name: string :param name: The account name. """ |
self.name = name
self.changed_event.emit(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_password(self, password):
""" Changes the password of the account. :type password: string :param password: The account password. """ |
self.password = password
self.changed_event.emit(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_authorization_password(self, password):
""" Changes the authorization password of the account. :type password: string :param password: The new authorizat... |
self.authorization_password = password
self.changed_event.emit(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def for_host(parent, host):
""" Returns a new AccountProxy that has an account acquired. The account is chosen based on what the connected AccountManager selects... |
account = AccountProxy(parent)
account.host = host
if account.acquire():
return account
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def for_account_hash(parent, account_hash):
""" Returns a new AccountProxy that acquires the account with the given hash, if such an account is known to the acco... |
account = AccountProxy(parent)
account.account_hash = account_hash
if account.acquire():
return account
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acquire(self):
""" Locks the account. Returns True on success, False if the account is thread-local and must not be locked. """ |
if self.host:
self.parent.send(('acquire-account-for-host', self.host))
elif self.account_hash:
self.parent.send(('acquire-account-from-hash', self.account_hash))
else:
self.parent.send(('acquire-account'))
response = self.parent.recv()
if is... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def release(self):
""" Unlocks the account. """ |
self.parent.send(('release-account', self.account_hash))
response = self.parent.recv()
if isinstance(response, Exception):
raise response
if response != 'ok':
raise ValueError('unexpected response: ' + repr(response)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_account_from_hash(self, account_hash):
""" Returns the account with the given hash, or None if no such account is included in the account pool. """ |
for account in self.accounts:
if account.__hash__() == account_hash:
return account
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_account(self, accounts):
""" Adds one or more account instances to the pool. :type accounts: Account|list[Account] :param accounts: The account to be add... |
with self.unlock_cond:
for account in to_list(accounts):
account.acquired_event.listen(self._on_account_acquired)
account.released_event.listen(self._on_account_released)
self.accounts.add(account)
self.unlocked_accounts.append(account... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset(self):
""" Removes all accounts. """ |
with self.unlock_cond:
for owner in self.owner2account:
self.release_accounts(owner)
self._remove_account(self.accounts.copy())
self.unlock_cond.notify_all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_account_from_name(self, name):
""" Returns the account with the given name. :type name: string :param name: The name of the account. """ |
for account in self.accounts:
if account.get_name() == name:
return account
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acquire_account(self, account=None, owner=None):
""" Waits until an account becomes available, then locks and returns it. If an account is not passed, the ne... |
with self.unlock_cond:
if len(self.accounts) == 0:
raise ValueError('account pool is empty')
if account:
# Specific account requested.
while account not in self.unlocked_accounts:
self.unlock_cond.wait()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_pool(self, pool, match=None):
""" Adds a new account pool. If the given match argument is None, the pool the default pool. Otherwise, the match argument ... |
if match is None:
self.default_pool = pool
else:
self.pools.append((match, pool)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_account_from_hash(self, account_hash):
""" Returns the account with the given hash, if it is contained in any of the pools. Returns None otherwise. :type... |
for _, pool in self.pools:
account = pool.get_account_from_hash(account_hash)
if account is not None:
return account
return self.default_pool.get_account_from_hash(account_hash) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acquire_account(self, account=None, owner=None):
""" Acquires the given account. If no account is given, one is chosen from the default pool. :type account: ... |
if account is not None:
for _, pool in self.pools:
if pool.has_account(account):
return pool.acquire_account(account, owner)
if not self.default_pool.has_account(account):
# The account is not in any pool.
account.acqu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acquire_account_for(self, host, owner=None):
""" Acquires an account for the given host and returns it. The host is passed to each of the match functions tha... |
# Check whether a matching account pool exists.
for match, pool in self.pools:
if match(host) is True:
return pool.acquire_account(owner=owner)
# Else, choose an account from the default account pool.
return self.default_pool.acquire_account(owner=owner) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eval(self, command):
""" Evaluate the given string against all registered commands and return the defined response. :type command: str :param command: The co... |
for cmd, response in self.response_list:
if not cmd.match(command):
continue
if response is None:
return None
elif hasattr(response, '__call__'):
return response(command)
else:
return response
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_host(host, default_protocol='telnet', default_domain=''):
""" Given a string or a Host object, this function returns a Host object. :type host: string|Hos... |
if host is None:
raise TypeError('None can not be cast to Host')
if hasattr(host, 'get_address'):
return host
if default_domain and not '.' in host:
host += '.' + default_domain
return Exscript.Host(host, default_protocol=default_protocol) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_hosts(hosts, default_protocol='telnet', default_domain=''):
""" Given a string or a Host object, or a list of strings or Host objects, this function retur... |
return [to_host(h, default_protocol, default_domain)
for h in to_list(hosts)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_regex(regex, flags=0):
""" Given a string, this function returns a new re.RegexObject. Given a re.RegexObject, this function just returns the same object.... |
if regex is None:
raise TypeError('None can not be cast to re.RegexObject')
if hasattr(regex, 'match'):
return regex
return re.compile(regex, flags) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_ip(string):
""" Returns True if the given string is an IPv4 address, False otherwise. :type string: string :param string: Any string. :rtype: bool :return... |
mo = re.match(r'(\d+)\.(\d+)\.(\d+)\.(\d+)', string)
if mo is None:
return False
for group in mo.groups():
if int(group) not in list(range(0, 256)):
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def network(prefix, default_length=24):
""" Given a prefix, this function returns the corresponding network address. :type prefix: string :param prefix: An IP pr... |
address, pfxlen = parse_prefix(prefix, default_length)
ip = ip2int(address)
return int2ip(ip & pfxlen2mask_int(pfxlen)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def matches_prefix(ip, prefix):
""" Returns True if the given IP address is part of the given network, returns False otherwise. :type ip: string :param ip: An IP... |
ip_int = ip2int(ip)
network, pfxlen = parse_prefix(prefix)
network_int = ip2int(network)
mask_int = pfxlen2mask_int(pfxlen)
return ip_int&mask_int == network_int&mask_int |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_private(ip):
""" Returns True if the given IP address is private, returns False otherwise. :type ip: string :param ip: An IP address. :rtype: bool :return... |
if matches_prefix(ip, '10.0.0.0/8'):
return True
if matches_prefix(ip, '172.16.0.0/12'):
return True
if matches_prefix(ip, '192.168.0.0/16'):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort(iterable):
""" Given an IP address list, this function sorts the list. :type iterable: Iterator :param iterable: An IP address list. :rtype: list :retur... |
ips = sorted(normalize_ip(ip) for ip in iterable)
return [clean_ip(ip) for ip in ips] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_url(path):
"""Given a urlencoded path, returns the path and the dictionary of query arguments, all in Unicode.""" |
# path changes from bytes to Unicode in going from Python 2 to
# Python 3.
if sys.version_info[0] < 3:
o = urlparse(urllib.parse.unquote_plus(path).decode('utf8'))
else:
o = urlparse(urllib.parse.unquote_plus(path))
path = o.path
args = {}
# Convert parse_qs' str --> [str... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _require_authenticate(func):
'''A decorator to add digest authorization checks to HTTP Request Handlers'''
def wrapped(self):
if not hasattr(self, 'authenticated'):
self.authenticated = None
if self.authenticated:
return func(self)
auth = self.headers.get(u'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_POSTGET(self, handler):
"""handle an HTTP request""" |
# at first, assume that the given path is the actual path and there are
# no arguments
self.server._dbg(self.path)
self.path, self.args = _parse_url(self.path)
# Extract POST data, if any. Clumsy syntax due to Python 2 and
# 2to3's lack of a byte literal.
self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def head(self, bytes):
""" Returns the number of given bytes from the head of the buffer. The buffer remains unchanged. :type bytes: int :param bytes: The number... |
oldpos = self.io.tell()
self.io.seek(0)
head = self.io.read(bytes)
self.io.seek(oldpos)
return head |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tail(self, bytes):
""" Returns the number of given bytes from the tail of the buffer. The buffer remains unchanged. :type bytes: int :param bytes: The number... |
self.io.seek(max(0, self.size() - bytes))
return self.io.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, data):
""" Appends the given data to the buffer, and triggers all connected monitors, if any of them match the buffer content. :type data: str :... |
self.io.write(data)
if not self.monitors:
return
# Check whether any of the monitoring regular expressions matches.
# If it does, we need to disable that monitor until the matching
# data is no longer in the buffer. We accomplish this by keeping
# track of t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear(self):
""" Removes all data from the buffer. """ |
self.io.seek(0)
self.io.truncate()
for item in self.monitors:
item[2] = 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_monitor(self, pattern, callback, limit=80):
""" Calls the given function whenever the given pattern matches the buffer. Arguments passed to the callback ... |
self.monitors.append([to_regexs(pattern), callback, 0, limit]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_template_string(string, **kwargs):
""" Reads the given SMTP formatted template, and creates a new Mail object using the information. :type string: str :... |
tmpl = _render_template(string, **kwargs)
mail = Mail()
mail.set_from_template_string(tmpl)
return mail |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(mail, server='localhost'):
""" Sends the given mail. :type mail: Mail :param mail: The mail object. :type server: string :param server: The address of t... |
sender = mail.get_sender()
rcpt = mail.get_receipients()
session = smtplib.SMTP(server)
message = MIMEMultipart()
message['Subject'] = mail.get_subject()
message['From'] = mail.get_sender()
message['To'] = ', '.join(mail.get_to())
message['Cc'] = ', '.join(mail.get_cc())
message.pre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_smtp_header(self):
""" Returns the SMTP formatted header of the line. :rtype: string :return: The SMTP header. """ |
header = "From: %s\r\n" % self.get_sender()
header += "To: %s\r\n" % ',\r\n '.join(self.get_to())
header += "Cc: %s\r\n" % ',\r\n '.join(self.get_cc())
header += "Bcc: %s\r\n" % ',\r\n '.join(self.get_bcc())
header += "Subject: %s\r\n" % self.get_subject()
return header |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_smtp_mail(self):
""" Returns the SMTP formatted email, as it may be passed to sendmail. :rtype: string :return: The SMTP formatted mail. """ |
header = self.get_smtp_header()
body = self.get_body().replace('\n', '\r\n')
return header + '\r\n' + body + '\r\n' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status(logger):
""" Creates a one-line summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recor... |
aborted = logger.get_aborted_actions()
succeeded = logger.get_succeeded_actions()
total = aborted + succeeded
if total == 0:
return 'No actions done'
elif total == 1 and succeeded == 1:
return 'One action done (succeeded)'
elif total == 1 and succeeded == 0:
return 'One ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def summarize(logger):
""" Creates a short summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recor... |
summary = []
for log in logger.get_logs():
thestatus = log.has_error() and log.get_error(False) or 'ok'
name = log.get_name()
summary.append(name + ': ' + thestatus)
return '\n'.join(summary) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format(logger, show_successful=True, show_errors=True, show_traceback=True):
""" Prints a report of the actions that were logged by the given Logger. The rep... |
output = []
# Print failed actions.
errors = logger.get_aborted_actions()
if show_errors and errors:
output += _underline('Failed actions:')
for log in logger.get_aborted_logs():
if show_traceback:
output.append(log.get_name() + ':')
output.a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_vars(self):
""" Returns a complete dict of all variables that are defined in this scope, including the variables of the parent. """ |
if self.parent is None:
vars = {}
vars.update(self.variables)
return vars
vars = self.parent.get_vars()
vars.update(self.variables)
return vars |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_from_name(self, name):
""" Returns the item with the given name, or None if no such item is known. """ |
with self.condition:
try:
item_id = self.name2id[name]
except KeyError:
return None
return self.id2item[item_id]
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, item, name=None):
""" Adds the given item to the end of the pipeline. """ |
with self.condition:
self.queue.append(item)
uuid = self._register_item(name, item)
self.condition.notify_all()
return uuid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prioritize(self, item, force=False):
""" Moves the item to the very left of the queue. """ |
with self.condition:
# If the job is already running (or about to be forced),
# there is nothing to be done.
if item in self.working or item in self.force:
return
self.queue.remove(item)
if force:
self.force.append(item... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_hosts_from_file(filename, default_protocol='telnet', default_domain='', remove_duplicates=False, encoding='utf-8'):
""" Reads a list of hostnames from th... |
# Open the file.
if not os.path.exists(filename):
raise IOError('No such file: %s' % filename)
# Read the hostnames.
have = set()
hosts = []
with codecs.open(filename, 'r', encoding) as file_handle:
for line in file_handle:
hostname = line.split('#')[0].strip()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_to(logger):
""" Wraps a function that has a connection passed such that everything that happens on the connection is logged using the given logger. :type... |
logger_id = id(logger)
def decorator(function):
func = add_label(function, 'log_to', logger_id=logger_id)
return func
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def msg(self, msg, *args):
"""Print a debug message, when the debug level is > 0. If extra arguments are present, they are substituted in the message using the s... |
if self.debuglevel > 0:
self.stderr.write('Telnet(%s,%d): ' % (self.host, self.port))
if args:
self.stderr.write(msg % args)
else:
self.stderr.write(msg)
self.stderr.write('\n') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, buffer):
"""Write a string to the socket, doubling any IAC characters. Can block if the connection is blocked. May raise socket.error if the conn... |
if type(buffer) == type(0):
buffer = chr(buffer)
elif not isinstance(buffer, bytes):
buffer = buffer.encode(self.encoding)
if IAC in buffer:
buffer = buffer.replace(IAC, IAC+IAC)
self.msg("send %s", repr(buffer))
self.sock.send(buffer) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_all(self):
"""Read all data until EOF; block until connection closed.""" |
self.process_rawq()
while not self.eof:
self.fill_rawq()
self.process_rawq()
buf = self.cookedq.getvalue()
self.cookedq.seek(0)
self.cookedq.truncate()
return buf |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_eager(self):
"""Read readily available data. Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available oth... |
self.process_rawq()
while self.cookedq.tell() == 0 and not self.eof and self.sock_avail():
self.fill_rawq()
self.process_rawq()
return self.read_very_lazy() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_receive_callback(self, callback, *args, **kwargs):
"""The callback function called after each receipt of any data.""" |
self.data_callback = callback
self.data_callback_kwargs = kwargs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_window_size(self, rows, cols):
""" Change the size of the terminal window, if the remote end supports NAWS. If it doesn't, the method returns silently. "... |
if not self.can_naws:
return
self.window_size = rows, cols
size = struct.pack('!HH', cols, rows)
self.sock.send(IAC + SB + NAWS + size + IAC + SE) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interact(self):
"""Interaction function, emulates a very dumb telnet client.""" |
if sys.platform == "win32":
self.mt_interact()
return
while True:
rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
if self in rfd:
try:
text = self.read_eager()
except EOFError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def waitfor(self, relist, timeout=None, cleanup=None):
"""Read until one from a list of a regular expressions matches. The first argument is a list of regular ex... |
return self._waitfor(relist, timeout, False, cleanup) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(path):
""" Returns the process id from the given file if it exists, or None otherwise. Raises an exception for all other types of OSError while trying t... |
# Try to read the pid from the pidfile.
logging.info("Checking pidfile '%s'", path)
try:
return int(open(path).read())
except IOError as xxx_todo_changeme:
(code, text) = xxx_todo_changeme.args
if code == errno.ENOENT: # no such file or directory
return None
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.