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 lint(relative_path_to_file, contents, linter_functions, **kwargs): r"""Actually lints some file contents. relative_path_to_file should contain the relative path to the file being linted from the root source directory. Contents should be a raw string with \n's. """
lines = contents.splitlines(True) errors = list() for (code, info) in linter_functions.items(): error = info.function(relative_path_to_file, lines, kwargs) if error: if isinstance(error, list): errors.extend([(code, e) for e in error]) else: errors.append((code, error)) errors = [e for e in errors if not _error_is_suppressed(e[1], e[0], lines)] return sorted(errors, key=lambda e: e[1].line)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def linter_functions_from_filters(whitelist=None, blacklist=None): """Yield tuples of _LinterFunction matching whitelist but not blacklist."""
def _keyvalue_pair_if(dictionary, condition): """Return a key-value pair in dictionary if condition matched.""" return { k: v for (k, v) in dictionary.items() if condition(k) } def _check_list(check_list, cond): """Return function testing against a list if the list exists.""" def _check_against_list(key): """Return true if list exists and condition passes.""" return cond(check_list, key) if check_list is not None else True return _check_against_list linter_functions = LINTER_FUNCTIONS linter_functions = _keyvalue_pair_if(linter_functions, _check_list(whitelist, lambda l, k: k in l)) linter_functions = _keyvalue_pair_if(linter_functions, _check_list(blacklist, lambda l, k: k not in l)) for code, linter_function in linter_functions.items(): yield (code, linter_function)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _report_lint_error(error, file_path): """Report a linter error."""
line = error[1].line code = error[0] description = error[1].description sys.stdout.write("{0}:{1} [{2}] {3}\n".format(file_path, line, code, 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 _apply_replacement(error, found_file, file_lines): """Apply a single replacement."""
fixed_lines = file_lines fixed_lines[error[1].line - 1] = error[1].replacement concatenated_fixed_lines = "".join(fixed_lines) # Only fix one error at a time found_file.seek(0) found_file.write(concatenated_fixed_lines) found_file.truncate()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _obtain_queue(num_jobs): """Return queue type most appropriate for runtime model. If we are using multiprocessing, that should be multiprocessing.Manager().Queue. If we are just using a single process, then use a normal queue type. """
if _should_use_multiprocessing(num_jobs): return ReprQueue(multiprocessing.Manager().Queue()) return ReprQueue(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 tool_options_from_global(global_options, num_jobs): """From an argparse namespace, get a dict of options for the tools."""
internal_opt = ["whitelist", "blacklist", "fix_what_you_can"] queue_object = _obtain_queue(num_jobs) translate = defaultdict(lambda: (lambda x: x), log_technical_terms_to=lambda _: queue_object) tool_options = OrderedDict() for key in sorted(global_options.keys()): if key not in internal_opt and global_options[key] is not None: tool_options[key] = translate[key](global_options[key]) return tool_options
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_lint_on_file_stamped_args(file_path, # suppress(too-many-arguments) stamp_file_path, log_technical_terms_to, linter_functions, tool_options, fix_what_you_can): """Return tuple of args and kwargs that function would be called with."""
dictionary_path = os.path.abspath("DICTIONARY") dependencies = [file_path] if os.path.exists(dictionary_path): dependencies.append(dictionary_path) kwargs = OrderedDict() kwargs["jobstamps_dependencies"] = dependencies kwargs["jobstamps_cache_output_directory"] = stamp_file_path if log_technical_terms_to: kwargs["jobstamps_output_files"] = [log_technical_terms_to] return ((file_path, linter_functions, tool_options, fix_what_you_can), kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_lint_on_file_stamped(*args): """Run linter functions on file_path, stamping in stamp_file_path."""
# We pass an empty dictionary as keyword arguments here to work # around a bug in frosted, which crashes when no keyword arguments # are passed # # suppress(E204) stamp_args, stamp_kwargs = _run_lint_on_file_stamped_args(*args, **{}) return jobstamp.run(_run_lint_on_file_exceptions, *stamp_args, **stamp_kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ordered(generator, *args, **kwargs): """Sort keys of unordered_dict and store in OrderedDict."""
unordered_dict = {k: v for k, v in generator(*args, **kwargs)} keys = sorted(list(dict(unordered_dict).keys())) result = OrderedDict() for key in keys: result[key] = unordered_dict[key] return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _any_would_run(func, filenames, *args): """True if a linter function would be called on any of filenames."""
if os.environ.get("_POLYSQUARE_GENERIC_FILE_LINTER_NO_STAMPING", None): return True for filename in filenames: # suppress(E204) stamp_args, stamp_kwargs = _run_lint_on_file_stamped_args(filename, *args, **{}) dependency = jobstamp.out_of_date(func, *stamp_args, **stamp_kwargs) if dependency: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(arguments=None): # suppress(unused-function) """Entry point for the linter."""
result = _parse_arguments(arguments) linter_funcs = _ordered(linter_functions_from_filters, result.whitelist, result.blacklist) global_options = vars(result) tool_options = tool_options_from_global(global_options, len(result.files)) any_would_run = _any_would_run(_run_lint_on_file_exceptions, result.files, result.stamp_file_path, result.log_technical_terms_to, linter_funcs, tool_options, result.fix_what_you_can) if any_would_run: for linter_function in linter_funcs.values(): if linter_function.before_all: linter_function.before_all(global_options, tool_options) use_multiprocessing = _should_use_multiprocessing(len(result.files)) else: use_multiprocessing = False if use_multiprocessing: mapper = parmap.map else: # suppress(E731) mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i] errors = list(itertools.chain(*mapper(_run_lint_on_file_stamped, result.files, result.stamp_file_path, result.log_technical_terms_to, linter_funcs, tool_options, result.fix_what_you_can))) for error in sorted(errors): _report_lint_error(error.failure, os.path.relpath(error.absolute_path)) if any_would_run: for linter_funcs in linter_funcs.values(): if linter_funcs.after_all: linter_funcs.after_all(global_options, tool_options) return len(errors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, item, block=True, timeout=None): """Put item into underlying queue."""
return self._queue.put(item, block, timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, block=True, timeout=None): """Get item from underlying queue."""
return self._queue.get(block, timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def snake_to_camel(snake_str): ''' Convert `snake_str` from snake_case to camelCase ''' components = snake_str.split('_') if len(components) > 1: camel = (components[0].lower() + ''.join(x.title() for x in components[1:])) return camel # Not snake_case return snake_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 snake_to_pascal(snake_str): ''' Convert `snake_str` from snake_case to PascalCase ''' components = snake_str.split('_') if len(components) > 1: camel = ''.join(x.title() for x in components) return camel # Not snake_case return snake_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 camel_to_snake(camel_str): ''' Convert `camel_str` from camelCase to snake_case ''' # Attribution: https://stackoverflow.com/a/1176023/633213 s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_str) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_logging(cfg_obj): """ Enable or disable logging per config object parameter """
log_status = cfg_obj['LOGGING']['ENABLE_LOGGING'] if log_status: logger.disabled = False elif not log_status: logger.info( '%s: Logging disabled per local configuration file (%s) parameters.' % (inspect.stack()[0][3], cfg_obj['PROJECT']['CONFIG_PATH']) ) logger.disabled = True return log_status
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def precheck(): """ Verify project runtime dependencies """
cfg_path = local_config['PROJECT']['CONFIG_PATH'] # enable or disable logging based on config/ defaults logging = set_logging(local_config) if os.path.exists(cfg_path): logger.info('%s: config_path parameter: %s' % (inspect.stack()[0][3], cfg_path)) logger.info( '%s: Existing configuration file found. precheck pass.' % (inspect.stack()[0][3])) return True elif not os.path.exists(cfg_path) and logging is False: logger.info( '%s: No pre-existing configuration file found at %s. Using defaults. Logging disabled.' % (inspect.stack()[0][3], cfg_path) ) return True if logging: logger.info( '%s: Logging enabled per config file (%s).' % (inspect.stack()[0][3], cfg_path) ) return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(operation, profile, auto, debug, user_name=''): """ End-to-end renew of access keys for a specific profile in local awscli config """
if user_name: logger.info('user_name parameter given (%s) as surrogate' % user_name) try: if operation in VALID_INSTALL: print(operation) elif operation == 'list': print(operation) return True elif not operation: msg_accent = (Colors.BOLD + 'list' + Colors.RESET + ' | ' + Colors.BOLD + 'up' + Colors.RESET) msg = """You must provide a valid OPERATION for --operation parameter: --operation { """ + msg_accent + """ } """ stdout_message(msg) logger.warning('%s: No valid operation provided. Exit' % (inspect.stack()[0][3])) sys.exit(exit_codes['E_MISC']['Code']) else: msg = 'Unknown operation. Exit' stdout_message(msg) logger.warning('%s: %s' % (msg, inspect.stack()[0][3])) sys.exit(exit_codes['E_MISC']['Code']) except KeyError as e: logger.critical( '%s: Cannot find Key %s' % (inspect.stack()[0][3], str(e))) return False except OSError as e: logger.critical( '%s: problem writing to file %s. Error %s' % (inspect.stack()[0][3], output_file, str(e))) return False except Exception as e: logger.critical( '%s: Unknown error. Error %s' % (inspect.stack()[0][3], str(e))) raise e
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chooser_menu(): """ Master jump off point to ancillary functionality """
title = TITLE + "The" + Colors.ORANGE + " Metal" + Colors.RESET + TITLE + " Menu" + RESET menu = """ ________________________________________________________________ """ + title + """ ________________________________________________________________ ( """ + TITLE + "a" + RESET + """ ) : Install RKhunter Rootkit Scanner (v1.6) ( """ + TITLE + "b" + RESET + """ ) : Install Chkrootkit Rootkit Scanner (latest) ( """ + TITLE + "c" + RESET + """ ) : Run RKhunter Scan of Local Machine ( """ + TITLE + "d" + RESET + """ ) : Run Chkrootkit Scan of Local Machine """ print(menu) answer: str = input("\t\tEnter Choice [quit]: ") or '' if answer == 'a': return rkhunter() elif answer == 'b': print('\t\nrun chkrootkit installer\n') return chkrootkit.main() elif answer == 'c': print('\t\nrun rkhunter scan of local machine\n') elif answer == 'd': return chkrootkit_exec() return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, mode, disable): """ create logger object, enable or disable logging """
global logger try: if logger: if disable: logger.disabled = True else: if mode in ('STREAM', 'FILE'): logger = logd.getLogger(mode, __version__) except Exception as e: logger.exception( '%s: Problem incurred during logging setup' % inspect.stack()[0][3] ) return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _translate(unistr, table): '''Replace characters using a table.''' if type(unistr) is str: try: unistr = unistr.decode('utf-8') # Python 3 returns AttributeError when .decode() is called on a str # This means it is already unicode. except AttributeError: pass try: if type(unistr) is not unicode: return unistr # Python 3 returns NameError because unicode is not a type. except NameError: pass chars = [] for c in unistr: replacement = table.get(c) chars.append(replacement if replacement else c) return u''.join(chars)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def eval_conditions(conditions=None, data={}): ''' Evaluates conditions and returns Boolean value. Args: conditions (tuple) for the format of the tuple, see below data (dict) the keys of which can be used in conditions Returns: (boolea) Raises: ValueError if an invalid operator value is specified TypeError if: conditions are not a 3-item tuple the arguments of the condition don't have the same type e.g. ('abc', 'eq', 3) if a boolean operator does not get boolean arguments e.g. (True, 'and', 15) The format of the condition tuple is: (arg1, op, arg2) where: arg1, arg2 can be numerical values, strings or condition tuples op is a valid operator from the operator module If arg is a string, and the string is a key in <data> it is treated as a variable with value data[arg]. Notes: * If no conditions are specified True is returned. * empty or 0 values do *not* evaluate to booleans ''' #CONSIDER: implementing addition/subtraction/multiplication/division if not conditions: return True if isinstance(conditions, str) or isinstance(conditions, unicode): conditions = str2tuple(conditions) if not isinstance(conditions, tuple) or not len(conditions) == 3: raise TypeError('conditions must be a tuple with 3 items.') arg1 = conditions[0] op = conditions[1] arg2 = conditions[2] if arg1 in data: arg1 = data[arg1] elif isinstance(arg1, tuple): arg1 = eval_conditions(arg1, data) if arg2 in data: arg2 = data[arg2] elif isinstance(arg2, tuple): arg2 = eval_conditions(arg2, data) if op in ('lt', 'le', 'eq', 'ne', 'ge', 'gt'): if not (type(arg1) in (float, int) and type(arg2) in (float,int)) and \ type(arg1) != type(arg2): raise TypeError('both arguments must have the same type {}, {}'.\ format(arg1, arg2)) elif op in ('and', 'or'): if not isinstance(arg1, bool) or not isinstance(arg2, bool): raise TypeError('boolean operator {} needs boolean arguments {},'\ ' {}'.format(op, arg1, arg2)) op += '_' else: raise ValueError('operator {} not supported', op) return getattr(operator, op)(arg1, arg2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deep_force_unicode(value): """ Recursively call force_text on value. """
if isinstance(value, (list, tuple, set)): value = type(value)(map(deep_force_unicode, value)) elif isinstance(value, dict): value = type(value)(map(deep_force_unicode, value.items())) elif isinstance(value, Promise): value = force_text(value) return value
<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_settings_docs(docs_path, prefix=None): """ Converts names, descriptions and defaults for settings in ``yacms.conf.registry`` into RST format for use in docs, optionally filtered by setting names with the given prefix. """
# String to use instead of setting value for dynamic defaults dynamic = "[dynamic]" lines = [".. THIS DOCUMENT IS AUTO GENERATED VIA conf.py"] for name in sorted(registry.keys()): if prefix and not name.startswith(prefix): continue setting = registry[name] settings_name = "``%s``" % name settings_label = ".. _%s:" % name setting_default = setting["default"] if isinstance(setting_default, str): if gethostname() in setting_default or ( setting_default.startswith("/") and os.path.exists(setting_default)): setting_default = dynamic if setting_default != dynamic: setting_default = repr(deep_force_unicode(setting_default)) lines.extend(["", settings_label]) lines.extend(["", settings_name, "-" * len(settings_name)]) lines.extend(["", urlize(setting["description"] or "").replace( "<a href=\"", "`").replace( "\" rel=\"nofollow\">", " <").replace( "</a>", ">`_")]) if setting["choices"]: choices = ", ".join(["%s: ``%s``" % (str(v), force_text(k)) for k, v in setting["choices"]]) lines.extend(["", "Choices: %s" % choices, ""]) lines.extend(["", "Default: ``%s``" % setting_default]) with open(os.path.join(docs_path, "settings.rst"), "w") as f: f.write("\n".join(lines).replace("u'", "'").replace("yo'", "you'").replace("&#39;", "'"))
<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_modelgraph(docs_path, package_name="yacms"): """ Creates a diagram of all the models for yacms and the given package name, generates a smaller version and add it to the docs directory for use in model-graph.rst """
to_path = os.path.join(docs_path, "img", "graph.png") build_path = os.path.join(docs_path, "build", "_images") resized_path = os.path.join(os.path.dirname(to_path), "graph-small.png") settings = import_dotted_path(package_name + ".project_template.project_name.settings") apps = [a.rsplit(".")[1] for a in settings.INSTALLED_APPS if a.startswith("yacms.") or a.startswith(package_name + ".")] try: from django_extensions.management.commands import graph_models except ImportError: warn("Couldn't build model_graph, django_extensions not installed") else: options = {"inheritance": True, "outputfile": "graph.png", "layout": "dot"} try: graph_models.Command().execute(*apps, **options) except Exception as e: warn("Couldn't build model_graph, graph_models failed on: %s" % e) else: try: move("graph.png", to_path) except OSError as e: warn("Couldn't build model_graph, move failed on: %s" % e) # docs/img/graph.png should exist in the repo - move it to the build path. try: if not os.path.exists(build_path): os.makedirs(build_path) copyfile(to_path, os.path.join(build_path, "graph.png")) except OSError as e: warn("Couldn't build model_graph, copy to build failed on: %s" % e) try: from PIL import Image image = Image.open(to_path) image.width = 800 image.height = image.size[1] * 800 // image.size[0] image.save(resized_path, "PNG", quality=100) except Exception as e: warn("Couldn't build model_graph, resize failed on: %s" % e) return # Copy the dashboard screenshot to the build dir too. This doesn't # really belong anywhere, so we do it here since this is the only # spot we deal with doc images. d = "dashboard.png" copyfile(os.path.join(docs_path, "img", d), os.path.join(build_path, d))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_requirements(docs_path, package_name="yacms"): """ Updates the requirements file with yacms's version number. """
mezz_string = "yacms==" project_path = os.path.join(docs_path, "..") requirements_file = os.path.join(project_path, package_name, "project_template", "requirements.txt") with open(requirements_file, "r") as f: requirements = f.readlines() with open(requirements_file, "w") as f: f.write("yacms==%s\n" % __version__) for requirement in requirements: if requirement.strip() and not requirement.startswith(mezz_string): f.write(requirement)
<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_flagged_blocks(self, content: str) -> str: '''Replace flagged blocks either with their contents or nothing, depending on the value of ``FOLIANT_FLAGS`` environment variable and ``flags`` config value. :param content: Markdown content :returns: Markdown content without flagged blocks ''' def _sub(flagged_block): options = self.get_options(flagged_block.group('options')) required_flags = { flag.lower() for flag in re.split(self._flag_delimiters, options.get('flags', '')) if flag } | { f'target:{target.lower()}' for target in re.split(self._flag_delimiters, options.get('targets', '')) if target } | { f'backend:{backend.lower()}' for backend in re.split(self._flag_delimiters, options.get('backends', '')) if backend } env_flags = { flag.lower() for flag in re.split(self._flag_delimiters, getenv(self._flags_envvar, '')) if flag } config_flags = {flag.lower() for flag in self.options['flags']} set_flags = env_flags \ | config_flags \ | {f'target:{self.context["target"]}', f'backend:{self.context["backend"]}'} kind = options.get('kind', 'all') if (kind == 'all' and required_flags <= set_flags) \ or (kind == 'any' and required_flags & set_flags) \ or (kind == 'none' and not required_flags & set_flags): return flagged_block.group('body').strip() else: return '' return self.pattern.sub(_sub, content)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def form(request): """ Ajax handler for Google Form submition """
if request.method == 'POST': url = request.POST['url'] submit_url = '%s%shl=%s' % ( url, '&' if '?' in url else '?', request.LANGUAGE_CODE ) params = urllib.urlencode(request.POST) f = urllib2.urlopen(submit_url, params) text = f.read() else: text = _('Error: request type has to be POST') response = http.HttpResponse(text, mimetype="text/plain") return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def signup(request, **kwargs): """ Overrides allauth.account.views.signup """
if not ALLAUTH: return http.HttpResponse(_('allauth not installed...')) if request.method == "POST" and 'login' in request.POST: form_class = LoginForm form = form_class(request.POST) redirect_field_name = "next" success_url = get_default_redirect(request, redirect_field_name) if form.is_valid(): return form.login(request, redirect_url=success_url) response = allauth_signup(request, **kwargs) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_operation(self, method="GET", ops_path="", payload=""): """ Executes a Kubernetes operation using the specified method against a path. This is part of the low-level API. :Parameters: - `method`: The HTTP method to use, defaults to `GET` - `ops_path`: The path of the operation, for example, `/api/v1/events` which would result in an overall: `GET http://localhost:8080/api/v1/events` - `payload`: The optional payload which is relevant for `POST` or `PUT` methods only """
operation_path_URL = "".join([self.api_server, ops_path]) logging.debug("%s %s" %(method, operation_path_URL)) if payload == "": res = requests.request(method, operation_path_URL) else: logging.debug("PAYLOAD:\n%s" %(payload)) res = requests.request(method, operation_path_URL, data=payload) logging.debug("RESPONSE:\n%s" %(res.json())) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_rc(self, manifest_filename, namespace="default"): """ Creates an RC based on a manifest. :Parameters: - `manifest_filename`: The manifest file containing the ReplicationController definition, for example: `manifest/nginx-webserver-rc.yaml` - `namespace`: In which namespace the RC should be created, defaults to, well, `default` """
rc_manifest, rc_manifest_json = util.load_yaml(filename=manifest_filename) logging.debug("%s" %(rc_manifest_json)) create_rc_path = "".join(["/api/v1/namespaces/", namespace, "/replicationcontrollers"]) res = self.execute_operation(method="POST", ops_path=create_rc_path, payload=rc_manifest_json) try: rc_url = res.json()["metadata"]["selfLink"] except KeyError: raise ResourceCRUDException("".join(["Sorry, can not create the RC: ", rc_manifest["metadata"]["name"], ". Maybe it exists already?"])) logging.info("From %s I created the RC %s at %s" %(manifest_filename, rc_manifest["metadata"]["name"], rc_url)) return (res, rc_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 scale_rc(self, manifest_filename, namespace="default", num_replicas=0): """ Changes the replicas of an RC based on a manifest. Note that it defaults to 0, meaning to effectively disable this RC. :Parameters: - `manifest_filename`: The manifest file containing the ReplicationController definition, for example: `manifest/nginx-webserver-rc.yaml` - `namespace`: In which namespace the RC is, defaulting to `default` - `num_replicas`: How many copies of the pods that match the selector are supposed to run """
rc_manifest, rc_manifest_json = util.load_yaml(filename=manifest_filename) logging.debug("%s" %(rc_manifest_json)) rc_path = "".join(["/api/v1/namespaces/", namespace, "/replicationcontrollers/", rc_manifest["metadata"]["name"]]) rc_manifest["spec"]["replicas"] = num_replicas res = self.execute_operation(method="PUT", ops_path=rc_path, payload=util.serialize_tojson(rc_manifest)) try: rc_url = res.json()["metadata"]["selfLink"] except KeyError: raise ResourceCRUDException("".join(["Sorry, can not scale the RC: ", rc_manifest["metadata"]["name"]])) logging.info("I scaled the RC %s at %s to %d replicas" %(rc_manifest["metadata"]["name"], rc_url, num_replicas)) return (res, rc_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 create_svc(self, manifest_filename, namespace="default"): """ Creates a service based on a manifest. :Parameters: - `manifest_filename`: The manifest file containing the service definition, for example: `manifest/webserver-svc.yaml` - `namespace`: In which namespace the service should be created, defaults to, well, `default` """
svc_manifest, svc_manifest_json = util.load_yaml(filename=manifest_filename) logging.debug("%s" %(svc_manifest_json)) create_svc_path = "".join(["/api/v1/namespaces/", namespace, "/services"]) res = self.execute_operation(method="POST", ops_path=create_svc_path, payload=svc_manifest_json) try: svc_url = res.json()["metadata"]["selfLink"] except KeyError: raise ResourceCRUDException("".join(["Sorry, can not create the service: ", svc_manifest["metadata"]["name"], ". Maybe it exists already?"])) logging.info("From %s I created the service %s at %s" %(manifest_filename, svc_manifest["metadata"]["name"], svc_url)) return (res, svc_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 set_site(request): """ Put the selected site ID into the session - posted to from the "Select site" drop-down in the header of the admin. The site ID is then used in favour of the current request's domain in ``yacms.core.managers.CurrentSiteManager``. """
site_id = int(request.GET["site_id"]) if not request.user.is_superuser: try: SitePermission.objects.get(user=request.user, sites=site_id) except SitePermission.DoesNotExist: raise PermissionDenied request.session["site_id"] = site_id admin_url = reverse("admin:index") next = next_url(request) or admin_url # Don't redirect to a change view for an object that won't exist # on the selected site - go to its list view instead. if next.startswith(admin_url): parts = next.split("/") if len(parts) > 4 and parts[4].isdigit(): next = "/".join(parts[:4]) return redirect(next)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def direct_to_template(request, template, extra_context=None, **kwargs): """ Replacement for Django's ``direct_to_template`` that uses ``TemplateResponse`` via ``yacms.utils.views.render``. """
context = extra_context or {} context["params"] = kwargs for (key, value) in context.items(): if callable(value): context[key] = value() return TemplateResponse(request, template, context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit(request): """ Process the inline editing form. """
model = apps.get_model(request.POST["app"], request.POST["model"]) obj = model.objects.get(id=request.POST["id"]) form = get_edit_form(obj, request.POST["fields"], data=request.POST, files=request.FILES) if not (is_editable(obj, request) and has_site_permission(request.user)): response = _("Permission denied") elif form.is_valid(): form.save() model_admin = ModelAdmin(model, admin.site) message = model_admin.construct_change_message(request, form, None) model_admin.log_change(request, obj, message) response = "" else: response = list(form.errors.values())[0][0] return HttpResponse(response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(request, template="search_results.html", extra_context=None): """ Display search results. Takes an optional "contenttype" GET parameter in the form "app-name.ModelName" to limit search results to a single model. """
query = request.GET.get("q", "") page = request.GET.get("page", 1) per_page = settings.SEARCH_PER_PAGE max_paging_links = settings.MAX_PAGING_LINKS try: parts = request.GET.get("type", "").split(".", 1) search_model = apps.get_model(*parts) search_model.objects.search # Attribute check except (ValueError, TypeError, LookupError, AttributeError): search_model = Displayable search_type = _("Everything") else: search_type = search_model._meta.verbose_name_plural.capitalize() results = search_model.objects.search(query, for_user=request.user) paginated = paginate(results, page, per_page, max_paging_links) context = {"query": query, "results": paginated, "search_type": search_type} context.update(extra_context or {}) return TemplateResponse(request, template, context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def static_proxy(request): """ Serves TinyMCE plugins inside the inline popups and the uploadify SWF, as these are normally static files, and will break with cross-domain JavaScript errors if ``STATIC_URL`` is an external host. URL for the file is passed in via querystring in the inline popup plugin template, and we then attempt to pull out the relative path to the file, so that we can serve it locally via Django. """
normalize = lambda u: ("//" + u.split("://")[-1]) if "://" in u else u url = normalize(request.GET["u"]) host = "//" + request.get_host() static_url = normalize(settings.STATIC_URL) for prefix in (host, static_url, "/"): if url.startswith(prefix): url = url.replace(prefix, "", 1) response = "" (content_type, encoding) = mimetypes.guess_type(url) if content_type is None: content_type = "application/octet-stream" path = finders.find(url) if path: if isinstance(path, (list, tuple)): path = path[0] if url.endswith(".htm"): # Inject <base href="{{ STATIC_URL }}"> into TinyMCE # plugins, since the path static files in these won't be # on the same domain. static_url = settings.STATIC_URL + os.path.split(url)[0] + "/" if not urlparse(static_url).scheme: static_url = urljoin(host, static_url) base_tag = "<base href='%s'>" % static_url with open(path, "r") as f: response = f.read().replace("<head>", "<head>" + base_tag) else: try: with open(path, "rb") as f: response = f.read() except IOError: return HttpResponseNotFound() return HttpResponse(response, content_type=content_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def page_not_found(request, template_name="errors/404.html"): """ Mimics Django's 404 handler but with a different template path. """
context = { "STATIC_URL": settings.STATIC_URL, "request_path": request.path, } t = get_template(template_name) return HttpResponseNotFound(t.render(context, 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 server_error(request, template_name="errors/500.html"): """ Mimics Django's error handler but adds ``STATIC_URL`` to the context. """
context = {"STATIC_URL": settings.STATIC_URL} t = get_template(template_name) return HttpResponseServerError(t.render(context, 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 _runhook(ui, repo, hooktype, filename, kwargs): """Run the hook in `filename` and return its result."""
hname = hooktype + ".autohooks." + os.path.basename(filename) if filename.lower().endswith(".py"): try: mod = mercurial.extensions.loadpath(filename, "hghook.%s" % hname) except Exception: ui.write(_("loading %s hook failed:\n") % hname) raise return mercurial.hook._pythonhook(ui, repo, hooktype, hname, getattr(mod, hooktype.replace("-", "_")), kwargs, True) elif filename.lower().endswith(".sh"): return mercurial.hook._exthook(ui, repo, hname, filename, kwargs, True) return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autohook(ui, repo, hooktype, **kwargs): """Look for hooks inside the repository to run."""
cmd = hooktype.replace("-", "_") if not repo or not cmd.replace("_", "").isalpha(): return False result = False trusted = ui.configlist("autohooks", "trusted") if "" not in trusted: default_path = ui.config("paths", "default") if not default_path: return False for match in trusted: if default_path.startswith(match): break else: return False for hookdir in ("hg-autohooks", ".hg-autohooks"): dirname = os.path.join(repo.root, hookdir) if not os.path.exists(dirname): continue for leafname in os.listdir(dirname): if not leafname.startswith(cmd + "."): continue filename = os.path.join(dirname, leafname) result = _runhook(ui, repo, hooktype, filename, kwargs) or result return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def i_batch(max_size, iterable): """ Generator that iteratively batches items to a max size and consumes the items iterable as each batch is yielded. :param max_size: Max size of each batch. :type max_size: int :param iterable: An iterable :type iterable: iter """
iterable_items = iter(iterable) for items_batch in iter(lambda: tuple(islice(iterable_items, max_size)), tuple()): yield items_batch
<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_rate_limit_adapters(cls, session=None, rls_config=None, **kwargs): """Mount rate-limits adapters on the specified `requests.Session` object. :param py:class:`requests.Session` session: Session to mount. If not specified, then use the global `HTTP_SESSION`. :param dict rls_config: Rate-limits configuration. If not specified, then use the one defined at application level. :param kwargs: Additional keywords argument given to py:class:`docido_sdk.toolbox.rate_limits.RLRequestAdapter` constructor. """
session = session or HTTP_SESSION if rls_config is None: rls_config = RateLimiter.get_configs() for name, rl_conf in rls_config.items(): urls = rl_conf.get('urls', []) if not urls: continue rl_adapter = RLRequestAdapter(name, config=rls_config, **kwargs) for url in urls: session.mount(url, rl_adapter)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_add_strdec(*args, prec=28): """add two columns that contain numbers as strings"""
# load modules import pandas as pd import numpy as np import re from decimal import Decimal, getcontext getcontext().prec = prec # initialize result as 0.0 def proc_elem(*args): t = Decimal('0.0') for a in args: if isinstance(a, str): a = re.sub('[^0-9\.\-]+', '', a) if a and pd.notnull(a): t += Decimal(a) return str(t) def proc_list(arr): return [proc_elem(*row) for row in arr] def proc_ndarray(arr): return np.array(proc_list(arr)) # transform depending on provided datatypes if isinstance(args[0], (list, tuple)): return proc_list(args[0]) elif isinstance(args[0], np.ndarray): return proc_ndarray(args[0]) elif isinstance(args[0], pd.DataFrame): return pd.DataFrame(proc_ndarray(args[0].values), index=args[0].index) else: return proc_elem(*args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ps_extract_pid(self, line): """ Extract PID and parent PID from an output line from the PS command """
this_pid = self.regex['pid'].sub(r'\g<1>', line) this_parent = self.regex['parent'].sub(r'\g<1>', line) # Return the main / parent PIDs return this_pid, this_parent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ps(self): """ Get the process information from the system PS command. """
# Get the process ID pid = self.get() # Parent / child processes parent = None children = [] # If the process is running if pid: proc = Popen(['ps', '-ef'], stdout=PIPE) for _line in proc.stdout.readlines(): line = self.unicode(_line.rstrip()) # Get the current PID / parent PID this_pid, this_parent = self._ps_extract_pid(line) try: # If scanning a child process if int(pid) == int(this_parent): children.append('{}; [{}]'.format(this_pid.rstrip(), re.sub(' +', ' ', line))) # If scanning the parent process if int(pid) == int(this_pid): parent = re.sub(' +', ' ', line) # Ignore value errors except ValueError: continue # Return the parent PID and any children processes return (parent, children)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def age(self): """ Get the age of the PID file. """
# Created timestamp created = self.created() # Age in seconds / minutes / hours / days age_secs = time() - created age_mins = 0 if (age_secs < 60) else (age_secs / 60) age_hours = 0 if (age_secs < 3600) else (age_mins / 60) age_days = 0 if (age_secs < 86400) else (age_hours / 24) # Return the age tuple return ( int(age_secs), int(age_mins), int(age_hours), int(age_days) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def birthday(self): """ Return a string representing the age of the process. """
if isfile(self.pid_file): # Timestamp / timezone string tstamp = datetime.fromtimestamp(self.created()) tzone = tzname[0] weekday = WEEKDAY[tstamp.isoweekday()] # PID file age / age string age = self.age() age_str = '{}s ago'.format(age[0]) # Birthday string bday = '{} {} {}; {}'.format(weekday, tstamp, tzone, age_str) # Return timestamp / timestamp string return (self.created(), bday) return (None, 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 make(self, pnum): """ Make a PID file and populate with PID number. """
try: # Create the PID file self.mkfile(self.pid_file, pnum) except Exception as e: self.die('Failed to generate PID file: {}'.format(str(e)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self): """ Remove the PID file. """
if isfile(self.pid_file): try: remove(self.pid_file) except Exception as e: self.die('Failed to remove PID file: {}'.format(str(e))) else: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def role_settings(self): """ Filter out unwanted to show groups """
result = super(SharingView, self).role_settings() uid = self.context.UID() filter_func = lambda x: not any(( x["id"].endswith(uid), x["id"] == "AuthenticatedUsers", x["id"] == INTRANET_USERS_GROUP_ID, )) return filter(filter_func, result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initdb(config): """ Initializing database settings by using config from .ini file. """
engine = sa.engine_from_config(config, 'sqlalchemy.') Session.configure(bind=engine)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_chanmsg(self, from_, channel, message): """ Event handler for channel messages. """
if message == 'hello': self.privmsg(channel, 'Hello, %s!' % from_[0]) print('%s said hello!' % from_[0]) elif message == '!quit': self.quit('Bye!')
<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_package_data(): """Iterate over the `init` dir for directories and returns all files within them. Only files within `binaries` and `templates` will be added. """
from os import listdir as ls from os.path import join as jn x = 'init' b = jn('serv', x) dr = ['binaries', 'templates'] return [jn(x, d, f) for d in ls(b) if d in dr for f in ls(jn(b, d))]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def path_for_import(name): """ Returns the directory path for the given package or module. """
return os.path.dirname(os.path.abspath(import_module(name).__file__))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_the_call(self, method, url, body=None): """Note that a request response is being used here, not webob."""
self.log.debug("%s call to %s with body = %s" % (method, url, body)) params = {"url": url, "headers": self.headers, "verify": self.verify} if body is not None: params["data"] = body func = getattr(requests, method.lower()) try: resp = func(**params) except Exception as e: self.log.error("Call to %s failed with %s, %s" % (url, repr(e), e.message)) return None, e else: self.log.debug("Call to %s returned with status %s and body " "%s" % (url, resp.status, resp.text)) return resp.status_code, resp.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 reduce_multiline(string): """ reduces a multiline string to a single line of text. args: string: the text to reduce """
string = str(string) return " ".join([item.strip() for item in string.split("\n") if item.strip()])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_max_width(text, max_width=None, **kwargs): """ Takes a string and formats it to a max width seperated by carriage returns args: max_width: the max with for a line kwargs: indent: the number of spaces to add to the start of each line prepend: text to add to the start of each line """
ind = '' if kwargs.get("indent"): ind = ''.ljust(kwargs['indent'], ' ') prepend = ind + kwargs.get("prepend", "") if not max_width: return "{}{}".format(prepend, text) len_pre = len(kwargs.get("prepend", "")) + kwargs.get("indent", 0) test_words = text.split(" ") word_limit = max_width - len_pre if word_limit < 3: word_limit = 3 max_width = len_pre + word_limit words = [] for word in test_words: if len(word) + len_pre > max_width: n = max_width - len_pre words += [word[i:i + word_limit] for i in range(0, len(word), word_limit)] else: words.append(word) idx = 0 lines = [] idx_limit = len(words) - 1 sub_idx_limit = idx_limit while idx < idx_limit: current_len = len_pre line = prepend for i, word in enumerate(words[idx:]): if (current_len + len(word)) == max_width and line == prepend: idx += i or 1 line += word lines.append(line) if idx == idx_limit: idx -= 1 sub_idx_limit -= 1 del words[0] break if (current_len + len(word) + 1) > max_width: idx += i if idx == idx_limit: idx -= 1 sub_idx_limit -= 1 del words[0] if idx == 0: del words[0] lines.append(line) break if (i + idx) == sub_idx_limit: idx += i or 1 if line != prepend: line = " ".join([line, word]) elif word: line += word lines.append(line) else: if line != prepend: line = " ".join([line, word]) elif word: line += word current_len = len(line) return "\n".join(lines)
<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_details(app_url=defaults.APP_URL): """ returns environment details for the app url specified """
url = '%s/environment' % app_url response = requests.get(url) if response.status_code == 200: return response.json() else: raise JutException('Unable to retrieve environment details from %s, got %s: %s' % (url, response.status_code, response.text))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accept(self, evt): """ write setting to the preferences """
# determine if application is a script file or frozen exe (pyinstaller) frozen = getattr(sys, 'frozen', False) if frozen: app_file = sys.executable else: app_file = PathStr(__main__.__file__).abspath() if self.cb_startmenu.isChecked(): # TODO: allow only logo location # icon = app_file.dirname().join('media', 'logo.ico') StartMenuEntry(self.name, app_file, icon=self.icon, console=False).create() if self.cb_mime.isChecked(): # get admin rights if not isAdmin(): try: # run this file as __main__ with admin rights: if frozen: cmd = "from %s import embeddIntoOS\nembeddIntoOS('%s', '%s', '%s')" % ( __name__, '', self.ftype, self.name) # in this case there is no python.exe and no moduly.py to call # thats why we have to import the method and execute it runAsAdmin((sys.executable, '-exec', cmd)) else: runAsAdmin((sys.executable, __file__, app_file, self.ftype, self.name)) except: print('needs admin rights to work') else: embeddIntoOS(app_file, self.ftype, self.name) QtWidgets.QDialog.accept(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 build_row(self, line): """ Line describes an image or images to show Returns a dict with a list of dicts of image names or text items Examples: # A single image to display [{'image': 'foo.png'}] # Two images with text in between: [{'image': 'foo.png'}, {'text': 'or'}, {'image': 'bar.png'}] """
items = [] row = dict(items=items) fields = line.split(' ') image_exts = ['.png', '.jpg'] # nothing there, carry on if not fields: return row for field in fields: ext = os.path.splitext(field)[-1] if ext.lower() in image_exts: items.append( dict(image=field)) else: items.append( dict(text=field)) return row
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict(self): """ Returns dictionary of post fields and attributes """
post_dict = { 'id': self.id, 'link': self.link, 'permalink': self.permalink, 'content_type': self.content_type, 'slug': self.slug, 'updated': self.updated, #.strftime(conf.GOSCALE_ATOM_DATETIME_FORMAT), 'published': self.published, #.strftime(conf.GOSCALE_ATOM_DATETIME_FORMAT), 'title': self.title, 'description': self.description, 'author': self.author, 'categories': self.categories[1:-1].split(',') if self.categories else None, 'summary': self.summary, } if self.attributes: attributes = simplejson.loads(self.attributes) post_dict.update(attributes) return post_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 json(self, dict=None, indent=None): """ Returns post JSON representation """
if not dict: dict = self.dict() for key, value in dict.iteritems(): if type(value) == datetime.datetime: dict[key] = value.strftime(conf.GOSCALE_ATOM_DATETIME_FORMAT) return simplejson.dumps(dict, indent=indent)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_cache_key(self, offset=0, limit=0, order=None, post_slug=''): """ The return of Get """
return hashlib.sha1( '.'.join([ str(self._get_data_source_url()), str(offset), str(limit), str(order), str(post_slug), ]) ).hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_post(self, slug): """ This method returns a single post by slug """
cache_key = self.get_cache_key(post_slug=slug) content = cache.get(cache_key) if not content: post = Post.objects.get(slug=slug) content = self._format(post) cache_duration = conf.GOSCALE_CACHE_DURATION if post else 1 cache.set(cache_key, content, cache_duration) return content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def up_to_date(self): """ Returns True if plugin posts are up to date Determined by self.updated and conf.GOSCALE_POSTS_UPDATE_FREQUENCY """
# return False if not self.updated: return False return (utils.get_datetime_now() - self.updated).seconds < conf.GOSCALE_POSTS_UPDATE_FREQUENCY
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch(args): """ Parse the command line and dispatch the appropriate script. This function just performs dispatch on the command line that a user provided. Basically, look at the first argument, which specifies the function the user wants Ribocop to perform, then dispatch to the appropriate module. """
prog_name = args[0] if prog_name not in dispatchers: raise NoSuchScriptError("No such pyokit script: " + prog_name + "\n") else: dispatchers[prog_name](args[1:])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export(self, contentType): """ Export message to specified contentType via munge contentType <str> - eg. "json", "yaml" """
cls = munge.get_codec(contentType) codec = cls() return codec.dumps(self.__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 get_parser(): """ Return argument parser. """
parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter, description=__doc__, ) # connection to redis server parser.add_argument('--host', default='localhost') parser.add_argument('--port', default=6379, type=int) parser.add_argument('--db', default=0, type=int) # tools parser.add_argument('command', choices=(str('follow'), str('lock'), str('reset'), str('status'))) parser.add_argument('resources', nargs='*', metavar='RESOURCE') return parser
<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_ajax_votes(request, user_profile): """Build vote information for the request."""
vote_list = '' for profile in request.upvotes.all(): vote_list += \ '<li><a title="View Profile" href="{url}">{name}</a></li>'.format( url=reverse( 'member_profile', kwargs={'targetUsername': profile.user.username} ), name='You' if profile.user == user_profile.user \ else profile.user.get_full_name(), ) in_votes = user_profile in request.upvotes.all() count = request.upvotes.all().count() return (vote_list, in_votes, count)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(argv): """Sets up the ArgumentParser. Args: argv: an array of arguments """
parser = argparse.ArgumentParser( description='Compute Jekyl- and prose-aware wordcounts', epilog='Accepted filetypes: plaintext, markdown, markdown (Jekyll)') parser.add_argument('-S', '--split-hyphens', action='store_true', dest='split_hyphens', help='split hyphenated words rather than counting ' 'them as one word ("non-trivial" counts as two words ' 'rather than one)') parser.add_argument('-u', '--update', action='store_true', help='update the jekyll file in place with the counts.' ' Does nothing if the file is not a Jekyll markdown ' 'file. Implies format=yaml, invalid with input ' 'from STDIN and non-Jekyll files.') parser.add_argument('-f', '--format', nargs='?', choices=['yaml', 'json', 'default'], default='default', help='output format.') parser.add_argument('-i', '--indent', type=int, nargs='?', default=4, help='indentation depth (default: 4).') parser.add_argument('file', type=argparse.FileType('rb'), help='file to parse (or - for STDIN)') return parser.parse_args(argv)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prose_wc(args): """Processes data provided to print a count object, or update a file. Args: args: an ArgumentParser object returned by setup() """
if args.file is None: return 1 if args.split_hyphens: INTERSTITIAL_PUNCTUATION.append(re.compile(r'-')) content = args.file.read().decode('utf-8') filename = args.file.name body = strip_frontmatter(content) parsed = markdown_to_text(body) result = wc(filename, body, parsed=parsed, is_jekyll=(body != content)) if (args.update and filename != '_stdin_' and result['counts']['type'] == 'jekyll'): update_file(filename, result, content, args.indent) else: _mockable_print({ 'yaml': yaml.safe_dump(result, default_flow_style=False, indent=args.indent), 'json': json.dumps(result, indent=args.indent), 'default': default_dump(result), }[args.format]) return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def markdown_to_text(body): """Converts markdown to text. Args: body: markdown (or plaintext, or maybe HTML) input Returns: Plaintext with all tags and frills removed """
# Turn our input into HTML md = markdown.markdown(body, extensions=[ 'markdown.extensions.extra' ]) # Safely parse HTML so that we don't have to parse it ourselves soup = BeautifulSoup(md, 'html.parser') # Return just the text of the parsed HTML return soup.get_text()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wc(filename, contents, parsed=None, is_jekyll=False): """Count the words, characters, and paragraphs in a string. Args: contents: the original string to count filename (optional): the filename as provided to the CLI parsed (optional): a parsed string, expected to be plaintext only is_jekyll: whether the original contents were from a Jekyll file Returns: An object containing the various counts """
if is_jekyll: fmt = 'jekyll' else: fmt = 'md/txt' body = parsed.strip() if parsed else contents.strip() # Strip the body down to just words words = re.sub(r'\s+', ' ', body, re.MULTILINE) for punctuation in INTERSTITIAL_PUNCTUATION: words = re.sub(punctuation, ' ', words) punct = re.compile('[^\w\s]', re.U) words = punct.sub('', words) # Retrieve only non-space characters real_characters = re.sub(r'\s', '', words) # Count paragraphs in an intelligent way paragraphs = [1 if len(x) == 0 else 0 for x in contents.strip().splitlines()] for index, paragraph in enumerate(paragraphs): if paragraph == 1 and paragraphs[index + 1] == 1: paragraphs[index] = 0 return { 'counts': { 'file': filename, 'type': fmt, 'paragraphs': sum(paragraphs) + 1, 'words': len(re.split('\s+', words)), 'characters_real': len(real_characters), 'characters_total': len(words), } }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_file(filename, result, content, indent): """Updates a Jekyll file to contain the counts form an object This just converts the results to YAML and adds to the Jekyll frontmatter. Args: filename: the Jekyll file to update result: the results object from `wc` content: the contents of the original file indent: the indentation level for dumping YAML """
# Split the file into frontmatter and content parts = re.split('---+', content, 2) # Load the frontmatter into an object frontmatter = yaml.safe_load(parts[1]) # Add the counts entry in the results object to the frontmatter frontmatter['counts'] = result['counts'] # Set the frontmatter part backed to the stringified version of the # frontmatter object parts[1] = '\n{}'.format( yaml.safe_dump(frontmatter, default_flow_style=False, indent=indent)) result = '---'.join(parts) # Write everything back to the file with open(filename, 'wb') as f: f.write(result.encode('utf-8')) print('{} updated.'.format(filename))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log(message, level="info"): """ Add a new log entry to the nago log. Arguments: level - Arbritrary string, levels should be syslog style (debug,log,info,warning,error) message - Arbritary string, the message that is to be logged. """
now = time.time() entry = {} entry['level'] = level entry['message'] = message entry['timestamp'] = now _log_entries.append(entry)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nago_access(access_required="master", name=None): """ Decorate other functions with this one to allow access Arguments: nago_access -- Type of access required to call this function By default only master is allowed to make that call nago_name -- What name this function will have to remote api Default is the same as the name of the function being decorated. """
def real_decorator(func): func.nago_access = access_required func.nago_name = name or func.__name__ @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper return real_decorator
<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_nodes(): """ Returns all nodes in a list of dicts format """
cfg_file = "/etc/nago/nago.ini" config = ConfigParser.ConfigParser() config.read(cfg_file) result = {} for section in config.sections(): if section in ['main']: continue token = section node = Node(token) for key, value in config.items(token): node[key] = value result[token] = node return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_token(): """ Generate a new random security token. True Returns: string """
length = 50 stringset = string.ascii_letters + string.digits token = ''.join([stringset[i % len(stringset)] for i in [ord(x) for x in os.urandom(length)]]) return token
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_my_info(): """ Return general information about this node """
result = {} result['host_name'] = platform.node() result['real_host_name'] = platform.node() result['dist'] = platform.dist() result['nago_version'] = nago.get_version() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self): """ Delete this node from config files """
cfg_file = "/etc/nago/nago.ini" config = ConfigParser.ConfigParser() config.read(cfg_file) result = {} token = self.data.pop("token", self.token) if token not in config.sections(): raise Exception("Cannot find node in config. Delete aborted.") config.remove_section(self.token) with open(cfg_file, 'w') as f: return config.write(f)
<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_info(self, key=None): """ Return all posted info about this node """
node_data = nago.extensions.info.node_data.get(self.token, {}) if key is None: return node_data else: return node_data.get(key, {})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def include(pattern, matching): """ Including a other matching, to get as matching pattern's child paths. """
matching.matching_records = [ MatchingRecord( PathTemplate(pattern) + child_path_template, case, child_name ) for child_path_template, case, child_name in matching.matching_records ] return matching
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_wsgi_app(matching, not_found_app=not_found_app): """ Making a WSGI application from Matching object registered other WSGI applications on each 'case' argument. """
def wsgi_app(environ, start_response): environ['matcha.matching'] = matching try: matched_case, matched_dict = matching(environ) except NotMatched: return not_found_app(environ, start_response) else: environ['matcha.matched_dict'] = matched_dict return matched_case(environ, start_response) return wsgi_app
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reverse(self, matching_name, **kwargs): """ Getting a matching name and URL args and return a corresponded URL """
for record in self.matching_records: if record.name == matching_name: path_template = record.path_template break else: raise NotReversed if path_template.wildcard_name: l = kwargs.get(path_template.wildcard_name) if not l: raise NotReversed additional_path = '/'.join(l) extra_path_elements = path_template.pattern.split('/')[:-1] pattern = join_paths('/'.join(extra_path_elements), additional_path) else: pattern = path_template.pattern try: url = pattern.format(**kwargs) except KeyError: raise NotReversed return 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 nextversion(current_version): """Returns incremented module version number. :param current_version: version string to increment :returns: Next version string (PEP 386 compatible) if possible. If impossible (since `current_version` is too far from PEP 386), `None` is returned. """
norm_ver = verlib.suggest_normalized_version(current_version) if norm_ver is None: return None norm_ver = verlib.NormalizedVersion(norm_ver) # increment last version figure parts = norm_ver.parts # see comments of `verlib.py` to get the idea of `parts` assert(len(parts) == 3) if len(parts[2]) > 1: # postdev if parts[2][-1] == 'f': # when `post` exists but `dev` doesn't parts = _mk_incremented_parts(parts, part_idx=2, in_part_idx=-2, incval=1) else: # when both `post` and `dev` exist parts = _mk_incremented_parts(parts, part_idx=2, in_part_idx=-1, incval=1) elif len(parts[1]) > 1: # prerel parts = _mk_incremented_parts(parts, part_idx=1, in_part_idx=-1, incval=1) else: # version & extraversion parts = _mk_incremented_parts(parts, part_idx=0, in_part_idx=-1, incval=1) norm_ver.parts = parts return str(norm_ver)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def find_date(url): "Extract date from URL page if exists." def _clean_split(div_str): sl = [] for div in div_str.split('/'): div = div.strip().lower() if div != '': sl.append(div) return sl url_path = find_path(url) url_path_parts = _clean_split(url_path) date_parts = [] for part in url_path_parts: try: _dateparse(part) # is part date-like? date_parts.append(part) except ValueError: continue if len(date_parts) == 0: return date_str = '/'.join(date_parts) return _dateparse(date_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 compute_coordinate(self, index): '''Compute two-dimension coordinate from one-dimension list''' j = index%self.board_size i = (index - j) // self.board_size return (i, j)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def print_pos(self, coordinates=None, pos=None): '''Print the chessboard''' if not pos: pos = self.pos self.graph = [list(map(self._transform, pos[i])) for i in self.pos_range] xaxis = ' '.join([chr(ASC_ONE + _) for _ in range(min(self.board_size, MAX_NUM))]) if (self.board_size > MAX_NUM): xaxis += ' ' xaxis += ' '.join([chr(ASC_A + _ - MAX_NUM) for _ in range(MAX_NUM, min(self.board_size, MAX_CAP))]) if (self.board_size > MAX_CAP): xaxis += ' ' xaxis += ' '.join([chr(ASC_a + _ - MAX_CAP) for _ in range(MAX_CAP, self.board_size)]) print(' ', end='') print(xaxis) for i in range(self.board_size): out = '|'.join(self.graph[i]) if i < MAX_NUM: print(chr(i + ASC_ONE), end='') elif MAX_NUM <= i < MAX_CAP: print(chr(i - MAX_NUM + ASC_A), end='') elif MAX_CAP <= i < MAX_LOW: print(chr(i - MAX_CAP + ASC_a), end='') print('|', end='') #Colorful print if coordinates: for j in range(self.board_size): if (i, j) in coordinates: new_print = cprint params = { 'color': 'w', 'bcolor': 'r', } else: new_print = print params = {} new_print(self._transform(pos[i][j]), end='', **params) print('|', end='') else: print() else: print(out, end='') print('|')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_pos(self, pos, check=False): '''Set a chess''' self.validate_pos(pos) x, y = pos user = self.get_player() self.history[self._game_round] = copy.deepcopy(self.pos) self.pos[x][y] = user pos_str = self._cal_key(pos) self._pos_dict[pos_str] = user self._user_pos_dict[user].append(pos) self._game_round += 1 if check: winning = self.check_win_by_step(x, y, user) return winning else: return (x, y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def clear(self): '''Clear a chessboard''' self.pos = [[0 for _ in range(self.board_size)] for _ in range(self.board_size)] self.graph = copy.deepcopy(self.pos) self._game_round = 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def handle_input(self, input_str, place=True, check=False): '''Transfer user input to valid chess position''' user = self.get_player() pos = self.validate_input(input_str) if pos[0] == 'u': self.undo(pos[1]) return pos if place: result = self.set_pos(pos, check) return result else: return pos
<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_win_by_step(self, x, y, user, line_number=None): '''Check winners by current step''' if not line_number: line_number = self.win for ang in self.angle: self.win_list = [(x, y)] angs = [ang, ang + math.pi] line_num = 1 radius = 1 direction = [1, 1] while True: if line_num == line_number: return True if direction == [0, 0]: break for ind, a in enumerate(angs): target_x = int(x + radius*(sign(math.cos(a)))) if direction[ind] else -1 target_y = int(y - radius*(sign(math.sin(a)))) if direction[ind] else -1 if target_x < 0 or target_y < 0 or target_x > self.board_size - 1 or target_y > self.board_size - 1: direction[ind] = 0 elif self.pos[target_x][target_y] == user: self.win_list.append((target_x, target_y)) line_num += 1 else: direction[ind] = 0 else: radius += 1 else: return (x, y)
<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_not_num(self, seq, num=0): '''Find the index of first non num element''' ind = next((i for i, x in enumerate(seq) if x != num), None) if ind == None: return self.board_size else: return ind
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def compare_board(self, dst, src=None): '''Compare two chessboard''' if not src: src = self.pos if src == dst: return True else: #May return details return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reduce_number(num): """Reduces the string representation of a number. If the decimal portion of the number has a repeating decimal, followed by up to two trailing numbers, such as: 0.3333333 or 0.343434346 It will return just one instance of the repeating decimals: 0.3 or 0.34 """
parts = str(num).split(".") if len(parts) == 1 or parts[1] == "0": return int(parts[0]) else: match = _REPEATING_NUMBER_TRIM_RE.search(parts[1]) if match: from_index, _ = match.span() if from_index == 0 and match.group(2) == "0": return int(parts[0]) else: return Decimal(parts[0] + "." + parts[1][:from_index] + match.group(2)) else: return num
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_cell_empty(self, cell): """Checks if the cell is empty."""
if cell is None: return True elif self._is_cell_empty: return self._is_cell_empty(cell) else: return cell 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 is_row_empty(self, row): """Returns True if every cell in the row is empty."""
for cell in row: if not self.is_cell_empty(cell): return False return True