text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Return the content of the specified file as a string. <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 packages. """
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:> Execute the method with args <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: logging.error(exception, exc_info=1) response['error'] = str(exception) return response
<SYSTEM_TASK:> Register function on this service <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:> Receive data from socket and process request <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: {}' .format(exception), exc_info=1) except AuthenticatorInvalidSignature as exception: logging.error( 'Service error while authenticating request: {}' .format(exception), exc_info=1) except DecodeError as exception: logging.error( 'Service error while decoding request: {}' .format(exception), exc_info=1) except RequestParseError as exception: logging.error( 'Service error while parsing request: {}' .format(exception), exc_info=1) else: logging.debug('Service received payload: {}'.format(payload)) if response: self.send(response) else: self.send('')
<SYSTEM_TASK:> Build the payload to be sent to a `Responder` <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:> Make a call to a `Responder` and return the result <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:> Read the json file located at `filepath` <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 loaded instead. Usage: config.load(filepath=None, filecontent=None): Provide either a filepath or a json string """
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:> Runs the checks and exits. <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 returned the status code. """
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(): handler.run_linter(linter()) for security in get_security(): handler.run_linter(security()) for tool in get_tools(): tool = tool() # Only run pypi if everything else passed if tool.name == "pypi" and handler.status_code != 0: continue handler.run_linter(tool) if do_exit: handler.exit() return handler.status_code
<SYSTEM_TASK:> Main entry point for console commands. <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', metavar='file', nargs='*', default=[], help='Files to run checks against') parser.add_argument( "--init", help="generate snekrc", action="store_true", default=False) args = parser.parse_args() run_main(args)
<SYSTEM_TASK:> Connect to server <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': self.server = smtplib.LMTP(host=self.host, port=self.port, local_hostname=self.local_hostname, source_address=self.source_address) else: self.server = smtplib.SMTP(host=self.host, port=self.port, local_hostname=self.local_hostname, timeout=self.timeout, source_address=self.source_address) self.server.login(self.username, self.password)
<SYSTEM_TASK:> This function gets as arguments an array of dicts through the dicts_objects parameter, <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 it'll return the dicts that have a value value_of_filter of the key field_to_filter. """
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:> Get filename from url and join to provided folder or temporary folder if no folder supplied, ensuring uniqueness <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 join to provided folder or temporary folder if no folder supplied, ensuring uniqueness Args: url (str): URL to download folder (Optional[str]): Folder to download it to. Defaults to None (temporary folder). filename (Optional[str]): Filename to use for downloaded file. Defaults to None (derive from the url). overwrite (bool): Whether to overwrite existing file. Defaults to False. Returns: str: Path of downloaded file """
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: remove(path) except OSError: pass else: count = 0 while exists(path): count += 1 path = join(folder, '%s%d%s' % (filename, count, extension)) return path
<SYSTEM_TASK:> Get full url including any additional parameters <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: str: Full url including any additional parameters """
request = Request('GET', url) preparedrequest = self.session.prepare_request(request) return preparedrequest.url
<SYSTEM_TASK:> Get full url for GET request including parameters <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 download parameters (Optional[Dict]): Parameters to pass. Defaults to None. Returns: str: Full url """
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:> Get full url for POST request and all parameters including any in the url <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 including any in the url Args: url (str): URL to download parameters (Optional[Dict]): Parameters to pass. Defaults to None. Returns: Tuple[str, Dict]: (Full url, parameters) """
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:> Setup download from provided url returning the response <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 """Setup download from provided url returning the response Args: url (str): URL to download stream (bool): Whether to stream download. Defaults to True. post (bool): Whether to use POST instead of GET. Defaults to False. parameters (Optional[Dict]): Parameters to pass. Defaults to None. timeout (Optional[float]): Timeout for connecting to URL. Defaults to None (no timeout). Returns: requests.Response: requests.Response object """
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: self.response = self.session.get(self.get_url_for_get(url, parameters), stream=stream, timeout=timeout) self.response.raise_for_status() except Exception as e: raisefrom(DownloadError, 'Setup of Streaming Download of %s failed!' % url, e) return self.response
<SYSTEM_TASK:> Stream file from url and hash it using MD5. Must call setup method first. <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 Returns: str: MD5 hash of file """
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(DownloadError, 'Download of %s failed in retrieval of stream!' % url, e)
<SYSTEM_TASK:> Stream file from url and store in provided folder or temporary folder if no folder supplied. <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 store in provided folder or temporary folder if no folder supplied. Must call setup method first. Args: url (str): URL to download filename (Optional[str]): Filename to use for downloaded file. Defaults to None (derive from the url). folder (Optional[str]): Folder to download it to. Defaults to None (temporary folder). overwrite (bool): Whether to overwrite existing file. Defaults to False. Returns: str: Path of downloaded file """
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) f.flush() return f.name except Exception as e: raisefrom(DownloadError, 'Download of %s failed in retrieval of stream!' % url, e) finally: if f: f.close()
<SYSTEM_TASK:> Download file from url and store in provided folder or temporary folder if no folder supplied <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], bool, bool, Optional[Dict], Optional[float]) -> str """Download file from url and store in provided folder or temporary folder if no folder supplied Args: url (str): URL to download folder (Optional[str]): Folder to download it to. Defaults to None. filename (Optional[str]): Filename to use for downloaded file. Defaults to None (derive from the url). overwrite (bool): Whether to overwrite existing file. Defaults to False. post (bool): Whether to use POST instead of GET. Defaults to False. parameters (Optional[Dict]): Parameters to pass. Defaults to None. timeout (Optional[float]): Timeout for connecting to URL. Defaults to None (no timeout). Returns: str: Path of downloaded file """
self.setup(url, stream=True, post=post, parameters=parameters, timeout=timeout) return self.stream_file(url, folder, filename, overwrite)
<SYSTEM_TASK:> Get Tabulator stream. <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 (Union[int, List[int], List[str]]): Number of row(s) containing headers or list of headers file_type (Optional[str]): Type of file. Defaults to inferring. delimiter (Optional[str]): Delimiter used for values in each row. Defaults to inferring. Returns: tabulator.Stream: Tabulator Stream object """
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.response except TabulatorException as e: raisefrom(DownloadError, 'Getting tabular stream for %s failed!' % url, e)
<SYSTEM_TASK:> Get iterator for reading rows from tabular data. Each row is returned as a dictionary. <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 row is returned as a dictionary. Args: url (str): URL to download dict_rows (bool): Return dict (requires headers parameter) or list for each row. Defaults to False (list). **kwargs: headers (Union[int, List[int], List[str]]): Number of row(s) containing headers or list of headers file_type (Optional[str]): Type of file. Defaults to inferring. delimiter (Optional[str]): Delimiter used for values in each row. Defaults to inferring. Returns: Iterator[Union[List,Dict]]: Iterator where each row is returned as a list or dictionary. """
return self.get_tabular_stream(url, **kwargs).iter(keyed=dict_rows)
<SYSTEM_TASK:> Download multicolumn csv from url and return dictionary where keys are first column and values are <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] """Download multicolumn csv from url and return dictionary where keys are first column and values are dictionaries with keys from column headers and values from columns beneath Args: url (str): URL to download headers (Union[int, List[int], List[str]]): Number of row(s) containing headers or list of headers. Defaults to 1. keycolumn (int): Number of column to be used for key. Defaults to 1. **kwargs: file_type (Optional[str]): Type of file. Defaults to inferring. delimiter (Optional[str]): Delimiter used for values in each row. Defaults to inferring. Returns: Dict[Dict]: Dictionary where keys are first column and values are dictionaries with keys from column headers and values from columns beneath """
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] = dict() for header in row: if header == key_header: continue else: output_dict[first_val][header] = row[header] return output_dict
<SYSTEM_TASK:> Wizard to create the user-level configuration file. <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' 'the --force flag to overwrite it.' ) ctx.exit(1) click.echo('Address of the issue tracker (your JIRA instance). \n' 'Normally in the form https://<company>.atlassian.net.') tracker_url = click.prompt('URL') tracker_user = click.prompt('Username for {}'.format(tracker_url)) click.echo() click.echo('Address of the time tracker (your Harvest instance). \n' 'Normally in the form https://<company>.harvestapp.com.') timer_url = click.prompt('URL') timer_user = click.prompt('Username for {}'.format(timer_url)) click.echo() config = configparser.ConfigParser() config.add_section('tracker') config.set('tracker', 'url', tracker_url) config.set('tracker', 'username', tracker_user) config.add_section('harvest') config.set('harvest', 'url', timer_url) config.set('harvest', 'username', timer_user) with open(USER_CONFIG, 'w') as fh: config.write(fh) click.secho('Configuration correctly written to "{}".' .format(USER_CONFIG), fg='green')
<SYSTEM_TASK:> Wizard to create a project-level configuration file. <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' 'the --force flag to overwrite it.' ) ctx.exit(1) project_key = click.prompt('Project key on the issue tracker') base_branch = click.prompt('Integration branch', default='master') virtualenvs = ('.venv', '.env', 'venv', 'env') for p in virtualenvs: if os.path.exists(os.path.join(p, 'bin', 'activate')): venv = p break else: venv = '' venv_path = click.prompt('Path to virtual environment', default=venv) project_id = click.prompt('Project ID on Harvest', type=int) task_id = click.prompt('Task id on Harvest', type=int) config = configparser.ConfigParser() config.add_section('lancet') config.set('lancet', 'virtualenv', venv_path) config.add_section('tracker') config.set('tracker', 'default_project', project_key) config.add_section('harvest') config.set('harvest', 'project_id', str(project_id)) config.set('harvest', 'task_id', str(task_id)) config.add_section('repository') config.set('repository', 'base_branch', base_branch) with open(PROJECT_CONFIG, 'w') as fh: config.write(fh) click.secho('\nConfiguration correctly written to "{}".' .format(PROJECT_CONFIG), fg='green')
<SYSTEM_TASK:> List all currently configured services. <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:> Convert a given language identifier into an ISO 639 Part 2 code, such <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- or three- letter format, and some language names. If the given string cannot be converted, ``None`` will be returned. """
code = normalize_code(code) code = ISO3_MAP.get(code, code) if code in ISO3_ALL: return code
<SYSTEM_TASK:> Create a new pull request for this issue. <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_transition(ctx, lancet, issue, review_status) # Get the working branch branch = get_branch(lancet, issue, create=False) with taskstatus("Checking pre-requisites") as ts: if not branch: ts.abort("No working branch found") if lancet.tracker.whoami() not in issue.assignees: ts.abort("Issue currently not assigned to you") # TODO: Check mergeability # TODO: Check remote status (PR does not already exist) # Push to remote with taskstatus('Pushing to "{}"', remote_name) as ts: remote = lancet.repo.lookup_remote(remote_name) if not remote: ts.abort('Remote "{}" not found', remote_name) from ..git import CredentialsCallbacks remote.push([branch.name], callbacks=CredentialsCallbacks()) ts.ok('Pushed latest changes to "{}"', remote_name) # Create pull request with taskstatus("Creating pull request") as ts: template_path = lancet.config.get("repository", "pr_template") message = edit_template(template_path, issue=issue) if not message: ts.abort("You didn't provide a title for the pull request") title, body = message.split("\n", 1) title = title.strip() if not title: ts.abort("You didn't provide a title for the pull request") try: pr = lancet.scm_manager.create_pull_request( branch.branch_name, base_branch, title, body.strip("\n") ) except PullRequestAlreadyExists as e: pr = e.pull_request ts.ok("Pull request does already exist at {}", pr.link) else: ts.ok("Pull request created at {}", pr.link) # Update issue set_issue_status(lancet, issue, review_status, transition) # TODO: Post to activity stream on JIRA? # TODO: Post to Slack? # Stop harvest timer if stop_timer: with taskstatus("Pausing harvest timer") as ts: lancet.timer.pause() ts.ok("Harvest timer paused") # Open the pull request page in the browser if requested if open_pr: click.launch(pr.link)
<SYSTEM_TASK:> Checkout the branch for the given issue. <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 "{}"', branch.name)
<SYSTEM_TASK:> Extract HTML table as list of dictionaries <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: Text of tag stripped of leading and trailing whitespace and newlines and with &nbsp replaced with space """
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') table = list() for trtag in trtags: row = dict() tdtags = trtag.find_all('td') for i, tag in enumerate(tdtags): row[headers[i]] = get_text(tag) table.append(row) return table
<SYSTEM_TASK:> Wraps function-based callable_obj into a `Route` instance, else <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.BaseHandler` subclass instance. Args: uri (str): The uri relative path. methods (tuple): A tuple of valid method strings. callable_obj (instance): The callable object. Returns: A route instance. Raises: RouteError for invalid callable object type. """
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 RouteError("Invalid handler type.")
<SYSTEM_TASK:> Register the route object to a `bottle.Bottle` app instance. <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 purposes) """
app.route(self.uri, methods=self.methods)(self.callable_obj) return self
<SYSTEM_TASK:> Register a handler callable to a specific route. <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 relative path. methods (tuple): A tuple of valid method strings. callable_obj (callable): The callable object. Returns: The Router instance (for chaining purposes). Raises: RouteError, for missing routing params or invalid callable object type. """
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 "Missing params: methods: {} - entrypoint: {}".format( methods, entrypoint ) )
<SYSTEM_TASK:> Mounts all registered routes to a bottle.py application instance. <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. Returns: The Router instance (for chaining purposes). """
for endpoint in self._routes: endpoint.register_app(app) return self
<SYSTEM_TASK:> log with different level <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:> Returns a class method from bottle.HTTPError.status_line attribute. <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 web services. Args: status_line (str): bottle.HTTPError.status_line text. msg: The message data for response. Returns: Class method based on status_line arg. Examples: >>> status_line = '401 Unauthorized' >>> error_msg = 'Get out!' >>> resp = WSResponse.from_status(status_line, error_msg) >>> resp['errors'] ['Get out!'] >>> resp['status_text'] 'Unauthorized' """
method = getattr(cls, status_line.lower()[4:].replace(' ', '_')) return method(msg)
<SYSTEM_TASK:> Shortcut API for HTTP 404 `Not found` response. <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:> Shortcut API for HTTP 405 `Method not allowed` response. <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: WSResponse Instance. """
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:> Asks a question yes no style <END_TASK> <USER_TASK:> Description: def ask_bool(question: str, default: bool = True) -> bool: """Asks a question yes no style"""
default_q = "Y/n" if default else "y/N" answer = input("{0} [{1}]: ".format(question, default_q)) lower = answer.lower() if not lower: return default return lower == "y"
<SYSTEM_TASK:> Asks for a number in a question <END_TASK> <USER_TASK:> Description: def ask_int(question: str, default: int = None) -> int: """Asks for a number in a question"""
default_q = " [default: {0}]: ".format( default) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if not answer: if default is None: print("No default set, try again.") return ask_int(question, default) return default if any(x not in "1234567890" for x in answer): print("Please enter only numbers (0-9).") return ask_int(question, default) return int(answer)
<SYSTEM_TASK:> Asks for a comma seperated list of strings <END_TASK> <USER_TASK:> Description: def ask_list(question: str, default: list = None) -> list: """Asks for a comma seperated list of strings"""
default_q = " [default: {0}]: ".format( ",".join(default)) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if answer == "": return default return [ans.strip() for ans in answer.split(",")]
<SYSTEM_TASK:> Asks for a simple string <END_TASK> <USER_TASK:> Description: def ask_str(question: str, default: str = None): """Asks for a simple string"""
default_q = " [default: {0}]: ".format( default) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if answer == "": return default return answer
<SYSTEM_TASK:> Lets the user enter the tools he want to use <END_TASK> <USER_TASK:> Description: def get_tools(self) -> list: """Lets the user enter the tools he want to use"""
tools = "flake8,pylint,vulture,pyroma,isort,yapf,safety,dodgy,pytest,pypi".split( ",") print("Available tools: {0}".format(",".join(tools))) answer = ask_list("What tools would you like to use?", ["flake8", "pytest"]) if any(tool not in tools for tool in answer): print("Invalid answer, retry.") self.get_tools() return answer
<SYSTEM_TASK:> The main function for generating the config file <END_TASK> <USER_TASK:> Description: def main(self) -> None: """The main function for generating the config file"""
path = ask_path("where should the config be stored?", ".snekrc") conf = configobj.ConfigObj() tools = self.get_tools() for tool in tools: conf[tool] = getattr(self, tool)() # pylint: disable=assignment-from-no-return conf.filename = path conf.write() print("Written config file!") if "pylint" in tools: print( "Please also run `pylint --generate-rcfile` to complete setup")
<SYSTEM_TASK:> Compute pagination info for collection filtering. <END_TASK> <USER_TASK:> Description: def paginator(limit, offset, record_count, base_uri, page_nav_tpl='&limit={}&offset={}'): """Compute pagination info for collection filtering. Args: limit (int): Collection filter limit. offset (int): Collection filter offset. record_count (int): Collection filter total record count. base_uri (str): Collection filter base uri (without limit, offset) page_nav_tpl (str): Pagination template. Returns: A mapping of pagination info. """
total_pages = int(math.ceil(record_count / limit)) next_cond = limit + offset <= record_count prev_cond = offset >= limit next_page = base_uri + page_nav_tpl.format(limit, offset + limit) if next_cond else None prev_page = base_uri + page_nav_tpl.format(limit, offset - limit) if prev_cond else None return OrderedDict([ ('total_count', record_count), ('total_pages', total_pages), ('next_page', next_page), ('prev_page', prev_page) ])
<SYSTEM_TASK:> Check whether the status code of the response equals expected_status and <END_TASK> <USER_TASK:> Description: def check(response, expected_status=200, url=None): """ Check whether the status code of the response equals expected_status and raise an APIError otherwise. @param url: The url of the response (for error messages). Defaults to response.url @param json: if True, return r.json(), otherwise return r.text """
if response.status_code != expected_status: if url is None: url = response.url try: err = response.json() except: err = {} # force generic error if all(x in err for x in ("status", "message", "description", "details")): raise _APIError(err["status"], err['message'], url, err, err["description"], err["details"]) else: # generic error suffix = ".html" if "<html" in response.text else ".txt" msg = response.text if len(msg) > 200: with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as f: f.write(response.text.encode("utf-8")) msg = "{}...\n\n[snipped; full response written to {f.name}".format(msg[:100], **locals()) msg = ("Request {url!r} returned code {response.status_code}," " expected {expected_status}. \n{msg}".format(**locals())) raise _APIError(response.status_code, msg, url, response.text) if response.headers.get('Content-Type') == 'application/json': try: return response.json() except: raise Exception("Cannot decode json; text={response.text!r}" .format(**locals())) else: return response.text
<SYSTEM_TASK:> Make an HTTP request to the given relative URL with the host, <END_TASK> <USER_TASK:> Description: def request(self, url, method="get", format="json", data=None, expected_status=None, headers=None, use_xpost=True, **options): """ Make an HTTP request to the given relative URL with the host, user, and password information. Returns the deserialized json if successful, and raises an exception otherwise """
if expected_status is None: if method == "get": expected_status = 200 elif method == "post": expected_status = 201 else: raise ValueError("No expected status supplied and method unknown.") if not url.startswith("http"): url = "{self.host}/api/v4/{url}".format(**locals()) if format is not None: options = dict({'format': format}, **options) options = {field: value for field, value in options.items() if value is not None} headers = dict(headers or {}, Authorization="Token {}".format(self.token)) #headers['Accept-encoding'] = 'gzip' if method == "get" and use_xpost: # If method is purely GET, we can use X-HTTP-METHOD-OVERRIDE to send our # query via POST. This allows for a large number of parameters to be supplied assert(data is None) headers.update({"X-HTTP-METHOD-OVERRIDE": method}) data = options options = None method = "post" r = requests.request(method, url, data=data, params=options, headers=headers) log.debug( "HTTP {method} {url} (options={options!r}, data={data!r}," "headers={headers}) -> {r.status_code}".format(**locals()) ) return check(r, expected_status=expected_status)
<SYSTEM_TASK:> List the articles in a set <END_TASK> <USER_TASK:> Description: def list_articles(self, project, articleset, page=1, **filters): """List the articles in a set"""
url = URL.article.format(**locals()) return self.get_pages(url, page=page, **filters)
<SYSTEM_TASK:> Create a new article set. Provide the needed arguments using <END_TASK> <USER_TASK:> Description: def create_set(self, project, json_data=None, **options): """ Create a new article set. Provide the needed arguments using post_data or with key-value pairs """
url = URL.articlesets.format(**locals()) if json_data is None: # form encoded request return self.request(url, method="post", data=options) else: if not isinstance(json_data, (string_types)): json_data = json.dumps(json_data,default = serialize) headers = {'content-type': 'application/json'} return self.request( url, method='post', data=json_data, headers=headers)
<SYSTEM_TASK:> Create one or more articles in the set. Provide the needed arguments <END_TASK> <USER_TASK:> Description: def create_articles(self, project, articleset, json_data=None, **options): """ Create one or more articles in the set. Provide the needed arguments using the json_data or with key-value pairs @param json_data: A dictionary or list of dictionaries. Each dict can contain a 'children' attribute which is another list of dictionaries. """
url = URL.article.format(**locals()) # TODO duplicated from create_set, move into requests # (or separate post method?) if json_data is None: # form encoded request return self.request(url, method="post", data=options) else: if not isinstance(json_data, string_types): json_data = json.dumps(json_data, default=serialize) headers = {'content-type': 'application/json'} return self.request(url, method='post', data=json_data, headers=headers)
<SYSTEM_TASK:> Return authentication signature of encoded bytes <END_TASK> <USER_TASK:> Description: def sign(self, encoded): """ Return authentication signature of encoded bytes """
signature = self._hmac.copy() signature.update(encoded) return signature.hexdigest().encode('utf-8')
<SYSTEM_TASK:> Split into signature and message <END_TASK> <USER_TASK:> Description: def split(self, encoded): """ Split into signature and message """
maxlen = len(encoded) - self.sig_size message = encoded[:maxlen] signature = encoded[-self.sig_size:] return message, signature
<SYSTEM_TASK:> Validate integrity of encoded bytes <END_TASK> <USER_TASK:> Description: def auth(self, encoded): """ Validate integrity of encoded bytes """
message, signature = self.split(encoded) computed = self.sign(message) if not hmac.compare_digest(signature, computed): raise AuthenticatorInvalidSignature
<SYSTEM_TASK:> A memorization decorator for class properties. <END_TASK> <USER_TASK:> Description: def cached_classproperty(fun): """A memorization decorator for class properties. It implements the above `classproperty` decorator, with the difference that the function result is computed and attached to class as direct attribute. (Lazy loading and caching.) """
@functools.wraps(fun) def get(cls): try: return cls.__cache[fun] except AttributeError: cls.__cache = {} except KeyError: # pragma: no cover pass ret = cls.__cache[fun] = fun(cls) return ret return classproperty(get)
<SYSTEM_TASK:> Plugin Method decorator. <END_TASK> <USER_TASK:> Description: def plugin_method(*plugin_names): """Plugin Method decorator. Signs a web handler function with the plugins to be applied as attributes. Args: plugin_names (list): A list of plugin callable names Returns: A wrapped handler callable. Examples: >>> @plugin_method('json', 'bill') ... def method(): ... return "Hello!" ... >>> print method.json True >>> print method.bill True """
def wrapper(callable_obj): for plugin_name in plugin_names: if not hasattr(callable_obj, plugin_name): setattr(callable_obj, plugin_name, True) return callable_obj return wrapper
<SYSTEM_TASK:> Custom handler routing decorator. <END_TASK> <USER_TASK:> Description: def route_method(method_name, extra_part=False): """Custom handler routing decorator. Signs a web handler callable with the http method as attribute. Args: method_name (str): HTTP method name (i.e GET, POST) extra_part (bool): Indicates if wrapped callable name should be a part of the actual endpoint. Returns: A wrapped handler callable. examples: >>> @route_method('GET') ... def method(): ... return "Hello!" ... >>> method.http_method 'GET' >>> method.url_extra_part None """
def wrapper(callable_obj): if method_name.lower() not in DEFAULT_ROUTES: raise HandlerHTTPMethodError( 'Invalid http method in method: {}'.format(method_name) ) callable_obj.http_method = method_name.upper() callable_obj.url_extra_part = callable_obj.__name__ if extra_part\ else None return classmethod(callable_obj) return wrapper
<SYSTEM_TASK:> Create a new issue on the issue tracker. <END_TASK> <USER_TASK:> Description: def issue_add(lancet, assign, add_to_sprint, summary): """ Create a new issue on the issue tracker. """
summary = " ".join(summary) issue = create_issue( lancet, summary, # project_id=project_id, add_to_active_sprint=add_to_sprint, ) if assign: if assign == "me": username = lancet.tracker.whoami() else: username = assign assign_issue(lancet, issue, username) click.echo("Created issue")
<SYSTEM_TASK:> DRY helper. If the specified attribute of the user differs from the <END_TASK> <USER_TASK:> Description: def _maybe_update(self, user, attribute, new_value): """ DRY helper. If the specified attribute of the user differs from the specified value, it will be updated. """
old_value = getattr(user, attribute) if new_value != old_value: self.stderr.write( _('Setting {attribute} for user "{username}" to "{new_value}"').format( attribute=attribute, username=user.username, new_value=new_value ) ) setattr(user, attribute, new_value)
<SYSTEM_TASK:> DRY helper. <END_TASK> <USER_TASK:> Description: def _check_email_match(self, user, email): """ DRY helper. Requiring the user to specify both username and email will help catch certain issues, for example if the expected username has already been taken by someone else. """
if user.email != email: # The passed email address doesn't match this username's email address. # Assume a problem and fail. raise CommandError( _( 'Skipping user "{}" because the specified and existing email ' 'addresses do not match.' ).format(user.username) )
<SYSTEM_TASK:> Check the provided credentials using the Harvest API. <END_TASK> <USER_TASK:> Description: def credentials_checker(url, username, password): """Check the provided credentials using the Harvest API."""
api = HarvestAPI(url, (username, password)) try: api.whoami() except HarvestError: return False else: return True
<SYSTEM_TASK:> Gets the next feedback message. <END_TASK> <USER_TASK:> Description: def get_feedback(self, block = True, timeout = None): """ Gets the next feedback message. Each feedback message is a 2-tuple of (timestamp, device_token)."""
if self._feedback_greenlet is None: self._feedback_greenlet = gevent.spawn(self._feedback_loop) return self._feedback_queue.get(block = block, timeout = timeout)
<SYSTEM_TASK:> Wait until all queued messages are sent. <END_TASK> <USER_TASK:> Description: def wait_send(self, timeout = None): """Wait until all queued messages are sent."""
self._send_queue_cleared.clear() self._send_queue_cleared.wait(timeout = timeout)
<SYSTEM_TASK:> Start the message sending loop. <END_TASK> <USER_TASK:> Description: def start(self): """Start the message sending loop."""
if self._send_greenlet is None: self._send_greenlet = gevent.spawn(self._send_loop)
<SYSTEM_TASK:> Simultaneously replace multiple strigns in a string <END_TASK> <USER_TASK:> Description: def multiple_replace(string, replacements): # type: (str, Dict[str,str]) -> str """Simultaneously replace multiple strigns in a string Args: string (str): Input string replacements (Dict[str,str]): Replacements dictionary Returns: str: String with replacements """
pattern = re.compile("|".join([re.escape(k) for k in sorted(replacements, key=len, reverse=True)]), flags=re.DOTALL) return pattern.sub(lambda x: replacements[x.group(0)], string)
<SYSTEM_TASK:> Returns a list of matching blocks of text in a and b <END_TASK> <USER_TASK:> Description: def get_matching_text_in_strs(a, b, match_min_size=30, ignore='', end_characters=''): # type: (str, str, int, str, str) -> List[str] """Returns a list of matching blocks of text in a and b Args: a (str): First string to match b (str): Second string to match match_min_size (int): Minimum block size to match on. Defaults to 30. ignore (str): Any characters to ignore in matching. Defaults to ''. end_characters (str): End characters to look for. Defaults to ''. Returns: List[str]: List of matching blocks of text """
compare = difflib.SequenceMatcher(lambda x: x in ignore) compare.set_seqs(a=a, b=b) matching_text = list() for match in compare.get_matching_blocks(): start = match.a text = a[start: start+match.size] if end_characters: prev_text = text while len(text) != 0 and text[0] in end_characters: text = text[1:] while len(text) != 0 and text[-1] not in end_characters: text = text[:-1] if len(text) == 0: text = prev_text if len(text) >= match_min_size: matching_text.append(text) return matching_text
<SYSTEM_TASK:> Set that we are expanding a sequence, and return whether a release is required by the caller. <END_TASK> <USER_TASK:> Description: def set_expanding(self): """Set that we are expanding a sequence, and return whether a release is required by the caller."""
status = not self.expanding if status: self.expanding = True return status
<SYSTEM_TASK:> Returns a generator that squashes two iterables into one. <END_TASK> <USER_TASK:> Description: def squash(self, a, b): """ Returns a generator that squashes two iterables into one. ``` ['this', 'that'], [[' and', ' or']] => ['this and', 'this or', 'that and', 'that or'] ``` """
return ((''.join(x) if isinstance(x, tuple) else x) for x in itertools.product(a, b))
<SYSTEM_TASK:> Get a string literal. <END_TASK> <USER_TASK:> Description: def get_literals(self, c, i, depth): """ Get a string literal. Gather all the literal chars up to opening curly or closing brace. Also gather chars between braces and commas within a group (is_expanding). """
result = [''] is_dollar = False try: while c: ignore_brace = is_dollar is_dollar = False if c == '$': is_dollar = True elif c == '\\': c = [self.get_escape(c, i)] elif not ignore_brace and c == '{': # Try and get the group index = i.index try: seq = self.get_sequence(next(i), i, depth + 1) if seq: c = seq except StopIteration: # Searched to end of string # and still didn't find it. i.rewind(i.index - index) elif self.is_expanding() and c in (',', '}'): # We are Expanding within a group and found a group delimiter # Return what we gathered before the group delimiters. i.rewind(1) return (x for x in result) # Squash the current set of literals. result = self.squash(result, [c] if isinstance(c, str) else c) c = next(i) except StopIteration: if self.is_expanding(): return None return (x for x in result)
<SYSTEM_TASK:> A generator that combines two iterables. <END_TASK> <USER_TASK:> Description: def combine(self, a, b): """A generator that combines two iterables."""
for l in (a, b): for x in l: yield x
<SYSTEM_TASK:> Get the sequence. <END_TASK> <USER_TASK:> Description: def get_sequence(self, c, i, depth): """ Get the sequence. Get sequence between `{}`, such as: `{a,b}`, `{1..2[..inc]}`, etc. It will basically crawl to the end or find a valid series. """
result = [] release = self.set_expanding() has_comma = False # Used to indicate validity of group (`{1..2}` are an exception). is_empty = True # Tracks whether the current slot is empty `{slot,slot,slot}`. # Detect numerical and alphabetic series: `{1..2}` etc. i.rewind(1) item = self.get_range(i) i.advance(1) if item is not None: self.release_expanding(release) return (x for x in item) try: while c: # Bash has some special top level logic. if `}` follows `{` but hasn't matched # a group yet, keep going except when the first 2 bytes are `{}` which gets # completely ignored. keep_looking = depth == 1 and not has_comma # and i.index not in self.skip_index if (c == '}' and (not keep_looking or i.index == 2)): # If there is no comma, we know the sequence is bogus. if is_empty: result = (x for x in self.combine(result, [''])) if not has_comma: result = ('{' + literal + '}' for literal in result) self.release_expanding(release) return (x for x in result) elif c == ',': # Must be the first element in the list. has_comma = True if is_empty: result = (x for x in self.combine(result, [''])) else: is_empty = True else: if c == '}': # Top level: If we didn't find a comma, we haven't # completed the top level group. Request more and # append to what we already have for the first slot. if not result: result = (x for x in self.combine(result, [c])) else: result = self.squash(result, [c]) value = self.get_literals(next(i), i, depth) if value is not None: result = self.squash(result, value) is_empty = False else: # Lower level: Try to find group, but give up if cannot acquire. value = self.get_literals(c, i, depth) if value is not None: result = (x for x in self.combine(result, value)) is_empty = False c = next(i) except StopIteration: self.release_expanding(release) raise
<SYSTEM_TASK:> Check and retrieve range if value is a valid range. <END_TASK> <USER_TASK:> Description: def get_range(self, i): """ Check and retrieve range if value is a valid range. Here we are looking to see if the value is series or range. We look for `{1..2[..inc]}` or `{a..z[..inc]}` (negative numbers are fine). """
try: m = i.match(RE_INT_ITER) if m: return self.get_int_range(*m.groups()) m = i.match(RE_CHR_ITER) if m: return self.get_char_range(*m.groups()) except Exception: # pragma: no cover # TODO: We really should never fail here, # but if we do, assume the sequence range # was invalid. This catch can probably # be removed in the future with more testing. pass return None
<SYSTEM_TASK:> Get padding adjusting for negative values. <END_TASK> <USER_TASK:> Description: def format_value(self, value, padding): """Get padding adjusting for negative values."""
# padding = padding - 1 if value < 0 and padding > 0 else padding # prefix = '-' if value < 0 else '' if padding: return "{:0{pad}d}".format(value, pad=padding) else: return str(value)
<SYSTEM_TASK:> Get an integer range between start and end and increments of increment. <END_TASK> <USER_TASK:> Description: def get_int_range(self, start, end, increment=None): """Get an integer range between start and end and increments of increment."""
first, last = int(start), int(end) increment = int(increment) if increment is not None else 1 max_length = max(len(start), len(end)) # Zero doesn't make sense as an incrementer # but like bash, just assume one if increment == 0: increment = 1 if start[0] == '-': start = start[1:] if end[0] == '-': end = end[1:] if (len(start) > 1 and start[0] == '0') or (len(end) > 1 and end[0] == '0'): padding = max_length else: padding = 0 if first < last: r = range(first, last + 1, -increment if increment < 0 else increment) else: r = range(first, last - 1, increment if increment < 0 else -increment) return (self.format_value(value, padding) for value in r)
<SYSTEM_TASK:> Merges b into a and returns merged result <END_TASK> <USER_TASK:> Description: def merge_two_dictionaries(a, b, merge_lists=False): # type: (DictUpperBound, DictUpperBound, bool) -> DictUpperBound """Merges b into a and returns merged result NOTE: tuples and arbitrary objects are not handled as it is totally ambiguous what should happen Args: a (DictUpperBound): dictionary to merge into b (DictUpperBound): dictionary to merge from merge_lists (bool): Whether to merge lists (True) or replace lists (False). Default is False. Returns: DictUpperBound: Merged dictionary """
key = None # ## debug output # sys.stderr.write('DEBUG: %s to %s\n' %(b,a)) try: if a is None or isinstance(a, (six.string_types, six.text_type, six.integer_types, float)): # border case for first run or if a is a primitive a = b elif isinstance(a, list): # lists can be appended or replaced if isinstance(b, list): if merge_lists: # merge lists a.extend(b) else: # replace list a = b else: # append to list a.append(b) elif isinstance(a, (dict, UserDict)): # dicts must be merged if isinstance(b, (dict, UserDict)): for key in b: if key in a: a[key] = merge_two_dictionaries(a[key], b[key], merge_lists=merge_lists) else: a[key] = b[key] else: raise ValueError('Cannot merge non-dict "%s" into dict "%s"' % (b, a)) else: raise ValueError('NOT IMPLEMENTED "%s" into "%s"' % (b, a)) except TypeError as e: raise ValueError('TypeError "%s" in key "%s" when merging "%s" into "%s"' % (e, key, b, a)) return a
<SYSTEM_TASK:> Merges all dictionaries in dicts into a single dictionary and returns result <END_TASK> <USER_TASK:> Description: def merge_dictionaries(dicts, merge_lists=False): # type: (List[DictUpperBound], bool) -> DictUpperBound """Merges all dictionaries in dicts into a single dictionary and returns result Args: dicts (List[DictUpperBound]): Dictionaries to merge into the first one in the list merge_lists (bool): Whether to merge lists (True) or replace lists (False). Default is False. Returns: DictUpperBound: Merged dictionary """
dict1 = dicts[0] for other_dict in dicts[1:]: merge_two_dictionaries(dict1, other_dict, merge_lists=merge_lists) return dict1
<SYSTEM_TASK:> Compares two dictionaries <END_TASK> <USER_TASK:> Description: def dict_diff(d1, d2, no_key='<KEYNOTFOUND>'): # type: (DictUpperBound, DictUpperBound, str) -> Dict """Compares two dictionaries Args: d1 (DictUpperBound): First dictionary to compare d2 (DictUpperBound): Second dictionary to compare no_key (str): What value to use if key is not found Defaults to '<KEYNOTFOUND>'. Returns: Dict: Comparison dictionary """
d1keys = set(d1.keys()) d2keys = set(d2.keys()) both = d1keys & d2keys diff = {k: (d1[k], d2[k]) for k in both if d1[k] != d2[k]} diff.update({k: (d1[k], no_key) for k in d1keys - both}) diff.update({k: (no_key, d2[k]) for k in d2keys - both}) return diff
<SYSTEM_TASK:> Add value to a list in a dictionary by key <END_TASK> <USER_TASK:> Description: def dict_of_lists_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a list in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to list in dictionary Returns: None """
list_objs = dictionary.get(key, list()) list_objs.append(value) dictionary[key] = list_objs
<SYSTEM_TASK:> Add value to a set in a dictionary by key <END_TASK> <USER_TASK:> Description: def dict_of_sets_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a set in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to set in dictionary Returns: None """
set_objs = dictionary.get(key, set()) set_objs.add(value) dictionary[key] = set_objs
<SYSTEM_TASK:> Extract a list by looking up key in each member of a list of dictionaries <END_TASK> <USER_TASK:> Description: def extract_list_from_list_of_dict(list_of_dict, key): # type: (List[DictUpperBound], Any) -> List """Extract a list by looking up key in each member of a list of dictionaries Args: list_of_dict (List[DictUpperBound]): List of dictionaries key (Any): Key to find in each dictionary Returns: List: List containing values returned from each dictionary """
result = list() for dictionary in list_of_dict: result.append(dictionary[key]) return result
<SYSTEM_TASK:> Convert keys of dictionary to integers <END_TASK> <USER_TASK:> Description: def integer_key_convert(dictin, dropfailedkeys=False): # type: (DictUpperBound, bool) -> Dict """Convert keys of dictionary to integers Args: dictin (DictUpperBound): Input dictionary dropfailedkeys (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False. Returns: Dict: Dictionary with keys converted to integers """
return key_value_convert(dictin, keyfn=int, dropfailedkeys=dropfailedkeys)
<SYSTEM_TASK:> Convert values of dictionary to integers <END_TASK> <USER_TASK:> Description: def integer_value_convert(dictin, dropfailedvalues=False): # type: (DictUpperBound, bool) -> Dict """Convert values of dictionary to integers Args: dictin (DictUpperBound): Input dictionary dropfailedvalues (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False. Returns: Dict: Dictionary with values converted to integers """
return key_value_convert(dictin, valuefn=int, dropfailedvalues=dropfailedvalues)
<SYSTEM_TASK:> Convert values of dictionary to floats <END_TASK> <USER_TASK:> Description: def float_value_convert(dictin, dropfailedvalues=False): # type: (DictUpperBound, bool) -> Dict """Convert values of dictionary to floats Args: dictin (DictUpperBound): Input dictionary dropfailedvalues (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False. Returns: Dict: Dictionary with values converted to floats """
return key_value_convert(dictin, valuefn=float, dropfailedvalues=dropfailedvalues)
<SYSTEM_TASK:> Create a new dictionary from two dictionaries by averaging values <END_TASK> <USER_TASK:> Description: def avg_dicts(dictin1, dictin2, dropmissing=True): # type: (DictUpperBound, DictUpperBound, bool) -> Dict """Create a new dictionary from two dictionaries by averaging values Args: dictin1 (DictUpperBound): First input dictionary dictin2 (DictUpperBound): Second input dictionary dropmissing (bool): Whether to drop keys missing in one dictionary. Defaults to True. Returns: Dict: Dictionary with values being average of 2 input dictionaries """
dictout = dict() for key in dictin1: if key in dictin2: dictout[key] = (dictin1[key] + dictin2[key]) / 2 elif not dropmissing: dictout[key] = dictin1[key] if not dropmissing: for key in dictin2: if key not in dictin1: dictout[key] = dictin2[key] return dictout
<SYSTEM_TASK:> Convert command line arguments in a comma separated string to a dictionary <END_TASK> <USER_TASK:> Description: def args_to_dict(args): # type: (str) -> DictUpperBound[str,str] """Convert command line arguments in a comma separated string to a dictionary Args: args (str): Command line arguments Returns: DictUpperBound[str,str]: Dictionary of arguments """
arguments = dict() for arg in args.split(','): key, value = arg.split('=') arguments[key] = value return arguments
<SYSTEM_TASK:> Returns the delta between two files using -, ?, + format excluding <END_TASK> <USER_TASK:> Description: def compare_files(path1, path2): # type: (str, str) -> List[str] """Returns the delta between two files using -, ?, + format excluding lines that are the same Args: path1 (str): Path to first file path2 (str): Path to second file Returns: List[str]: Delta between the two files """
diff = difflib.ndiff(open(path1).readlines(), open(path2).readlines()) return [x for x in diff if x[0] in ['-', '+', '?']]
<SYSTEM_TASK:> Asserts that two files are the same and returns delta using <END_TASK> <USER_TASK:> Description: def assert_files_same(path1, path2): # type: (str, str) -> None """Asserts that two files are the same and returns delta using -, ?, + format if not Args: path1 (str): Path to first file path2 (str): Path to second file Returns: None """
difflines = compare_files(path1, path2) assert len(difflines) == 0, ''.join(['\n'] + difflines)
<SYSTEM_TASK:> Apply the HTTPError wrapper to the callback. <END_TASK> <USER_TASK:> Description: def apply(self, callback, context): # pragma: no cover """Apply the HTTPError wrapper to the callback. """
def wrapper(*args, **kwargs): try: return callback(*args, **kwargs) except bottle.HTTPError as error: return self.error_wrapper.from_status( status_line=error.status_line, msg=error.body ) return wrapper
<SYSTEM_TASK:> Add a new episode to the podcast. <END_TASK> <USER_TASK:> Description: def add_episode(self, text, text_format, title, author, summary=None, publish_date=None, synthesizer='watson', synth_args=None, sentence_break='. '): """ Add a new episode to the podcast. :param text: See :meth:`Episode`. :param text_format: See :meth:`Episode`. :param title: See :meth:`Episode`. :param author: See :meth:`Episode`. :param summary: See :meth:`Episode`. :param publish_date: See :meth:`Episode`. :param synthesizer: See :meth:`typecaster.utils.text_to_speech`. :param synth_args: See :meth:`typecaster.utils.text_to_speech`. :param sentence_break: See :meth:`typecaster.utils.text_to_speech`. """
if title in self.episodes: raise ValueError('"' + title + '" already exists as an episode title.') link = self.output_path + '/' + title.replace(' ', '_').lower() + '.mp3' episode_text = convert_to_ssml(text, text_format) new_episode = Episode(episode_text, text_format, title, author, link, summary, publish_date, synthesizer, synth_args, sentence_break) self.episodes[title] = new_episode
<SYSTEM_TASK:> Add and start a new scheduled job to dynamically generate podcasts. <END_TASK> <USER_TASK:> Description: def add_scheduled_job(self, text_source, cron_args, text_format, title, author, summary=None, synthesizer='watson', synth_args=None, sentence_break='. '): """ Add and start a new scheduled job to dynamically generate podcasts. Note: scheduling will end when the process ends. This works best when run inside an existing application. :param text_source: A function that generates podcast text. Examples: a function that opens a file with today's date as a filename or a function that requests a specific url and extracts the main text. Also see :meth:`Episode`. :param cron_args: A dictionary of cron parameters. Keys can be: 'year', 'month', 'day', 'week', 'day_of_week', 'hour', 'minute' and 'second'. Keys that are not specified will be parsed as 'any'/'*'. :param text_format: See :meth:`Episode`. :param title: See :meth:`Episode`. Since titles need to be unique, a timestamp will be appended to the title for each episode. :param author: See :meth:`Episode`. :param summary: See :meth:`Episode`. :param publish_date: See :meth:`Episode`. :param synthesizer: See :meth:`typecaster.utils.text_to_speech`. :param synth_args: See :meth:`typecaster.utils.text_to_speech`. :param sentence_break: See :meth:`typecaster.utils.text_to_speech`. """
if not callable(text_source): raise TypeError('Argument "text" must be a function') def add_episode(): episode_text = text_source() episode_title = title + '_' + datetime.utcnow().strftime('%Y%m%d%H%M%S') self.add_episode(episode_text, text_format, episode_title, author, summary, datetime.utcnow(), synthesizer, synth_args, sentence_break) self.scheduled_jobs[title] = self._scheduler.add_job(add_episode, 'cron', id=title, **cron_args) if not self._scheduler.running: self._scheduler.start()
<SYSTEM_TASK:> Publish a set of episodes to the Podcast's RSS feed. <END_TASK> <USER_TASK:> Description: def publish(self, titles): """ Publish a set of episodes to the Podcast's RSS feed. :param titles: Either a single episode title or a sequence of episode titles to publish. """
if isinstance(titles, Sequence) and not isinstance(titles, six.string_types): for title in titles: self.episodes[title].publish() elif isinstance(titles, six.string_types): self.episodes[titles].publish() else: raise TypeError('titles must be a string or a sequence of strings.') self.update_rss_feed()
<SYSTEM_TASK:> Synthesize audio from the episode's text. <END_TASK> <USER_TASK:> Description: def render_audio(self): """ Synthesize audio from the episode's text. """
segment = text_to_speech(self._text, self.synthesizer, self.synth_args, self.sentence_break) milli = len(segment) seconds = '{0:.1f}'.format(float(milli) / 1000 % 60).zfill(2) minutes = '{0:.0f}'.format((milli / (1000 * 60)) % 60).zfill(2) hours = '{0:.0f}'.format((milli / (1000 * 60 * 60)) % 24).zfill(2) self.duration = hours + ':' + minutes + ':' + seconds segment.export(self.link, format='mp3') self.length = os.path.getsize(self.link)
<SYSTEM_TASK:> Mark an episode as published. <END_TASK> <USER_TASK:> Description: def publish(self): """ Mark an episode as published. """
if self.published is False: self.published = True else: raise Warning(self.title + ' is already published.')
<SYSTEM_TASK:> Mark an episode as not published. <END_TASK> <USER_TASK:> Description: def unpublish(self): """ Mark an episode as not published. """
if self.published is True: self.published = False else: raise Warning(self.title + ' is already not published.')
<SYSTEM_TASK:> Construct user agent <END_TASK> <USER_TASK:> Description: def _construct(configdict, prefix, ua): # type: (Dict, str, str) -> str """ Construct user agent Args: configdict (str): Additional configuration for user agent prefix (str): Text to put at start of user agent ua (str): Custom user agent text Returns: str: Full user agent string """
if not ua: raise UserAgentError("User_agent parameter missing. It can be your project's name for example.") preprefix = configdict.get('preprefix') if preprefix: user_agent = '%s:' % preprefix else: user_agent = '' if prefix: user_agent = '%s%s-' % (user_agent, prefix) user_agent = '%s%s' % (user_agent, ua) return user_agent
<SYSTEM_TASK:> Get full user agent string <END_TASK> <USER_TASK:> Description: def _create(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> str """ Get full user agent string Args: user_agent (Optional[str]): User agent string. HDXPythonLibrary/X.X.X- is prefixed. user_agent_config_yaml (Optional[str]): Path to YAML user agent configuration. Ignored if user_agent supplied. Defaults to ~/.useragent.yml. user_agent_lookup (Optional[str]): Lookup key for YAML. Ignored if user_agent supplied. Returns: str: Full user agent string """
kwargs = UserAgent._environment_variables(**kwargs) if 'user_agent' in kwargs: user_agent = kwargs['user_agent'] del kwargs['user_agent'] prefix = kwargs.get('prefix') if prefix: del kwargs['prefix'] else: prefix = 'HDXPythonUtilities/%s' % get_utils_version() if not user_agent: ua = cls._load(prefix, user_agent_config_yaml, user_agent_lookup) else: ua = cls._construct(kwargs, prefix, user_agent) return ua
<SYSTEM_TASK:> Get full user agent string from parameters if supplied falling back on global user agent if set. <END_TASK> <USER_TASK:> Description: def get(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> str """ Get full user agent string from parameters if supplied falling back on global user agent if set. Args: user_agent (Optional[str]): User agent string. HDXPythonLibrary/X.X.X- is prefixed. user_agent_config_yaml (Optional[str]): Path to YAML user agent configuration. Ignored if user_agent supplied. Defaults to ~/.useragent.yml. user_agent_lookup (Optional[str]): Lookup key for YAML. Ignored if user_agent supplied. Returns: str: Full user agent string """
if user_agent or user_agent_config_yaml or 'user_agent' in UserAgent._environment_variables(**kwargs): return UserAgent._create(user_agent, user_agent_config_yaml, user_agent_lookup, **kwargs) if cls.user_agent: return cls.user_agent else: raise UserAgentError( 'You must either set the global user agent: UserAgent.set_global(...) or pass in user agent parameters!')
<SYSTEM_TASK:> Save dictionary to YAML file preserving order if it is an OrderedDict <END_TASK> <USER_TASK:> Description: def save_yaml(dictionary, path, pretty=False, sortkeys=False): # type: (Dict, str, bool, bool) -> None """Save dictionary to YAML file preserving order if it is an OrderedDict Args: dictionary (Dict): Python dictionary to save path (str): Path to YAML file pretty (bool): Whether to pretty print. Defaults to False. sortkeys (bool): Whether to sort dictionary keys. Defaults to False. Returns: None """
if sortkeys: dictionary = dict(dictionary) with open(path, 'w') as f: if pretty: pyaml.dump(dictionary, f) else: yaml.dump(dictionary, f, default_flow_style=None, Dumper=yamlloader.ordereddict.CDumper)
<SYSTEM_TASK:> Save dictionary to JSON file preserving order if it is an OrderedDict <END_TASK> <USER_TASK:> Description: def save_json(dictionary, path, pretty=False, sortkeys=False): # type: (Dict, str, bool, bool) -> None """Save dictionary to JSON file preserving order if it is an OrderedDict Args: dictionary (Dict): Python dictionary to save path (str): Path to JSON file pretty (bool): Whether to pretty print. Defaults to False. sortkeys (bool): Whether to sort dictionary keys. Defaults to False. Returns: None """
with open(path, 'w') as f: if pretty: indent = 2 separators = (',', ': ') else: indent = None separators = (', ', ': ') json.dump(dictionary, f, indent=indent, sort_keys=sortkeys, separators=separators)
<SYSTEM_TASK:> Load YAML file into an ordered dictionary <END_TASK> <USER_TASK:> Description: def load_yaml(path): # type: (str) -> OrderedDict """Load YAML file into an ordered dictionary Args: path (str): Path to YAML file Returns: OrderedDict: Ordered dictionary containing loaded YAML file """
with open(path, 'rt') as f: yamldict = yaml.load(f.read(), Loader=yamlloader.ordereddict.CSafeLoader) if not yamldict: raise (LoadError('YAML file: %s is empty!' % path)) return yamldict
<SYSTEM_TASK:> Load JSON file into an ordered dictionary <END_TASK> <USER_TASK:> Description: def load_json(path): # type: (str) -> OrderedDict """Load JSON file into an ordered dictionary Args: path (str): Path to JSON file Returns: OrderedDict: Ordered dictionary containing loaded JSON file """
with open(path, 'rt') as f: jsondict = json.loads(f.read(), object_pairs_hook=OrderedDict) if not jsondict: raise (LoadError('JSON file: %s is empty!' % path)) return jsondict
<SYSTEM_TASK:> Load file into a string removing newlines <END_TASK> <USER_TASK:> Description: def load_file_to_str(path): # type: (str) -> str """ Load file into a string removing newlines Args: path (str): Path to file Returns: str: String contents of file """
with open(path, 'rt') as f: string = f.read().replace(linesep, '') if not string: raise LoadError('%s file is empty!' % path) return string