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 p... |
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:
... |
<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 ... |
<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().Q... |
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()):
... |
<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... |
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
... |
<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,
**{})... |
<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,
... |
<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_... |
<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... |
<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'])
)... |
<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: Existi... |
<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 = (Colo... |
<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 +... |
<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(
... |
<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:
... |
<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 inval... |
<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... |
# 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_n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 ... |
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... |
<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(requi... |
<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 flagg... |
<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.r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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... |
<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 o... |
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(m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_rc(self, manifest_filename, namespace="default"):
""" Creates an RC based on a manifest. :Parameters: - `manifest_filename`: The manifest file contain... |
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_man... |
<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, me... |
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
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_svc(self, manifest_filename, namespace="default"):
""" Creates a service based on a manifest. :Parameters: - `manifest_filename`: The manifest file co... |
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_js... |
<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... |
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:in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def direct_to_template(request, template, extra_context=None, **kwargs):
""" Replacement for Django's ``direct_to_template`` that uses ``TemplateResponse`` via `... |
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)):
... |
<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 "a... |
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 # Att... |
<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 cro... |
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... |
<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... |
<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
... |
<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_... |
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:... |
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, confi... |
<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... |
<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():
... |
<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 (a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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()... |
<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 a... |
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)
... |
<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 wit... |
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_limi... |
<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():
... |
<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 im... |
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:
... |
<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.publis... |
<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,... |
<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... |
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, t... |
<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}
),
... |
<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',
... |
<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=p... |
<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 re... |
# 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 coun... |
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, ' ', word... |
<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... |
# 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 p... |
<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,warn... |
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 require... |
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):
... |
<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.... |
<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' ar... |
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
... |
<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)
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nextversion(current_version):
"""Returns incremented module version number. :param current_version: version string to increment :returns: Next version string... |
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 ... |
<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... |
<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... |
<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
... |
<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.s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def 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 = ... |
<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 tra... |
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 Dec... |
<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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.