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 _unique_names(): """Generates unique sequences of bytes. """
characters = ("abcdefghijklmnopqrstuvwxyz" "0123456789") characters = [characters[i:i + 1] for i in irange(len(characters))] rng = random.Random() while True: letters = [rng.choice(characters) for i in irange(10)] yield ''.join(letters)
<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_ssh_destination(destination): """Parses the SSH destination argument. """
match = _re_ssh.match(destination) if not match: raise InvalidDestination("Invalid destination: %s" % destination) user, password, host, port = match.groups() info = {} if user: info['username'] = user else: info['username'] = getpass.getuser() if password: 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 _ssh_client(self): """Gets an SSH client to connect with. """
ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.RejectPolicy()) return ssh
<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): """Connects via SSH. """
ssh = self._ssh_client() logger.debug("Connecting with %s", ', '.join('%s=%r' % (k, v if k != "password" else "***") for k, v in iteritems(self.destination))) ssh.connect(**self.destination) logger.debug("Connected to %s", self.destina...
<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_client(self): """Gets the SSH client. This will check that the connection is still alive first, and reconnect if necessary. """
if self._ssh is None: self._connect() return self._ssh else: try: chan = self._ssh.get_transport().open_session() except (socket.error, paramiko.SSHException): logger.warning("Lost connection, reconnecting...") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _call(self, cmd, get_output): """Calls a command through the SSH connection. Remote stderr gets printed to this program's stderr. Output is captured and may ...
server_err = self.server_logger() chan = self.get_client().get_transport().open_session() try: logger.debug("Invoking %r%s", cmd, " (stdout)" if get_output else "") chan.exec_command('/bin/sh -c %s' % shell_escape(cmd)) output = 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 check_call(self, cmd): """Calls a command through SSH. """
ret, _ = self._call(cmd, False) if ret != 0: # pragma: no cover raise RemoteCommandFailure(command=cmd, ret=ret)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_output(self, cmd): """Calls a command through SSH and returns its output. """
ret, output = self._call(cmd, True) if ret != 0: # pragma: no cover raise RemoteCommandFailure(command=cmd, ret=ret) logger.debug("Output: %r", output) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resolve_queue(self, queue, depth=0, links=None): """Finds the location of tej's queue directory on the server. The `queue` set when constructing this `Remot...
if depth == 0: logger.debug("resolve_queue(%s)", queue) answer = self.check_output( 'if [ -d %(queue)s ]; then ' ' cd %(queue)s; echo "dir"; cat version; pwd; ' 'elif [ -f %(queue)s ]; then ' ' cat %(queue)s; ' '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_queue(self): """Gets the actual location of the queue, or None. """
if self._queue is None: self._links = [] queue, depth = self._resolve_queue(self.queue, links=self._links) if queue is None and depth > 0: raise QueueLinkBroken self._queue = queue return 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 setup(self, links=None, force=False, only_links=False): """Installs the runtime at the target location. This will not replace an existing installation, unles...
if not links: links = [] if only_links: logger.info("Only creating links") for link in links: self.check_call('echo "tejdir:" %(queue)s > %(link)s' % { 'queue': escape_queue(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 _setup(self): """Actually installs the runtime. """
# Expands ~user in queue if self.queue.path[0:1] == b'/': queue = self.queue else: if self.queue.path[0:1] == b'~': output = self.check_output('echo %s' % escape_queue(self.queue)) queue = PosixPa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def submit(self, job_id, directory, script=None): """Submits a job to the queue. If the runtime is not there, it will be installed. If it is a broken chain of li...
if job_id is None: job_id = '%s_%s_%s' % (Path(directory).unicodename, self.destination['username'], make_unique_name()) else: check_jobid(job_id) queue = self._get_queue() if queue 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 status(self, job_id): """Gets the status of a previously-submitted job. """
check_jobid(job_id) queue = self._get_queue() if queue is None: raise QueueDoesntExist ret, output = self._call('%s %s' % ( shell_escape(queue / 'commands/status'), job_id), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(self, job_id, files, **kwargs): """Downloads files from server. """
check_jobid(job_id) if not files: return if isinstance(files, string_types): files = [files] directory = False recursive = kwargs.pop('recursive', True) if 'destination' in kwargs and 'directory' in kwargs: raise TypeError("Only use ...
<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(self, job_id): """Kills a job on the server. """
check_jobid(job_id) queue = self._get_queue() if queue is None: raise QueueDoesntExist ret, output = self._call('%s %s' % ( shell_escape(queue / 'commands/kill'), job_id), Fa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list(self): """Lists the jobs on the server. """
queue = self._get_queue() if queue is None: raise QueueDoesntExist output = self.check_output('%s' % shell_escape(queue / 'commands/list')) job_id, info = None, None for line in output.splitlines(): line = line.decode(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multi_substitution(*substitutions): """ Take a sequence of pairs specifying substitutions, and create a function that performs those substitutions. 'baz'...
substitutions = itertools.starmap(substitution, substitutions) # compose function applies last function first, so reverse the # substitutions to get the expected order. substitutions = reversed(tuple(substitutions)) return compose(*substitutions)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simple_html_strip(s): r""" Remove HTML from the string `s`. '' A stormy day in paradise Somebody tell the truth. What about multiple lines? """
html_stripper = re.compile('(<!--.*?-->)|(<[^>]*>)|([^<]+)', re.DOTALL) texts = ( match.group(3) or '' for match in html_stripper.finditer(s) ) return ''.join(texts)
<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_prefix(text, prefix): """ Remove the prefix from the text if it exists. 'performance' 'something special' """
null, prefix, rest = text.rpartition(prefix) return rest
<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_suffix(text, suffix): """ Remove the suffix from the text if it exists. 'name' 'something special' """
rest, suffix, null = text.partition(suffix) return rest
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def common_prefix(s1, s2): """ Return the common prefix of two lines. """
index = min(len(s1), len(s2)) while s1[:index] != s2[:index]: index -= 1 return s1[: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 _get_graph(self, ctx, bundle, extensions, caller=None): """ Run a graph and render the tag contents for each output """
request = ctx.get('request') if request is None: request = get_current_request() if ':' in bundle: config_name, bundle = bundle.split(':') else: config_name = 'DEFAULT' webpack = request.webpack(config_name) assets = (caller(a) for a 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 activate(lancet, method, project): """Switch to this project."""
with taskstatus("Looking up project") as ts: if method == "key": func = get_project_keys elif method == "dir": func = get_project_keys for key, project_path in func(lancet): if key.lower() == project.lower(): break 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 workon(ctx, issue_id, new, base_branch): """ Start work on a given issue. This command retrieves the issue from the issue tracker, creates and checks out a n...
lancet = ctx.obj if not issue_id and not new: raise click.UsageError("Provide either an issue ID or the --new flag.") elif issue_id and new: raise click.UsageError( "Provide either an issue ID or the --new flag, but not both." ) if new: # Create a new issue...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time(lancet, issue): """ Start an Harvest timer for the given issue. This command takes care of linking the timer with the issue tracker page for the given i...
issue = get_issue(lancet, issue) with taskstatus("Starting harvest timer") as ts: lancet.timer.start(issue) ts.ok("Started harvest timer")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pause(ctx): """ Pause work on the current issue. This command puts the issue in the configured paused status and stops the current Harvest timer. """
lancet = ctx.obj paused_status = lancet.config.get("tracker", "paused_status") # Get the issue issue = get_issue(lancet) # Make sure the issue is in a correct status transition = get_transition(ctx, lancet, issue, paused_status) # Activate environment set_issue_status(lancet, issue, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resume(ctx): """ Resume work on the currently active issue. The issue is retrieved from the currently active branch name. """
lancet = ctx.obj username = lancet.tracker.whoami() active_status = lancet.config.get("tracker", "active_status") # Get the issue issue = get_issue(lancet) # Make sure the issue is in a correct status transition = get_transition(ctx, lancet, issue, active_status) # Make sure the iss...
<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(lancet, print_cmd, environment): """ SSH into the given environment, based on the dploi configuration. """
namespace = {} with open(lancet.config.get('dploi', 'deployment_spec')) as fh: code = compile(fh.read(), 'deployment.py', 'exec') exec(code, {}, namespace) config = namespace['settings'][environment] host = '{}@{}'.format(config['user'], config['hosts'][0]) cmd = ['ssh', '-p', str...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setup_helper(): """Print the shell integration code."""
base = os.path.abspath(os.path.dirname(__file__)) helper = os.path.join(base, "helper.sh") with open(helper) as fh: click.echo(fh.read())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _commands(ctx): """Prints a list of commands for shell completion hooks."""
ctx = ctx.parent ctx.show_hidden_subcommands = False main = ctx.command for subcommand in main.list_commands(ctx): cmd = main.get_command(ctx, subcommand) if cmd is None: continue help = cmd.short_help or "" click.echo("{}:{}".format(subcommand, help))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _arguments(ctx, command_name=None): """Prints a list of arguments for shell completion hooks. If a command name is given, returns the arguments for that subc...
ctx = ctx.parent main = ctx.command if command_name: command = main.get_command(ctx, command_name) if not command: return else: command = main types = ["option", "argument"] all_params = sorted( command.get_params(ctx), key=lambda p: types.index(p.pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _autocomplete(ctx, shell): """Print the shell autocompletion code."""
if not shell: shell = os.environ.get("SHELL", "") shell = os.path.basename(shell).lower() if not shell: click.secho( "Your shell could not be detected, please pass its name " "as the argument.", fg="red", ) ctx.exit(-1) base = os....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raisefrom(exc_type, message, exc): # type: (Any, str, BaseException) -> None """Call Python 3 raise from or emulate it for Python 2 Args: exc_type (Any): Ty...
if sys.version_info[:2] >= (3, 2): six.raise_from(exc_type(message), exc) else: six.reraise(exc_type, '%s - %s' % (message, exc), sys.exc_info()[2])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def init_runner(self, parser, tracers, projinfo): ''' initial some instances for preparing to run test case @note: should not override @param parser: instance of TestCaseParser @param tracers: dict type for the instance of Tracer. Such as {"":tracer_obj} or {"192.168.0.1:5555":trace...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def init_project_env(subject='Automation', proj_path = None, sysencoding = "utf-8", debug = False): ''' Set the environment for pyrunner ''' # if sysencoding: # set_sys_encode(sysencoding) if not proj_path: try: executable_file_path = os.path.dirname(os....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def until(method, timeout = 30, message=''): """Calls the method until the return value is not False."""
end_time = time.time() + timeout while True: try: value = method() if value: return value except: pass time.sleep(1) if time.time() > end_time: brea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def force_delete_file(file_path): ''' force delete a file ''' if os.path.isfile(file_path): try: os.remove(file_path) return file_path except: return FileSystemUtils.add_unique_postfix(file_path) 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_imported_module_from_file(file_path): """ import module from python file path and return imported module """
if p_compat.is_py3: imported_module = importlib.machinery.SourceFileLoader('module_name', file_path).load_module() elif p_compat.is_py2: imported_module = imp.load_source('module_name', file_path) else: raise RuntimeError("Neither Python 3 nor Python 2....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_module(module, filter_type): """ filter functions or variables from import module @params module: imported module filter_type: "function" or "vari...
filter_type = ModuleUtils.is_function if filter_type == "function" else ModuleUtils.is_variable module_functions_dict = dict(filter(filter_type, vars(module).items())) return module_functions_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_conf_item(start_path, item_type, item_name): """ search expected function or variable recursive upward @param start_path: search start path item_t...
dir_path = os.path.dirname(os.path.abspath(start_path)) target_file = os.path.join(dir_path, "preference.py") if os.path.isfile(target_file): imported_module = ModuleUtils.get_imported_module_from_file(target_file) items_dict = ModuleUtils.filter_module(im...
<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_to_order_dict(map_list): """ convert mapping in list to ordered dict @param (list) map_list [ {"a": 1}, {"b": 2} ] @return (OrderDict) OrderD...
ordered_dict = OrderedDict() for map_dict in map_list: ordered_dict.update(map_dict) return ordered_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shell_escape(s): r"""Given bl"a, returns "bl\\"a". """
if isinstance(s, PosixPath): s = unicode_(s) elif isinstance(s, bytes): s = s.decode('utf-8') if not s or any(c not in safe_shell_chars for c in s): return '"%s"' % (s.replace('\\', '\\\\') .replace('"', '\\"') .replace('`', '\\`')...
<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_long_description(): """ Retrieve the long description from DESCRIPTION.rst """
here = os.path.abspath(os.path.dirname(__file__)) with copen(os.path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as description: return description.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten(nested_list: list) -> list: """Flattens a list, ignore all the lambdas."""
return list(sorted(filter(lambda y: y is not None, list(map(lambda x: (nested_list.extend(x) # noqa: T484 if isinstance(x, list) else x), nested_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 get_py_files(dir_name: str) -> list: """Get all .py files."""
return flatten([ x for x in [["{0}/{1}".format(path, f) for f in files if f.endswith(".py")] for path, _, files in os.walk(dir_name) if not path.startswith("./build")] if 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 exit(self) -> None: """Raise SystemExit with correct status code and output logs."""
total = sum(len(logs) for logs in self.logs.values()) if self.json: self.logs['total'] = total print(json.dumps(self.logs, indent=self.indent)) else: for name, log in self.logs.items(): if not log or self.parser[name].as_bool("quiet"): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_linter(self, linter) -> None: """Run a checker class"""
self.current = linter.name if (linter.name not in self.parser["all"].as_list("linters") or linter.base_pyversion > sys.version_info): # noqa: W503 return if any(x not in self.installed for x in linter.requires_install): raise ModuleNotInstalled(linter....
<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_rcfile(): """ Try to read a rcfile from a list of paths """
files = [ '{}/.millipederc'.format(os.environ.get('HOME')), '/usr/local/etc/millipederc', '/etc/millipederc', ] for filepath in files: if os.path.isfile(filepath): with open(filepath) as rcfile: return parse_rcfile(rcfile) 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 compute_settings(args, rc_settings): """ Merge arguments and rc_settings. """
settings = {} for key, value in args.items(): if key in ['reverse', 'opposite']: settings[key] = value ^ rc_settings.get(key, False) else: settings[key] = value or rc_settings.get(key) if not settings['size']: settings['size'] = DEFAULT_SIZE return setti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def api_post(message, url, name, http_data=None, auth=None): """ Send `message` as `name` to `url`. You can specify extra variables in `http_data` """
try: import requests except ImportError: print('requests is required to do api post.', file=sys.stderr) sys.exit(1) data = {name : message} if http_data: for var in http_data: key, value = var.split('=') data[key] = value response = requests...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def content_from_path(path, encoding='utf-8'): """Return the content of the specified file as a string. This function also supports loading resources from packag...
if not os.path.isabs(path) and ':' in path: package, path = path.split(':', 1) content = resource_string(package, path) else: path = os.path.expanduser(path) with open(path, 'rb') as fh: content = fh.read() return content.decode(encoding)
<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, method, args, ref): """ Execute the method with args """
response = {'result': None, 'error': None, 'ref': ref} fun = self.methods.get(method) if not fun: response['error'] = 'Method `{}` not found'.format(method) else: try: response['result'] = fun(*args) except Exception as exception: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, name, fun, description=None): """ Register function on this service """
self.methods[name] = fun self.descriptions[name] = description
<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(cls, payload): """ Parse client request """
try: method, args, ref = payload except Exception as exception: raise RequestParseError(exception) else: return method, args, ref
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process(self): """ Receive data from socket and process request """
response = None try: payload = self.receive() method, args, ref = self.parse(payload) response = self.execute(method, args, ref) except AuthenticateError as exception: logging.error( 'Service error while authenticating request: ...
<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_payload(cls, method, args): """ Build the payload to be sent to a `Responder` """
ref = str(uuid.uuid4()) return (method, args, ref)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call(self, method, *args): """ Make a call to a `Responder` and return the result """
payload = self.build_payload(method, args) logging.debug('* Client will send payload: {}'.format(payload)) self.send(payload) res = self.receive() assert payload[2] == res['ref'] return res['result'], res['error']
<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(filepath=None, filecontent=None): """ Read the json file located at `filepath` If `filecontent` is specified, its content will be json decoded and loade...
conf = DotDict() assert filepath or filecontent if not filecontent: with io.FileIO(filepath) as handle: filecontent = handle.read().decode('utf-8') configs = json.loads(filecontent) conf.update(configs.items()) return conf
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_main(args: argparse.Namespace, do_exit=True) -> None: """Runs the checks and exits. To extend this tool, use this function and set do_exit to False to get...
if args.init: generate() return None # exit after generate instead of starting to lint handler = CheckHandler( file=args.config_file, out_json=args.json, files=args.files) for style in get_stylers(): handler.run_linter(style()) for linter in get_linters(): ha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main() -> None: """Main entry point for console commands."""
parser = argparse.ArgumentParser() parser.add_argument( "--json", help="output in JSON format", action="store_true", default=False) parser.add_argument( "--config-file", help="Select config file to use", default=".snekrc") parser.add_argument( 'files', ...
<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): # type: () -> None """ Connect to server Returns: None """
if self.connection_type.lower() == 'ssl': self.server = smtplib.SMTP_SSL(host=self.host, port=self.port, local_hostname=self.local_hostname, timeout=self.timeout, source_address=self.source_address) elif self.connection_type.lower() == 'lmtp': ...
<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_session(db_url): # type: (str) -> Session """Gets SQLAlchemy session given url. Your tables must inherit from Base in hdx.utilities.database. Args: db_ur...
engine = create_engine(db_url, poolclass=NullPool, echo=False) Session = sessionmaker(bind=engine) Base.metadata.create_all(engine) return Session()
<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_params_from_sqlalchemy_url(db_url): # type: (str) -> Dict[str,Any] """Gets PostgreSQL database connection parameters from SQLAlchemy url Args: db_url (st...
result = urlsplit(db_url) return {'database': result.path[1:], 'host': result.hostname, 'port': result.port, 'username': result.username, 'password': result.password, 'driver': result.scheme}
<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_sqlalchemy_url(database=None, host=None, port=None, username=None, password=None, driver='postgres'): # type: (Optional[str], Optional[str], Union[int, s...
strings = ['%s://' % driver] if username: strings.append(username) if password: strings.append(':%s@' % password) else: strings.append('@') if host: strings.append(host) if port is not None: stri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_for_postgres(database, host, port, username, password): # type: (Optional[str], Optional[str], Union[int, str, None], Optional[str], Optional[str]) -> N...
connecting_string = 'Checking for PostgreSQL...' if port is not None: port = int(port) while True: try: logger.info(connecting_string) connection = psycopg2.connect( database=database, host=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 dicts_filter(dicts_object, field_to_filter, value_of_filter): """This function gets as arguments an array of dicts through the dicts_objects parameter, then ...
lambda_query = lambda value: value[field_to_filter] == value_of_filter filtered_coin = filter(lambda_query, dicts_object) selected_coins = list(filtered_coin) #if not selected_coin: #Empty list, no coin found # raise AttributeError('attribute %s not found' % attr) return selected_coins
<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_path_for_url(url, folder=None, filename=None, overwrite=False): # type: (str, Optional[str], Optional[str], bool) -> str """Get filename from url and joi...
if not filename: urlpath = urlsplit(url).path filename = basename(urlpath) filename, extension = splitext(filename) if not folder: folder = get_temp_dir() path = join(folder, '%s%s' % (filename, extension)) if overwrite: 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 get_full_url(self, url): # type: (str) -> str """Get full url including any additional parameters Args: url (str): URL for which to get full url Returns: st...
request = Request('GET', url) preparedrequest = self.session.prepare_request(request) return preparedrequest.url
<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_url_for_get(url, parameters=None): # type: (str, Optional[Dict]) -> str """Get full url for GET request including parameters Args: url (str): URL to dow...
spliturl = urlsplit(url) getparams = OrderedDict(parse_qsl(spliturl.query)) if parameters is not None: getparams.update(parameters) spliturl = spliturl._replace(query=urlencode(getparams)) return urlunsplit(spliturl)
<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_url_params_for_post(url, parameters=None): # type: (str, Optional[Dict]) -> Tuple[str, Dict] """Get full url for POST request and all parameters includin...
spliturl = urlsplit(url) getparams = OrderedDict(parse_qsl(spliturl.query)) if parameters is not None: getparams.update(parameters) spliturl = spliturl._replace(query='') full_url = urlunsplit(spliturl) return full_url, getparams
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(self, url, stream=True, post=False, parameters=None, timeout=None): # type: (str, bool, bool, Optional[Dict], Optional[float]) -> requests.Response """...
self.close_response() self.response = None try: if post: full_url, parameters = self.get_url_params_for_post(url, parameters) self.response = self.session.post(full_url, data=parameters, stream=stream, timeout=timeout) 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 hash_stream(self, url): # type: (str) -> str """Stream file from url and hash it using MD5. Must call setup method first. Args: url (str): URL to download R...
md5hash = hashlib.md5() try: for chunk in self.response.iter_content(chunk_size=10240): if chunk: # filter out keep-alive new chunks md5hash.update(chunk) return md5hash.hexdigest() except Exception as e: raisefrom(Downloa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stream_file(self, url, folder=None, filename=None, overwrite=False): # type: (str, Optional[str], Optional[str], bool) -> str """Stream file from url and sto...
path = self.get_path_for_url(url, folder, filename, overwrite) f = None try: f = open(path, 'wb') for chunk in self.response.iter_content(chunk_size=10240): if chunk: # filter out keep-alive new chunks f.write(chunk) ...
<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_file(self, url, folder=None, filename=None, overwrite=False, post=False, parameters=None, timeout=None): # type: (str, Optional[str], Optional[str],...
self.setup(url, stream=True, post=post, parameters=parameters, timeout=timeout) return self.stream_file(url, folder, filename, overwrite)
<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_tabular_stream(self, url, **kwargs): # type: (str, Any) -> tabulator.Stream """Get Tabulator stream. Args: url (str): URL to download **kwargs: headers ...
self.close_response() file_type = kwargs.get('file_type') if file_type is not None: kwargs['format'] = file_type del kwargs['file_type'] try: self.response = tabulator.Stream(url, **kwargs) self.response.open() return self.resp...
<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_tabular_rows(self, url, dict_rows=False, **kwargs): # type: (str, bool, Any) -> Iterator[Dict] """Get iterator for reading rows from tabular data. Each r...
return self.get_tabular_stream(url, **kwargs).iter(keyed=dict_rows)
<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_tabular_rows_as_dicts(self, url, headers=1, keycolumn=1, **kwargs): # type: (str, Union[int, List[int], List[str]], int, Any) -> Dict[Dict] """Downl...
kwargs['headers'] = headers stream = self.get_tabular_stream(url, **kwargs) output_dict = dict() headers = stream.headers key_header = headers[keycolumn - 1] for row in stream.iter(keyed=True): first_val = row[key_header] output_dict[first_val] = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(ctx, force): """Wizard to create the user-level configuration file."""
if os.path.exists(USER_CONFIG) and not force: click.secho( 'An existing configuration file was found at "{}".\n' .format(USER_CONFIG), fg='red', bold=True ) click.secho( 'Please remove it before in order to run the setup wizard or use\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 init(ctx, force): """Wizard to create a project-level configuration file."""
if os.path.exists(PROJECT_CONFIG) and not force: click.secho( 'An existing configuration file was found at "{}".\n' .format(PROJECT_CONFIG), fg='red', bold=True ) click.secho( 'Please remove it before in order to run the setup wizard or use\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 logout(lancet, service): """Forget saved passwords for the web services."""
if service: services = [service] else: services = ['tracker', 'harvest'] for service in services: url = lancet.config.get(service, 'url') key = 'lancet+{}'.format(url) username = lancet.config.get(service, 'username') with taskstatus('Logging out from {}', u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _services(lancet): """List all currently configured services."""
def get_services(config): for s in config.sections(): if config.has_option(s, 'url'): if config.has_option(s, 'username'): yield s for s in get_services(lancet.config): click.echo('{}[Logout from {}]'.format(s, lancet.config.get(s, 'url')))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iso_639_alpha3(code): """Convert a given language identifier into an ISO 639 Part 2 code, such as "eng" or "deu". This will accept language codes in the two-...
code = normalize_code(code) code = ISO3_MAP.get(code, code) if code in ISO3_ALL: return code
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pull_request(ctx, base_branch, open_pr, stop_timer): """Create a new pull request for this issue."""
lancet = ctx.obj review_status = lancet.config.get("tracker", "review_status") remote_name = lancet.config.get("repository", "remote_name") if not base_branch: base_branch = lancet.config.get("repository", "base_branch") # Get the issue issue = get_issue(lancet) transition = 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 checkout(lancet, force, issue): """ Checkout the branch for the given issue. It is an error if the branch does no exist yet. """
issue = get_issue(lancet, issue) # Get the working branch branch = get_branch(lancet, issue, create=force) with taskstatus("Checking out working branch") as ts: if not branch: ts.abort("Working branch not found") lancet.repo.checkout(branch.name) ts.ok('Checked out...
<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_table(tabletag): # type: (Tag) -> List[Dict] """ Extract HTML table as list of dictionaries Args: tabletag (Tag): BeautifulSoup tag Returns: str: Te...
theadtag = tabletag.find_next('thead') headertags = theadtag.find_all('th') if len(headertags) == 0: headertags = theadtag.find_all('td') headers = [] for tag in headertags: headers.append(get_text(tag)) tbodytag = tabletag.find_next('tbody') trtags = tbodytag.find_all('tr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap_callable(cls, uri, methods, callable_obj): """Wraps function-based callable_obj into a `Route` instance, else proxies a `bottle_neck.handlers.BaseHandle...
if isinstance(callable_obj, HandlerMeta): callable_obj.base_endpoint = uri callable_obj.is_valid = True return callable_obj if isinstance(callable_obj, types.FunctionType): return cls(uri=uri, methods=methods, callable_obj=callable_obj) raise Ro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_app(self, app): """Register the route object to a `bottle.Bottle` app instance. Args: app (instance): Returns: Route instance (for chaining purpose...
app.route(self.uri, methods=self.methods)(self.callable_obj) 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 register_handler(self, callable_obj, entrypoint, methods=('GET',)): """Register a handler callable to a specific route. Args: entrypoint (str): The uri rela...
router_obj = Route.wrap_callable( uri=entrypoint, methods=methods, callable_obj=callable_obj ) if router_obj.is_valid: self._routes.add(router_obj) return self raise RouteError( # pragma: no cover "Missi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mount(self, app=None): """Mounts all registered routes to a bottle.py application instance. Args: app (instance): A `bottle.Bottle()` application instance. ...
for endpoint in self._routes: endpoint.register_app(app) 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 _tolog(self,level): """ log with different level """
def wrapper(msg): if self.log_colors: color = self.log_colors[level.upper()] getattr(self.logger, level.lower())(coloring("- {}".format(msg), color)) else: getattr(self.logger, level.lower())(msg) return wrapper
<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_status(cls, status_line, msg=None): """Returns a class method from bottle.HTTPError.status_line attribute. Useful for patching `bottle.HTTPError` for we...
method = getattr(cls, status_line.lower()[4:].replace(' ', '_')) return method(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 created(cls, data=None): """Shortcut API for HTTP 201 `Created` response. Args: data (object): Response key/value data. Returns: WSResponse Instance. """
if cls.expose_status: # pragma: no cover cls.response.content_type = 'application/json' cls.response._status_line = '201 Created' return cls(201, data=data).to_json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def not_modified(cls, errors=None): """Shortcut API for HTTP 304 `Not Modified` response. Args: errors (list): Response key/value data. Returns: WSResponse Inst...
if cls.expose_status: # pragma: no cover cls.response.content_type = 'application/json' cls.response._status_line = '304 Not Modified' return cls(304, None, errors).to_json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bad_request(cls, errors=None): """Shortcut API for HTTP 400 `Bad Request` response. Args: errors (list): Response key/value data. Returns: WSResponse Instan...
if cls.expose_status: # pragma: no cover cls.response.content_type = 'application/json' cls.response._status_line = '400 Bad Request' return cls(400, errors=errors).to_json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unauthorized(cls, errors=None): """Shortcut API for HTTP 401 `Unauthorized` response. Args: errors (list): Response key/value data. Returns: WSResponse Inst...
if cls.expose_status: # pragma: no cover cls.response.content_type = 'application/json' cls.response._status_line = '401 Unauthorized' return cls(401, errors=errors).to_json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forbidden(cls, errors=None): """Shortcut API for HTTP 403 `Forbidden` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. ...
if cls.expose_status: # pragma: no cover cls.response.content_type = 'application/json' cls.response._status_line = '403 Forbidden' return cls(403, errors=errors).to_json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def not_found(cls, errors=None): """Shortcut API for HTTP 404 `Not found` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. ...
if cls.expose_status: # pragma: no cover cls.response.content_type = 'application/json' cls.response._status_line = '404 Not Found' return cls(404, None, errors).to_json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def method_not_allowed(cls, errors=None): """Shortcut API for HTTP 405 `Method not allowed` response. Args: errors (list): Response key/value data. Returns: WSR...
if cls.expose_status: # pragma: no cover cls.response.content_type = 'application/json' cls.response._status_line = '405 Method Not Allowed' return cls(405, None, errors).to_json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def not_implemented(cls, errors=None): """Shortcut API for HTTP 501 `Not Implemented` response. Args: errors (list): Response key/value data. Returns: WSRespons...
if cls.expose_status: # pragma: no cover cls.response.content_type = 'application/json' cls.response._status_line = '501 Not Implemented' return cls(501, None, errors).to_json