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 disable_directory_service(self, check_peer=False):
"""Disable the directory service. :param check_peer: If True, disables server authenticity enforcement. If... |
if check_peer:
return self.set_directory_service(check_peer=False)
return self.set_directory_service(enabled=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 enable_directory_service(self, check_peer=False):
"""Enable the directory service. :param check_peer: If True, enables server authenticity enforcement. If Fa... |
if check_peer:
return self.set_directory_service(check_peer=True)
return self.set_directory_service(enabled=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 create_snmp_manager(self, manager, host, **kwargs):
"""Create an SNMP manager. :param manager: Name of manager to be created. :type manager: str :param host:... |
data = {"host": host}
data.update(kwargs)
return self._request("POST", "snmp/{0}".format(manager), data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_array(self, address, connection_key, connection_type, **kwargs):
"""Connect this array with another one. :param address: IP address or DNS name of ot... |
data = {"management_address": address,
"connection_key": connection_key,
"type": connection_type}
data.update(kwargs)
return self._request("POST", "array/connection", data) |
<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_pgroup_snapshot(self, source, **kwargs):
"""Create snapshot of pgroup from specified source. :param source: Name of pgroup of which to take snapshot. ... |
# In REST 1.4, support was added for snapshotting multiple pgroups. As a
# result, the endpoint response changed from an object to an array of
# objects. To keep the response type consistent between REST versions,
# we unbox the response when creating a single snapshot.
result ... |
<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_pgroup_snapshots(self, sources, **kwargs):
"""Create snapshots of pgroups from specified sources. :param sources: Names of pgroups of which to take sn... |
data = {"source": sources, "snap": True}
data.update(kwargs)
return self._request("POST", "pgroup", data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eradicate_pgroup(self, pgroup, **kwargs):
"""Eradicate a destroyed pgroup. :param pgroup: Name of pgroup to be eradicated. :type pgroup: str :param \*\*kwarg... |
eradicate = {"eradicate": True}
eradicate.update(kwargs)
return self._request("DELETE", "pgroup/{0}".format(pgroup), eradicate) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clone_pod(self, source, dest, **kwargs):
"""Clone an existing pod to a new one. :param source: Name of the pod the be cloned. :type source: str :param dest: ... |
data = {"source": source}
data.update(kwargs)
return self._request("POST", "pod/{0}".format(dest), data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_pod(self, pod, array, **kwargs):
"""Remove arrays from a pod. :param pod: Name of the pod. :type pod: str :param array: Array to remove from pod. :typ... |
return self._request("DELETE", "pod/{0}/array/{1}".format(pod, array), 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 page_through(page_size, function, *args, **kwargs):
"""Return an iterator over all pages of a REST operation. :param page_size: Number of elements to retriev... |
kwargs["limit"] = page_size
def get_page(token):
page_kwargs = kwargs.copy()
if token:
page_kwargs["token"] = token
return function(*args, **page_kwargs)
def page_generator():
token = None
while 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 read_all(self, n, check_rekey=False):
""" Read as close to N bytes as possible, blocking as long as necessary. @param n: number of bytes to read @type n: int... |
out = ''
# handle over-reading from reading the banner line
if len(self.__remainder) > 0:
out = self.__remainder[:n]
self.__remainder = self.__remainder[n:]
n -= len(out)
if PY22:
return self._py22_read_all(n, out)
while n > 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 send_message(self, data):
""" Write a block of data using the current cipher, as an SSH block. """ |
# encrypt this sucka
data = str(data)
cmd = ord(data[0])
if cmd in MSG_NAMES:
cmd_name = MSG_NAMES[cmd]
else:
cmd_name = '$%x' % cmd
orig_len = len(data)
self.__write_lock.acquire()
try:
if self.__compress_engine_out 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 from_line(cls, line):
""" Parses the given line of text to find the names for the host, the type of key, and the key data. The line is expected to be in the ... |
fields = line.split(' ')
if len(fields) < 3:
# Bad number of fields
return None
fields = fields[:3]
names, keytype, key = fields
names = names.split(',')
# Decide what kind of key we're looking at and create an object
# to hold it accord... |
<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_line(self):
""" Returns a string in OpenSSH known_hosts file format, or None if the object is not in a valid state. A trailing newline is included. """ |
if self.valid:
return '%s %s %s\n' % (','.join(self.hostnames), self.key.get_name(),
self.key.get_base64())
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 check(self, hostname, key):
""" Return True if the given key is associated with the given hostname in this dictionary. @param hostname: hostname (or IP) of t... |
k = self.lookup(hostname)
if k is None:
return False
host_key = k.get(key.get_name(), None)
if host_key is None:
return False
return str(host_key) == str(key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hash_host(hostname, salt=None):
""" Return a "hashed" form of the hostname, as used by openssh when storing hashed hostnames in the known_hosts file. @param ... |
if salt is None:
salt = rng.read(SHA.digest_size)
else:
if salt.startswith('|1|'):
salt = salt.split('|')[2]
salt = base64.decodestring(salt)
assert len(salt) == SHA.digest_size
hmac = HMAC.HMAC(salt, hostname, SHA).digest()
ho... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def retry_on_signal(function):
"""Retries function until it doesn't raise an EINTR error""" |
while True:
try:
return function()
except EnvironmentError, e:
if e.errno != errno.EINTR:
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lookup(self, hostname):
""" Return a dict of config options for a given hostname. The host-matching rules of OpenSSH's C{ssh_config} man page are used, which... |
matches = [x for x in self._config if fnmatch.fnmatch(hostname, x['host'])]
# Move * to the end
_star = matches.pop(0)
matches.append(_star)
ret = {}
for m in matches:
for k,v in m.iteritems():
if not k in ret:
ret[k] = v
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url(proto, server, port=None, uri=None):
"""Construct a URL from the given components.""" |
url_parts = [proto, '://', server]
if port:
port = int(port)
if port < 1 or port > 65535:
raise ValueError('invalid port value')
if not ((proto == 'http' and port == 80) or
(proto == 'https' and port == 443)):
url_p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_url(self, container=None, resource=None, query_items=None):
"""Create a URL from the specified parts.""" |
pth = [self._base_url]
if container:
pth.append(container.strip('/'))
if resource:
pth.append(resource)
else:
pth.append('')
url = '/'.join(pth)
if isinstance(query_items, (list, tuple, set)):
url += RestHttp._list_query_st... |
<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_request(self, container, resource=None):
"""Send a HEAD request.""" |
url = self.make_url(container, resource)
headers = self._make_headers(None)
try:
rsp = requests.head(url, headers=self._base_headers,
verify=self._verify, timeout=self._timeout)
except requests.exceptions.ConnectionError as e:
Res... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_file(self, container, src_file_path, dst_name=None, put=True, content_type=None):
"""Upload a single file.""" |
if not os.path.exists(src_file_path):
raise RuntimeError('file not found: ' + src_file_path)
if not dst_name:
dst_name = os.path.basename(src_file_path)
if not content_type:
content_type = "application/octet.stream"
headers = dict(self._base_headers)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_file_mp(self, container, src_file_path, dst_name=None, content_type=None):
"""Upload a file using multi-part encoding.""" |
if not os.path.exists(src_file_path):
raise RuntimeError('file not found: ' + src_file_path)
if not dst_name:
dst_name = os.path.basename(src_file_path)
if not content_type:
content_type = "application/octet.stream"
url = self.make_url(container, 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 upload_files(self, container, src_dst_map, content_type=None):
"""Upload multiple files.""" |
if not content_type:
content_type = "application/octet.stream"
url = self.make_url(container, None, None)
headers = self._base_headers
multi_files = []
try:
for src_path in src_dst_map:
dst_name = src_dst_map[src_path]
if 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 new_session(self, server=None, session_name=None, user_name=None, existing_session=None):
"""Create a new session or attach to existing. Normally, this funct... |
if not server:
server = os.environ.get('STC_SERVER_ADDRESS')
if not server:
raise EnvironmentError('STC_SERVER_ADDRESS not set')
self._stc = stchttp.StcHttp(server)
if not session_name:
session_name = os.environ.get('STC_SESSION_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 _end_session(self, kill=None):
"""End the client session.""" |
if self._stc:
if kill is None:
kill = os.environ.get('STC_SESSION_TERMINATE_ON_DISCONNECT')
kill = _is_true(kill)
self._stc.end_session(kill)
self._stc = 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 setup(app):
""" This isn't used in Production, but allows this module to be used as a standalone extension. """ |
app.add_directive('readthedocs-embed', EmbedDirective)
app.add_config_value('readthedocs_embed_project', '', 'html')
app.add_config_value('readthedocs_embed_version', '', 'html')
app.add_config_value('readthedocs_embed_doc', '', 'html')
return app |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def finalize_media(app):
"""Point media files at our media server.""" |
if (app.builder.name == 'readthedocssinglehtmllocalmedia' or
app.builder.format != 'html' or
not hasattr(app.builder, 'script_files')):
return # Use local media for downloadable files
# Pull project data from conf.py if it exists
context = app.builder.config.html_context
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_body(app, pagename, templatename, context, doctree):
""" Add Read the Docs content to Sphinx body content. This is the most reliable way to inject our... |
STATIC_URL = context.get('STATIC_URL', DEFAULT_STATIC_URL)
online_builders = [
'readthedocs', 'readthedocsdirhtml', 'readthedocssinglehtml'
]
if app.builder.name == 'readthedocssinglehtmllocalmedia':
if 'html_theme' in context and context['html_theme'] == 'sphinx_rtd_theme':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_json_artifacts(app, pagename, templatename, context, doctree):
""" Generate JSON artifacts for each page. This way we can skip generating this in ot... |
try:
# We need to get the output directory where the docs are built
# _build/json.
build_json = os.path.abspath(
os.path.join(app.outdir, '..', 'json')
)
outjson = os.path.join(build_json, pagename + '.fjson')
outdir = os.path.dirname(outjson)
if ... |
<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_searchtools(self, renderer=None):
"""Copy and patch searchtools This uses the included Sphinx version's searchtools, but patches it to remove automatic... |
log.info(bold('copying searchtools... '), nonl=True)
if sphinx.version_info < (1, 8):
search_js_file = 'searchtools.js_t'
else:
search_js_file = 'searchtools.js'
path_src = os.path.join(
package_dir, 'themes', 'basic', 'static', search_js_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 stc_system_info(stc_addr):
"""Return dictionary of STC and API information. If a session already exists, then use it to get STC information and avoid taking ... |
stc = stchttp.StcHttp(stc_addr)
sessions = stc.sessions()
if sessions:
# If a session already exists, use it to get STC information.
stc.join_session(sessions[0])
sys_info = stc.system_info()
else:
# Create a new session to get STC information.
stc.new_session('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 new_session(self, user_name=None, session_name=None, kill_existing=False, analytics=None):
"""Create a new test session. The test session is identified by th... |
if self.started():
return False
if not session_name or not session_name.strip():
session_name = ''
if not user_name or not user_name.strip():
user_name = ''
params = {'userid': user_name, 'sessionname': session_name}
if analytics not in (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 join_session(self, sid):
"""Attach to an existing session.""" |
self._rest.add_header('X-STC-API-Session', sid)
self._sid = sid
try:
status, data = self._rest.get_request('objects', 'system1',
['version', 'name'])
except resthttp.RestHttpError as e:
self._rest.del_header('X-ST... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def end_session(self, end_tcsession=True, sid=None):
"""End this test session. A session can be ended in three ways, depending on the value of the end_tcsession ... |
if not sid or sid == self._sid:
if not self.started():
return False
sid = self._sid
self._sid = None
self._rest.del_header('X-STC-API-Session')
if end_tcsession is None:
if self._dbg_print:
print('===> detache... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def session_info(self, session_id=None):
"""Get information on session. If session_id is None, the default, then return information about this session. If a sess... |
if not session_id:
if not self.started():
return []
session_id = self._sid
status, data = self._rest.get_request('sessions', session_id)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def files(self):
"""Get list of files, for this session, on server.""" |
self._check_session()
status, data = self._rest.get_request('files')
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bll_version(self):
"""Get the BLL version this session is connected to. Return: Version string if session started. None if session not started. """ |
if not self.started():
return None
status, data = self._rest.get_request('objects', 'system1',
['version', 'name'])
return data['version'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, handle):
"""Delete the specified object. Arguments: handle -- Handle of object to delete. """ |
self._check_session()
self._rest.delete_request('objects', str(handle)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def config(self, handle, attributes=None, **kwattrs):
"""Sets or modifies one or more object attributes or relations. Arguments can be supplied either as a dicti... |
self._check_session()
if kwattrs:
if attributes:
attributes.update(kwattrs)
else:
attributes = kwattrs
self._rest.put_request('objects', str(handle), attributes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chassis(self):
"""Get list of chassis known to test session.""" |
self._check_session()
status, data = self._rest.get_request('chassis')
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chassis_info(self, chassis):
"""Get information about the specified chassis.""" |
if not chassis or not isinstance(chassis, str):
raise RuntimeError('missing chassis address')
self._check_session()
status, data = self._rest.get_request('chassis', chassis)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connections(self):
"""Get list of connections.""" |
self._check_session()
status, data = self._rest.get_request('connections')
return data |
<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_connected(self, chassis):
"""Get Boolean connected status of the specified chassis.""" |
self._check_session()
try:
status, data = self._rest.get_request('connections', chassis)
except resthttp.RestHttpError as e:
if int(e) == 404:
# 404 NOT FOUND means the chassis in unknown, so return false.
return False
return bool(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self, chassis_list):
"""Establish connection to one or more chassis. Arguments: chassis_list -- List of chassis (IP addresses or DNS names) Return: L... |
self._check_session()
if not isinstance(chassis_list, (list, tuple, set, dict, frozenset)):
chassis_list = (chassis_list,)
if len(chassis_list) == 1:
status, data = self._rest.put_request(
'connections', chassis_list[0])
data = [data]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disconnect(self, chassis_list):
"""Remove connection with one or more chassis. Arguments: chassis_list -- List of chassis (IP addresses or DNS names) """ |
self._check_session()
if not isinstance(chassis_list, (list, tuple, set, dict, frozenset)):
chassis_list = (chassis_list,)
if len(chassis_list) == 1:
self._rest.delete_request('connections', chassis_list[0])
else:
params = {chassis: True for chassis ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def help(self, subject=None, args=None):
"""Get help information about Automation API. The following values can be specified for the subject: None -- gets an ove... |
if subject:
if subject not in (
'commands', 'create', 'config', 'get', 'delete', 'perform',
'connect', 'connectall', 'disconnect', 'disconnectall',
'apply', 'log', 'help'):
self._check_session()
status, data = self._rest.ge... |
<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(self, level, msg):
"""Write a diagnostic message to a log file or to standard output. Arguments: level -- Severity level of entry. One of: INFO, WARN, ER... |
self._check_session()
level = level.upper()
allowed_levels = ('INFO', 'WARN', 'ERROR', 'FATAL')
if level not in allowed_levels:
raise ValueError('level must be one of: ' +
', '.join(allowed_levels))
self._rest.post_request(
'l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, file_name, save_as=None):
"""Download the specified file from the server. Arguments: file_name -- Name of file resource to save. save_as -- Op... |
self._check_session()
try:
if save_as:
save_as = os.path.normpath(save_as)
save_dir = os.path.dirname(save_as)
if save_dir:
if not os.path.exists(save_dir):
os.makedirs(save_dir)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_all(self, dst_dir=None):
"""Download all available files. Arguments: dst_dir -- Optional destination directory to write files to. If not specified, ... |
saved = {}
save_as = None
for f in self.files():
if dst_dir:
save_as = os.path.join(dst_dir, f.split('/')[-1])
name, bytes = self.download(f, save_as)
saved[name] = bytes
return saved |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload(self, src_file_path, dst_file_name=None):
"""Upload the specified file to the server.""" |
self._check_session()
status, data = self._rest.upload_file(
'files', src_file_path, dst_file_name)
return data |
<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_until_complete(self, timeout=None):
"""Wait until sequencer is finished. This method blocks your application until the sequencer has completed its opera... |
timeout_at = None
if timeout:
timeout_at = time.time() + int(timeout)
sequencer = self.get('system1', 'children-sequencer')
while True:
cur_test_state = self.get(sequencer, 'state')
if 'PAUSE' in cur_test_state or 'IDLE' in cur_test_state:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mock_signal_receiver(signal, wraps=None, **kwargs):
""" Temporarily attaches a receiver to the provided ``signal`` within the scope of the context manager. T... |
if wraps is None:
def wraps(*args, **kwrags):
return None
receiver = mock.Mock(wraps=wraps)
signal.connect(receiver, **kwargs)
yield receiver
signal.disconnect(receiver) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def QuerySetMock(model, *return_value):
""" Get a SharedMock that returns self for most attributes and a new copy of itself for any method that ordinarily genera... |
def make_get(self, model):
def _get(*a, **k):
results = list(self)
if len(results) > 1:
raise model.MultipleObjectsReturned
try:
return results[0]
except IndexError:
raise model.DoesNotExist
return _get... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def csrf_token():
""" Generate a token string from bytes arrays. The token in the session is user specific. """ |
if "_csrf_token" not in session:
session["_csrf_token"] = os.urandom(128)
return hmac.new(app.secret_key, session["_csrf_token"],
digestmod=sha1).hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_csrf_token():
"""Checks that token is correct, aborting if not""" |
if request.method in ("GET",): # not exhaustive list
return
token = request.form.get("csrf_token")
if token is None:
app.logger.warning("Expected CSRF Token: not present")
abort(400)
if not safe_str_cmp(token, csrf_token()):
app.logger.warning("CSRF Token incorrect")
... |
<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_request(cls):
""" Get the HTTPRequest object from thread storage or from a callee by searching each frame in the call stack. """ |
request = cls.get_global('request')
if request:
return request
try:
stack = inspect.stack()
except IndexError:
# in some cases this may return an index error
# (pyc files dont match py files for example)
return
for fram... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_response(sijax_response):
"""Takes a Sijax response object and returns a valid Flask response object.""" |
from types import GeneratorType
if isinstance(sijax_response, GeneratorType):
# Streaming response using a generator (non-JSON response).
# Upon returning a response, Flask would automatically destroy
# the request data and uploaded files - done by `flask.ctx.RequestContext.auto_pop()`... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_callback(self, *args, **kwargs):
"""Executes a callback and returns the proper response. Refer to :meth:`sijax.Sijax.execute_callback` for more detai... |
response = self._sijax.execute_callback(*args, **kwargs)
return _make_response(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 logout(self, request):
"Logs out user and redirects them to Nexus home"
from django.contrib.auth import logout
logout(request)
return HttpResponseRedirect(reverse('nexus:index', current_app=self.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 dashboard(self, request):
"Basic dashboard panel"
# TODO: these should be ajax
module_set = []
for namespace, module in self.get_modules():
home_url = module.get_home_url(request)
if hasattr(module, 'render_on_dashboard'):
# Show by default, 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 submit_row(context):
""" Displays the row of buttons for delete and save. """ |
opts = context['opts']
change = context['change']
is_popup = context['is_popup']
save_as = context['save_as']
return {
'onclick_attrib': (opts.get_ordered_objects() and change
and 'onclick="submitOrderForm();"' or ''),
'show_delete_link': (not is_popup an... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autodiscover(site=None):
""" Auto-discover INSTALLED_APPS nexus.py modules and fail silently when not present. This forces an import on them to register any ... |
# Bail out if autodiscover didn't finish loading from a previous call so
# that we avoid running autodiscover again when the URLconf is loaded by
# the exception handler to resolve the handler500 view. This prevents an
# admin.py module with errors from re-registering models and raising a
# spurio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getAllNodes(self):
'''
getAllNodes - Get every element
@return TagCollection<AdvancedTag>
'''
ret = TagCollection()
for rootNode in self.getRootNodes():
ret.append(rootNode)
ret += rootNode.getAllChildNodes()
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getElementsByAttr(self, attrName, attrValue, root='root'):
'''
getElementsByAttr - Searches the full tree for elements with a given attribute name and value combination. This is always a full scan.
@param attrName <lowercase str> - A lowercase attribute 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 getElementsCustomFilter(self, filterFunc, root='root'):
'''
getElementsCustomFilter - Scan elements using a provided function
@param filterFunc <function>(node) - A function that takes an AdvancedTag as an argument, and returns True if some arbitrary criteria is met
@re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getFirstElementCustomFilter(self, filterFunc, root='root'):
'''
getFirstElementCustomFilter - Scan elements using a provided function, stop and return the first match.
@see getElementsCustomFilter to match multiple elements
@param filterFunc <function>(node) - A fun... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getHTML(self):
'''
getHTML - Get the full HTML as contained within this tree.
If parsed from a document, this will contain the original whitespacing.
@returns - <str> of html
@see getFormattedHTML
@see getMiniHTML
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getFormattedHTML(self, indent=' '):
'''
getFormattedHTML - Get formatted and xhtml of this document, replacing the original whitespace
with a pretty-printed version
@param indent - space/tab/newline of each level of indent, or integer for how many spaces per level
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getMiniHTML(self):
'''
getMiniHTML - Gets the HTML representation of this document without any pretty formatting
and disregarding original whitespace beyond the functional.
@return <str> - HTML with only functional whitespace present
'''
from .For... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def feed(self, contents):
'''
feed - Feed contents. Use parseStr or parseFile instead.
@param contents - Contents
'''
contents = stripIEConditionals(contents)
try:
HTMLParser.feed(self, contents)
except MultipleRootNodeException:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def parseFile(self, filename):
'''
parseFile - Parses a file and creates the DOM tree and indexes
@param filename <str/file> - A string to a filename or a file object. If file object, it will not be closed, you must close.
'''
self.reset()
if isinstance(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def parseStr(self, html):
'''
parseStr - Parses a string and creates the DOM tree and indexes.
@param html <str> - valid HTML
'''
self.reset()
if isinstance(html, bytes):
self.feed(html.decode(self.encoding))
else:
self.feed(h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def createElementFromHTML(cls, html, encoding='utf-8'):
'''
createElementFromHTML - Creates an element from a string of HTML.
If this could create multiple root-level elements (children are okay),
you must use #createElementsFromHTML which returns a list of element... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def createElementsFromHTML(cls, html, encoding='utf-8'):
'''
createElementsFromHTML - Creates elements from provided html, and returns a list of the root-level elements
children of these root-level nodes are accessable via the usual means.
@param html <str> - Some html d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def handle_starttag(self, tagName, attributeList, isSelfClosing=False):
'''
internal for parsing
'''
newTag = AdvancedHTMLParser.handle_starttag(self, tagName, attributeList, isSelfClosing)
self._indexTag(newTag)
return newTag |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reindex(self, newIndexIDs=None, newIndexNames=None, newIndexClassNames=None, newIndexTagNames=None):
'''
reindex - reindex the tree. Optionally, change what fields are indexed.
@param newIndexIDs <bool/None> - None to leave same, otherwise new value to index IDs
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def disableIndexing(self):
'''
disableIndexing - Disables indexing. Consider using plain AdvancedHTMLParser class.
Maybe useful in some scenarios where you want to parse, add a ton of elements, then index
and do a bunch of searching.
'''
self.indexIDs = 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 addIndexOnAttribute(self, attributeName):
'''
addIndexOnAttribute - Add an index for an arbitrary attribute. This will be used by the getElementsByAttr function.
You should do this prior to parsing, or call reindex. Otherwise it will be blank. "name" and "id" will have no effect.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getElementsByAttr(self, attrName, attrValue, root='root', useIndex=True):
'''
getElementsByAttr - Searches the full tree for elements with a given attribute name and value combination. If you want multiple potential values, see getElementsWithAttrValues
If you want an index on a r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def uniqueTags(tagList):
'''
uniqueTags - Returns the unique tags in tagList.
@param tagList list<AdvancedTag> : A list of tag objects.
'''
ret = []
alreadyAdded = set()
for tag in tagList:
myUid = tag.getUid()
if myUid in alreadyAdded:
contin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def toggleAttributesDOM(isEnabled):
'''
toggleAttributesDOM - Toggle if the old DOM tag.attributes NamedNodeMap model should be used for the .attributes method, versus
a more sane direct dict implementation.
The DOM version is always accessable as AdvancedTag.attributesDOM
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def appendText(self, text):
'''
appendText - append some inner text
'''
# self.text is just raw string of the text
self.text += text
self.isSelfClosing = False # inner text means it can't self close anymo
# self.blocks is either text or tags, in order of appea... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def appendChild(self, child):
'''
appendChild - Append a child to this element.
@param child <AdvancedTag> - Append a child element to this element
'''
# Associate parentNode of #child to this tag
child.parentNode = self
# Associate owner document to ch... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def appendInnerHTML(self, html):
'''
appendInnerHTML - Appends nodes from arbitrary HTML as if doing element.innerHTML += 'someHTML' in javascript.
@param html <str> - Some HTML
NOTE: If associated with a document ( AdvancedHTMLParser ), the html will use the encoding assoc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def removeChild(self, child):
'''
removeChild - Remove a child tag, if present.
@param child <AdvancedTag> - The child to remove
@return - The child [with parentNode cleared] if removed, otherwise None.
NOTE: This removes a tag. If removing a text b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def removeChildren(self, children):
'''
removeChildren - Remove multiple child AdvancedTags.
@see removeChild
@return list<AdvancedTag/None> - A list of all tags removed in same order as passed.
Item is "None" if it was not attached to this node, and thus wa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def firstChild(self):
'''
firstChild - property, Get the first child block, text or tag.
@return <str/AdvancedTag/None> - The first child block, or None if no child blocks
'''
blocks = object.__getattribute__(self, 'blocks')
# First block is empty string for ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def lastChild(self):
'''
lastChild - property, Get the last child block, text or tag
@return <str/AdvancedTag/None> - The last child block, or None if no child blocks
'''
blocks = object.__getattribute__(self, 'blocks')
# First block is empty string for inden... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def nextSibling(self):
'''
nextSibling - Returns the next sibling. This is the child following this node in the parent's list of children.
This could be text or an element. use nextSiblingElement to ensure element
@return <None/str/AdvancedTag> - None if there 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 nextElementSibling(self):
'''
nextElementSibling - Returns the next sibling that is an element.
This is the tag node following this node in the parent's list of children
@return <None/AdvancedTag> - None if there are no children (tag) in the parent after this nod... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def previousElementSibling(self):
'''
previousElementSibling - Returns the previous sibling that is an element.
This is the previous tag node in the parent's list of children
@return <None/AdvancedTag> - None if there are no children (tag... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getBlocksTags(self):
'''
getBlocksTags - Returns a list of tuples referencing the blocks which are direct children of this node, and the block is an AdvancedTag.
The tuples are ( block, blockIdx ) where "blockIdx" is the index of self.blocks wherein the tag resides.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def textContent(self):
'''
textContent - property, gets the text of this node and all inner nodes.
Use .innerText for just this node's text
@return <str> - The text of all nodes at this level or lower
'''
def _collateText(curNode):
'''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getAllChildNodes(self):
'''
getAllChildNodes - Gets all the children, and their children,
and their children, and so on, all the way to the end as a TagCollection.
Use .childNodes for a regular list
@return TagCollection<AdvancedTag> - ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getAllChildNodeUids(self):
'''
getAllChildNodeUids - Returns all the unique internal IDs for all children, and there children,
so on and so forth until the end.
For performing "contains node" kind of logic, this is more efficent than copying the entire nodeset
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getAllNodeUids(self):
'''
getAllNodeUids - Returns all the unique internal IDs from getAllChildNodeUids, but also includes this tag's uid
@return set<uuid.UUID> A set of uuid objects
'''
# Start with a set including this tag's uuid
ret = { self.uid }
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getPeers(self):
'''
getPeers - Get elements who share a parent with this element
@return - TagCollection of elements
'''
parentNode = self.parentNode
# If no parent, no peers
if not parentNode:
return None
peers = parentNode.child... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getStartTag(self):
'''
getStartTag - Returns the start tag represented as HTML
@return - String of start tag with attributes
'''
attributeStrings = []
# Get all attributes as a tuple (name<str>, value<str>)
for name, val in self._attributes.items():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getEndTag(self):
'''
getEndTag - returns the end tag representation as HTML string
@return - String of end tag
'''
# If this is a self-closing tag, we have no end tag (opens and closes in the start)
if self.isSelfClosing is True:
return ''
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.