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 listdir(directory): """Returns list of nested files and directories for local directory by path :param directory: absolute or relative path to local director...
file_names = list() for filename in os.listdir(directory): file_path = os.path.join(directory, filename) if os.path.isdir(file_path): filename = f'{filename}{os.path.sep}' file_names.append(filename) return file_names
<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_options(option_type, from_options): """Extract options for specified option type from all options :param option_type: the object of specified type of opt...
_options = dict() for key in option_type.keys: key_with_prefix = f'{option_type.prefix}{key}' if key not in from_options and key_with_prefix not in from_options: _options[key] = '' elif key in from_options: _options[key] = from_options.get(key) else: ...
<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_headers(self, action, headers_ext=None): """Returns HTTP headers of specified WebDAV actions. :param action: the identifier of action. :param headers_ext...
if action in Client.http_header: try: headers = Client.http_header[action].copy() except AttributeError: headers = Client.http_header[action][:] else: headers = list() if headers_ext: headers.extend(headers_ext) ...
<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_request(self, action, path, data=None, headers_ext=None): """Generate request to WebDAV server for specified action and path and execute it. :param a...
response = self.session.request( method=Client.requests[action], url=self.get_url(path), auth=self.webdav.auth, headers=self.get_headers(action, headers_ext), timeout=self.timeout, data=data ) if response.status_code == 507...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def valid(self): """Validates of WebDAV and proxy settings. :return: True in case settings are valid and False otherwise. """
return True if self.webdav.valid() and self.proxy.valid() else 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 download_from(self, buff, remote_path): """Downloads file from WebDAV and writes it in buffer. :param buff: buffer object for writing of downloaded file cont...
urn = Urn(remote_path) if self.is_dir(urn.path()): raise OptionNotValid(name='remote_path', value=remote_path) if not self.check(urn.path()): raise RemoteResourceNotFound(urn.path()) response = self.execute_request(action='download', path=urn.quote()) 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 download_directory(self, remote_path, local_path, progress=None): """Downloads directory and downloads all nested files and directories from remote WebDAV to...
urn = Urn(remote_path, directory=True) if not self.is_dir(urn.path()): raise OptionNotValid(name='remote_path', value=remote_path) if os.path.exists(local_path): shutil.rmtree(local_path) os.makedirs(local_path) for resource_name in self.list(urn.path(...
<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_sync(self, remote_path, local_path, callback=None): """Downloads remote resources from WebDAV server synchronously. :param remote_path: the path to ...
self.download(local_path=local_path, remote_path=remote_path) if callback: callback()
<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_async(self, remote_path, local_path, callback=None): """Downloads remote resources from WebDAV server asynchronously :param remote_path: the path to...
target = (lambda: self.download_sync(local_path=local_path, remote_path=remote_path, callback=callback)) threading.Thread(target=target).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 upload_directory(self, remote_path, local_path, progress=None): """Uploads directory to remote path on WebDAV server. In case directory is exist on remote se...
urn = Urn(remote_path, directory=True) if not urn.is_dir(): raise OptionNotValid(name='remote_path', value=remote_path) if not os.path.isdir(local_path): raise OptionNotValid(name='local_path', value=local_path) if not os.path.exists(local_path): ra...
<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_sync(self, remote_path, local_path, callback=None): """Uploads resource to remote path on WebDAV server synchronously. In case resource is directory i...
self.upload(local_path=local_path, remote_path=remote_path) if callback: callback()
<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_async(self, remote_path, local_path, callback=None): """Uploads resource to remote path on WebDAV server asynchronously. In case resource is directory...
target = (lambda: self.upload_sync(local_path=local_path, remote_path=remote_path, callback=callback)) threading.Thread(target=target).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 parse_get_list_response(content): """Parses of response content XML from WebDAV server and extract file and directory names. :param content: the XML content ...
try: tree = etree.fromstring(content) hrees = [Urn.separate + unquote(urlsplit(hree.text).path) for hree in tree.findall('.//{DAV:}href')] return [Urn(hree) for hree in hrees] except etree.XMLSyntaxError: return list()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_free_space_request_content(): """Creates an XML for requesting of free space on remote WebDAV server. :return: the XML string of request content. """
root = etree.Element('propfind', xmlns='DAV:') prop = etree.SubElement(root, 'prop') etree.SubElement(prop, 'quota-available-bytes') etree.SubElement(prop, 'quota-used-bytes') tree = etree.ElementTree(root) return WebDavXmlUtils.etree_to_string(tree)
<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_free_space_response(content, hostname): """Parses of response content XML from WebDAV server and extract an amount of free space. :param content: the X...
try: tree = etree.fromstring(content) node = tree.find('.//{DAV:}quota-available-bytes') if node is not None: return int(node.text) else: raise MethodNotSupported(name='free', server=hostname) except TypeError: ...
<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_get_property_request_content(option): """Creates an XML for requesting of getting a property value of remote WebDAV resource. :param option: the prope...
root = etree.Element('propfind', xmlns='DAV:') prop = etree.SubElement(root, 'prop') etree.SubElement(prop, option.get('name', ''), xmlns=option.get('namespace', '')) tree = etree.ElementTree(root) return WebDavXmlUtils.etree_to_string(tree)
<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_get_property_response(content, name): """Parses of response content XML from WebDAV server for getting metadata property value for some resource. :para...
tree = etree.fromstring(content) return tree.xpath('//*[local-name() = $name]', name=name)[0].text
<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_set_property_batch_request_content(options): """Creates an XML for requesting of setting a property values for remote WebDAV resource in batch. :param...
root_node = etree.Element('propertyupdate', xmlns='DAV:') set_node = etree.SubElement(root_node, 'set') prop_node = etree.SubElement(set_node, 'prop') for option in options: opt_node = etree.SubElement(prop_node, option['name'], xmlns=option.get('namespace', '')) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def etree_to_string(tree): """Creates string from lxml.etree.ElementTree with XML declaration and UTF-8 encoding. :param tree: the instance of ElementTree :retur...
buff = BytesIO() tree.write(buff, xml_declaration=True, encoding='UTF-8') return buff.getvalue()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_response_for_path(content, path, hostname): """Extracts single response for specified remote resource. :param content: raw content of response as str...
try: tree = etree.fromstring(content) responses = tree.findall('{DAV:}response') n_path = Urn.normalize_path(path) for resp in responses: href = resp.findtext('{DAV:}href') if Urn.compare_path(n_path, href) is 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 cleanup(config_dir): """Remove temporary stderr and stdout files as well as the daemon socket."""
stdout_path = os.path.join(config_dir, 'pueue.stdout') stderr_path = os.path.join(config_dir, 'pueue.stderr') if os._exists(stdout_path): os.remove(stdout_path) if os._exists(stderr_path): os.remove(stderr_path) socketPath = os.path.join(config_dir, 'pueue.sock') if os.path.exi...
<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_descriptor_output(descriptor, key, handler=None): """Get the descriptor output and handle incorrect UTF-8 encoding of subprocess logs. In case an process...
line = 'stub' lines = '' while line != '': try: line = descriptor.readline() lines += line except UnicodeDecodeError: error_msg = "Error while decoding output of process {}".format(key) if handler: handler.logger.error("{} with...
<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(self, hash_, quickkey, doc_type, page=None, output=None, size_id=None, metadata=None, request_conversion_only=None): """Query conversion server hash_...
if len(hash_) > 4: hash_ = hash_[:4] query = QueryParams({ 'quickkey': quickkey, 'doc_type': doc_type, 'page': page, 'output': output, 'size_id': size_id, 'metadata': metadata, 'request_conversion_only': 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 bp_commands(self, frame, breakpoint_hits): """Call every command that was set for the current active breakpoints. Returns True if the normal interaction func...
# Handle multiple breakpoints on the same line (issue 14789) effective_bp_list, temporaries = breakpoint_hits silent = True doprompt = False atleast_one_cmd = False for bp in effective_bp_list: if bp in self.commands: if not atleast_one_cmd: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def precmd(self, line): """Handle alias expansion and ';;' separator."""
if not line.strip(): return line args = line.split() while args[0] in self.aliases: line = self.aliases[args[0]] ii = 1 for tmpArg in args[1:]: line = line.replace("%" + str(ii), tmpArg) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onecmd(self, line): """Interpret the argument as though it had been typed in response to the prompt. Checks whether this line is typed at the normal prompt o...
if not self.commands_defining: return cmd.Cmd.onecmd(self, line) else: return self.handle_command_def(line)
<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_command_def(self, line): """Handles one command line during command list definition."""
cmd, arg, line = self.parseline(line) if not cmd: return if cmd == 'silent': self.commands_silent[self.commands_bnum] = True return # continue to handle other cmd def in the cmd list elif cmd == 'end': self.cmdqueue = [] return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def defaultFile(self): """Produce a reasonable default."""
filename = self.curframe.f_code.co_filename if filename == '<string>' and self.mainpyfile: filename = self.mainpyfile return filename
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_retval(self, arg): """retval Print the return value for the last return of a function. """
locals = self.get_locals(self.curframe) if '__return__' in locals: self.message(bdb.safe_repr(locals['__return__'])) else: self.error('Not yet returned!')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_p(self, arg): """p expression Print the value of the expression. """
try: self.message(bdb.safe_repr(self._getval(arg))) except Exception: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_pp(self, arg): """pp expression Pretty-print the value of the expression. """
obj = self._getval(arg) try: repr(obj) except Exception: self.message(bdb.safe_repr(obj)) else: self.message(pprint.pformat(obj))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_longlist(self, arg): """longlist | ll List the whole source code for the current function or frame. """
filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: lines, lineno = getsourcelines(self.curframe, self.get_locals(self.curframe)) except IOError as err: self.error(err) return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_source(self, arg): """source expression Try to get source code for the given object and display it. """
try: obj = self._getval(arg) except Exception: return try: lines, lineno = getsourcelines(obj, self.get_locals(self.curframe)) except (IOError, TypeError) as err: self.error(err) return self._print_lines(lines, lineno)
<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_lines(self, lines, start, breaks=(), frame=None): """Print a range of lines."""
if frame: current_lineno = frame.f_lineno exc_lineno = self.tb_lineno.get(frame, -1) else: current_lineno = exc_lineno = -1 for lineno, line in enumerate(lines, start): s = str(lineno).rjust(3) if len(s) < 4: 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 do_whatis(self, arg): """whatis arg Print the type of the argument. """
try: value = self._getval(arg) except Exception: # _getval() already printed the error return code = None # Is it a function? try: code = value.__code__ except Exception: pass if code: self.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 do_unalias(self, arg): """unalias name Delete the specified alias. """
args = arg.split() if len(args) == 0: return if args[0] in self.aliases: del self.aliases[args[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 read(self, limit=-1): """Read content. See file.read"""
remaining = self.len - self.parent_fd.tell() + self.offset if limit > remaining or limit == -1: limit = remaining return self.parent_fd.read(limit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def seek(self, offset, whence=os.SEEK_SET): """Seek to position in stream, see file.seek"""
pos = None if whence == os.SEEK_SET: pos = self.offset + offset elif whence == os.SEEK_CUR: pos = self.tell() + offset elif whence == os.SEEK_END: pos = self.offset + self.len + offset else: raise ValueError("invalid whence {}".fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Close file, see file.close"""
try: self.parent_fd.fileno() except io.UnsupportedOperation: logger.debug("Not closing parent_fd - reusing existing") else: self.parent_fd.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 _build_query(self, uri, params=None, action_token_type=None): """Prepare query string"""
if params is None: params = QueryParams() params['response_format'] = 'json' session_token = None if action_token_type in self._action_tokens: # Favor action token using_action_token = True session_token = self._action_tokens[action_to...
<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(self, action, params=None, action_token_type=None, upload_info=None, headers=None): """Perform request to MediaFire API action -- "category/name" of ...
uri = self._build_uri(action) if isinstance(params, six.text_type): query = params else: query = self._build_query(uri, params, action_token_type) if headers is None: headers = {} if upload_info is None: # Use request body 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 _regenerate_secret_key(self): """Regenerate secret key http://www.mediafire.com/developers/core_api/1.3/getting_started/#call_signature """
# Don't regenerate the key if we have none if self._session and 'secret_key' in self._session: self._session['secret_key'] = ( int(self._session['secret_key']) * 16807) % 2147483647
<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(self, value): """Set session token value -- dict returned by user/get_session_token"""
# unset session token if value is None: self._session = None return if not isinstance(value, dict): raise ValueError("session info is required") session_parsed = {} for key in ["session_token", "time", "secret_key"]: if key not...
<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_action_token(self, type_=None, action_token=None): """Set action tokens type_ -- either "upload" or "image" action_token -- string obtained from user/get...
if action_token is None: del self._action_tokens[type_] else: self._action_tokens[type_] = action_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 _reset(self): '''Reset all of our stateful variables''' self._socket = None # The pending messages we have to send, and the current buffer we're # sending self._pending = deque() self._out_buffer = '' # Our read buffer self._buffer = '' # The i...
<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, force=False): '''Establish a connection''' # Don't re-establish existing connections if not force and self.alive(): return True self._reset() # Otherwise, try to connect with self._socket_lock: try: logger.info('...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def close(self): '''Close our connection''' # Flush any unsent message try: while self.pending(): self.flush() except socket.error: pass with self._socket_lock: try: if self._socket: self._soc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def socket(self, blocking=True): '''Blockingly yield the socket''' # If the socket is available, then yield it. Otherwise, yield nothing if self._socket_lock.acquire(blocking): try: yield self._socket finally: self._socket_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 identified(self, res): '''Handle a response to our 'identify' command. Returns response''' # If they support it, they should give us a JSON blob which we should # inspect. try: res.data = json.loads(res.data) self._identify_response = res.data logg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def setblocking(self, blocking): '''Set whether or not this message is blocking''' for sock in self.socket(): sock.setblocking(blocking) self._blocking = blocking
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def flush(self): '''Flush some of the waiting messages, returns count written''' # When profiling, we found that while there was some efficiency to be # gained elsewhere, the big performance hit is sending lots of small # messages at a time. In particular, consumers send many 'FIN' messa...
<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, command, message=None): '''Send a command over the socket with length endcoded''' if message: joined = command + constants.NL + util.pack(message) else: joined = command + constants.NL if self._blocking: for sock in self.socket(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def identify(self, data): '''Send an identification message''' return self.send(constants.IDENTIFY, json.dumps(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 pub(self, topic, message): '''Publish to a topic''' return self.send(' '.join((constants.PUB, topic)), message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mpub(self, topic, *messages): '''Publish multiple messages to a topic''' return self.send(constants.MPUB + ' ' + topic, messages)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rdy(self, count): '''Indicate that you're ready to receive''' self.ready = count self.last_ready_sent = count return self.send(constants.RDY + ' ' + str(count))
<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, limit=1000): '''Return all the responses read''' # It's important to know that it may return no responses or multiple # responses. It depends on how the buffering works out. First, read from # the socket for sock in self.socket(): if sock is 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(self): '''Responses from an established socket''' responses = self._read() # Determine the number of messages in here and decrement our ready # count appropriately self.ready -= sum( map(int, (r.frame_type == Message.FRAME_TYPE for r in responses))) 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 discover(self, topic): '''Run the discovery mechanism''' logger.info('Discovering on topic %s', topic) producers = [] for lookupd in self._lookupd: logger.info('Discovering on %s', lookupd) try: # Find all the current producers on this instance...
<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_connections(self): '''Connect to all the appropriate instances''' logger.info('Checking connections') if self._lookupd: self.discover(self._topic) # Make sure we're connected to all the prescribed hosts for hostspec in self._nsqd_tcp_addresses: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def connection_checker(self): '''Run periodic reconnection checks''' thread = ConnectionChecker(self) logger.info('Starting connection-checker thread') thread.start() try: yield thread finally: logger.info('Stopping connection-checker') ...
<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, host, port): '''Connect to the provided host, port''' conn = connection.Connection(host, port, reconnection_backoff=self._reconnection_backoff, auth_secret=self._auth_secret, timeout=self._connect_timeout, **self._identify_options) ...
<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(self, connection): '''Add a connection''' key = (connection.host, connection.port) with self._lock: if key not in self._connections: self._connections[key] = connection self.added(connection) return connection else: ...
<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(self, connection): '''Remove a connection''' key = (connection.host, connection.port) with self._lock: found = self._connections.pop(key, None) try: self.close_connection(found) except Exception as exc: logger.warn('Failed to 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 read(self): '''Read from any of the connections that need it''' # We'll check all living connections connections = [c for c in self.connections() if c.alive()] if not connections: # If there are no connections, obviously we return no messages, but # we should...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def random_connection(self): '''Pick a random living connection''' # While at the moment there's no need for this to be a context manager # per se, I would like to use that interface since I anticipate # adding some wrapping around it at some point. yield random.choice( ...
<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_response(self): '''Wait for a response''' responses = self.read() while not responses: responses = self.read() return responses
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pub(self, topic, message): '''Publish the provided message to the provided topic''' with self.random_connection() as client: client.pub(topic, message) return self.wait_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 mpub(self, topic, *messages): '''Publish messages to a topic''' with self.random_connection() as client: client.mpub(topic, *messages) return self.wait_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 create_socket(self): """Create a socket for the daemon, depending on the directory location. Args: config_dir (str): The absolute path to the config directo...
socket_path = os.path.join(self.config_dir, 'pueue.sock') # Create Socket and exit with 1, if socket can't be created try: if os.path.exists(socket_path): os.remove(socket_path) self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) 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 initialize_directories(self, root_dir): """Create all directories needed for logs and configs."""
if not root_dir: root_dir = os.path.expanduser('~') # Create config directory, if it doesn't exist self.config_dir = os.path.join(root_dir, '.config/pueue') if not os.path.exists(self.config_dir): os.makedirs(self.config_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 respond_client(self, answer, socket): """Send an answer to the client."""
response = pickle.dumps(answer, -1) socket.sendall(response) self.read_list.remove(socket) socket.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 read_config(self): """Read a previous configuration file or create a new with default values."""
config_file = os.path.join(self.config_dir, 'pueue.ini') self.config = configparser.ConfigParser() # Try to get configuration file and return it # If this doesn't work, a new default config file will be created if os.path.exists(config_file): try: sel...
<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(self): """Write the current configuration to the config file."""
config_file = os.path.join(self.config_dir, 'pueue.ini') with open(config_file, 'w') as file_descriptor: self.config.write(file_descriptor)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_daemon(self, payload=None): """Kill current processes and initiate daemon shutdown. The daemon will shut down after a last check on all killed processes...
kill_signal = signals['9'] self.process_handler.kill_all(kill_signal, True) self.running = False return {'message': 'Pueue daemon shutting down', 'status': 'success'}
<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_config(self, payload): """Update the current config depending on the payload and save it."""
self.config['default'][payload['option']] = str(payload['value']) if payload['option'] == 'maxProcesses': self.process_handler.set_max(payload['value']) if payload['option'] == 'customShell': path = payload['value'] if os.path.isfile(path) and os.access(path...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pipe_to_process(self, payload): """Send something to stdin of a specific process."""
message = payload['input'] key = payload['key'] if not self.process_handler.is_running(key): return {'message': 'No running process for this key', 'status': 'error'} self.process_handler.send_to_process(message, key) return {'message': 'Message 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 send_status(self, payload): """Send the daemon status and the current queue for displaying."""
answer = {} data = [] # Get daemon status if self.paused: answer['status'] = 'paused' else: answer['status'] = 'running' # Add current queue or a message, that queue is empty if len(self.queue) > 0: data = deepcopy(self.queue....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_everything(self, payload): """Kill all processes, delete the queue and clean everything up."""
kill_signal = signals['9'] self.process_handler.kill_all(kill_signal, True) self.process_handler.wait_for_finish() self.reset = True answer = {'message': 'Resetting current queue', 'status': 'success'} return answer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self, payload): """Clear queue from any `done` or `failed` entries. The log will be rotated once. Otherwise we would loose all logs from thoes finished...
self.logger.rotate(self.queue) self.queue.clear() self.logger.write(self.queue) answer = {'message': 'Finished entries have been removed.', 'status': 'success'} return answer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_command(self, payload): """Edit the command of a specific entry."""
key = payload['key'] command = payload['command'] if self.queue[key]: if self.queue[key]['status'] in ['queued', 'stashed']: self.queue[key]['command'] = command answer = {'message': 'Command updated', 'status': 'error'} else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stash(self, payload): """Stash the specified processes."""
succeeded = [] failed = [] for key in payload['keys']: if self.queue.get(key) is not None: if self.queue[key]['status'] == 'queued': self.queue[key]['status'] = 'stashed' succeeded.append(str(key)) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kill_process(self, payload): """Pause the daemon and kill all processes or kill a specific process."""
# Kill specific processes, if `keys` is given in the payload kill_signal = signals[payload['signal'].lower()] kill_shell = payload.get('all', False) if payload.get('keys'): succeeded = [] failed = [] for key in payload.get('keys'): suc...
<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(self, payload): """Remove specified entries from the queue."""
succeeded = [] failed = [] for key in payload['keys']: running = self.process_handler.is_running(key) if not running: removed = self.queue.remove(key) if removed: succeeded.append(str(key)) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switch(self, payload): """Switch the two specified entry positions in the queue."""
first = payload['first'] second = payload['second'] running = self.process_handler.is_running(first) or self.process_handler.is_running(second) if running: answer = { 'message': "Can't switch running processes, " "please stop the processes bef...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restart(self, payload): """Restart the specified entries."""
succeeded = [] failed = [] for key in payload['keys']: restarted = self.queue.restart(key) if restarted: succeeded.append(str(key)) else: failed.append(str(key)) message = '' if len(succeeded) > 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 sendall(self, data, flags=0): '''Same as socket.sendall''' count = len(data) while count: sent = self.send(data, flags) # This could probably be a buffer object data = data[sent:] count -= sent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_file_show(client, args): """Output file contents to stdout"""
for src_uri in args.uris: client.download_file(src_uri, sys.stdout.buffer) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pub(self, topic, message): '''Publish a message to a topic''' return self.post('pub', params={'topic': topic}, data=message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mpub(self, topic, messages, binary=True): '''Send multiple messages to a topic. Optionally pack the messages''' if binary: # Pack and ship the data return self.post('mpub', data=pack(messages)[4:], params={'topic': topic, 'binary': True}) elif any('\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 clean_stats(self): '''Stats with topics and channels keyed on topic and channel names''' stats = self.stats() if 'topics' in stats: # pragma: no branch topics = stats['topics'] topics = dict((t.pop('topic_name'), t) for t in topics) for topic, data in top...
<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_add(args, root_dir=None): """Add a new command to the daemon queue. Args: args['command'] (list(str)): The actual programm call. Something like ['ls...
# We accept a list of strings. # This is done to create a better commandline experience with argparse. command = ' '.join(args['command']) # Send new instruction to daemon instruction = { 'command': command, 'path': os.getcwd() } print_command_factory('add')(instruction, 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 execute_edit(args, root_dir=None): """Edit a existing queue command in the daemon. Args: args['key'] int: The key of the queue entry to be edited root_dir (s...
# Get editor EDITOR = os.environ.get('EDITOR', 'vim') # Get command from server key = args['key'] status = command_factory('status')({}, root_dir=root_dir) # Check if queue is not empty, the entry exists and is queued or stashed if not isinstance(status['data'], str) and key in status['dat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_factory(command): """A factory which returns functions for direct daemon communication. This factory will create a function which sends a payload to ...
def communicate(body={}, root_dir=None): """Communicate with the daemon. This function sends a payload to the daemon and returns the unpickled object sent by the daemon. Args: body (dir): Any other arguments that should be put into the payload. root_dir (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 get_descriptor(self, number): """Create file descriptors for process output."""
# Create stdout file and get file descriptor stdout_path = os.path.join(self.config_dir, 'pueue_process_{}.stdout'.format(number)) if os.path.exists(stdout_path): os.remove(stdout_path) out_descriptor = open(stdout_path, 'w+') # Cr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_descriptor(self, number): """Close file descriptor and remove underlying files."""
self.descriptors[number]['stdout'].close() self.descriptors[number]['stderr'].close() if os.path.exists(self.descriptors[number]['stdout_path']): os.remove(self.descriptors[number]['stdout_path']) if os.path.exists(self.descriptors[number]['stderr_path']): os.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 check_finished(self): """Poll all processes and handle any finished processes."""
changed = False for key in list(self.processes.keys()): # Poll process and check if it finshed process = self.processes[key] process.poll() if process.returncode is not None: # If a process is terminated by `stop` or `kill` ...
<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_for_new(self): """Check if we can start a new process."""
free_slots = self.max_processes - len(self.processes) for item in range(free_slots): key = self.queue.next() if key is not None: self.spawn_new(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 spawn_new(self, key): """Spawn a new task and save it to the queue."""
# Check if path exists if not os.path.exists(self.queue[key]['path']): self.queue[key]['status'] = 'failed' error_msg = "The directory for this command doesn't exist anymore: {}".format(self.queue[key]['path']) self.logger.error(error_msg) self.queue[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 kill_all(self, kill_signal, kill_shell=False): """Kill all running processes."""
for key in self.processes.keys(): self.kill_process(key, kill_signal, kill_shell)