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 write_debug_log(self, file_path):
""" Write the debug log to a file """ |
with open(file_path, "wb+") as fh:
fh.write(system.get_system_info().encode('utf-8'))
# writing to debug stream
self._debug_stream.seek(0)
fh.write(self._debug_stream.read().encode('utf-8'))
fh.write("The following errors occured:\n".encode('utf-8'))
for error in self._errors:
fh.write((error + "\n").encode('utf-8'))
for k, v in self._error_dict.items():
if len(v) > 0:
fh.write(("Error(s) in %s with formula %s:\n" % k).encode('utf-8'))
for error in v:
fh.write((error + "\n").encode('utf-8')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_manifest(self):
""" Write the manifest to the file """ |
if os.path.exists(self.directory.manifest_path):
self.main_manifest.write(open(self.directory.manifest_path, "w+")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def message_failure(self):
""" return a failure message, if one exists """ |
if not isinstance(self.main_manifest, Manifest):
return None
return self.main_manifest.get('config', 'message_failure', default=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 warmup(self):
""" initialize variables necessary to perform a sprinter action """ |
self.logger.debug("Warming up...")
try:
if not isinstance(self.source, Manifest) and self.source:
self.source = load_manifest(self.source)
if not isinstance(self.target, Manifest) and self.target:
self.target = load_manifest(self.target)
self.main_manifest = self.target or self.source
except lib.BadCredentialsException:
e = sys.exc_info()[1]
self.logger.error(str(e))
raise SprinterException("Fatal error! Bad credentials to grab manifest!")
if not getattr(self, 'namespace', None):
if self.target:
self.namespace = self.target.namespace
elif not self.namespace and self.source:
self.namespace = self.source.namespace
else:
raise SprinterException("No environment name has been specified!")
self.directory_root = self.custom_directory_root
if not self.directory:
if not self.directory_root:
self.directory_root = os.path.join(self.root, self.namespace)
self.directory = Directory(self.directory_root,
shell_util_path=self.shell_util_path)
if not self.injections:
self.injections = Injections(wrapper="%s_%s" % (self.sprinter_namespace.upper(),
self.namespace),
override="SPRINTER_OVERRIDES")
if not self.global_injections:
self.global_injections = Injections(wrapper="%s" % self.sprinter_namespace.upper() + "GLOBALS",
override="SPRINTER_OVERRIDES")
# append the bin, in the case sandboxes are necessary to
# execute commands further down the sprinter lifecycle
os.environ['PATH'] = self.directory.bin_path() + ":" + os.environ['PATH']
self.warmed_up = 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 _inject_config_source(self, source_filename, files_to_inject):
""" Inject existing environmental config with namespace sourcing. Returns a tuple of the first file name and path found. """ |
# src_path = os.path.join(self.directory.root_dir, source_filename)
# src_exec = "[ -r %s ] && . %s" % (src_path, src_path)
src_exec = "[ -r {0} ] && . {0}".format(os.path.join(self.directory.root_dir, source_filename))
# The ridiculous construction above is necessary to avoid failing tests(!)
for config_file in files_to_inject:
config_path = os.path.expanduser(os.path.join("~", config_file))
if os.path.exists(config_path):
self.injections.inject(config_path, src_exec)
break
else:
config_file = files_to_inject[0]
config_path = os.path.expanduser(os.path.join("~", config_file))
self.logger.info("No config files found to source %s, creating ~/%s!" % (source_filename, config_file))
self.injections.inject(config_path, src_exec)
return (config_file, 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 _finalize(self):
""" command to run at the end of sprinter's run """ |
self.logger.info("Finalizing...")
self.write_manifest()
if self.directory.rewrite_config:
# always ensure .rc is written (sourcing .env)
self.directory.add_to_rc('')
# prepend brew for global installs
if system.is_osx() and self.main_manifest.is_affirmative('config', 'use_global_packagemanagers'):
self.directory.add_to_env('__sprinter_prepend_path "%s" PATH' % '/usr/local/bin')
self.directory.add_to_env('__sprinter_prepend_path "%s" PATH' % self.directory.bin_path())
self.directory.add_to_env('__sprinter_prepend_path "%s" LIBRARY_PATH' % self.directory.lib_path())
self.directory.add_to_env('__sprinter_prepend_path "%s" C_INCLUDE_PATH' % self.directory.include_path())
self.directory.finalize()
self.injections.commit()
self.global_injections.commit()
if not os.path.exists(os.path.join(self.root, ".global")):
self.logger.debug("Global directory doesn't exist! creating...")
os.makedirs(os.path.join(self.root, ".global"))
self.logger.debug("Writing shell util file...")
with open(self.shell_util_path, 'w+') as fh:
fh.write(shell_utils_template)
if self.error_occured:
raise SprinterException("Error occured!")
if self.message_success():
self.logger.info(self.message_success())
self.logger.info("Done!")
self.logger.info("NOTE: Please remember to open new shells/terminals to use the modified environment") |
<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_logger(self, level=logging.INFO):
""" return a logger. if logger is none, generate a logger from stdout """ |
self._debug_stream = StringIO()
logger = logging.getLogger('sprinter')
# stdout log
out_hdlr = logging.StreamHandler(sys.stdout)
out_hdlr.setLevel(level)
logger.addHandler(out_hdlr)
# debug log
debug_hdlr = logging.StreamHandler(self._debug_stream)
debug_hdlr.setFormatter(logging.Formatter('%(asctime)s %(message)s'))
debug_hdlr.setLevel(logging.DEBUG)
logger.addHandler(debug_hdlr)
logger.setLevel(logging.DEBUG)
return logger |
<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_action(self, feature, action, run_if_error=False, raise_exception=True):
""" Run an action, and log it's output in case of errors """ |
if len(self._error_dict[feature]) > 0 and not run_if_error:
return
error = None
instance = self.features[feature]
try:
getattr(instance, action)()
# catch a generic exception within a feature
except Exception as e:
e = sys.exc_info()[1]
self.logger.info("An exception occurred with action %s in feature %s!" %
(action, feature))
self.logger.debug("Exception", exc_info=sys.exc_info())
error = str(e)
self.log_feature_error(feature, str(e))
# any error in a feature should fail immediately - unless it occurred
# from the remove() method in which case continue the rest of the
# feature removal from there
if error is not None and raise_exception:
exception_msg = "%s action failed for feature %s: %s" % (action, feature, error)
if self.phase == PHASE.REMOVE:
raise FormulaException(exception_msg)
else:
raise SprinterException(exception_msg)
return error |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _specialize(self, reconfigure=False):
""" Add variables and specialize contexts """ |
# add in the 'root_dir' directories to the context dictionaries
for manifest in [self.source, self.target]:
context_dict = {}
if manifest:
for s in manifest.formula_sections():
context_dict["%s:root_dir" % s] = self.directory.install_directory(s)
context_dict['config:root_dir'] = self.directory.root_dir
context_dict['config:node'] = system.NODE
manifest.add_additional_context(context_dict)
self._validate_manifest()
for feature in self.features.run_order:
if not reconfigure:
self.run_action(feature, 'resolve')
# if a target doesn't exist, no need to prompt.
instance = self.features[feature]
if instance.target:
self.run_action(feature, 'prompt') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _copy_source_to_target(self):
""" copy source user configuration to target """ |
if self.source and self.target:
for k, v in self.source.items('config'):
# always have source override target.
self.target.set_input(k, v) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grab_inputs(self, reconfigure=False):
""" Resolve the source and target config section """ |
self._copy_source_to_target()
if self.target:
self.target.grab_inputs(force=reconfigure) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_domain(url):
""" parse the domain from the url """ |
domain_match = lib.DOMAIN_REGEX.match(url)
if domain_match:
return domain_match.group() |
<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_credentials(options, environment):
""" Get credentials or prompt for them from options """ |
if options['--username'] or options['--auth']:
if not options['--username']:
options['<username>'] = lib.prompt("Please enter the username for %s..." % environment)
if not options['--password']:
options['<password>'] = lib.prompt("Please enter the password for %s..." % environment, secret=True)
return 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 full_name(self):
""" The full name of the field. This is the field's entities name concatenated with the field's name. If the field is unnamed or not bound to an entity, the result respectively contains None. """ |
entity = self.entity.__name__ if self.entity is not None else None
name = self.name if self.name is not None else None
if entity and name:
return entity + '.' + name
elif entity:
return entity + '.<unnamed>'
elif name:
return '<unbound>.' + name
else:
return '<unbound>.<unnamed>' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def type_name(self):
""" Returns the full type identifier of the field. """ |
res = self.type.__name__
if self.type.__module__ not in ('__builtin__', 'builtins'):
res = self.type.__module__ + '.' + res
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 get_subclass_from_module(module, parent_class):
""" Get a subclass of parent_class from the module at module get_subclass_from_module performs reflection to find the first class that extends the parent_class in the module path, and returns it. """ |
try:
r = __recursive_import(module)
member_dict = dict(inspect.getmembers(r))
sprinter_class = parent_class
for v in member_dict.values():
if inspect.isclass(v) and issubclass(v, parent_class) and v != parent_class:
if sprinter_class is parent_class:
sprinter_class = v
if sprinter_class is None:
raise SprinterException("No subclass %s that extends %s exists in classpath!" % (module, str(parent_class)))
return sprinter_class
except ImportError:
e = sys.exc_info()[1]
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 __recursive_import(module_name):
""" Recursively looks for and imports the names, returning the module desired currently module with relative imports don't work. """ |
names = module_name.split(".")
path = None
module = None
while len(names) > 0:
if module:
path = module.__path__
name = names.pop(0)
(module_file, pathname, description) = imp.find_module(name, path)
module = imp.load_module(name, module_file, pathname, description)
return module |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def err_exit(msg, rc=1):
"""Print msg to stderr and exit with rc. """ |
print(msg, file=sys.stderr)
sys.exit(rc) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_file(self, infile):
"""Read a reST file into a string. """ |
try:
with open(infile, 'rt') as file:
return file.read()
except UnicodeDecodeError as e:
err_exit('Error reading %s: %s' % (infile, e))
except (IOError, OSError) as e:
err_exit('Error reading %s: %s' % (infile, e.strerror or 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 write_file(self, html, outfile):
"""Write an HTML string to a file. """ |
try:
with open(outfile, 'wt') as file:
file.write(html)
except (IOError, OSError) as e:
err_exit('Error writing %s: %s' % (outfile, e.strerror or 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 convert_string(self, rest):
"""Convert a reST string to an HTML string. """ |
try:
html = publish_string(rest, writer_name='html')
except SystemExit as e:
err_exit('HTML conversion failed with error: %s' % e.code)
else:
if sys.version_info[0] >= 3:
return html.decode('utf-8')
return html |
<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_styles(self, html, styles):
"""Insert style information into the HTML string. """ |
index = html.find('</head>')
if index >= 0:
return ''.join((html[:index], styles, html[index:]))
return html |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish_string(self, rest, outfile, styles=''):
"""Render a reST string as HTML. """ |
html = self.convert_string(rest)
html = self.strip_xml_header(html)
html = self.apply_styles(html, styles)
self.write_file(html, outfile)
return outfile |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish_file(self, infile, outfile, styles=''):
"""Render a reST file as HTML. """ |
rest = self.read_file(infile)
return self.publish_string(rest, outfile, styles) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upgrade(self):
"""Upgrade the config file. """ |
warn('Upgrading ' + self.filename)
if self.backup_config(self.filename):
return self.write_default_config(self.filename)
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 backup_config(self, filename):
"""Backup the current config file. """ |
backup_name = filename + '-' + self.version
warn('Moving current configuration to ' + backup_name)
try:
shutil.copy2(filename, backup_name)
return True
except (IOError, OSError) as e:
print('Error copying %s: %s' % (filename, e.strerror or e), file=sys.stderr)
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 write_default_config(self, filename):
"""Write the default config file. """ |
try:
with open(filename, 'wt') as file:
file.write(DEFAULT_CONFIG)
return True
except (IOError, OSError) as e:
print('Error writing %s: %s' % (filename, e.strerror or e), file=sys.stderr)
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 reset_defaults(self, config_file):
"""Reset defaults. """ |
if not exists(config_file):
err_exit('No such file: %(config_file)s' % locals())
if not isfile(config_file):
err_exit('Not a file: %(config_file)s' % locals())
if not os.access(config_file, os.R_OK):
err_exit('File cannot be read: %(config_file)s' % locals())
self.set_defaults(config_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 write_defaults(self):
"""Create default config file and reload. """ |
self.defaults.write()
self.reset_defaults(self.defaults.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 upgrade_defaults(self):
"""Upgrade config file and reload. """ |
self.defaults.upgrade()
self.reset_defaults(self.defaults.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 list_styles(self):
"""Print available styles and exit. """ |
known = sorted(self.defaults.known_styles)
if not known:
err_exit('No styles', 0)
for style in known:
if style == self.defaults.default_style:
print(style, '(default)')
else:
print(style)
sys.exit(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 render_file(self, filename):
"""Convert a reST file to HTML. """ |
dirname, basename = split(filename)
with changedir(dirname):
infile = abspath(basename)
outfile = abspath('.%s.html' % basename)
self.docutils.publish_file(infile, outfile, self.styles)
return outfile |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_long_description(self, dirname):
"""Convert a package's long description to HTML. """ |
with changedir(dirname):
self.setuptools.check_valid_package()
long_description = self.setuptools.get_long_description()
outfile = abspath('.long-description.html')
self.docutils.publish_string(long_description, outfile, self.styles)
return outfile |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_in_browser(self, outfile):
"""Open the given HTML file in a browser. """ |
if self.browser == 'default':
webbrowser.open('file://%s' % outfile)
else:
browser = webbrowser.get(self.browser)
browser.open('file://%s' % outfile) |
<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(self):
"""Render and display Python package documentation. """ |
os.environ['JARN_RUN'] = '1'
self.python.check_valid_python()
args = self.parse_options(self.args)
if args:
arg = args[0]
else:
arg = os.curdir
if arg:
arg = expanduser(arg)
if isfile(arg):
outfile = self.render_file(arg)
elif isdir(arg):
outfile = self.render_long_description(arg)
else:
err_exit('No such file or directory: %s' % arg)
self.open_in_browser(outfile) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preprocess_cell( self, cell: "NotebookNode", resources: dict, cell_index: int ) -> Tuple["NotebookNode", dict]: """Apply a transformation on each cell. Parameters cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. cell_index : int Index of the cell being processed (see base.py) """ |
# Get files directory if it has been specified
output_files_dir = resources.get("output_files_dir", None)
# Make sure outputs key exists
if not isinstance(resources["outputs"], dict):
resources["outputs"] = {}
# Loop through all of the attachments in the cell
for name, attach in cell.get("attachments", {}).items():
orig_name = name
name = re.sub(r"%[\w\d][\w\d]", "-", name)
for mime, data in attach.items():
if mime not in self.extract_output_types:
continue
# Binary files are base64-encoded, SVG is already XML
if mime in {"image/png", "image/jpeg", "application/pdf"}:
# data is b64-encoded as text (str, unicode),
# we want the original bytes
data = a2b_base64(data)
elif sys.platform == "win32":
data = data.replace("\n", "\r\n").encode("UTF-8")
else:
data = data.encode("UTF-8")
filename = self.output_filename_template.format(
cell_index=cell_index,
name=name,
unique_key=resources.get("unique_key", ""),
)
if output_files_dir is not None:
filename = os.path.join(output_files_dir, filename)
if name.endswith(".gif") and mime == "image/png":
filename = filename.replace(".gif", ".png")
# In the resources, make the figure available via
# resources['outputs']['filename'] = data
resources["outputs"][filename] = data
# now we need to change the cell source so that it links to the
# filename instead of `attachment:`
attach_str = "attachment:" + orig_name
if attach_str in cell.source:
cell.source = cell.source.replace(attach_str, filename)
return cell, resources |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def combine_pdf_as_bytes(pdfs: List[BytesIO]) -> bytes: """Combine PDFs and return a byte-string with the result. Arguments --------- pdfs A list of BytesIO representations of PDFs """ |
writer = PdfWriter()
for pdf in pdfs:
writer.addpages(PdfReader(pdf).pages)
bio = BytesIO()
writer.write(bio)
bio.seek(0)
output = bio.read()
bio.close()
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split(self, granularity_after_split, exclude_partial=True):
""" Split a period into a given granularity. Optionally include partial periods at the start and end of the period. """ |
if granularity_after_split == Granularity.DAY:
return self.get_days()
elif granularity_after_split == Granularity.WEEK:
return self.get_weeks(exclude_partial)
elif granularity_after_split == Granularity.MONTH:
return self.get_months(exclude_partial)
elif granularity_after_split == Granularity.QUARTER:
return self.get_quarters(exclude_partial)
elif granularity_after_split == Granularity.HALF_YEAR:
return self.get_half_years(exclude_partial)
elif granularity_after_split == Granularity.YEAR:
return self.get_years(exclude_partial)
else:
raise Exception("Invalid granularity: %s" % granularity_after_split) |
<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_calibration(df, calibration_df, calibration):
'''
Apply calibration values from `fit_fb_calibration` result to `calibration`
object.
'''
from dmf_control_board_firmware import FeedbackResults
for i, (fb_resistor, R_fb, C_fb) in calibration_df[['fb_resistor', 'R_fb', 'C_fb']].iterrows():
calibration.R_fb[int(fb_resistor)] = R_fb
calibration.C_fb[int(fb_resistor)] = C_fb
cleaned_df = df.dropna()
grouped = cleaned_df.groupby(['frequency', 'test_capacitor', 'repeat_index'])
for (f, channel, repeat_index), group in grouped:
r = FeedbackResults(group.V_actuation.iloc[0], f, 5.0,
group.V_hv.values, group.hv_resistor.values,
group.V_fb.values, group.fb_resistor.values,
calibration)
# Update the measured capacitance values based on the updated
# calibration model.
df.loc[group.index, 'C'] = r.capacitance() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def config_dict(config):
""" Given a Sphinx config object, return a dictionary of config values. """ |
return dict(
(key, getattr(config, key))
for key in config.values
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def from_defn(cls, defn):
"Return the first Repl subclass that works with this"
instances = (subcl(defn) for subcl in cls.__subclasses__())
return next(filter(None, instances)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_colormap(cls, names=[], N=10, show=True, *args, **kwargs):
"""Show a colormap dialog Parameters %(show_colormaps.parameters.no_use_qt)s""" |
names = safe_list(names)
obj = cls(names, N, *args, **kwargs)
vbox = obj.layout()
buttons = QDialogButtonBox(QDialogButtonBox.Close, parent=obj)
buttons.rejected.connect(obj.close)
vbox.addWidget(buttons)
if show:
obj.show()
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_list(args):
"""List all element in pen""" |
for penlist in penStore.data:
puts(penlist + " (" + str(len(penStore.data[penlist])) + ")") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_all(args):
"""List everything recursively""" |
for penlist in penStore.data:
puts(penlist)
with indent(4, ' -'):
for penfile in penStore.data[penlist]:
puts(penfile) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_create(args):
"""Creates a list""" |
name = args.get(0)
if name:
penStore.createList(name)
else:
puts("not valid") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_touch_note(args):
"""Create a note""" |
major = args.get(0)
minor = args.get(1)
if major in penStore.data:
if minor is None: # show items in list
for note in penStore.data[major]:
puts(note)
elif minor in penStore.data[major]:
penStore.openNote(major, minor)
else:
penStore.createNote(major, minor)
penStore.openNote(major, minor)
else:
puts("No list of that name.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_delete(args):
"""Deletes a node""" |
major = args.get(0)
minor = args.get(1)
if major is not None:
if major in penStore.data:
if minor is None:
if len(penStore.data[major]) > 0:
if raw_input("are you sure (y/n)? ") not in ['y', 'Y', 'yes', 'Yes']:
return ExitStatus.ABORT
penStore.deleteList(major)
puts("list deleted")
elif minor in penStore.data[major]:
penStore.deleteNote(major, minor)
puts("note deleted")
else:
puts("no such note, sorry! (%s)" % minor)
else:
puts("no such list, sorry! (%s)" % major)
else:
print """
- pen: delete help ------------------------------------------------------------
pen delete <list> deletes list and all of its notes
pen delete <list> <note> deletes note
""" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restclient_admin_required(view_func):
""" View decorator that checks whether the user is permitted to view proxy restclients. Calls login_required in case the user is not authenticated. """ |
def wrapper(request, *args, **kwargs):
template = 'access_denied.html'
if hasattr(settings, 'RESTCLIENTS_ADMIN_AUTH_MODULE'):
auth_func = import_string(settings.RESTCLIENTS_ADMIN_AUTH_MODULE)
else:
context = {'error_msg': (
"Your application must define an authorization function as "
"RESTCLIENTS_ADMIN_AUTH_MODULE in settings.py.")}
return render(request, template, context=context, status=401)
service = args[0] if len(args) > 0 else None
url = args[1] if len(args) > 1 else None
if auth_func(request, service, url):
return view_func(request, *args, **kwargs)
return render(request, template, status=401)
return login_required(function=wrapper) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def destination_heuristic(data):
""" A heuristic to get the folder with all other files from bib, using majority vote. """ |
counter = collections.Counter()
for entry in data:
file_field = entry['fields'].get('file')
if not file_field:
continue
path = os.path.dirname(file_field)
counter[path] += 1
if not counter: # No paths found
raise click.ClickException(
'Path finding heuristics failed: no paths in the database'
)
# Find the paths that appears most often
sorted_paths = sorted(counter, reverse=True)
groupby = itertools.groupby(sorted_paths, key=len)
_, group = next(groupby)
# We know that there's at least one candidate. Make sure it's
# the only one
candidate = next(group)
try:
next(group)
except StopIteration:
return candidate
else:
raise click.ClickException(
'Path finding heuristics failed: '
'there are multiple equally valid paths in the database'
) |
<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_entry(data, entry):
'''
Remove an entry in place.
'''
file_field = entry['fields'].get('file')
if file_field:
try:
os.remove(file_field)
except IOError:
click.echo('This entry\'s file was missing')
data.remove(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 string_to_basename(s):
'''
Converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
'''
s = s.strip().lower()
s = re.sub(r'[^\w\s-]', '', s)
return re.sub(r'[\s-]+', '-', 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 editor(*args, **kwargs):
'''
Wrapper for `click.edit` that raises an error when None is returned.
'''
result = click.edit(*args, **kwargs)
if result is None:
msg = 'Editor exited without saving, command aborted'
raise click.ClickException(msg)
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 terms(self, facet_name, field, size=10, order=None, all_terms=False, exclude=[], regex='', regex_flags=''):
'''
Allow to specify field facets that return the N most frequent terms.
Ordering: Allow to control the ordering of the terms facets, to be ordered by count, term, reverse_count or reverse_term. The default is count.
All Terms: Allow to get all the terms in the terms facet, ones that do not match a hit, will have a count of 0. Note, this should not be used with fields that have many terms.
Excluding Terms: It is possible to specify a set of terms that should be excluded from the terms facet request result.
Regex Patterns: The terms API allows to define regex expression that will control which terms will be included in the faceted list.
'''
self[facet_name] = dict(terms=dict(field=field, size=size))
if order:
self[facet_name][terms]['order'] = order
if all_terms:
self[facet_name][terms]['all_terms'] = True
if exclude:
self[facet_name][terms]['exclude'] = exclude
if regex:
self[facet_name][terms]['regex'] = regex
if regex_flags:
self[facet_name][terms]['regex_flags'] = regex_flags
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def backup_file(filename):
""" create a backup of the file desired """ |
if not os.path.exists(filename):
return
BACKUP_SUFFIX = ".sprinter.bak"
backup_filename = filename + BACKUP_SUFFIX
shutil.copyfile(filename, backup_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 inject(self, filename, content):
""" add the injection content to the dictionary """ |
# ensure content always has one trailing newline
content = _unicode(content).rstrip() + "\n"
if filename not in self.inject_dict:
self.inject_dict[filename] = ""
self.inject_dict[filename] += 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 commit(self):
""" commit the injections desired, overwriting any previous injections in the file. """ |
self.logger.debug("Starting injections...")
self.logger.debug("Injections dict is:")
self.logger.debug(self.inject_dict)
self.logger.debug("Clear list is:")
self.logger.debug(self.clear_set)
for filename, content in self.inject_dict.items():
content = _unicode(content)
self.logger.debug("Injecting values into %s..." % filename)
self.destructive_inject(filename, content)
for filename in self.clear_set:
self.logger.debug("Clearing injection from %s..." % filename)
self.destructive_clear(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 injected(self, filename):
""" Return true if the file has already been injected before. """ |
full_path = os.path.expanduser(filename)
if not os.path.exists(full_path):
return False
with codecs.open(full_path, 'r+', encoding="utf-8") as fh:
contents = fh.read()
return self.wrapper_match.search(contents) is not 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 destructive_inject(self, filename, content):
""" Injects the injections desired immediately. This should generally be run only during the commit phase, when no future injections will be done. """ |
content = _unicode(content)
backup_file(filename)
full_path = self.__generate_file(filename)
with codecs.open(full_path, 'r', encoding="utf-8") as f:
new_content = self.inject_content(f.read(), content)
with codecs.open(full_path, 'w+', encoding="utf-8") as f:
f.write(new_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 __generate_file(self, file_path):
""" Generate the file at the file_path desired. Creates any needed directories on the way. returns the absolute path of the file. """ |
file_path = os.path.expanduser(file_path)
if not os.path.exists(os.path.dirname(file_path)):
self.logger.debug("Directories missing! Creating directories for %s..." % file_path)
os.makedirs(os.path.dirname(file_path))
if not os.path.exists(file_path):
open(file_path, "w+").close()
return 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 in_noninjected_file(self, file_path, content):
""" Checks if a string exists in the file, sans the injected """ |
if os.path.exists(file_path):
file_content = codecs.open(file_path, encoding="utf-8").read()
file_content = self.wrapper_match.sub(u"", file_content)
else:
file_content = ""
return file_content.find(content) != -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 clear_content(self, content):
""" Clear the injected content from the content buffer, and return the results """ |
content = _unicode(content)
return self.wrapper_match.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 add_order(self, order):
""" Adds a MarketOrder instance to the list of market orders contained within this order list. Does some behind-the-scenes magic to get it all ready for serialization. :param MarketOrder order: The order to add to this order list. """ |
# This key is used to group the orders based on region.
key = '%s_%s' % (order.region_id, order.type_id)
if not self._orders.has_key(key):
# We don't have any orders for this yet. Prep the region+item
# combo by instantiating a new MarketItemsInRegionList for
# the MarketOrders.
self.set_empty_region(
order.region_id,
order.type_id,
order.generated_at
)
# The MarketOrder gets stuffed into the MarketItemsInRegionList for this
# item+region combo.
self._orders[key].add_order(order) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_entry(self, entry):
""" Adds a MarketHistoryEntry instance to the list of market history entries contained within this instance. Does some behind-the-scenes magic to get it all ready for serialization. :param MarketHistoryEntry entry: The history entry to add to instance. """ |
# This key is used to group the orders based on region.
key = '%s_%s' % (entry.region_id, entry.type_id)
if not self._history.has_key(key):
# We don't have any orders for this yet. Prep the region+item
# combo by instantiating a new MarketItemsInRegionList for
# the MarketOrders.
self.set_empty_region(
entry.region_id,
entry.type_id,
entry.generated_at
)
# The MarketOrder gets stuffed into the MarketItemsInRegionList for this
# item+region combo.
self._history[key].add_entry(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 _find_file(self, file_name: str, lookup_dir: Path) -> Path or None:
'''Find a file in a directory by name. Check subdirectories recursively.
:param file_name: Name of the file
:lookup_dir: Starting directory
:returns: Path to the found file or None if the file was not found
:raises: FileNotFoundError
'''
self.logger.debug('Trying to find the file {file_name} inside the directory {lookup_dir}')
result = None
for item in lookup_dir.rglob('*'):
if item.name == file_name:
result = item
break
else:
raise FileNotFoundError(file_name)
self.logger.debug('File found: {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 _sync_repo(self, repo_url: str, revision: str or None = None) -> Path:
'''Clone a Git repository to the cache dir. If it has been cloned before, update it.
:param repo_url: Repository URL
:param revision: Revision: branch, commit hash, or tag
:returns: Path to the cloned repository
'''
repo_name = repo_url.split('/')[-1].rsplit('.', maxsplit=1)[0]
repo_path = (self._cache_path / repo_name).resolve()
self.logger.debug(f'Synchronizing with repo; URL: {repo_url}, revision: {revision}')
try:
self.logger.debug(f'Cloning repo {repo_url} to {repo_path}')
run(
f'git clone {repo_url} {repo_path}',
shell=True,
check=True,
stdout=PIPE,
stderr=STDOUT
)
except CalledProcessError as exception:
if repo_path.exists():
self.logger.debug('Repo already cloned; pulling from remote')
try:
run(
'git pull',
cwd=repo_path,
shell=True,
check=True,
stdout=PIPE,
stderr=STDOUT
)
except CalledProcessError as exception:
self.logger.warning(str(exception))
else:
self.logger.error(str(exception))
if revision:
run(
f'git checkout {revision}',
cwd=repo_path,
shell=True,
check=True,
stdout=PIPE,
stderr=STDOUT
)
return repo_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 _shift_headings(self, content: str, shift: int) -> str:
'''Shift Markdown headings in a string by a given value. The shift can
be positive or negative.
:param content: Markdown content
:param shift: Heading shift
:returns: Markdown content with headings shifted by ``shift``
'''
def _sub(heading):
new_heading_level = len(heading.group('hashes')) + shift
self.logger.debug(f'Shift heading level to {new_heading_level}, heading title: {heading.group("title")}')
if new_heading_level <= 6:
return f'{"#" * new_heading_level} {heading.group("title")}{heading.group("tail")}'
else:
self.logger.debug('New heading level is out of range, using bold paragraph text instead of heading')
return f'**{heading.group("title")}**{heading.group("tail")}'
return self._heading_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 _cut_from_heading_to_heading(
self,
content: str,
from_heading: str,
to_heading: str or None = None,
options={}
) -> str:
'''Cut part of Markdown string between two headings, set internal heading level,
and remove top heading.
If only the starting heading is defined, cut to the next heading
of the same level.
Heading shift and top heading elimination are optional.
:param content: Markdown content
:param from_heading: Starting heading
:param to_heading: Ending heading (will not be incuded in the output)
:param options: ``sethead``, ``nohead``
:returns: Part of the Markdown content between headings with internal headings adjusted
'''
self.logger.debug(f'Cutting from heading: {from_heading}, to heading: {to_heading}, options: {options}')
from_heading_pattern = re.compile(r'^\#{1,6}\s+' + rf'{from_heading}\s*$', flags=re.MULTILINE)
if not from_heading_pattern.findall(content):
return ''
from_heading_line = from_heading_pattern.findall(content)[0]
from_heading_level = len(self._heading_pattern.match(from_heading_line).group('hashes'))
self.logger.debug(f'From heading level: {from_heading_level}')
result = from_heading_pattern.split(content)[1]
if to_heading:
to_heading_pattern = re.compile(r'^\#{1,6}\s+' + rf'{to_heading}\s*$', flags=re.MULTILINE)
else:
to_heading_pattern = re.compile(
rf'^\#{{1,{from_heading_level}}}[^\#]+?$',
flags=re.MULTILINE
)
result = to_heading_pattern.split(result)[0]
if not options.get('nohead'):
result = from_heading_line + result
if options.get('sethead'):
if options['sethead'] > 0:
result = self._shift_headings(
result,
options['sethead'] - from_heading_level
)
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 _cut_to_heading(
self,
content: str,
to_heading: str or None = None,
options={}
) -> str:
'''Cut part of Markdown string from the start to a certain heading,
set internal heading level, and remove top heading.
If not heading is defined, the whole string is returned.
Heading shift and top heading elimination are optional.
:param content: Markdown content
:param to_heading: Ending heading (will not be incuded in the output)
:param options: ``sethead``, ``nohead``
:returns: Part of the Markdown content from the start to ``to_heading``,
with internal headings adjusted
'''
self.logger.debug(f'Cutting to heading: {to_heading}, options: {options}')
content_buffer = StringIO(content)
first_line = content_buffer.readline()
if self._heading_pattern.fullmatch(first_line):
from_heading_line = first_line
from_heading_level = len(self._heading_pattern.match(from_heading_line).group('hashes'))
result = content_buffer.read()
else:
from_heading_line = ''
from_heading_level = self._find_top_heading_level(content)
result = content
self.logger.debug(f'From heading level: {from_heading_level}')
if to_heading:
to_heading_pattern = re.compile(r'^\#{1,6}\s+' + rf'{to_heading}\s*$', flags=re.MULTILINE)
result = to_heading_pattern.split(result)[0]
if not options.get('nohead'):
result = from_heading_line + result
if options.get('sethead'):
if options['sethead'] > 0:
result = self._shift_headings(
result,
options['sethead'] - from_heading_level
)
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 _adjust_image_paths(self, content: str, md_file_path: Path) -> str:
'''Locate images referenced in a Markdown string and replace their paths
with the absolute ones.
:param content: Markdown content
:param md_file_path: Path to the Markdown file containing the content
:returns: Markdown content with absolute image paths
'''
def _sub(image):
image_caption = image.group('caption')
image_path = md_file_path.parent / Path(image.group('path'))
self.logger.debug(
f'Updating image reference; user specified path: {image.group("path")}, ' +
f'absolute path: {image_path}, caption: {image_caption}'
)
return f'.as_posix()})'
return self._image_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 _get_src_file_path(self, markdown_file_path: Path) -> Path:
'''Translate the path of Markdown file that is located inside the temporary working directory
into the path of the corresponding Markdown file that is located inside the source directory
of Foliant project.
:param markdown_file_path: Path to Markdown file that is located inside the temporary working directory
:returns: Mapping of Markdown file path to the source directory
'''
path_relative_to_working_dir = markdown_file_path.relative_to(self.working_dir.resolve())
self.logger.debug(
'Currently processed Markdown file path relative to working dir: ' +
f'{path_relative_to_working_dir}'
)
path_mapped_to_src_dir = (
self.project_path.resolve() /
self.config['src_dir'] /
path_relative_to_working_dir
)
self.logger.debug(
'Currently processed Markdown file path mapped to source dir: ' +
f'{path_mapped_to_src_dir}'
)
return path_mapped_to_src_dir |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _get_included_file_path(self, user_specified_path: str, current_processed_file_path: Path) -> Path:
'''Resolve user specified path to the local included file.
:param user_specified_path: User specified string that represents
the path to a local file
:param current_processed_file_path: Path to the currently processed Markdown file
that contains include statements
:returns: Local path of the included file relative to the currently processed Markdown file
'''
self.logger.debug(f'Currently processed Markdown file: {current_processed_file_path}')
included_file_path = (current_processed_file_path.parent / user_specified_path).resolve()
self.logger.debug(f'User-specified included file path: {included_file_path}')
if (
self.working_dir.resolve() in current_processed_file_path.parents
and
self.working_dir.resolve() not in included_file_path.parents
):
self.logger.debug(
'Currently processed file is located inside the working dir, ' +
'but included file is located outside the working dir. ' +
'So currently processed file path should be rewritten with the path of corresponding file ' +
'that is located inside the source dir'
)
included_file_path = (
self._get_src_file_path(current_processed_file_path).parent / user_specified_path
).resolve()
else:
self.logger.debug(
'Using these paths without changes'
)
self.logger.debug(f'Finally, included file path: {included_file_path}')
return included_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 process_includes(self, markdown_file_path: Path, content: str) -> str:
'''Replace all include statements with the respective file contents.
:param markdown_file_path: Path to curently processed Markdown file
:param content: Markdown content
:returns: Markdown content with resolved includes
'''
markdown_file_path = markdown_file_path.resolve()
self.logger.debug(f'Processing Markdown file: {markdown_file_path}')
processed_content = ''
include_statement_pattern = re.compile(
rf'((?<!\<)\<{"|".join(self.tags)}(?:\s[^\<\>]*)?\>.*?\<\/{"|".join(self.tags)}\>)',
flags=re.DOTALL
)
content_parts = include_statement_pattern.split(content)
for content_part in content_parts:
include_statement = self.pattern.fullmatch(content_part)
if include_statement:
body = self._tag_body_pattern.match(include_statement.group('body').strip())
options = self.get_options(include_statement.group('options'))
self.logger.debug(f'Processing include statement; body: {body}, options: {options}')
if body.group('repo'):
repo = body.group('repo')
repo_from_alias = self.options['aliases'].get(repo)
revision = None
if repo_from_alias:
self.logger.debug(f'Alias found: {repo}, resolved as: {repo_from_alias}')
if '#' in repo_from_alias:
repo_url, revision = repo_from_alias.split('#', maxsplit=1)
else:
repo_url = repo_from_alias
else:
repo_url = repo
if body.group('revision'):
revision = body.group('revision')
self.logger.debug(f'Highest priority revision specified in the include statement: {revision}')
self.logger.debug(f'File in Git repository referenced; URL: {repo_url}, revision: {revision}')
repo_path = self._sync_repo(repo_url, revision)
self.logger.debug(f'Local path of the repo: {repo_path}')
included_file_path = repo_path / body.group('path')
self.logger.debug(f'Resolved path to the included file: {included_file_path}')
processed_content_part = self._process_include(
included_file_path,
body.group('from_heading'),
body.group('to_heading'),
options
)
else:
self.logger.debug('Local file referenced')
included_file_path = self._get_included_file_path(body.group('path'), markdown_file_path)
self.logger.debug(f'Resolved path to the included file: {included_file_path}')
processed_content_part = self._process_include(
included_file_path,
body.group('from_heading'),
body.group('to_heading'),
options
)
if self.options['recursive'] and self.pattern.search(processed_content_part):
self.logger.debug('Recursive call of include statements processing')
processed_content_part = self.process_includes(included_file_path, processed_content_part)
if options.get('inline'):
self.logger.debug('Processing included content part as inline')
processed_content_part = re.sub(r'\s+', ' ', processed_content_part).strip()
else:
processed_content_part = content_part
processed_content += processed_content_part
return processed_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 get_logger(name, CFG=None):
"""set up logging for a service using the py 2.7 dictConfig """ |
logger = logging.getLogger(name)
if CFG:
# Make log directory if it doesn't exist
for handler in CFG.get('handlers', {}).itervalues():
if 'filename' in handler:
log_dir = os.path.dirname(handler['filename'])
if not os.path.exists(log_dir):
os.makedirs(log_dir)
try:
#TODO: This requires python 2.7
logging.config.dictConfig(CFG)
except AttributeError:
print >> sys.stderr, '"logging.config.dictConfig" doesn\'t seem to be supported in your python'
raise
return logger |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def t_trailingwhitespace(self, token):
ur'.+? \n'
print "Error: trailing whitespace at line %s in text '%s'" % (token.lexer.lineno + 1, token.value[:-1])
token.lexer.lexerror = True
token.lexer.skip(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 exec_before_request_actions(actions, **kwargs):
"""Execute actions in the "before" and "before_METHOD" groups """ |
groups = ("before", "before_" + flask.request.method.lower())
return execute_actions(actions, limit_groups=groups, **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 exec_after_request_actions(actions, response, **kwargs):
"""Executes actions of the "after" and "after_METHOD" groups. A "response" var will be injected in the current context. """ |
current_context["response"] = response
groups = ("after_" + flask.request.method.lower(), "after")
try:
rv = execute_actions(actions, limit_groups=groups, **kwargs)
except ReturnValueException as e:
rv = e.value
if rv:
return rv
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 as_view(url=None, methods=None, view_class=ActionsView, name=None, url_rules=None, **kwargs):
"""Decorator to transform a function into a view class. Be warned that this will replace the function with the view class. """ |
def decorator(f):
if url is not None:
f = expose(url, methods=methods)(f)
clsdict = {"name": name or f.__name__,
"actions": getattr(f, "actions", None),
"url_rules": url_rules or getattr(f, "urls", None)}
if isinstance(f, WithActionsDecorator):
f = f.func
clsdict['func'] = f
def constructor(self, **ctorkwargs):
for k, v in kwargs.items():
if k not in ctorkwargs or ctorkwargs[k] is None:
ctorkwargs[k] = v
view_class.__init__(self, func=f, **ctorkwargs)
clsdict["__init__"] = constructor
return type(f.__name__, (view_class,), clsdict)
return 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 register(self, target):
"""Registers url_rules on the blueprint """ |
for rule, options in self.url_rules:
target.add_url_rule(rule, self.name, self.dispatch_request, **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 view(self, *args, **kwargs):
"""Decorator to automatically apply as_view decorator and register it. """ |
def decorator(f):
kwargs.setdefault("view_class", self.view_class)
return self.add_view(as_view(*args, **kwargs)(f))
return 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 add_action_view(self, name, url, actions, **kwargs):
"""Creates an ActionsView instance and registers it. """ |
view = ActionsView(name, url=url, self_var=self, **kwargs)
if isinstance(actions, dict):
for group, actions in actions.iteritems():
view.actions.extend(load_actions(actions, group=group or None))
else:
view.actions.extend(load_actions(actions))
self.add_view(view)
return view |
<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(exam_num: int, time: str, date: str) -> None: """Process the exams in the exam_num folder for the time.""" |
prefix = Path(f"exams/exam-{exam_num}")
problems = list(prefix.glob(f"exam-{exam_num}-{time}-[0-9].ipynb"))
problems = sorted(problems, key=lambda k: k.stem[-1])
output_directory = (prefix / "output").resolve()
fw = FilesWriter(build_directory=str(output_directory))
assignment_zip_name = output_directory / f"exam-{exam_num}-{time}.zip"
solution_zip_name = output_directory / f"exam-{exam_num}-{time}-soln.zip"
solution_pdfs: List[BytesIO] = []
exam_date_time = datetime.strptime(time + date, "%H%M%d-%b-%Y")
res: Dict[str, Union[str, int]] = {
"exam_num": exam_num,
"time": exam_date_time.strftime("%I:%M %p"),
"date": exam_date_time.strftime("%b. %d, %Y"),
"delete_pymarkdown": True,
}
for problem in problems:
res["unique_key"] = problem.stem
problem_fname = str(problem.resolve())
if problem.stem.endswith("1"):
assignment_nb, _ = sa_nb_exp.from_filename(problem_fname, resources=res)
with ZipFile(assignment_zip_name, mode="a") as zip_file:
zip_file.writestr(problem.name, assignment_nb)
else:
assignment_nb, _ = prob_nb_exp.from_filename(problem_fname, resources=res)
with ZipFile(assignment_zip_name, mode="a") as zip_file:
zip_file.writestr(problem.name, assignment_nb)
solution_pdf, _ = solution_pdf_exp.from_filename(problem_fname, resources=res)
solution_pdfs.append(BytesIO(solution_pdf))
solution_nb, _ = solution_nb_exp.from_filename(problem_fname, resources=res)
with ZipFile(solution_zip_name, mode="a") as zip_file:
zip_file.writestr(problem.name, solution_nb)
resources: Dict[str, Any] = {
"metadata": {
"name": f"exam-{exam_num}-{time}-soln",
"path": str(prefix),
"modified_date": datetime.today().strftime("%B %d, %Y"),
},
"output_extension": ".pdf",
}
fw.write(
combine_pdf_as_bytes(solution_pdfs), resources, f"exam-{exam_num}-{time}-soln"
) |
<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(argv: Optional[Sequence[str]] = None) -> None: """Parse arguments and process the exam assignment.""" |
parser = ArgumentParser(description="Convert Jupyter Notebook exams to PDFs")
parser.add_argument(
"--exam",
type=int,
required=True,
help="Exam number to convert",
dest="exam_num",
)
parser.add_argument(
"--time", type=str, required=True, help="Time of exam to convert"
)
parser.add_argument(
"--date", type=str, required=True, help="The date the exam will take place"
)
args = parser.parse_args(argv)
process(args.exam_num, args.time, args.date) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_meta(self, text):
""" Takes input as the entire file. Reads the first yaml document as metadata. and the rest of the document as text """ |
first_line = True
metadata = []
content = []
metadata_parsed = False
for line in text.split('\n'):
if first_line:
first_line = False
if line.strip() != '---':
raise MetaParseException('Invalid metadata')
else:
continue
if line.strip() == '' and not metadata_parsed:
continue
if line.strip() == '---' and not metadata_parsed:
# reached the last line
metadata_parsed = True
elif not metadata_parsed:
metadata.append(line)
else:
content.append(line)
content = '\n'.join(content)
try:
metadata = yaml.load('\n'.join(metadata))
except:
raise
content = text
metadata = yaml.load('')
return content, metadata |
<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_defaults(self):
""" Add each model entry with it's default """ |
for key, value in self.spec.items():
setattr(self, key.upper(), value.get("default", 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 load_env(self):
""" Load the model fron environment variables """ |
for key, value in self.spec.items():
if value['type'] in (dict, list):
envar = (self.env_prefix + "_" + key).upper()
try:
envvar = env.json(envar,
default=getattr(self, key.upper(), value.get('default')))
except ConfigurationError as _err: #pragma: no cover
print(_err)
self.log.critical(f"Error parsing json from env var. {os.environ.get(envar)}")
print(envar)
raise
else:
envvar = env((self.env_prefix + "_" + key).upper(),
default=getattr(self, key.upper(), value.get('default')),
cast=value['type'])
setattr(self, key.upper(), envvar) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_args(self):
""" Parse the cli args Returns: args (namespace):
The args """ |
parser = ArgumentParser(description='',
formatter_class=RawTextHelpFormatter)
parser.add_argument("--generate", action="store", dest='generate',
choices=['command', 'docker-run', 'docker-compose',
'ini', 'env', 'kubernetes', 'readme', 'drone-plugin'],
help="Generate a template ")
parser.add_argument("--settings", action="store", dest='settings',
help="Specify a settings file. (ie settings.dev)")
for key, value in self.spec.items():
if value['type'] in [str, int, float]:
parser.add_argument(f"--{key.lower()}", action="store", dest=key,
type=value['type'],
choices=value.get("choices"),
help=self.help(value))
elif value['type'] == bool:
parser.add_argument(f"--{key.lower()}", action="store", dest=key,
type=lambda x:bool(strtobool(x)),
choices=value.get("choices"),
help=self.help(value))
elif value['type'] == list:
parser.add_argument(f"--{key.lower()}", action="store", dest=key,
nargs='+',
choices=value.get("choices"),
help=self.help(value))
elif value['type'] == dict:
parser.add_argument(f"--{key.lower()}", action="store", dest=key,
type=json.loads,
choices=value.get("choices"),
help=self.help(value))
args, _unknown = parser.parse_known_args()
return 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 add_args(self, args):
""" Add the args Args: args (namespace):
The commandline args """ |
for key, value in vars(args).items():
if value is not None:
setattr(self, key.upper(), 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 load_ini(self, ini_file):
""" Load the contents from the ini file Args: ini_file (str):
The file from which the settings should be loaded """ |
if ini_file and not os.path.exists(ini_file):
self.log.critical(f"Settings file specified but not found. {ini_file}")
sys.exit(1)
if not ini_file:
ini_file = f"{self.cwd}/settings.ini"
if os.path.exists(ini_file):
config = configparser.RawConfigParser(allow_no_value=True)
config.read(ini_file)
for key, value in self.spec.items():
entry = None
if value['type'] == str:
entry = config.get("settings", option=key.lower(), fallback=None)
elif value['type'] == bool:
entry = config.getboolean("settings", option=key.lower(), fallback=None)
elif value['type'] == int:
entry = config.getint("settings", option=key.lower(), fallback=None)
elif value['type'] == float:
entry = config.getfloat("settings", option=key.lower(), fallback=None)
elif value['type'] in [list, dict]:
entries = config.get("settings", option=key.lower(), fallback=None)
if entries:
try:
entry = json.loads(entries)
except json.decoder.JSONDecodeError as _err: #pragma: no cover
self.log.critical(f"Error parsing json from ini file. {entries}")
sys.exit(1)
if entry is not None:
setattr(self, key.upper(), 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 check_required(self):
""" Check all required settings have been provided """ |
die = False
for key, value in self.spec.items():
if not getattr(self, key.upper()) and value['required']:
print(f"{key} is a required setting. "
"Set via command-line params, env or file. "
"For examples, try '--generate' or '--help'.")
die = True
if die:
sys.exit(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 generate(self):
""" Generate sample settings """ |
otype = getattr(self, 'GENERATE')
if otype:
if otype == 'env':
self.generate_env()
elif otype == "command":
self.generate_command()
elif otype == "docker-run":
self.generate_docker_run()
elif otype == "docker-compose":
self.generate_docker_compose()
elif otype == "kubernetes":
self.generate_kubernetes()
elif otype == 'ini':
self.generate_ini()
elif otype == 'readme':
self.generate_readme()
elif otype == 'drone-plugin':
self.generate_drone_plugin()
sys.exit(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 generate_env(self):
""" Generate sample environment variables """ |
for key in sorted(list(self.spec.keys())):
if self.spec[key]['type'] in (dict, list):
value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'"
else:
value = f"{self.spec[key].get('example', '')}"
print(f"export {self.env_prefix}_{key.upper()}={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 generate_command(self):
""" Generate a sample command """ |
example = []
example.append(f"{sys.argv[0]}")
for key in sorted(list(self.spec.keys())):
if self.spec[key]['type'] == list:
value = " ".join(self.spec[key].get('example', ''))
elif self.spec[key]['type'] == dict:
value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'"
else:
value = self.spec[key].get('example', '')
string = f" --{key.lower()} {value}"
example.append(string)
print(" \\\n".join(example)) |
<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_docker_run(self):
""" Generate a sample docker run """ |
example = []
example.append("docker run -it")
for key in sorted(list(self.spec.keys())):
if self.spec[key]['type'] in (dict, list):
value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'"
else:
value = f"{self.spec[key].get('example', '')}"
string = f" -e {self.env_prefix}_{key.upper()}={value}"
example.append(string)
example.append(" <container-name>")
print(" \\\n".join(example)) |
<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_docker_compose(self):
""" Generate a sample docker compose """ |
example = {}
example['app'] = {}
example['app']['environment'] = []
for key in sorted(list(self.spec.keys())):
if self.spec[key]['type'] in (dict, list):
value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'"
else:
value = f"{self.spec[key].get('example', '')}"
example['app']['environment'].append(f"{self.env_prefix}_{key.upper()}={value}")
print(yaml.dump(example, default_flow_style=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 generate_ini(self):
""" Generate a sample ini """ |
example = []
example.append("[settings]")
for key in sorted(list(self.spec.keys())):
if self.spec[key]['type'] in [list, dict]:
value = json.dumps(self.spec[key].get('example', ''))
else:
value = self.spec[key].get('example', '')
string = f"{key.lower()}={value}"
example.append(string)
print("\n".join(example)) |
<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_kubernetes(self):
""" Generate a sample kubernetes """ |
example = {}
example['spec'] = {}
example['spec']['containers'] = []
example['spec']['containers'].append({"name": '', "image": '', "env": []})
for key, value in self.spec.items():
if value['type'] in (dict, list):
kvalue = f"\'{json.dumps(value.get('example', ''))}\'"
else:
kvalue = f"{value.get('example', '')}"
entry = {"name": f"{self.env_prefix}_{key.upper()}", "value": kvalue}
example['spec']['containers'][0]['env'].append(entry)
print(yaml.dump(example, default_flow_style=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 generate_drone_plugin(self):
""" Generate a sample drone plugin configuration """ |
example = {}
example['pipeline'] = {}
example['pipeline']['appname'] = {}
example['pipeline']['appname']['image'] = ""
example['pipeline']['appname']['secrets'] = ""
for key, value in self.spec.items():
if value['type'] in (dict, list):
kvalue = f"\'{json.dumps(value.get('example', ''))}\'"
else:
kvalue = f"{value.get('example', '')}"
example['pipeline']['appname'][key.lower()] = kvalue
print(yaml.dump(example, default_flow_style=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 generate_readme(self):
""" Generate a readme with all the generators """ |
print("## Examples of settings runtime params")
print("### Command-line parameters")
print("```")
self.generate_command()
print("```")
print("### Environment variables")
print("```")
self.generate_env()
print("```")
print("### ini file")
print("```")
self.generate_ini()
print("```")
print("### docker run")
print("```")
self.generate_docker_run()
print("```")
print("### docker compose")
print("```")
self.generate_docker_compose()
print("```")
print("### kubernetes")
print("```")
self.generate_kubernetes()
print("```")
print("### drone plugin")
print("```")
self.generate_drone_plugin()
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 file_exists(self, subdir, prefix, suffix):
"""Returns true if the resource file exists, else False. Positional arguments: subdir -- sub directory name under the resource's main directory (e.g. css or js, or an empty string if the resource's directory structure is flat). prefix -- file name without the file extension. suffix -- file extension (if self.minify = True, includes .min before the extension). """ |
real_path = os.path.join(self.STATIC_DIR, self.DIR, subdir, prefix + suffix)
return os.path.exists(real_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 add_css(self, subdir, file_name_prefix):
"""Add a css file for this resource. If self.minify is True, checks if the .min.css file exists. If not, falls back to non-minified file. If that file also doesn't exist, IOError is raised. Positional arguments: subdir -- sub directory name under the resource's main directory (e.g. css or js, or an empty string). file_name_prefix -- file name without the file extension. """ |
suffix_maxify = '.css'
suffix_minify = '.min.css'
if self.minify and self.file_exists(subdir, file_name_prefix, suffix_minify):
self.resources_css.append(posixpath.join(self.DIR, subdir, file_name_prefix + suffix_minify))
elif self.file_exists(subdir, file_name_prefix, suffix_maxify):
self.resources_css.append(posixpath.join(self.DIR, subdir, file_name_prefix + suffix_maxify))
else:
file_path = os.path.join(self.STATIC_DIR, self.DIR, subdir, file_name_prefix + suffix_maxify)
raise IOError('Resource file not found: {0}'.format(file_path)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.