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 create_object(self, filename, img_properties=None):
"""Create an image object on local disk from the given file. The file is copied to a new local directory ... |
# Get the file name, i.e., last component of the given absolute path
prop_name = os.path.basename(os.path.normpath(filename))
# Ensure that the image file has a valid suffix. Currently we do not
# check whether the file actually is an image. If the suffix is valid
# get the asso... |
<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_dict(self, document):
"""Create image object from JSON document retrieved from database. Parameters document : JSON Json document in database Returns --... |
# Get object properties from Json document
identifier = str(document['_id'])
active = document['active']
timestamp = datetime.datetime.strptime(document['timestamp'], '%Y-%m-%dT%H:%M:%S.%f')
properties = document['properties']
# The directory is not materilaized in datab... |
<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_directory(self, identifier):
"""Implements the policy for naming directories for image objects. Image object directories are name by their identifier. In... |
return os.path.join(
os.path.join(self.directory, identifier[:2]),
identifier
) |
<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_object(self, name, images, filename, options=None, object_identifier=None, read_only=False):
"""Create an image group object with the given list of im... |
# Raise an exception if given image group is not valied.
self.validate_group(images)
# Create a new object identifier if none is given.
if object_identifier is None:
identifier = str(uuid.uuid4()).replace('-','')
else:
identifier = object_identifier
... |
<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_dict(self, document):
"""Create image group object from JSON document retrieved from database. Parameters document : JSON Json document in database Retu... |
# Get object attributes from Json document
identifier = str(document['_id'])
# Create list of group images from Json
images = list()
for grp_image in document['images']:
images.append(GroupImage(
grp_image['identifier'],
grp_image['fol... |
<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_collections_for_image(self, image_id):
"""Get identifier of all collections that contain a given image. Parameters image_id : string Unique identifierof ... |
result = []
# Get all active collections that contain the image identifier
for document in self.collection.find({'active' : True, 'images.identifier' : image_id}):
result.append(str(document['_id']))
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 to_dict(self, img_coll):
"""Create a Json-like dictionary for image group. Extends the basic object with an array of image identifiers. Parameters img_coll :... |
# Get the basic Json object from the super class
json_obj = super(DefaultImageGroupManager, self).to_dict(img_coll)
# Add list of images as Json array
images = []
for img_group in img_coll.images:
images.append({
'identifier' : img_group.identifier,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_group(images):
"""Validates that the combination of folder and name for all images in a group is unique. Raises a ValueError exception if uniqueness... |
image_ids = set()
for image in images:
key = image.folder + image.name
if key in image_ids:
raise ValueError('Duplicate images in group: ' + key)
else:
image_ids.add(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 create_object(self, name, image_sets):
"""Create a prediction image set list. Parameters name : string User-provided name for the image group. image_sets : l... |
# Create a new object identifier
identifier = str(uuid.uuid4()).replace('-','')
properties = {datastore.PROPERTY_NAME: name}
# Create the image group object and store it in the database before
# returning it.
obj = PredictionImageSetHandle(identifier, properties, image_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 from_dict(self, document):
"""Create a prediction image set resource from a dictionary serialization. Parameters document : dict Dictionary serialization of ... |
return PredictionImageSetHandle(
str(document['_id']),
document['properties'],
[PredictionImageSet.from_dict(img) for img in document['images']],
timestamp=datetime.datetime.strptime(
document['timestamp'],
'%Y-%m-%dT%H:%M:%S.%f'
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self, img_sets):
"""Create a dictionary serialization for a prediction image set handle. Parameters img_sets : PredictionImageSetHandle Returns -----... |
# Get the basic Json object from the super class
json_obj = super(DefaultPredictionImageSetManager, self).to_dict(img_sets)
# Add list of image sets as Json array
json_obj['images'] = [img_set.to_dict() for img_set in img_sets.images]
return json_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 _load_tasks(self, tasks, vars={}, additional_conditions=[]):
''' handle task and handler include statements '''
results = []
if tasks is None:
# support empty handler files, and the like.
tasks = []
for x in tasks:
task_vars = self.vars.copy()
... |
<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_vars(self):
''' load the vars section from a play, accounting for all sorts of variable features
including loading from yaml files, prompting, and conditional includes of the first
file found in a list. '''
if self.vars is None:
self.vars = {}
if type(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 key_event_to_name(event):
""" Converts a keystroke event into a corresponding key name. """ |
key_code = event.key()
modifiers = event.modifiers()
if modifiers & QtCore.Qt.KeypadModifier:
key = keypad_map.get(key_code)
else:
key = None
if key is None:
key = key_map.get(key_code)
name = ''
if modifiers & QtCore.Qt.ControlModifier:
name += 'Ctrl'
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def readmodule(module, path=None):
'''Backwards compatible interface.
Call readmodule_ex() and then only keep Class objects from the
resulting dictionary.'''
res = {}
for key, value in _readmodule(module, path or []).items():
if isinstance(value, Class):
res[key] = value
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 _basic_field_data(field, obj):
"""Returns ``obj.field`` data as a dict""" |
value = field.value_from_object(obj)
return {Field.TYPE: FieldType.VAL, Field.VALUE: 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 _related_field_data(field, obj):
"""Returns relation ``field`` as a dict. Dict contains related pk info and some meta information for reconstructing objects.... |
data = _basic_field_data(field, obj)
relation_info = {
Field.REL_DB_TABLE: field.rel.to._meta.db_table,
Field.REL_APP: field.rel.to._meta.app_label,
Field.REL_MODEL: field.rel.to.__name__
}
data[Field.TYPE] = FieldType.REL
data[Field.REL] = relation_info
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _m2m_field_data(field, obj):
"""Returns m2m ``field`` as a dict. Value is an array of related primary keys and some meta information for reconstructing objec... |
data = _basic_field_data(field, obj)
data[Field.TYPE] = FieldType.M2M
related = field.rel.to
relation_info = {
Field.REL_DB_TABLE: related._meta.db_table,
Field.REL_APP: related._meta.app_label,
Field.REL_MODEL: related.__name__
}
data[Field.REL] = relation_info
valu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump_model(obj):
"""Returns ``obj`` as a dict. Returnded dic has a form of: { 'field_name': { 'type': `FieldType`, 'value': field value, # if field is a rela... |
data = {}
for field in obj._meta.fields:
if isinstance(field, RELATED_FIELDS):
field_data = _related_field_data(field, obj)
else:
field_data = _basic_field_data(field, obj)
data[field.name] = field_data
if obj.pk:
for m2m in obj._meta.many_to_many:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restore_model(cls, data):
"""Returns instance of ``cls`` with attributed loaded from ``data`` dict. """ |
obj = cls()
for field in data:
setattr(obj, field, data[field][Field.VALUE])
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 retrieve_object(cache, template, indexes):
"""Retrieve an object from Redis using a pipeline. Arguments: template: a dictionary containg the keys for the obj... |
keys = []
with cache as redis_connection:
pipe = redis_connection.pipeline()
for (result_key, redis_key_template) in template.items():
keys.append(result_key)
pipe.get(redis_key_template % indexes)
results = pipe.execute()
return None if None in results 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 set_object(cache, template, indexes, data):
"""Set an object in Redis using a pipeline. Only sets the fields that are present in both the template and the da... |
# TODO(mattmillr): Handle expiration times
with cache as redis_connection:
pipe = redis_connection.pipeline()
for key in set(template.keys()) & set(data.keys()):
pipe.set(template[key] % indexes, str(data[key]))
pipe.execute() |
<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_object(cache, template, indexes):
"""Delete an object in Redis using a pipeline. Deletes all fields defined by the template. Arguments: template: a di... |
with cache as redis_connection:
pipe = redis_connection.pipeline()
for key in set(template.keys()):
pipe.delete(template[key] % indexes)
pipe.execute() |
<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_value(cache, key, value):
"""Set a value by key. Arguments: cache: instance of Cache key: 'user:342:username', """ |
with cache as redis_connection:
return redis_connection.set(key, 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 create(url, filename, properties):
"""Create new subject at given SCO-API by uploading local file. Expects an tar-archive containing FreeSurfer archive file.... |
# Ensure that the file has valid suffix
if not has_tar_suffix(filename):
raise ValueError('invalid file suffix: ' + filename)
# Upload file to create subject. If response is not 201 the uploaded
# file is not a valid FreeSurfer archive
files = {'file': open(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 getdata(inputfile, argnum=None, close=False):
""" Get data from the .dat files args: inputfile: file Input File close: bool, default=False Closes inputfile i... |
# get data and converts them to list
# outputtype - list, dict, all
output = []
add_data = {}
line_num = 0
for line in inputfile:
line_num += 1
if ("#" not in line) and (line != ""):
linesplit = line.split()
if argnum is not None and len(linesplit) != int... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_supervisor(self, update=False):
""" install supervisor config for redis """ |
script = supervisor.Recipe(
self.buildout,
self.name,
{'user': self.options.get('user'),
'program': self.options.get('program'),
'command': templ_cmd.render(config=self.conf_filename, prefix=self.prefix),
'stopwaitsecs': '30',
... |
<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(val, valtype, floatfmt, missingval="", has_invisible=True):
"""Format a value accoding to its type. Unicode is supported: tbl = [['\u0430\u0437', 2],... |
if val is None:
return missingval
if valtype in [int, _long_type, _text_type]:
return "{0}".format(val)
elif valtype is _binary_type:
try:
return _text_type(val, "ascii")
except TypeError:
return _text_type(val)
elif valtype is float:
is_... |
<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_view_model(cls):
""" Get the model to use in the filter_class by inspecting the queryset or by using a declared auto_filters_model """ |
msg = 'When using get_queryset you must set a auto_filters_model field in the viewset'
if cls.queryset is not None:
return cls.queryset.model
else:
assert hasattr(cls, 'auto_filters_model'), msg
return cls.auto_filters_model |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auto_filters(cls):
""" Adds a dynamic filterclass to a viewset with all auto filters available for the field type that are declared in a tuple auto_filter_fi... |
msg = 'Viewset must have auto_filters_fields or auto_filters_exclude attribute when using auto_filters decorator'
if not hasattr(cls, 'auto_filters_fields') and not hasattr(cls, 'auto_filters_exclude'):
raise AssertionError(msg)
dict_ = {}
view_model = get_view_model(cls)
auto_filters_fiel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def env(*_vars, **kwargs):
"""Search for the first defined of possibly many env vars. Returns the first environment variable defined in vars, or returns the defa... |
for v in _vars:
value = os.environ.get(v, None)
if value:
return value
return kwargs.get('default', '') |
<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_option_parser(self, description, version):
"""Return an argparse option parser for this application. Subclasses may override this method to extend the ... |
parser = argparse.ArgumentParser(
description=description,
add_help=False, )
parser.add_argument(
'--version',
action='version',
version=__version__, )
parser.add_argument(
'-v', '--verbose', '--debug',
action='... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bash_completion(self):
"""Prints all of the commands and options for bash-completion.""" |
commands = set()
options = set()
for option, _action in self.parser._option_string_actions.items():
options.add(option)
for _name, _command in self.command_manager:
commands.add(_name)
cmd_factory = _command.load()
cmd = cmd_factory(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 run(self, argv):
"""Equivalent to the main program for the application. :param argv: input arguments and options :paramtype argv: list of str """ |
try:
index = 0
command_pos = -1
help_pos = -1
help_command_pos = -1
for arg in argv:
if arg == 'bash-completion' and help_command_pos == -1:
self._bash_completion()
return 0
if ar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authenticate_user(self):
"""Confirm user authentication Make sure the user has provided all of the authentication info we need. """ |
cloud_config = os_client_config.OpenStackConfig().get_one_cloud(
cloud=self.options.os_cloud, argparse=self.options,
network_api_version=self.api_version,
verify=not self.options.insecure)
verify, cert = cloud_config.get_requests_verify_args()
# TODO(singhj)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_logging(self):
"""Create logging handlers for any log output.""" |
root_logger = logging.getLogger('')
# Set up logging to a file
root_logger.setLevel(logging.DEBUG)
# Send higher-level messages to the console via stderr
console = logging.StreamHandler(self.stderr)
console_level = {self.WARNING_LEVEL: logging.WARNING,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def max_substring(words, position=0, _last_letter=''):
"""Finds max substring shared by all strings starting at position Args: words (list):
list of unicode of ... |
# If end of word is reached, begin reconstructing the substring
try:
letter = [word[position] for word in words]
except IndexError:
return _last_letter
# Recurse if position matches, else begin reconstructing the substring
if all(l == letter[0] for l in letter) is True:
_l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _map_generator(f, generator):
"""Apply ``f`` to the results of the given bi-directional generator. Unfortunately, generator comprehension (``f(x) for x in ge... |
item = next(generator)
while True:
try:
result = yield f(item)
except Exception:
item = generator.throw(*sys.exc_info())
else:
item = generator.send(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 compile_markdown_file(source_file):
'''Compiles a single markdown file to a remark.js slideshow.'''
template = pkg_resources.resource_string('md2remark.resources.templates', 'slideshow.mustache')
renderer = pystache.Renderer(search_dirs='./templates')
f = open(source_file, 'r')
slideshow_md = f.read()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def compile_slides(source):
'''Compiles the source to a remark.js slideshow.'''
# if it's a directory, do all md files.
if os.path.isdir(source):
for f in os.listdir(source):
if f.lower().endswith('.md'):
compile_markdown_file(os.path.join(source, f))
else:
compile_markdown_file(source) |
<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_cl_args(arg_vector):
'''Parses the command line arguments'''
parser = argparse.ArgumentParser(description='Compiles markdown files into html files for remark.js')
parser.add_argument('source', metavar='source', help='the source to compile. If a directory is provided, all markdown files in that directory... |
<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_filter_qobj(self, keys=None):
""" Return a copy of this Query object with additional where clauses for the keys in the argument """ |
# only care about columns in aggregates right?
cols = set()
for agg in self.select.aggregates:
cols.update(agg.cols)
sels = [SelectExpr(col, [col], col, None) for col in cols]
select = Select(sels)
where = list(self.where)
if keys:
keys = list(keys)
keys = map(sqlize, li... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def total_build_duration_for_chain(self, build_chain_id):
"""Returns the total duration for one specific build chain run""" |
return sum([
int(self.__build_duration_for_id(id))
for id in self.__build_ids_of_chain(build_chain_id)
]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_cycle_time(self, build_id):
"""Returns a BuildCycleTime object for the given build""" |
json_form = self.__retrieve_as_json(self.builds_path % build_id)
return BuildCycleTime(
build_id,
json_form[u'buildTypeId'],
as_date(json_form, u'startDate'),
(as_date(json_form, u'finishDate') - as_date(json_form, u'queuedDate')).seconds * 1000
) |
<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_stats_for_chain(self, build_chain_id):
"""Returns a list of Build tuples for all elements in the build chain. This method allows insight into the runti... |
json_form = self.__retrieve_as_json(self.build_chain_path % build_chain_id)
builds = [{'build_id': build[u'id'], 'configuration_id': build[u'buildTypeId']} for build in json_form[u'build']]
return [
BuildStat(
build['build_id'],
build['configuration_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quadratic_2d(data):
""" Compute the quadratic estimate of the centroid in a 2d-array. Args: data (2darray):
two dimensional data array Returns center (tuple... |
arg_data_max = np.argmax(data)
i, j = np.unravel_index(arg_data_max, data.shape)
z_ = data[i-1:i+2, j-1:j+2]
# our quadratic function is defined as
# f(x, y | a, b, c, d, e, f) := a + b * x + c * y + d * x^2 + e * xy + f * y^2
# therefore, the best fit coeffiecients are given as
# note that... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def depsOf_of_mirteFile_instance_definition(man, insts):
""" Returns a function that returns the dependencies of an instance definition by its name, where insts ... |
return lambda x: [a[1] for a in six.iteritems(insts[x])
if a[0] in [dn for dn, d in (
six.iteritems(man.modules[insts[x]['module']].deps)
if 'module' in insts[x] 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 depsOf_of_mirteFile_module_definition(defs):
""" Returns a function that returns the dependencies of a module definition by its name, where defs is a diction... |
return lambda x: (list(filter(lambda z: z is not None and z in defs,
map(lambda y: y[1].get('type'),
six.iteritems(defs[x]['settings'])
if 'settings' in defs[x] else [])))) + \
(list(defs[x]['inherits']) if 'inhe... |
<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, size=None):
"Generates a new word"
corpus_letters = list(self.vectors.keys())
current_letter = random.choice(corpus_letters)
if size is None:
size = int(random.normalvariate(self.avg, self.std_dev))
letters = [current_letter]
for _ in ran... |
<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_tasks(env, tasks, mark_active=False):
""" Prints task information using io stream. `env` ``Environment`` object. `tasks` List of tuples (task_name, op... |
if env.task.active and mark_active:
active_task = env.task.name
else:
active_task = None
for task, options, blocks in tasks:
# print heading
invalid = False
if task == active_task:
method = 'success'
else:
if options is None and blo... |
<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_task_config(env, task_config, confirm):
""" Launches text editor to edit provided task configuration file. `env` Runtime ``Environment`` instance. `tas... |
# get editor program
if common.IS_MACOSX:
def_editor = 'open'
else:
def_editor = 'vi'
editor = os.environ.get('EDITOR', def_editor)
def _edit_file(filename):
""" Launches editor for given filename.
"""
proc = subprocess.Popen('{0} {1}'.format(editor, fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, env, args):
""" Starts a new task. `env` Runtime ``Environment`` instance. `args` Arguments object from arg parser. """ |
# start the task
if env.task.start(args.task_name):
env.io.success(u'Task Loaded.') |
<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_parser(self, parser):
""" Setup the argument parser. `parser` ``FocusArgParser`` object. """ |
parser.add_argument('task_name', help='task to create')
parser.add_argument('clone_task', nargs='?',
help='existing task to clone')
parser.add_argument('--skip-edit', action='store_true',
help='skip editing of task configuration') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, env, args):
""" Creates a new task. `env` Runtime ``Environment`` instance. `args` Arguments object from arg parser. """ |
task_name = args.task_name
clone_task = args.clone_task
if not env.task.create(task_name, clone_task):
raise errors.FocusError(u'Could not create task "{0}"'
.format(task_name))
# open in task config in editor
if not args.skip_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 execute(self, env, args):
""" Edits task configuration. `env` Runtime ``Environment`` instance. `args` Arguments object from arg parser. """ |
task_name = args.task_name
if not env.task.exists(task_name):
raise errors.TaskNotFound(task_name)
if env.task.active and task_name == env.task.name:
raise errors.ActiveTask
# open in task config in editor
task_config = env.task.get_config_path(task_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 execute(self, env, args):
""" Lists all valid tasks. `env` Runtime ``Environment`` instance. `args` Arguments object from arg parser. """ |
tasks = env.task.get_list_info()
if not tasks:
env.io.write("No tasks found.")
else:
if args.verbose:
_print_tasks(env, tasks, mark_active=True)
else:
if env.task.active:
active_task = env.task.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 no_content_response(response):
"Cautious assessment of the response body for no content."
if not hasattr(response, '_container'):
return True
if response._container is None:
return True
if isinstance(response._container, (list, tuple)):
if len(response._container) == 1 and ... |
<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_template_file(file_name, context):
""" Renders and overrides Jinja2 template files """ |
with open(file_name, 'r+') as f:
template = Template(f.read())
output = template.render(context)
f.seek(0)
f.write(output)
f.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 main(name, output, font):
""" Easily bootstrap an OS project to fool HR departments and pad your resume. """ |
# The path of the directory where the final files will end up in
bootstrapped_directory = os.getcwd() + os.sep + name.lower().replace(' ', '-') + os.sep
# Copy the template files to the target directory
copy_tree(get_real_path(os.sep + 'my-cool-os-template'), bootstrapped_directory)
# Create th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dbfreader(f):
"""Returns an iterator over records in a Xbase DBF file. The first row returned contains the field names. The second row contains field specs: ... |
# See DBF format spec at:
# http://www.pgts.com.au/download/public/xbase.htm#DBF_STRUCT
numrec, lenheader = struct.unpack('<xxxxLH22x', f.read(32))
numfields = (lenheader - 33) // 32
fields = []
for fieldno in xrange(numfields):
name, typ, size, deci = struct.unpack('<11sc4xBB14x'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dbf_asdict(fn, usecols=None, keystyle='ints'):
"""Return data from dbf file fn as a dict. fn: str The filename string. usecols: seqence The columns to use, 0... |
if keystyle not in ['ints', 'names']:
raise ValueError('Unknown keyword: ' + str(keystyle))
with open(fn, 'rb') as fo:
rit = dbfreader(fo)
names = rit.next()
specs = rit.next() # NOQA
R = [tuple(r) for r in rit]
def getkey(i):
if keystyle == 'ints':
... |
<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(self):
""" Check that this table is complete, that is, every character of this table can be followed by a new character. :return: True if the table is ... |
for character, followers in self.items():
for follower in followers:
if follower not in self:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_word(self, length, prefix=0, start=False, end=False, flatten=False):
""" Generate a random word of length from this table. :param length: the length o... |
if start:
word = ">"
length += 1
return self._extend_word(word, length, prefix=prefix, end=end,
flatten=flatten)[1:]
else:
first_letters = list(k for k in self if len(k) == 1 and k != ">")
while 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 _extend_word(self, word, length, prefix=0, end=False, flatten=False):
""" Extend the given word with a random suffix up to length. :param length: the length ... |
if len(word) == length:
if end and "<" not in self[word[-1]]:
raise GenerationError(word + " cannot be extended")
else:
return word
else: # len(word) < length
exclude = {"<"}
while True:
choices = self.weig... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_module(module_path):
""" Try to import and return the given module, if it exists, None if it doesn't exist :raises ImportError: When imported module c... |
if six.PY2:
try:
return importlib.import_module(module_path)
except ImportError:
tb = sys.exc_info()[2]
stack = traceback.extract_tb(tb, 3)
if len(stack) > 2:
raise
else:
from importlib import find_loader
if find_lo... |
<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_password(length, chars=string.letters + string.digits + '#$%&!'):
""" Generate and return a random password :param length: Desired length :param chars: ... |
return get_random_string(length, chars) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __load_section(self, section_key):
""" Reads the set of article links for a section if they are not cached. """ |
if self._sections[section_key] is not None: return
articles = []
for page in count(1):
if page > 50:
raise Exception('Last page detection is probably broken')
url = '{domain}{section}&iMenuID=1&iSubMenuID={page}'.format(
domain = DOMAIN,... |
<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(self):
""" Loads text and photos if they are not cached. """ |
if self._text is not None: return
body = self._session.get(self.url).content
root = html.fromstring(body)
self._text = "\n".join((
p_tag.text_content()
for p_tag in root.findall('.//p[@class="ArticleContent"]')
if 'justify' in p_tag.get('styl... |
<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_whitelisted(self, req):
"""Return True if role is whitelisted or roles cannot be determined.""" |
if not self.roles_whitelist:
return False
if not hasattr(req, 'context'):
self.log.info("No context found.")
return False
if not hasattr(req.context, 'roles'):
self.log.info("No roles found in context")
return False
roles =... |
<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_topic(request, forum_slug=None):
""" Adds a topic to a given forum """ |
forum = Forum.objects.get(slug=forum_slug)
form = AddTopicForm(request.POST or None, request.FILES or None, initial={'forum': forum})
current_time = time.time()
user = request.user
if form.is_valid():
instance = form.save(commit=False)
instance.forum = forum... |
<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_post(request, t_slug, t_id, p_id = False):
# topic slug, topic id, post id """ Creates a new post and attaches it to a topic """ |
topic = get_object_or_404(Topic, id=t_id)
topic_url = '{0}page{1}/'.format(topic.get_short_url(), topic.page_count)
user = request.user
current_time = time.time()
form_title = 'Add a post'
if topic.is_locked: # If we mistakenly allowed reply on locked topic, bail with error msg.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def edit_post(request, post_id):
""" Allows user to edit an existing post. This needs to be rewritten. Badly. """ |
post = get_object_or_404(Post, id=post_id)
user = request.user
topic = post.topic
# oughta build a get_absolute_url method for this, maybe.
post_url = '{0}page{1}/#post{2}'.format(topic.get_short_url(), topic.page_count, post.id)
if topic.is_locked:
messages.error(request, 'Sorry... |
<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_post(request, post_id, topic_id):
""" Deletes a post, if the user has correct permissions. Also updates topic.post_count """ |
try:
topic = Topic.objects.get(id=topic_id)
post = Post.objects.get(id=post_id)
except:
messages.error(request, 'Sorry, but this post can not be found. It may have been deleted already.')
raise Http404
return_url = "/forum/%s/%s/%s/" % (topic.forum.slug, topic.slug, topic_id... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emit(self, record):
""" Emit a record. The record is formatted, and then sent to the syslog server. If exception information is present, it is NOT... |
msg = self.format(record) + '\000'
"""
We need to convert record level to lowercase, maybe this will
change in the future.
"""
prio = '<%d>' % self.encodePriority(self.facility,
self.mapPriority(record.levelname))
prio = prio.encode('utf-8')
# Message is a string. Convert to bytes as required by 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 jackknife_loop(func, data, d=1, combolimit=int(1e6)):
"""Generic Jackknife Subsampling procedure func : function A function pointer to a python function that... |
# load modules
import scipy.special
import warnings
import itertools
import numpy as np
# How many observations contains data?
N = data.shape[0]
# throw a warning!
numcombos = scipy.special.comb(N, d, exact=True) # binocoeff
if numcombos > 1e5:
warnings.warn((
... |
<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_zone(server, token, domain, identifier, dtype, master=None):
"""Create zone records. Arguments: server: TonicDNS API server token: TonicDNS API authen... |
method = 'PUT'
uri = 'https://' + server + '/zone'
obj = JSONConverter(domain)
obj.generate_zone(domain, identifier, dtype, master)
connect.tonicdns_client(uri, method, token, obj.zone) |
<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_records(server, token, domain, data):
"""Create records of specific domain. Arguments: server: TonicDNS API server token: TonicDNS API authentication ... |
method = 'PUT'
uri = 'https://' + server + '/zone/' + domain
for i in data:
connect.tonicdns_client(uri, method, token, 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 delete_records(server, token, data):
"""Delete records of specific domain. Arguments: server: TonicDNS API server token: TonicDNS API authentication token da... |
method = 'DELETE'
uri = 'https://' + server + '/zone'
for i in data:
connect.tonicdns_client(uri, method, token, 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 get_zone(server, token, domain, keyword='', raw_flag=False):
"""Retrieve zone records. Argument: server: TonicDNS API server token: TonicDNS API authenticati... |
method = 'GET'
uri = 'https://' + server + '/zone/' + domain
data = connect.tonicdns_client(uri, method, token, data=False,
keyword=keyword, raw_flag=raw_flag)
return data |
<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_zone(server, token, domain):
"""Delete specific zone. Argument: server: TonicDNS API server token: TonicDNS API authentication token domain: Specify d... |
method = 'DELETE'
uri = 'https://' + server + '/zone/' + domain
connect.tonicdns_client(uri, method, token, data=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 create_template(server, token, identifier, template):
"""Create template. Argument: server: TonicDNS API server token: TonicDNS API authentication token iden... |
method = 'PUT'
uri = 'https://' + server + '/template/' + identifier
connect.tonicdns_client(uri, method, token, data=template) |
<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_all_templates(server, token):
"""Retrieve all templates. Argument: server: TonicDNS API server token: TonicDNS API authentication token x-authentication-... |
method = 'GET'
uri = 'https://' + server + '/template'
connect.tonicdns_client(uri, method, token, data=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 update_soa_serial(server, token, soa_content):
"""Update SOA serial Argument: server: TonicDNS API server token: TonicDNS API authentication token soa_conten... |
method = 'GET'
uri = 'https://' + server + '/zone/' + soa_content.get('domain')
cur_soa, new_soa = connect.tonicdns_client(
uri, method, token, data=False, keyword='serial', content=soa_content)
# set JSON
domain = soa_content.get('domain')
cur_o = JSONConverter(domain)
new_o = JSO... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decompose_seconds_in_day(seconds):
"""Decomposes seconds in day into hour, minute and second components. Arguments --------- seconds : int A time of day by t... |
if seconds > SECONDS_IN_DAY:
seconds = seconds - SECONDS_IN_DAY
if seconds < 0:
raise ValueError("seconds param must be non-negative!")
hour = int(seconds / 3600)
leftover = seconds - hour * 3600
minute = int(leftover / 60)
second = leftover - minute * 60
return hour, minute... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def seconds_in_day_to_time(seconds):
"""Decomposes atime of day into hour, minute and seconds components. Arguments --------- seconds : int A time of day by the ... |
try:
return time(*decompose_seconds_in_day(seconds))
except ValueError:
print("Seconds = {}".format(seconds))
print("H = {}, M={}, S={}".format(*decompose_seconds_in_day(seconds)))
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 _as_rdf_xml(self, ns):
""" Return identity details for the element as XML nodes """ |
self.rdf_identity = self._get_identity(ns)
elements = []
elements.append(ET.Element(NS('sbol', 'persistentIdentity'),
attrib={NS('rdf', 'resource'):
self._get_persistent_identitity(ns)}))
if self.name is not 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 get_requirement_files(args=None):
""" Get the "best" requirements file we can find """ |
if args and args.input_filename:
return [args.input_filename]
paths = []
for regex in settings.REQUIREMENTS_SOURCE_GLOBS:
paths.extend(glob.glob(regex))
return paths |
<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_domains(self):
""" Return all domains. Domain is a key, so group by them """ |
self.connect()
results = self.server.list_domains(self.session_id)
return {i['domain']: i['subdomains'] for i in results} |
<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_websites(self):
""" Return all websites, name is not a key """ |
self.connect()
results = self.server.list_websites(self.session_id)
return results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def website_exists(self, website, websites=None):
""" Look for websites matching the one passed """ |
if websites is None:
websites = self.list_websites()
if isinstance(website, str):
website = {"name": website}
ignored_fields = ('id',) # changes in these fields are ignored
results = []
for other in websites:
different = False
fo... |
<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_month_namedays(self, month=None):
"""Return names as a tuple based on given month. If no month given, use current one""" |
if month is None:
month = datetime.now().month
return self.NAMEDAYS[month-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 has_moderator_permissions(self, request):
""" Find if user have global or per object permission firstly on category instance, if not then on thread instance ... |
return any(request.user.has_perm(perm) for perm in self.permission_required) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getvar(key, default=None, template='OPENSHIFT_{key}'):
""" Get OPENSHIFT envvar """ |
return os.environ.get(template.format(key=key), default) |
<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(parent, idx, value):
"""Add a value to a dict.""" |
if isinstance(parent, dict):
if idx in parent:
raise JSONPatchError("Item already exists")
parent[idx] = value
elif isinstance(parent, list):
if idx == "" or idx == "~":
parent.append(value)
else:
parent.insert(int(idx), value)
else:
raise JSONPathError("Invalid path for ope... |
<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(parent, idx):
"""Remove a value from a dict.""" |
if isinstance(parent, dict):
del parent[idx]
elif isinstance(parent, list):
del parent[int(idx)]
else:
raise JSONPathError("Invalid path for operation") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace(parent, idx, value, check_value=_NO_VAL):
"""Replace a value in a dict.""" |
if isinstance(parent, dict):
if idx not in parent:
raise JSONPatchError("Item does not exist")
elif isinstance(parent, list):
idx = int(idx)
if idx < 0 or idx >= len(parent):
raise JSONPatchError("List index out of range")
if check_value is not _NO_VAL:
if parent[idx] != check_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 merge(parent, idx, value):
"""Merge a value.""" |
target = get_child(parent, idx)
for key, val in value.items():
target[key] = val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(src_parent, src_idx, dest_parent, dest_idx):
"""Copy an item.""" |
if isinstance(dest_parent, list):
dest_idx = int(dest_idx)
dest_parent[dest_idx] = get_child(src_parent, src_idx) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move(src_parent, src_idx, dest_parent, dest_idx):
"""Move an item.""" |
copy(src_parent, src_idx, dest_parent, dest_idx)
remove(src_parent, src_idx) |
<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_remove(parent, idx, value):
"""Remove an item from a list.""" |
lst = get_child(parent, idx)
if value in lst:
lst.remove(value) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.