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 index(self, *index):
""" Set the index for the search. If called empty it will remove all information. Example: s = Search() s = s.index('twitter-2015.01.01'... |
# .index() resets
s = self._clone()
if not index:
s._index = None
else:
indexes = []
for i in index:
if isinstance(i, string_types):
indexes.append(i)
elif isinstance(i, list):
in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def doc_type(self, *doc_type, **kwargs):
""" Set the type to search through. You can supply a single value or multiple. Values can be strings or subclasses of ``... |
# .doc_type() resets
s = self._clone()
if not doc_type and not kwargs:
s._doc_type = []
s._doc_type_map = {}
else:
s._doc_type.extend(doc_type)
s._doc_type.extend(kwargs.keys())
s._doc_type_map.update(kwargs)
return 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 using(self, client):
""" Associate the search request with an elasticsearch client. A fresh copy will be returned with current instance remaining unchanged. ... |
s = self._clone()
s._using = client
return 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 extra(self, **kwargs):
""" Add extra keys to the request body. Mostly here for backwards compatibility. """ |
s = self._clone()
if 'from_' in kwargs:
kwargs['from'] = kwargs.pop('from_')
s._extra.update(kwargs)
return 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 source(self, fields=None, **kwargs):
""" Selectively control how the _source field is returned. :arg fields: wildcard string, array of wildcards, or dictiona... |
s = self._clone()
if fields and kwargs:
raise ValueError("You cannot specify fields and kwargs at the same time.")
if fields is not None:
s._source = fields
return s
if kwargs and not isinstance(s._source, dict):
s._source = {}
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def suggest(self, name, text, **kwargs):
""" Add a suggestions request to the search. :arg name: name of the suggestion :arg text: text to suggest on All keyword... |
s = self._clone()
s._suggest[name] = {'text': text}
s._suggest[name].update(kwargs)
return 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 to_dict(self, count=False, **kwargs):
""" Serialize the search into the dictionary that will be sent over as the request's body. :arg count: a flag to specif... |
d = {}
if self.query:
d["query"] = self.query.to_dict()
# count request doesn't care for sorting and other things
if not count:
if self.post_filter:
d['post_filter'] = self.post_filter.to_dict()
if self.aggs.aggs:
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 count(self):
""" Return the number of hits matching the query and filters. Note that only the actual number is returned. """ |
if hasattr(self, '_response'):
return self._response.hits.total
es = connections.get_connection(self._using)
d = self.to_dict(count=True)
# TODO: failed shards detection
return es.count(
index=self._index,
body=d,
**self._params
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scan(self):
""" Turn the search into a scan search and return a generator that will iterate over all the documents matching the query. Use ``params`` method ... |
es = connections.get_connection(self._using)
for hit in scan(
es,
query=self.to_dict(),
index=self._index,
**self._params
):
yield self._get_result(hit) |
<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(self, ignore_cache=False, raise_on_error=True):
""" Execute the multi search request and return a list of search results. """ |
if ignore_cache or not hasattr(self, '_response'):
es = connections.get_connection(self._using)
responses = es.msearch(
index=self._index,
body=self.to_dict(),
**self._params
)
out = []
for s, r in zip... |
<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_kexgss_continue(self, m):
""" Parse the SSH2_MSG_KEXGSS_CONTINUE message. :param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE message """ |
if not self.transport.server_mode:
srv_token = m.get_string()
m = Message()
m.add_byte(c_MSG_KEXGSS_CONTINUE)
m.add_string(
self.kexgss.ssh_init_sec_context(
target=self.gss_host, recv_token=srv_token
)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _data_in_prefetch_buffers(self, offset):
""" if a block of data is present in the prefetch buffers, at the given offset, return the offset of the relevant pr... |
k = [i for i in self._prefetch_data.keys() if i <= offset]
if len(k) == 0:
return None
index = max(k)
buf_offset = offset - index
if buf_offset >= len(self._prefetch_data[index]):
# it's not here
return None
return index |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def seek(self, offset, whence=0):
""" Set the file's current position. See `file.seek` for details. """ |
self.flush()
if whence == self.SEEK_SET:
self._realpos = self._pos = offset
elif whence == self.SEEK_CUR:
self._pos += offset
self._realpos = self._pos
else:
self._realpos = self._pos = self._get_size() + offset
self._rbuffer = byt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stat(self):
""" Retrieve information about this file from the remote system. This is exactly like `.SFTPClient.stat`, except that it operates on an already-o... |
t, msg = self.sftp._request(CMD_FSTAT, self.handle)
if t != CMD_ATTRS:
raise SFTPError("Expected attributes")
return SFTPAttributes._from_msg(msg) |
<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, hash_algorithm, offset=0, length=0, block_size=0):
""" Ask the server for a hash of a section of this file. This can be used to verify a successf... |
t, msg = self.sftp._request(
CMD_EXTENDED,
"check-file",
self.handle,
hash_algorithm,
long(offset),
long(length),
block_size,
)
msg.get_text() # ext
msg.get_text() # alg
data = msg.get_remainde... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prefetch(self, file_size=None):
""" Pre-fetch the remaining contents of this file in anticipation of future `.read` calls. If reading the entire file, pre-fe... |
if file_size is None:
file_size = self.stat().st_size
# queue up async reads for the rest of the file
chunks = []
n = self._realpos
while n < file_size:
chunk = min(self.MAX_REQUEST_SIZE, file_size - n)
chunks.append((n, chunk))
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 _check_exception(self):
"""if there's a saved exception, raise & clear it""" |
if self._saved_exception is not None:
x = self._saved_exception
self._saved_exception = None
raise x |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_only(func):
""" Decorator for `.Channel` methods which performs an openness check. :raises: `.SSHException` -- If the wrapped method is called on an uno... |
@wraps(func)
def _check(self, *args, **kwds):
if (
self.closed
or self.eof_received
or self.eof_sent
or not self.active
):
raise SSHException("Channel is not open")
return func(self, *args, **kwds)
return _check |
<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_command(self, command):
""" Execute a command on the server. If the server allows it, the channel will then be directly connected to the stdin, stdout, ... |
m = Message()
m.add_byte(cMSG_CHANNEL_REQUEST)
m.add_int(self.remote_chanid)
m.add_string("exec")
m.add_boolean(True)
m.add_string(command)
self._event_pending()
self.transport._send_user_message(m)
self._wait_for_event() |
<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_environment(self, environment):
""" Updates this channel's remote shell environment. .. note:: This operation is additive - i.e. the current environme... |
for name, value in environment.items():
try:
self.set_environment_variable(name, value)
except SSHException as e:
err = 'Failed to set environment variable "{}".'
raise SSHException(err.format(name), e) |
<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_environment_variable(self, name, value):
""" Set the value of an environment variable. .. warning:: The server may reject this request depending on its `... |
m = Message()
m.add_byte(cMSG_CHANNEL_REQUEST)
m.add_int(self.remote_chanid)
m.add_string("env")
m.add_boolean(False)
m.add_string(name)
m.add_string(value)
self.transport._send_user_message(m) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recv_exit_status(self):
""" Return the exit status from the process on the server. This is mostly useful for retrieving the results of an `exec_command`. If ... |
self.status_event.wait()
assert self.status_event.is_set()
return self.exit_status |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request_x11( self, screen_number=0, auth_protocol=None, auth_cookie=None, single_connection=False, handler=None, ):
""" Request an x11 session on this channe... |
if auth_protocol is None:
auth_protocol = "MIT-MAGIC-COOKIE-1"
if auth_cookie is None:
auth_cookie = binascii.hexlify(os.urandom(16))
m = Message()
m.add_byte(cMSG_CHANNEL_REQUEST)
m.add_int(self.remote_chanid)
m.add_string("x11-req")
m.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 set_combine_stderr(self, combine):
""" Set whether stderr should be combined into stdout on this channel. The default is ``False``, but in some cases it may ... |
data = bytes()
self.lock.acquire()
try:
old = self.combine_stderr
self.combine_stderr = combine
if combine and not old:
# copy old stderr buffer into primary buffer
data = self.in_stderr_buffer.empty()
finally:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sendall(self, s):
""" Send data to the channel, without allowing partial results. Unlike `send`, this method continues to send data from the given string unt... |
while s:
sent = self.send(s)
s = s[sent:]
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 sendall_stderr(self, s):
""" Send data to the channel's "stderr" stream, without allowing partial results. Unlike `send_stderr`, this method continues to sen... |
while s:
sent = self.send_stderr(s)
s = s[sent:]
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 fileno(self):
""" Returns an OS-level file descriptor which can be used for polling, but but not for reading or writing. This is primarily to allow Python's ... |
self.lock.acquire()
try:
if self._pipe is not None:
return self._pipe.fileno()
# create the pipe and feed in any existing data
self._pipe = pipe.make_pipe()
p1, p2 = pipe.make_or_pipe(self._pipe)
self.in_buffer.set_event(p1)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shutdown(self, how):
""" Shut down one or both halves of the connection. If ``how`` is 0, further receives are disallowed. If ``how`` is 1, further sends are... |
if (how == 0) or (how == 2):
# feign "read" shutdown
self.eof_received = 1
if (how == 1) or (how == 2):
self.lock.acquire()
try:
m = self._send_eof()
finally:
self.lock.release()
if m is not 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 read_ready(self):
""" Returns true if data is buffered and ready to be read from this feeder. A ``False`` result does not mean that the feeder has closed; it... |
self._lock.acquire()
try:
if len(self._buffer) == 0:
return False
return True
finally:
self._lock.release() |
<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(self, nbytes, timeout=None):
""" Read data from the pipe. The return value is a string representing the data received. The maximum amount of data to be ... |
out = bytes()
self._lock.acquire()
try:
if len(self._buffer) == 0:
if self._closed:
return out
# should we block?
if timeout == 0.0:
raise PipeTimeout()
# loop here in case we 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 empty(self):
""" Clear out the buffer and return all data that was in it. :return: any data that was in the buffer prior to clearing it out, as a `str` """ |
self._lock.acquire()
try:
out = self._buffer_tobytes()
del self._buffer[:]
if (self._event is not None) and not self._closed:
self._event.clear()
return out
finally:
self._lock.release() |
<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(self):
""" Close this pipe object. Future calls to `read` after the buffer has been emptied will return immediately with an empty string. """ |
self._lock.acquire()
try:
self._closed = True
self._cv.notifyAll()
if self._event is not None:
self._event.set()
finally:
self._lock.release() |
<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(self, host):
""" Return a list of host_names from host value. """ |
try:
return shlex.split(host)
except ValueError:
raise Exception("Unparsable host {}".format(host)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_bool(self, key):
""" Express given key's value as a boolean type. Typically, this is used for ``ssh_config``'s pseudo-boolean values which are either ``"y... |
val = self[key]
if isinstance(val, bool):
return val
return val.lower() == "yes" |
<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_auth_gssapi_with_mic( self, username, gss_authenticated=AUTH_FAILED, cc_file=None ):
""" Authenticate the given user to the server if he is a valid krb... |
if gss_authenticated == AUTH_SUCCESSFUL:
return AUTH_SUCCESSFUL
return AUTH_FAILED |
<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_auth_gssapi_keyex( self, username, gss_authenticated=AUTH_FAILED, cc_file=None ):
""" Authenticate the given user to the server if he is a valid krb5 p... |
if gss_authenticated == AUTH_SUCCESSFUL:
return AUTH_SUCCESSFUL
return AUTH_FAILED |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ssh_gss_oids(self, mode="client"):
""" This method returns a single OID, because we only support the Kerberos V5 mechanism. :param str mode: Client for clien... |
from pyasn1.type.univ import ObjectIdentifier
from pyasn1.codec.der import encoder
OIDs = self._make_uint32(1)
krb5_OID = encoder.encode(ObjectIdentifier(self._krb5_mech))
OID_len = self._make_uint32(len(krb5_OID))
if mode == "server":
return OID_len + krb5_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ssh_build_mic(self, session_id, username, service, auth_method):
""" Create the SSH2 MIC filed for gssapi-with-mic. :param str session_id: The SSH session I... |
mic = self._make_uint32(len(session_id))
mic += session_id
mic += struct.pack("B", MSG_USERAUTH_REQUEST)
mic += self._make_uint32(len(username))
mic += username.encode()
mic += self._make_uint32(len(service))
mic += service.encode()
mic += self._make_uint... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ssh_init_sec_context( self, target, desired_mech=None, username=None, recv_token=None ):
""" Initialize a GSS-API context. :param str username: The name of t... |
from pyasn1.codec.der import decoder
self._username = username
self._gss_host = target
targ_name = gssapi.Name(
"host@" + self._gss_host, gssapi.C_NT_HOSTBASED_SERVICE
)
ctx = gssapi.Context()
ctx.flags = self._gss_flags
if desired_mech is No... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ssh_init_sec_context( self, target, desired_mech=None, username=None, recv_token=None ):
""" Initialize a SSPI context. :param str username: The name of the ... |
from pyasn1.codec.der import decoder
self._username = username
self._gss_host = target
error = 0
targ_name = "host/" + self._gss_host
if desired_mech is not None:
mech, __ = decoder.decode(desired_mech)
if mech.__str__() != self._krb5_mech:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ssh_get_mic(self, session_id, gss_kex=False):
""" Create the MIC token for a SSH2 message. :param str session_id: The SSH session ID :param bool gss_kex: Gen... |
self._session_id = session_id
if not gss_kex:
mic_field = self._ssh_build_mic(
self._session_id,
self._username,
self._service,
self._auth_method,
)
mic_token = self._gss_ctxt.sign(mic_field)
els... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ssh_check_mic(self, mic_token, session_id, username=None):
""" Verify the MIC token for a SSH2 message. :param str mic_token: The MIC token received from the... |
self._session_id = session_id
self._username = username
if username is not None:
# server mode
mic_field = self._ssh_build_mic(
self._session_id,
self._username,
self._service,
self._auth_method,
... |
<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_transport(cls, t, window_size=None, max_packet_size=None):
""" Create an SFTP client channel from an open `.Transport`. Setting the window and packet si... |
chan = t.open_session(
window_size=window_size, max_packet_size=max_packet_size
)
if chan is None:
return None
chan.invoke_subsystem("sftp")
return cls(chan) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def listdir_iter(self, path=".", read_aheads=50):
""" Generator version of `.listdir_attr`. See the API docs for `.listdir_attr` for overall details. This functi... |
path = self._adjust_cwd(path)
self._log(DEBUG, "listdir({!r})".format(path))
t, msg = self._request(CMD_OPENDIR, path)
if t != CMD_HANDLE:
raise SFTPError("Expected handle")
handle = msg.get_string()
nums = list()
while True:
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rename(self, oldpath, newpath):
""" Rename a file or folder from ``oldpath`` to ``newpath``. .. note:: This method implements 'standard' SFTP ``RENAME`` beha... |
oldpath = self._adjust_cwd(oldpath)
newpath = self._adjust_cwd(newpath)
self._log(DEBUG, "rename({!r}, {!r})".format(oldpath, newpath))
self._request(CMD_RENAME, oldpath, newpath) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def posix_rename(self, oldpath, newpath):
""" Rename a file or folder from ``oldpath`` to ``newpath``, following posix conventions. :param str oldpath: existing ... |
oldpath = self._adjust_cwd(oldpath)
newpath = self._adjust_cwd(newpath)
self._log(DEBUG, "posix_rename({!r}, {!r})".format(oldpath, newpath))
self._request(
CMD_EXTENDED, "posix-rename@openssh.com", oldpath, newpath
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def symlink(self, source, dest):
""" Create a symbolic link to the ``source`` path at ``destination``. :param str source: path of the original file :param str de... |
dest = self._adjust_cwd(dest)
self._log(DEBUG, "symlink({!r}, {!r})".format(source, dest))
source = b(source)
self._request(CMD_SYMLINK, source, dest) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def truncate(self, path, size):
""" Change the size of the file specified by ``path``. This usually extends or shrinks the size of the file, just like the `~file... |
path = self._adjust_cwd(path)
self._log(DEBUG, "truncate({!r}, {!r})".format(path, size))
attr = SFTPAttributes()
attr.st_size = size
self._request(CMD_SETSTAT, path, attr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _convert_status(self, msg):
""" Raises EOFError or IOError on error status; otherwise does nothing. """ |
code = msg.get_int()
text = msg.get_text()
if code == SFTP_OK:
return
elif code == SFTP_EOF:
raise EOFError(text)
elif code == SFTP_NO_SUCH_FILE:
# clever idea from john a. meinel: map the error codes to errno
raise IOError(errno.E... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def guard(ctx, opts=""):
""" Execute all tests and then watch for changes, re-running. """ |
# TODO if coverage was run via pytest-cov, we could add coverage here too
return test(ctx, include_slow=True, loop_on_fail=True, opts=opts) |
<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(ctx, sdist=True, wheel=True, sign=True, dry_run=False, index=None):
""" Wraps invocations.packaging.publish to add baked-in docs folder. """ |
# Build docs first. Use terribad workaround pending invoke #146
ctx.run("inv docs", pty=True, hide=False)
# Move the built docs into where Epydocs used to live
target = "docs"
rmtree(target, ignore_errors=True)
# TODO: make it easier to yank out this config val from the docs coll
copytree("... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_client(self, event=None, timeout=None):
""" Negotiate a new SSH2 session as a client. This is the first step after creating a new `.Transport`. A separ... |
self.active = True
if event is not None:
# async, return immediately and let the app poll for completion
self.completion_event = event
self.start()
return
# synchronous, wait for a result
self.completion_event = event = threading.Event()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_session( self, window_size=None, max_packet_size=None, timeout=None ):
""" Request a new channel to the server, of type ``"session"``. This is just an a... |
return self.open_channel(
"session",
window_size=window_size,
max_packet_size=max_packet_size,
timeout=timeout,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cancel_port_forward(self, address, port):
""" Ask the server to cancel a previous port-forwarding request. No more connections to the given address & port wi... |
if not self.active:
return
self._tcp_handler = None
self.global_request("cancel-tcpip-forward", (address, port), wait=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 accept(self, timeout=None):
""" Return the next channel opened by the client over this transport, in server mode. If no channel is opened before the given ti... |
self.lock.acquire()
try:
if len(self.server_accepts) > 0:
chan = self.server_accepts.pop(0)
else:
self.server_accept_cv.wait(timeout)
if len(self.server_accepts) > 0:
chan = self.server_accepts.pop(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 connect( self, hostkey=None, username="", password=None, pkey=None, gss_host=None, gss_auth=False, gss_kex=False, gss_deleg_creds=True, gss_trust_dns=True, ):... |
if hostkey is not None:
self._preferred_keys = [hostkey.get_name()]
self.set_gss_host(
gss_host=gss_host,
trust_dns=gss_trust_dns,
gssapi_requested=gss_kex or gss_auth,
)
self.start_client()
# check host key if we were given 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 auth_password(self, username, password, event=None, fallback=True):
""" Authenticate to the server using a password. The username and password are sent over ... |
if (not self.active) or (not self.initial_kex_done):
# we should never try to send the password unless we're on a secure
# link
raise SSHException("No existing session")
if event is None:
my_event = threading.Event()
else:
my_event = e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auth_publickey(self, username, key, event=None):
""" Authenticate to the server using a private key. The key is used to sign data from the server, so it must... |
if (not self.active) or (not self.initial_kex_done):
# we should never try to authenticate unless we're on a secure link
raise SSHException("No existing session")
if event is None:
my_event = threading.Event()
else:
my_event = event
self.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 auth_interactive(self, username, handler, submethods=""):
""" Authenticate to the server interactively. A handler is used to answer arbitrary questions from ... |
if (not self.active) or (not self.initial_kex_done):
# we should never try to authenticate unless we're on a secure link
raise SSHException("No existing session")
my_event = threading.Event()
self.auth_handler = AuthHandler(self)
self.auth_handler.auth_interactiv... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _next_channel(self):
"""you are holding the lock""" |
chanid = self._channel_counter
while self._channels.get(chanid) is not None:
self._channel_counter = (self._channel_counter + 1) & 0xffffff
chanid = self._channel_counter
self._channel_counter = (self._channel_counter + 1) & 0xffffff
return chanid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ensure_authed(self, ptype, message):
""" Checks message type against current auth state. If server mode, and auth has not succeeded, and the message is of a... |
if (
not self.server_mode
or ptype <= HIGHEST_USERAUTH_MESSAGE_ID
or self.is_authenticated()
):
return None
# WELP. We must be dealing with someone trying to do non-auth things
# without being authed. Tell them off, based on message class.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _activate_outbound(self):
"""switch on newly negotiated encryption parameters for outbound traffic""" |
m = Message()
m.add_byte(cMSG_NEWKEYS)
self._send_message(m)
block_size = self._cipher_info[self.local_cipher]["block-size"]
if self.server_mode:
IV_out = self._compute_key("B", block_size)
key_out = self._compute_key(
"D", self._cipher_in... |
<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):
""" Find a hostkey entry for a given hostname or IP. If no entry is found, ``None`` is returned. Otherwise a dictionary of keytype to... |
class SubDict(MutableMapping):
def __init__(self, hostname, entries, hostkeys):
self._hostname = hostname
self._entries = entries
self._hostkeys = hostkeys
def __iter__(self):
for k in self.keys():
yie... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _hostname_matches(self, hostname, entry):
""" Tests whether ``hostname`` string matches given SubDict ``entry``. :returns bool: """ |
for h in entry.hostnames:
if (
h == hostname
or h.startswith("|1|")
and not hostname.startswith("|1|")
and constant_time_bytes_eq(self.hash_host(hostname, h), h)
):
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 _query_pageant(msg):
""" Communication with the Pageant process is done through a shared memory-mapped file. """ |
hwnd = _get_pageant_window_object()
if not hwnd:
# Raise a failure to connect exception, pageant isn't running anymore!
return None
# create a name for the mmap
map_name = "PageantRequest%08x" % thread.get_ident()
pymap = _winapi.MemoryMap(
map_name, _AGENT_MAX_MSGLEN, _wi... |
<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_so_far(self):
""" Returns the `str` bytes of this message that have been parsed and returned. The string passed into a message's constructor can be regen... |
position = self.packet.tell()
self.rewind()
return self.packet.read(position) |
<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_boolean(self, b):
""" Add a boolean value to the stream. :param bool b: boolean value to add """ |
if b:
self.packet.write(one_byte)
else:
self.packet.write(zero_byte)
return 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 add_int64(self, n):
""" Add a 64-bit int to the stream. :param long n: long int to add """ |
self.packet.write(struct.pack(">Q", n))
return 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 generate(cls, curve=ec.SECP256R1(), progress_func=None, bits=None):
""" Generate a new private ECDSA key. This factory function can be used to generate a new... |
if bits is not None:
curve = cls._ECDSA_CURVES.get_by_key_length(bits)
if curve is None:
raise ValueError("Unsupported key length: {:d}".format(bits))
curve = curve.curve_class()
private_key = ec.generate_private_key(curve, backend=default_backend())... |
<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_type_and_load_cert(self, msg, key_type, cert_type):
""" Perform message type-checking & optional certificate loading. This includes fast-forwarding ce... |
# Normalization; most classes have a single key type and give a string,
# but eg ECDSA is a 1:N mapping.
key_types = key_type
cert_types = cert_type
if isinstance(key_type, string_types):
key_types = [key_types]
if isinstance(cert_types, string_types):
... |
<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(cls, filename):
""" Create a public blob from a ``-cert.pub``-style file on disk. """ |
with open(filename) as f:
string = f.read()
return cls.from_string(string) |
<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_string(cls, string):
""" Create a public blob from a ``-cert.pub``-style string. """ |
fields = string.split(None, 2)
if len(fields) < 2:
msg = "Not enough fields for public blob: {}"
raise ValueError(msg.format(fields))
key_type = fields[0]
key_blob = decodebytes(b(fields[1]))
try:
comment = fields[2].strip()
except Ind... |
<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_message(cls, message):
""" Create a public blob from a network `.Message`. Specifically, a cert-bearing pubkey auth packet, because by definition OpenSS... |
type_ = message.get_text()
return cls(type_=type_, blob=message.asbytes()) |
<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_or_pipe(pipe):
""" wraps a pipe into two pipe-like objects which are "or"d together to affect the real pipe. if either returned pipe is set, the wrapped... |
p1 = OrPipe(pipe)
p2 = OrPipe(pipe)
p1._partner = p2
p2._partner = p1
return p1, p2 |
<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_connection(self):
""" Return a pair of socket object and string address. May block! """ |
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
conn.bind(self._agent._get_filename())
conn.listen(1)
(r, addr) = conn.accept()
return r, addr
except:
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 close(self):
""" Close the current connection and terminate the agent Should be called manually """ |
if hasattr(self, "thread"):
self.thread._exit = True
self.thread.join(1000)
if self._conn is not None:
self._conn.close() |
<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(self):
""" Terminate the agent, clean the files, close connections Should be called manually """ |
os.remove(self._file)
os.rmdir(self._dir)
self.thread._exit = True
self.thread.join(1000)
self._close() |
<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_outbound_cipher( self, block_engine, block_size, mac_engine, mac_size, mac_key, sdctr=False, ):
""" Switch outbound data cipher. """ |
self.__block_engine_out = block_engine
self.__sdctr_out = sdctr
self.__block_size_out = block_size
self.__mac_engine_out = mac_engine
self.__mac_size_out = mac_size
self.__mac_key_out = mac_key
self.__sent_bytes = 0
self.__sent_packets = 0
# 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 set_inbound_cipher( self, block_engine, block_size, mac_engine, mac_size, mac_key ):
""" Switch inbound data cipher. """ |
self.__block_engine_in = block_engine
self.__block_size_in = block_size
self.__mac_engine_in = mac_engine
self.__mac_size_in = mac_size
self.__mac_key_in = mac_key
self.__received_bytes = 0
self.__received_packets = 0
self.__received_bytes_overflow = 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 start_handshake(self, timeout):
""" Tells `Packetizer` that the handshake process started. Starts a book keeping timer that can signal a timeout in the hands... |
if not self.__timer:
self.__timer = threading.Timer(float(timeout), self.read_timer)
self.__timer.start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handshake_timed_out(self):
""" Checks if the handshake has timed out. If `start_handshake` wasn't called before the call to this function, the return value w... |
if not self.__timer:
return False
if self.__handshake_complete:
return False
return self.__timer_expired |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def complete_handshake(self):
""" Tells `Packetizer` that the handshake has completed. """ |
if self.__timer:
self.__timer.cancel()
self.__timer_expired = False
self.__handshake_complete = 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 _get_next_files(self):
""" Used by the SFTP server code to retrieve a cached directory listing. """ |
fnlist = self.__files[:16]
self.__files = self.__files[16:]
return fnlist |
<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(self, content):
""" Write the content received from the SSH client to the standard input of the forked command. :param str content: string to be sent to... |
try:
self.process.stdin.write(content)
except IOError as e:
# There was a problem with the child process. It probably
# died and we can't proceed. The best option here is to
# raise an exception informing the user that the informed
# ProxyComm... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetTokenInformation(token, information_class):
""" Given a token, get the token information for it. """ |
data_size = ctypes.wintypes.DWORD()
ctypes.windll.advapi32.GetTokenInformation(
token, information_class.num, 0, 0, ctypes.byref(data_size)
)
data = ctypes.create_string_buffer(data_size.value)
handle_nonzero_success(
ctypes.windll.advapi32.GetTokenInformation(
token,
... |
<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_current_user():
""" Return a TOKEN_USER for the owner of this process. """ |
process = OpenProcessToken(
ctypes.windll.kernel32.GetCurrentProcess(), TokenAccess.TOKEN_QUERY
)
return GetTokenInformation(process, TOKEN_USER) |
<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_missing_host_key_policy(self, policy):
""" Set policy to use when connecting to servers without a known host key. Specifically: * A **policy** is a "poli... |
if inspect.isclass(policy):
policy = policy()
self._policy = policy |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _families_and_addresses(self, hostname, port):
""" Yield pairs of address families and addresses to try for connecting. :param str hostname: the server to co... |
guess = True
addrinfos = socket.getaddrinfo(
hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM
)
for (family, socktype, proto, canonname, sockaddr) in addrinfos:
if socktype == socket.SOCK_STREAM:
yield family, sockaddr
guess = ... |
<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(self):
""" Close this SSHClient and its underlying `.Transport`. .. warning:: Failure to do this may, in some situations, cause your Python interpreter... |
if self._transport is None:
return
self._transport.close()
self._transport = None
if self._agent is not None:
self._agent.close()
self._agent = 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 exec_command( self, command, bufsize=-1, timeout=None, get_pty=False, environment=None, ):
""" Execute a command on the SSH server. A new `.Channel` is opene... |
chan = self._transport.open_session(timeout=timeout)
if get_pty:
chan.get_pty()
chan.settimeout(timeout)
if environment:
chan.update_environment(environment)
chan.exec_command(command)
stdin = chan.makefile("wb", bufsize)
stdout = chan.mak... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def invoke_shell( self, term="vt100", width=80, height=24, width_pixels=0, height_pixels=0, environment=None, ):
""" Start an interactive shell session on the SS... |
chan = self._transport.open_session()
chan.get_pty(term, width, height, width_pixels, height_pixels)
chan.invoke_shell()
return chan |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def language(self, language):
"""Sets the language of this KernelPushRequest. The language that the kernel is written in # noqa: E501 :param language: The langua... |
if language is None:
raise ValueError("Invalid value for `language`, must not be `None`") # noqa: E501
allowed_values = ["python", "r", "rmarkdown"] # noqa: E501
if language not in allowed_values:
raise ValueError(
"Invalid value for `language` ({0}), m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kernel_type(self, kernel_type):
"""Sets the kernel_type of this KernelPushRequest. The type of kernel. Cannot be changed once the kernel has been created # n... |
if kernel_type is None:
raise ValueError("Invalid value for `kernel_type`, must not be `None`") # noqa: E501
allowed_values = ["script", "notebook"] # noqa: E501
if kernel_type not in allowed_values:
raise ValueError(
"Invalid value for `kernel_type` ({... |
<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_config_environment(self, config_data=None, quiet=False):
"""read_config_environment is the second effort to get a username and key to authenticate to th... |
# Add all variables that start with KAGGLE_ to config data
if config_data is None:
config_data = {}
for key, val in os.environ.items():
if key.startswith('KAGGLE_'):
config_key = key.replace('KAGGLE_', '', 1).lower()
config_data[config_k... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_config(self, config_data):
"""the final step of the authenticate steps, where we load the values from config_data into the Configuration object. Parame... |
# Username and password are required.
for item in [self.CONFIG_NAME_USER, self.CONFIG_NAME_KEY]:
if item not in config_data:
raise ValueError('Error: Missing %s in configuration.' % item)
configuration = Configuration()
# Add to the final configuration (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 read_config_file(self, config_data=None, quiet=False):
"""read_config_file is the first effort to get a username and key to authenticate to the Kaggle API. S... |
if config_data is None:
config_data = {}
if os.path.exists(self.config):
try:
if os.name != 'nt':
permissions = os.stat(self.config).st_mode
if (permissions & 4) or (permissions & 32):
print(
... |
<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_config_file(self):
"""read in the configuration file, a json file defined at self.config""" |
try:
with open(self.config, 'r') as f:
config_data = json.load(f)
except FileNotFoundError:
config_data = {}
return config_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 _write_config_file(self, config_data, indent=2):
"""write config data to file. Parameters ========== config_data: the Configuration object to save a username... |
with open(self.config, 'w') as f:
json.dump(config_data, f, indent=indent) |
<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_default_download_dir(self, *subdirs):
""" Get the download path for a file. If not defined, return default from config. Parameters ========== subdirs: a ... |
# Look up value for key "path" in the config
path = self.get_config_value(self.CONFIG_NAME_PATH)
# If not set in config, default to present working directory
if path is None:
return os.getcwd()
return os.path.join(path, *subdirs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_config_value(self, name, prefix='- ', separator=': '):
"""print a single configuration value, based on a prefix and separator Parameters ========== nam... |
value_out = 'None'
if name in self.config_values and self.config_values[name] is not None:
value_out = self.config_values[name]
print(prefix + name + separator + value_out) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.