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 remove_file(profile, branch, file_path, commit_message=None):
"""Remove a file from a branch. Args: profile A profile generated from ``simplygithub.authentic... |
branch_sha = get_branch_sha(profile, branch)
tree = get_files_in_branch(profile, branch_sha)
new_tree = remove_file_from_tree(tree, file_path)
data = trees.create_tree(profile, new_tree)
sha = data.get("sha")
if not commit_message:
commit_message = "Deleted " + file_path + "."
paren... |
<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_file(profile, branch, file_path):
"""Get a file from a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profi... |
branch_sha = get_branch_sha(profile, branch)
tree = get_files_in_branch(profile, branch_sha)
match = None
for item in tree:
if item.get("path") == file_path:
match = item
break
file_sha = match.get("sha")
blob = blobs.get_blob(profile, file_sha)
content = 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 make(self):
""" Make the lock file. """ |
try:
# Create the lock file
self.mkfile(self.lock_file)
except Exception as e:
self.die('Failed to generate lock file: {}'.format(str(e))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _short_circuit(value=None):
""" Add the `value` to the `collection` by modifying the collection to be either a dict or list depending on what is already in t... |
if not isinstance(value, list):
return value
if len(value) == 0:
return value
if len(value) == 1:
if not isinstance(value[0], list):
return value[0]
else:
if len(value[0]) == 1:
return value[0][0]
else:
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _query(_node_id, value=None, **kw):
"Look up value by using Query table"
query_result = []
try:
query_result = db.execute(text(fetch_query_string('select_query_from_node.sql')), **kw).fetchall()
except DatabaseError as err:
current_app.logger.error("DatabaseError: %s, %s", err, kw)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _template(node_id, value=None):
"Check if a template is assigned to it and render that with the value"
result = []
select_template_from_node = fetch_query_string('select_template_from_node.sql')
try:
result = db.execute(text(select_template_from_node), node_id=node_id)
template_resul... |
<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_node(_node_id, value=None, noderequest={}, **kw):
"Recursively render a node's value"
if value == None:
kw.update( noderequest )
results = _query(_node_id, **kw)
current_app.logger.debug("results: %s", results)
if results:
values = []
for (resul... |
<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, name, subject_id, image_group_id, properties):
"""Create a new experiment using the given SCO-API create experiment Url. Parameters url : string ... |
# Create list of key,value-pairs representing experiment properties for
# request. The given name overrides the name in properties (if present).
obj_props = [{'key':'name','value':name}]
if not properties is None:
# Catch TypeErrors if properties is not a list.
t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def runs(self, offset=0, limit=-1, properties=None):
"""Get a list of run descriptors associated with this expriment. Parameters offset : int, optional Starting ... |
return get_run_listing(
self.runs_url,
offset=offset,
limit=limit,
properties=properties
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def imapchain(*a, **kwa):
""" Like map but also chains the results. """ |
imap_results = map( *a, **kwa )
return itertools.chain( *imap_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 iskip( value, iterable ):
""" Skips all values in 'iterable' matching the given 'value'. """ |
for e in iterable:
if value is None:
if e is None:
continue
elif e == value:
continue
yield 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 format(self, password: str = '') -> str: """Format command along with any arguments, ready to be sent.""" |
return MARKER_START + \
self.name + \
self.action + \
self.args + \
password + \
MARKER_END |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lint(to_lint):
""" Run all linters against a list of files. :param to_lint: a list of files to lint. """ |
exit_code = 0
for linter, options in (('pyflakes', []), ('pep8', [])):
try:
output = local[linter](*(options + to_lint))
except commands.ProcessExecutionError as e:
output = e.stdout
if output:
exit_code = 1
print "{0} Errors:".format(lin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hacked_pep257(to_lint):
""" Check for the presence of docstrings, but ignore some of the options """ |
def ignore(*args, **kwargs):
pass
pep257.check_blank_before_after_class = ignore
pep257.check_blank_after_last_paragraph = ignore
pep257.check_blank_after_summary = ignore
pep257.check_ends_with_period = ignore
pep257.check_one_liners = ignore
pep257.check_imperative_mood = ignore
... |
<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(self, *directories):
""" The actual logic that runs the linters """ |
if not self.git and len(directories) == 0:
print ("ERROR: At least one directory must be provided (or the "
"--git-precommit flag must be passed.\n")
self.help()
return
if len(directories) > 0:
find = local['find']
files = ... |
<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_meta(request):
""" This context processor returns meta informations contained in cached files. If there aren't cache it calculates dictionary to return "... |
context_extras = {}
if not request.is_ajax() and hasattr(request, 'upy_context') and request.upy_context['PAGE']:
context_extras['PAGE'] = request.upy_context['PAGE']
context_extras['NODE'] = request.upy_context['NODE']
return context_extras |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def download_virtualenv(version, dldir=None):
'''
Download virtualenv package from pypi and return response that can be
read and written to file
:param str version: version to download or latest version if None
:param str dldir: directory to download into or None for cwd
'''
dl_url = PYPI_D... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create_virtualenv(venvpath, venvargs=None):
'''
Run virtualenv from downloaded venvpath using venvargs
If venvargs is None, then 'venv' will be used as the virtualenv directory
:param str venvpath: Path to root downloaded virtualenv package(must contain
virtualenv.py)
:param list venvar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def bootstrap_vi(version=None, venvargs=None):
'''
Bootstrap virtualenv into current directory
:param str version: Virtualenv version like 13.1.0 or None for latest version
:param list venvargs: argv list for virtualenv.py or None for default
'''
if not version:
version = get_latest_vir... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compose_path(pub, uuid_url=False):
""" Compose absolute path for given `pub`. Args: pub (obj):
:class:`.DBPublication` instance. uuid_url (bool, default Fal... |
if uuid_url:
return join(
"/",
UUID_DOWNLOAD_KEY,
str(pub.uuid)
)
return join(
"/",
DOWNLOAD_KEY,
basename(pub.file_pointer),
basename(pub.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 compose_tree_path(tree, issn=False):
""" Compose absolute path for given `tree`. Args: pub (obj):
:class:`.Tree` instance. issn (bool, default False):
Comp... |
if issn:
return join(
"/",
ISSN_DOWNLOAD_KEY,
basename(tree.issn)
)
return join(
"/",
PATH_DOWNLOAD_KEY,
quote_plus(tree.path).replace("%2F", "/"),
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compose_full_url(pub, uuid_url=False):
""" Compose full url for given `pub`, with protocol, server's address and port. Args: pub (obj):
:class:`.DBPublicati... |
url = compose_path(pub, uuid_url)
if WEB_PORT == 80:
return "%s://%s%s" % (_PROTOCOL, WEB_ADDR, url)
return "%s://%s:%d%s" % (_PROTOCOL, WEB_ADDR, WEB_PORT, url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compose_tree_url(tree, issn_url=False):
""" Compose full url for given `tree`, with protocol, server's address and port. Args: tree (obj):
:class:`.Tree` in... |
url = compose_tree_path(tree, issn_url)
if WEB_PORT == 80:
return "%s://%s%s" % (_PROTOCOL, WEB_ADDR, url)
return "%s://%s:%d%s" % (_PROTOCOL, WEB_ADDR, WEB_PORT, url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def profile(func):
""" Simple profile decorator, monitors method execution time """ |
@inlineCallbacks
def callme(*args, **kwargs):
start = time.time()
ret = yield func(*args, **kwargs)
time_to_execute = time.time() - start
log.msg('%s executed in %.3f seconds' % (func.__name__, time_to_execute))
returnValue(ret)
return callme |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepareClasses(locals):
"""Fix _userClasses and some stuff in classes. Traverses locals, which is a locals() dictionary from the namespace where Forgetter su... |
for (name, forgetter) in locals.items():
if not (type(forgetter) is types.TypeType and
issubclass(forgetter, Forgetter)):
# Only care about Forgetter objects
continue
# Resolve classes
for (key, userclass) in forgetter._userClasses.items():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setID(self, id):
"""Set the ID, ie. the values for primary keys. id can be either a list, following the _sqlPrimary, or some other type, that will be set as... |
if type(id) in (types.ListType, types.TupleType):
try:
for key in self._sqlPrimary:
value = id[0]
self.__dict__[key] = value
id = id[1:] # rest, go revursive
except IndexError:
raise 'Not enough ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getID(self):
"""Get the ID values as a tuple annotated by sqlPrimary""" |
id = []
for key in self._sqlPrimary:
value = self.__dict__[key]
if isinstance(value, Forgetter):
# It's another object, we store only the ID
if value._new:
# It's a new object too, it must be saved!
value.sa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _resetID(self):
"""Reset all ID fields.""" |
# Dirty.. .=))
self._setID((None,) * len(self._sqlPrimary))
self._new = 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 _checkTable(cls, field):
"""Split a field from _sqlFields into table, column. Registers the table in cls._tables, and returns a fully qualified table.column ... |
# Get table part
try:
(table, field) = field.split('.')
except ValueError:
table = cls._sqlTable
# clean away white space
table = table.strip()
field = field.strip()
# register table
cls._tables[table] = None
# and return 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 reset(self):
"""Reset all fields, almost like creating a new object. Note: Forgets changes you have made not saved to database! (Remember: Others might refer... |
self._resetID()
self._new = None
self._updated = None
self._changed = None
self._values = {}
# initially create fields
for field in self._sqlFields.keys():
self._values[field] = 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(self, id=None):
"""Load from database. Old values will be discarded.""" |
if id is not None:
# We are asked to change our ID to something else
self.reset()
self._setID(id)
if not self._new and self._validID():
self._loadDB()
self._updated = time.time() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self):
"""Save to database if anything has changed since last load""" |
if ( self._new or
(self._validID() and self._changed) or
(self._updated and self._changed > self._updated) ):
# Don't save if we have not loaded existing data!
self._saveDB()
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
"""Mark this object for deletion in the database. The object will then be reset and ready for use again with a new id. """ |
(sql, ) = self._prepareSQL("DELETE")
curs = self.cursor()
curs.execute(sql, self._getID())
curs.close()
self.reset() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _nextSequence(cls, name=None):
"""Return a new sequence number for insertion in self._sqlTable. Note that if your sequences are not named tablename_primaryke... |
if not name:
name = cls._sqlSequence
if not name:
# Assume it's tablename_primarykey_seq
if len(cls._sqlPrimary) <> 1:
raise "Could not guess sequence name for multi-primary-key"
primary = cls._sqlPrimary[0]
name = '%s_%s_seq' ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loadFromRow(self, result, fields, cursor):
"""Load from a database row, described by fields. ``fields`` should be the attribute names that will be set. Note... |
position = 0
for elem in fields:
value = result[position]
valueType = cursor.description[position][1]
if hasattr(self._dbModule, 'BOOLEAN') and \
valueType == self._dbModule.BOOLEAN and \
(value is not True or value is no... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loadDB(self):
"""Connect to the database to load myself""" |
if not self._validID():
raise NotFound, self._getID()
(sql, fields) = self._prepareSQL("SELECT")
curs = self.cursor()
curs.execute(sql, self._getID())
result = curs.fetchone()
if not result:
curs.close()
raise NotFound, self._getID()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _saveDB(self):
"""Insert or update into the database. Note that every field will be updated, not just the changed one. """ |
# We're a "fresh" copy now
self._updated = time.time()
if self._new:
operation = 'INSERT'
if not self._validID():
self._setID(self._nextSequence())
# Note that we assign this ID to our self
# BEFORE possibly saving any of our attri... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getAll(cls, where=None, orderBy=None):
"""Retrieve all the objects. If a list of ``where`` clauses are given, they will be AND-ed and will limit the search. ... |
ids = cls.getAllIDs(where, orderBy=orderBy)
# Instansiate a lot of them
if len(cls._sqlPrimary) > 1:
return [cls(*id) for id in ids]
else:
return [cls(id) for id in ids] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getAllIterator(cls, where=None, buffer=100, useObject=None, orderBy=None):
"""Retrieve every object as an iterator. Possibly limitted by the where list of cl... |
(sql, fields) = cls._prepareSQL("SELECTALL", where, orderBy=orderBy)
curs = cls.cursor()
fetchedAt = time.time()
curs.execute(sql)
# We might start eating memory at this point
def getNext(rows=[]):
forgetter = cls
if not rows:
ro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getAllIDs(cls, where=None, orderBy=None):
"""Retrive all the IDs, possibly matching the where clauses. Where should be some list of where clauses that will b... |
(sql, fields) = cls._prepareSQL("SELECTALL", where,
cls._sqlPrimary, orderBy=orderBy)
curs = cls.cursor()
curs.execute(sql)
# We might start eating memory at this point
rows = curs.fetchall()
curs.close()
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 getAllText(cls, where=None, SEPERATOR=' ', orderBy=None):
"""Retrieve a list of of all possible instances of this class. The list is composed of tuples in th... |
(sql, fields) = cls._prepareSQL("SELECTALL", where, orderBy=orderBy)
curs = cls.cursor()
curs.execute(sql)
# We might start eating memory at this point
rows = curs.fetchall()
curs.close()
result = []
idPositions = [fields.index(key) for key in cls._sqlPri... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getChildren(self, forgetter, field=None, where=None, orderBy=None):
"""Return the children that links to me. That means that I have to be listed in their _us... |
if type(where) in (types.StringType, types.UnicodeType):
where = (where,)
if not field:
for (i_field, i_class) in forgetter._userClasses.items():
if isinstance(self, i_class):
field = i_field
break # first one found is ok ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hide_address(func):
""" Used to decorate Serializer.to_representation method. It hides the address field if the Project has 'hidden_address' == True and the ... |
@wraps(func)
def _impl(self, instance):
# We pop address field to avoid AttributeError on default Serializer.to_representation
if instance.hidden_address:
for i, field in enumerate(self._readable_fields):
if field.field_name == "address":
address = self._readable_fields.pop(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 add_current_user_is_applied_representation(func):
""" Used to decorate Serializer.to_representation method. It sets the field "current_user_is_applied" if th... |
@wraps(func)
def _impl(self, instance):
# We pop current_user_is_applied field to avoid AttributeError on default Serializer.to_representation
ret = func(self, instance)
user = self.context["request"].user
applied = False
if not user.is_anonymous():
try:
applied = models.Apply.ob... |
<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(self, debug=None, quiet=None, verbosity=None, compile=None, compiler_factory=None, **kwargs):
"""configure managed args """ |
if debug is not None:
self.arg_debug = debug
if quiet is not None:
self.arg_quiet = quiet
if verbosity is not None:
self.arg_verbosity = verbosity
if compile is not None:
self.compile = compile
if compiler_factory 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 uninstall_bash_completion(self, script_name=None, dest="~/.bashrc"):
'''remove line to activate bash_completion for given script_name from given dest
You can use this for letting the user uninstall bash_completion::
from argdeco import command, main
@command("uninstall-bas... |
<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_bash_completion(self, script_name=None, dest="~/.bashrc"):
'''add line to activate bash_completion for given script_name into dest
You can use this for letting the user install bash_completion::
from argdeco import command, main
@command("install-bash-completion",
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fetch_arguments(handler, method):
"""Get the arguments depending on the type of HTTP method.""" |
if method.__name__ == 'get':
arguments = {}
for key, value in six.iteritems(handler.request.arguments):
# Tornado supports comma-separated lists of values in
# parameters. We're undoing that here, and if a list
# is expected the _validate method can handle it.
... |
<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_validator_chain(chain, value, handler):
"""Apply validators in sequence to a value.""" |
if hasattr(chain, 'validate'): # not a list
chain = [chain, ]
for validator in chain:
if hasattr(validator, 'validate'):
value = validator.validate(value, handler)
else:
raise web.HTTPError(500)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_arguments(self, method, parameters):
"""Parse arguments to method, returning a dictionary.""" |
# TODO: Consider raising an exception if there are extra arguments.
arguments = _fetch_arguments(self, method)
arg_dict = {}
errors = []
for key, properties in parameters:
if key in arguments:
value = arguments[key]
try:
arg_dict[key] = _apply_vali... |
<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(parameters):
"""Decorator to parse parameters according to a set of criteria. This outer method is called to set up the decorator. Arguments: parameter... |
# pylint: disable=protected-access
@decorators.include_original
def decorate(method):
"""Setup returns this decorator, which is called on the method."""
def call(self, *args):
"""This is called whenever the decorated method is invoked."""
kwargs = _parse_arguments(... |
<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_dict(parameters):
"""Decorator to parse parameters as a dict according to a set of criteria. This outer method is called to set up the decorator. Argum... |
# pylint: disable=protected-access
@decorators.include_original
def decorate(method):
"""Setup returns this decorator, which is called on the method."""
def call(self, *args):
"""This is called whenever the decorated method is invoked."""
arg_dict = _parse_argument... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mode_assignment(arg):
""" Translates arg to enforce proper assignment """ |
arg = arg.upper()
stream_args = ('STREAM', 'CONSOLE', 'STDOUT')
try:
if arg in stream_args:
return 'STREAM'
else:
return arg
except Exception:
return 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 save_object(self, obj):
"""Save an object with Discipline Only argument is a Django object. This function saves the object (regardless of whether it already ... |
obj.save()
try:
save_object(obj, editor=self)
except DisciplineException:
pass |
<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(self, obj, post_delete=False):
"""Delete an object with Discipline Only argument is a Django object. Analogous to Editor.save_object. """ |
# Collect related objects that will be deleted by cascading
links = [rel.get_accessor_name() for rel in \
obj._meta.get_all_related_objects()]
# Recursively delete each of them
for link in links:
objects = getattr(obj, link).all()
for o in object... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _description(self):
"""A concise html explanation of this Action.""" |
inst = self.timemachine.presently
if self.action_type == "dl":
return "Deleted %s" % inst.content_type.name
elif self.action_type == "cr":
return "Created %s" % inst._object_type_html()
else:
return "Modified %s" % inst._object_type_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 __get_timemachine(self):
"""Return a TimeMachine for the object on which this action was performed and at the time of this action.""" |
if not self.__timemachine:
self.__timemachine = TimeMachine(
self.object_uid,
step = self.id,
)
return self.__timemachine.at(self.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 __get_is_revertible(self):
"""Return a boolean representing whether this Action is revertible or not""" |
# If it was already reverted
if self.reverted:
return False
errors = []
inst = self.timemachine
if inst.fields != inst.presently.fields or \
inst.foreignkeys != inst.presently.foreignkeys:
self.__undo_errors = [
"Cannot... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def undo(self, editor):
"""Create a new Action that undos the effects of this one, or, more accurately, reverts the object of this Action to the state at which i... |
inst = self.timemachine
if not self.is_revertible:
raise DisciplineException("You tried to undo a non-revertible action! "
"Check action.is_revertible and action.undo_errors"
" before trying to undo.")
if self.action_typ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _status(self):
"""Return html saying whether this Action is reverted by another one or reverts another one.""" |
text = ""
# Turns out that is related field in null, Django
# doesn't even make it a property of the object
# http://code.djangoproject.com/ticket/11920
if hasattr(self, "reverts"):
text += '(reverts <a href="%s">%s</a>)<br/>' % (
self.reverts.get_abs... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __summary(self):
"""A plaintext summary of the Action, useful for debugging.""" |
text = "Time: %s\n" % self.when
text += "Comitter: %s\n" % self.editor
inst = self.timemachine.presently
if self.action_type == "dl":
text += "Deleted %s\n" % inst._object_type_text()
elif self.action_type == "cr":
text += "Created %s\n" % inst._object_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _details(self, nohtml=False):
"""Return the html representation of the Action.""" |
text = ""
inst = self.timemachine
# If deleted or created, show every field, otherwise only
# the modified
if self.action_type in ("dl","cr",):
fields = inst.fields + inst.foreignkeys
else: fields = [i.key for i in self.modification_commits.all()]
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 __update_information(self):
"""Gether information that doesn't change at different points in time""" |
info = {}
info["actions_count"] = Action.objects.count()
info["creation_times"] = []
info["deletion_times"] = []
info["content_type"] = None
# Find object type and when it was created
for ccommit in CreationCommit.objects.filter(object_uid=self.uid)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def at(self, step):
"""Return a TimeMachine for the same object at a different time. Takes an integer argument representing the id field of an Action. Returns th... |
return TimeMachine(
self.uid,
step = step,
info = copy.deepcopy(self.info)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, key):
"""Return the value of a field. Take a string argument representing a field name, return the value of that field at the time of this TimeMach... |
modcommit = self._get_modcommit(key)
if not modcommit: return None
# If this isn't a ForeignKey, then just return the value
if key not in self.foreignkeys:
return cPickle.loads(str(modcommit.value))
# If it is, then return the object instance
try:
... |
<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_timemachine_instance(self, key):
"""Return a TimeMachine for a related object. Take a string argument representing a ForeignKey field name, find what obj... |
modcommit = self._get_modcommit(key)
if not modcommit:
return None
return TimeMachine(uid = modcommit.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 get_object(self):
"""Return the object of this TimeMachine""" |
return self.content_type.model_class().objects.get(uid = self.uid) |
<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(self, nosave=False):
"""Restore all of the object attributes to the attributes. Return the Django object. """ |
if self.exists:
obj = self.content_type.model_class().objects.get(uid=self.uid)
else:
obj = self.content_type.model_class()(uid=self.uid)
for field in self.fields + self.foreignkeys:
obj.__setattr__(field, self.get(field))
if not nosave: obj.save()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url(self):
"""Return the admin url of the object.""" |
return urlresolvers.reverse(
"admin:%s_%s_change" % (self.content_type.app_label,
self.content_type.model),
args = (self.get_object().uid,)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _object_type_html(self):
"""Return an html admin link with the object's type as text. If the object doesn't exist, return the object's type crossed out. """ |
if self.exists:
return "<a href=\"%s\">%s</a>" % (self.url(),
self.content_type.name,)
else:
return "<s>%s</s>" % self.content_type.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 get_for_content_type(self, ct):
"""Return the schema for the model of the given ContentType object""" |
try:
return json.loads(self.state)[ct.app_label][ct.model]
except KeyError:
return 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 html_state(self):
"""Display state in HTML format for the admin form.""" |
ret = ""
state = json.loads(self.state)
for (app, appstate) in state.items():
for (model, modelstate) in appstate.items():
ret += "<p>%s.models.%s</p>" % (app, model,)
ret += "<ul>"
for field in modelstate["fields"] + ["uid"]:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def plot_prh_des_asc(p, r, h, asc, des):
'''Plot pitch, roll, and heading during the descent and ascent dive phases
Args
----
p: ndarray
Derived pitch data
r: ndarray
Derived roll data
h: ndarray
Derived heading data
des: ndarray
boolean mask for slicing desc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def plot_prh_filtered(p, r, h, p_lf, r_lf, h_lf):
'''Plot original and low-pass filtered PRH data
Args
----
p: ndarray
Derived pitch data
r: ndarray
Derived roll data
h: ndarray
Derived heading data
p_lf: ndarray
Low-pass filtered pitch data
r_lf: ndarray... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def plot_swim_speed(exp_ind, swim_speed):
'''Plot the swim speed during experimental indices
Args
----
exp_ind: ndarray
Indices of tag data where experiment is active
swim_speed: ndarray
Swim speed data at sensor sampling rate
'''
import numpy
fig, ax = plt.subplots()
... |
<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, skey, sdesc,
sdict=None, loaders=None, merge=False, writeback=False):
'''
Loads a dictionary into current settings
:param skey:
Type of data to load. Is be used to reference the data \
in the files sections within settings
:param sdesc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode(name, values, strict=True, encoding=pyamf.AMF0):
""" Produces a SharedObject encoded stream based on the name and values. @param name: The root name o... |
encoder = pyamf.get_encoder(encoding)
stream = encoder.stream
# write the header
stream.write(HEADER_VERSION)
if strict:
length_pos = stream.tell()
stream.write_ulong(0)
# write the signature
stream.write(HEADER_SIGNATURE)
# write the root name
name = name.encode('u... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mainloop(self):
""" Handles events and calls their handler for infinity. """ |
while self.keep_going:
with self.lock:
if self.on_connect and not self.readable(2):
self.on_connect()
self.on_connect = None
if not self.keep_going:
break
self.process_once() |
<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_cell(self, cell, coords, cell_mode=CellMode.cooked):
"""Parses a cell according to the cell.ctype.""" |
# pylint: disable=too-many-return-statements
if cell_mode == CellMode.cooked:
if cell.ctype == xlrd.XL_CELL_BLANK:
return None
if cell.ctype == xlrd.XL_CELL_BOOLEAN:
return cell.value
if cell.ctype == xlrd.XL_CELL_DATE:
if self.handle_ambiguous_date:
try:
... |
<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_note(self, coords):
"""Get the note for the cell at the given coordinates. coords is a tuple of (col, row) """ |
col, row = coords
note = self.raw_sheet.cell_note_map.get((row, col))
return note.text if note else 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 _parse_date(self, cell_value):
"""Attempts to parse a cell_value as a date.""" |
date_tuple = xlrd.xldate_as_tuple(cell_value, self.raw_sheet.book.datemode)
return self.tuple_to_datetime(date_tuple) |
<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(cls):
""" Method to parse command line arguments """ |
cls.parser = argparse.ArgumentParser()
cls.parser.add_argument(
"symbol", help="Symbol for horizontal line", nargs="*")
cls.parser.add_argument(
"--color", "-c", help="Color of the line", default=None, nargs=1)
cls.parser.add_argument(
"--version", "-... |
<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_args(self):
""" Pass in the parsed args to the script """ |
self.arg_parser = self._parse_args()
self.args = self.arg_parser.parse_args()
color_name = self.args.color
if color_name is not None:
color_name = color_name[0]
symbol = self.args.symbol
try:
self.tr(symbol, color_name)
except InvalidColor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _term_size(self):
""" Method returns lines and columns according to terminal size """ |
for fd in (0, 1, 2):
try:
return self._ioctl_GWINSZ(fd)
except:
pass
# try os.ctermid()
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
try:
return self._ioctl_GWINSZ(fd)
finally:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tr(self, args, color=None):
""" Method to print ASCII patterns to terminal """ |
width = self._term_size()[1]
if not args:
if color is not None:
print(self._echo("#" * width, color))
else:
print(self._echo("#" * width, "green"))
else:
for each_symbol in args:
chars = len(each_symbol)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cache_add(self, resource_url, cache_id):
"""Add entry permanently to local cache. Parameters resource_url : string Resource Url cache_id : string Unique cach... |
# Add entry to cache index
self.cache[resource_url] = cache_id
# Write cache index content to database file
with open(self.db_file, 'w') as f:
for resource in self.cache:
f.write(resource + '\t' + self.cache[resource] + '\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 cache_clear(self):
"""Clear local cache by deleting all cached resources and their downloaded files. """ |
# Delete content of local cache directory
for f in os.listdir(self.directory):
f = os.path.join(self.directory, f)
if os.path.isfile(f):
os.remove(f)
elif os.path.isdir(f):
shutil.rmtree(f)
# Empty cache index
self.cach... |
<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_api_references(self, api_url=None):
"""Get set of HATEOAS reference for the given SCO-API. Use the default SCO-API if none is given. References are cache... |
# Get subject listing Url for SCO-API
if not api_url is None:
url = api_url
else:
url = self.api_url
# Check if API references are in local cache. If not send GET request
# and add the result to the local cache
if not url in self.apis:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def experiments_create(self, name, subject_id, image_group_id, api_url=None, properties=None):
"""Create a new experiment at the given SCO-API. Subject and image... |
# Create experiment and return handle for created resource
return self.experiments_get(
ExperimentHandle.create(
self.get_api_references(api_url)[sco.REF_EXPERIMENTS_CREATE],
name,
subject_id,
image_group_id,
pr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def experiments_get(self, resource_url):
"""Get handle for experiment resource at given Url. Parameters resource_url : string Url for experiment resource at SCO-... |
# Get resource directory, Json representation, active flag, and cache id
obj_dir, obj_json, is_active, cache_id = self.get_object(resource_url)
# Create experiment handle. Will raise an exception if resource is not
# in cache and cannot be downloaded.
experiment = ExperimentHand... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def experiments_fmri_create(self, experiment_url, data_file):
"""Upload given data file as fMRI for experiment with given Url. Parameters experiment_url : string... |
# Get the experiment
experiment = self.experiments_get(experiment_url)
# Upload data
FunctionalDataHandle.create(
experiment.links[sco.REF_EXPERIMENTS_FMRI_CREATE],
data_file
)
# Get new fmri data handle and return it
return self.experimen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def experiments_fmri_get(self, resource_url):
"""Get handle for functional fMRI resource at given Url. Parameters resource_url : string Url for fMRI resource at ... |
# Get resource directory, Json representation, active flag, and cache id
obj_dir, obj_json, is_active, cache_id = self.get_object(resource_url)
# Create image group handle. Will raise an exception if resource is not
# in cache and cannot be downloaded.
fmri_data = FunctionalData... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def experiments_predictions_create(self, model_id, name, api_url, arguments={}, properties=None):
"""Create a new model run at the given SCO-API. Parameters mode... |
# Create experiment and return handle for created resource
return self.experiments_predictions_get(
ModelRunHandle.create(
api_url,
model_id,
name,
arguments,
properties=properties
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def experiments_predictions_get(self, resource_url):
"""Get handle for model run resource at given Url. Parameters resource_url : string Url for model run resour... |
# Get resource directory, Json representation, active flag, and cache id
obj_dir, obj_json, is_active, cache_id = self.get_object(resource_url)
# Create model run handle. Will raise an exception if resource is not
# in cache and cannot be downloaded.
run = ModelRunHandle(obj_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 get_object(self, resource_url):
"""Get remote resource information. Creates a local directory for the resource if this is the first access to the resource. D... |
# Check if resource is in local cache. If not, create a new cache
# identifier and set is_cached flag to false
if resource_url in self.cache:
cache_id = self.cache[resource_url]
else:
cache_id = str(uuid.uuid4())
# The local cahce directory for resource 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 image_groups_get(self, resource_url):
"""Get handle for image group resource at given Url. Parameters resource_url : string Url for image group resource at S... |
# Get resource directory, Json representation, active flag, and cache id
obj_dir, obj_json, is_active, cache_id = self.get_object(resource_url)
# Create image group handle. Will raise an exception if resource is not
# in cache and cannot be downloaded.
image_group = ImageGroupHa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def image_groups_list(self, api_url=None, offset=0, limit=-1, properties=None):
"""Get list of image group resources from a SCO-API. Parameters api_url : string,... |
# Get subject listing Url for given SCO-API and return the retrieved
# resource listing
return sco.get_resource_listing(
self.get_api_references(api_url)[sco.REF_IMAGE_GROUPS_LIST],
offset,
limit,
properties
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def models_get(self, resource_url):
"""Get handle for model resource at given Url. Parameters resource_url : string Url for subject resource at SCO-API Returns -... |
# Get resource directory, Json representation, active flag, and cache id
obj_dir, obj_json, is_active, cache_id = self.get_object(resource_url)
# Create model handle.
model = ModelHandle(obj_json)
# Add resource to cache if not exists
if not cache_id in self.cache:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def models_list(self, api_url=None, offset=0, limit=-1, properties=None):
"""Get list of model resources from a SCO-API. Parameters api_url : string, optional Ba... |
# Get subject listing Url for given SCO-API and return the retrieved
# resource listing
return sco.get_resource_listing(
self.get_api_references(api_url)[sco.REF_MODELS_LIST],
offset,
limit,
properties
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subjects_create(self, filename, api_url=None, properties=None):
"""Create new anatomy subject at given SCO-API by uploading local file. Expects an tar-archiv... |
# Create image group and return handle for created resource
return self.subjects_get(
SubjectHandle.create(
self.get_api_references(api_url)[sco.REF_SUBJECTS_CREATE],
filename,
properties
)
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.