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 get_messages_from_stream(data):
"""Extract complete messages from stream and cut out them from stream. @data - stream binary data @return - [list of messages... |
messages = []
iterator = HEADER_RE.finditer(data)
last_pos = 0
for match in iterator:
pos = match.span()[0]
header = read_machine_header(data[pos:])
h_len = __get_machine_header_length(header)
cur_last_pos = pos + h_len + header['meta_len'] + header['data_len']
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clone(self, options=None, attribute_options=None):
""" Returns a clone of this mapping that is configured with the given option and attribute option dictiona... |
copied_cfg = self.__configurations[-1].copy()
upd_cfg = type(copied_cfg)(options=options,
attribute_options=attribute_options)
copied_cfg.update(upd_cfg)
return self.__class__(self.__mp_reg, self.__mapped_cls,
self.__de_cl... |
<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(self, options=None, attribute_options=None):
""" Updates this mapping with the given option and attribute option maps. :param dict options: Maps repre... |
attr_map = self.__get_attribute_map(self.__mapped_cls, None, 0)
for attributes in attribute_options:
for attr_name in attributes:
if not attr_name in attr_map:
raise AttributeError('Trying to configure non-existing '
... |
<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_attribute_map(self, mapped_class=None, key=None):
""" Returns an ordered map of the mapped attributes for the given mapped class and attribute key. :para... |
if mapped_class is None:
mapped_class = self.__mapped_cls
if key is None:
key = MappedAttributeKey(())
return OrderedDict([(attr.resource_attr, attr)
for attr in self._attribute_iterator(mapped_class,
... |
<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_data_element(self, mapped_class=None):
""" Returns a new data element for the given mapped class. :returns: object implementing :class:`IResourceDataE... |
if not mapped_class is None and mapped_class != self.__mapped_cls:
mp = self.__mp_reg.find_or_create_mapping(mapped_class)
data_el = mp.create_data_element()
else:
data_el = self.__de_cls.create()
return data_el |
<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_linked_data_element(self, url, kind, id=None, # pylint: disable=W0622 relation=None, title=None):
""" Returns a new linked data element for the given ... |
mp = self.__mp_reg.find_or_create_mapping(Link)
return mp.data_element_class.create(url, kind, id=id,
relation=relation, title=title) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_data_element_from_resource(self, resource):
""" Returns a new data element for the given resource object. :returns: object implementing :class:`IResou... |
mp = self.__mp_reg.find_or_create_mapping(type(resource))
return mp.data_element_class.create_from_resource(resource) |
<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_linked_data_element_from_resource(self, resource):
""" Returns a new linked data element for the given resource object. :returns: object implementing ... |
mp = self.__mp_reg.find_or_create_mapping(Link)
return mp.data_element_class.create_from_resource(resource) |
<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_to_resource(self, data_element, resource=None):
""" Maps the given data element to a new resource or updates the given resource. :raises ValueError: If :... |
if not IDataElement.providedBy(data_element): # pylint:disable=E1101
raise ValueError('Expected data element, got %s.' % data_element)
if resource is None:
coll = \
create_staging_collection(data_element.mapping.mapped_class)
agg = coll.get_aggregate(... |
<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_to_data_element(self, resource):
""" Maps the given resource to a data element tree. """ |
trv = ResourceTreeTraverser(resource, self.as_pruning())
visitor = DataElementBuilderResourceTreeVisitor(self)
trv.run(visitor)
return visitor.data_element |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def push_configuration(self, configuration):
""" Pushes the given configuration object on the stack of configurations managed by this mapping and makes it the ac... |
self.__mapped_attr_cache.clear()
self.__configurations.append(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 pop_configuration(self):
""" Pushes the currently active configuration from the stack of configurations managed by this mapping. :raises IndexError: If there... |
if len(self.__configurations) == 1:
raise IndexError('Can not pop the last configuration from the '
'stack of configurations.')
self.__configurations.pop()
self.__mapped_attr_cache.clear() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def with_updated_configuration(self, options=None, attribute_options=None):
""" Returns a context in which this mapping is updated with the given options and att... |
new_cfg = self.__configurations[-1].copy()
if not options is None:
for o_name, o_value in iteritems_(options):
new_cfg.set_option(o_name, o_value)
if not attribute_options is None:
for attr_name, ao_opts in iteritems_(attribute_options):
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 _attribute_iterator(self, mapped_class, key):
""" Returns an iterator over the attributes in this mapping for the given mapped class and attribute key. If th... |
for attr in \
itervalues_(self.__get_attribute_map(mapped_class, key, 0)):
if self.is_pruning:
do_ignore = attr.should_ignore(key)
else:
do_ignore = False
if not do_ignore:
yield attr |
<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_mapping(self, mapped_class, configuration=None):
""" Creates a new mapping for the given mapped class and representer configuration. :param configurat... |
cfg = self.__configuration.copy()
if not configuration is None:
cfg.update(configuration)
provided_ifcs = provided_by(object.__new__(mapped_class))
if IMemberResource in provided_ifcs:
base_data_element_class = self.member_data_element_base_class
elif ICo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_mapping(self, mapped_class):
""" Returns the mapping registered for the given mapped class or any of its base classes. Returns `None` if no mapping can ... |
if not self.__is_initialized:
self.__is_initialized = True
self._initialize()
mapping = None
for base_cls in mapped_class.__mro__:
try:
mapping = self.__mappings[base_cls]
except KeyError:
continue
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 eachMethod(decorator, methodFilter=lambda fName: True):
""" Class decorator that wraps every single method in its own method decorator methodFilter: a functi... |
if isinstance(methodFilter, basestring):
# Is it a string? If it is, change it into a function that takes a string.
prefix = methodFilter
methodFilter = lambda fName: fName.startswith(prefix)
ismethod = lambda fn: inspect.ismethod(fn) or inspect.isfunction(fn)
def innerDeco(cls):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _sibpath(path, sibling):
""" Return the path to a sibling of a file in the filesystem. This is useful in conjunction with the special C{__file__} attribute t... |
return os.path.join(os.path.dirname(os.path.abspath(path)), sibling) |
<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(cls, func):
""" Global cache decorator :param func: the function to be decorated :return: the decorator """ |
@functools.wraps(func)
def func_wrapper(*args, **kwargs):
func_key = cls.get_key(func)
val_cache = cls.get_cache(func_key)
lock = cls.get_cache_lock(func_key)
return cls._get_value_from_cache(
func, val_cache, lock, *args, **kwargs)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instance_cache(cls, func):
""" Save the cache to `self` This decorator take it for granted that the decorated function is a method. The first argument of the... |
@functools.wraps(func)
def func_wrapper(*args, **kwargs):
if not args:
raise ValueError('`self` is not available.')
else:
the_self = args[0]
func_key = cls.get_key(func)
val_cache = cls.get_self_cache(the_self, func_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 clear_instance_cache(cls, func):
""" clear the instance cache Decorate a method of a class, the first parameter is supposed to be `self`. It clear all items ... |
@functools.wraps(func)
def func_wrapper(*args, **kwargs):
if not args:
raise ValueError('`self` is not available.')
else:
the_self = args[0]
cls.clear_self_cache(the_self)
return func(*args, **kwargs)
return func... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def persisted(cls, seconds=0, minutes=0, hours=0, days=0, weeks=0):
""" Cache the return of the function for given time. Default to 1 day. :param weeks: as name ... |
days += weeks * 7
hours += days * 24
minutes += hours * 60
seconds += minutes * 60
if seconds == 0:
# default to 1 day
seconds = 24 * 60 * 60
def get_persisted_file(hash_number):
folder = cls.get_persist_folder()
if not o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getEvents(self, repo_user, repo_name, until_id=None):
"""Get all repository events, following paging, until the end or until UNTIL_ID is seen. Returns a Defe... |
done = False
page = 0
events = []
while not done:
new_events = yield self.api.makeRequest(
['repos', repo_user, repo_name, 'events'],
page)
# terminate if we find a matching ID
if new_events:
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 from_project_path(cls, path):
"""Utility for finding a virtualenv location based on a project path""" |
path = vistir.compat.Path(path)
if path.name == 'Pipfile':
pipfile_path = path
path = path.parent
else:
pipfile_path = path / 'Pipfile'
pipfile_location = cls.normalize_path(pipfile_path)
venv_path = path / '.venv'
if venv_path.exists(... |
<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_setup_install_args(self, pkgname, setup_py, develop=False):
"""Get setup.py install args for installing the supplied package in the virtualenv :param str... |
headers = self.base_paths["headers"]
headers = headers / "python{0}".format(self.python_version) / pkgname
install_arg = "install" if not develop else "develop"
return [
self.python, "-u", "-c", SETUPTOOLS_SHIM % setup_py, install_arg,
"--single-version-external... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setuptools_install(self, chdir_to, pkg_name, setup_py_path=None, editable=False):
"""Install an sdist or an editable package into the virtualenv :param str c... |
install_options = ["--prefix={0}".format(self.prefix.as_posix()),]
with vistir.contextmanagers.cd(chdir_to):
c = self.run(
self.get_setup_install_args(pkg_name, setup_py_path, develop=editable) +
install_options, cwd=chdir_to
)
return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install(self, req, editable=False, sources=[]):
"""Install a package into the virtualenv :param req: A requirement to install :type req: :class:`requirements... |
try:
packagebuilder = self.safe_import("packagebuilder")
except ImportError:
packagebuilder = None
with self.activated(include_extras=False):
if not packagebuilder:
return 2
ireq = req.as_ireq()
sources = self.filter_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 activated(self, include_extras=True, extra_dists=[]):
"""A context manager which activates the virtualenv. :param list extra_dists: Paths added to the contex... |
original_path = sys.path
original_prefix = sys.prefix
original_user_base = os.environ.get("PYTHONUSERBASE", None)
original_venv = os.environ.get("VIRTUAL_ENV", None)
parent_path = vistir.compat.Path(__file__).absolute().parent.parent.as_posix()
prefix = self.prefix.as_p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_monkeypatched_pathset(self):
"""Returns a monkeypatched `UninstallPathset` for using to uninstall packages from the virtualenv :return: A patched `Uninst... |
from pip_shims.shims import InstallRequirement
# Determine the path to the uninstall module name based on the install module name
uninstall_path = InstallRequirement.__module__.replace(
"req_install", "req_uninstall"
)
req_uninstall = self.safe_import(uninstall_path... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uninstall(self, pkgname, *args, **kwargs):
"""A context manager which allows uninstallation of packages from the virtualenv :param str pkgname: The name of a... |
auto_confirm = kwargs.pop("auto_confirm", True)
verbose = kwargs.pop("verbose", False)
with self.activated():
pathset_base = self.get_monkeypatched_pathset()
dist = next(
iter(filter(lambda d: d.project_name == pkgname, self.get_working_set())),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getRootNode(nodes):
'''Return the node with the most children'''
max = 0
root = None
for i in nodes:
if len(i.children) > max:
max = len(i.children)
root = i
return root |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getNextNode(nodes,usednodes,parent):
'''Get next node in a breadth-first traversal of nodes that have not been used yet'''
for e in edges:
if e.source==parent:
if e.target in usednodes:
x = e.target
break
elif e.target==parent:
if e.sou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def calcPosition(self,parent_circle):
''' Position the circle tangent to the parent circle with the line connecting the centers of the two circles meeting the x axis at angle theta. '''
if r not in self:
raise AttributeError("radius must be calculated before position.")
if theta not ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_progress(request):
""" Used by Ajax calls Return the upload progress and total length values """ |
if 'X-Progress-ID' in request.GET:
progress_id = request.GET['X-Progress-ID']
elif 'X-Progress-ID' in request.META:
progress_id = request.META['X-Progress-ID']
if progress_id:
cache_key = "%s_%s" % (request.META['REMOTE_ADDR'], progress_id)
data = cache.get(cache_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 pre_save(self, model_instance, add):
"""Updates username created on ADD only.""" |
value = super(UserField, self).pre_save(model_instance, add)
if not value and not add:
# fall back to OS user if not accessing through browser
# better than nothing ...
value = self.get_os_username()
setattr(model_instance, self.attname, 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 sys_toolbox_dir():
""" Returns this site-package esri toolbox directory. """ |
return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'esri', 'toolboxes') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def appdata_roaming_dir():
"""Returns the roaming AppData directory for the installed ArcGIS Desktop.""" |
install = arcpy.GetInstallInfo('desktop')
app_data = arcpy.GetSystemEnvironment("APPDATA")
product_dir = ''.join((install['ProductName'], major_version()))
return os.path.join(app_data, 'ESRI', product_dir) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add_route(self, handler, uri, methods=frozenset({'GET'}), host=None,
strict_slashes=False):
'''A helper method to register class instance or
functions as a handler to the application url
routes.
:param handler: function or class instance
:param uri: path of... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def middleware(self, middleware_or_request):
'''Decorate and register middleware to be called before a request.
Can either be called as @app.middleware or @app.middleware('request')
'''
def register_middleware(middleware, attach_to='request'):
if attach_to == 'request':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def static(self, uri, file_or_directory, pattern=r'/?.+',
use_modified_since=True, use_content_range=False):
'''Register a root to serve files from. The input can either be a
file or a directory. See
'''
static_register(self, uri, file_or_directory, pattern,
... |
<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_for(self, view_name: str, **kwargs):
'''Build a URL based on a view name and the values provided.
In order to build a URL, all request parameters must be supplied as
keyword arguments, and each parameter must pass the test for the
specified parameter type. If these conditions 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 i2osp(self, long_integer, block_size):
'Convert a long integer into an octet string.'
hex_string = '%X' % long_integer
if len(hex_string) > 2 * block_size:
raise ValueError('integer %i too large to encode in %i octets' % (long_integer, block_size))
return a2b_hex(hex_stri... |
<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_output(self, max=100):
""" Generate a list of elements from the markov chain. The `max` value is in place in order to prevent excessive iteration. """ |
output = []
item1 = item2 = MarkovChain.START
for i in range(max-3):
item3 = self[(item1, item2)].roll()
if item3 is MarkovChain.END:
break
output.append(item3)
item1 = item2
item2 = item3
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
""" Start the periodic runner """ |
if self._isRunning:
return
if self._cease.is_set():
self._cease.clear() # restart
class Runner(threading.Thread):
@classmethod
def run(cls):
nextRunAt = cls.setNextRun()
while not self._cease.is_set():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def useThis(self, *args, **kwargs):
""" Change parameter of the callback function. :param *args, **kwargs: parameter(s) to use when executing the callback functi... |
self._callback = functools.partial(self._callback, *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
""" Stop the periodic runner """ |
self._cease.set()
time.sleep(0.1) # let the thread closing correctly.
self._isRunning = 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 condition(self) -> bool:
""" check JWT, then check session for validity """ |
jwt = JWT()
if jwt.verify_http_auth_token():
if not current_app.config['AUTH']['FAST_SESSIONS']:
session = SessionModel.where_session_id(
jwt.data['session_id'])
if session is None:
return False
Sess... |
<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_hidden(name, value):
""" render as hidden widget """ |
if isinstance(value, list):
return MultipleHiddenInput().render(name, value)
return HiddenInput().render(name, 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 next_task(self, item, raise_exceptions=None, **kwargs):
"""Deserializes all transactions for this batch and archives the file. """ |
filename = os.path.basename(item)
batch = self.get_batch(filename)
tx_deserializer = self.tx_deserializer_cls(
allow_self=self.allow_self, override_role=self.override_role
)
try:
tx_deserializer.deserialize_transactions(
transactions=batch... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_batch(self, filename=None):
"""Returns a batch instance given the filename. """ |
try:
history = self.history_model.objects.get(filename=filename)
except self.history_model.DoesNotExist as e:
raise TransactionsFileQueueError(
f"Batch history not found for '{filename}'."
) from e
if history.consumed:
raise Transa... |
<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_items(self, html):
""" Get state, county, zipcode, address code from lists page. Example: target url: http://www.zillow.com/browse/homes/md/ <<<<<<< HEAD... |
captcha_patterns = [
"https://www.google.com/recaptcha/api.js", "I'm not a robot"]
for captcha_pattern in captcha_patterns:
if captcha_pattern in html:
raise exc.CaptchaError("Found %r in html!" % captcha_pattern)
data = list()
soup = self.to_sou... |
<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_time(self, loc4d=None):
""" Based on a Location4D object and this Diel object, calculate the time at which this Diel migration is actually happening """ |
if loc4d is None:
raise ValueError("Location4D object can not be None")
if self.pattern == self.PATTERN_CYCLE:
c = SunCycles.cycles(loc=loc4d)
if self.cycle == self.CYCLE_SUNRISE:
r = c[SunCycles.RISING]
elif self.cycle == self.CYCLE_SUNS... |
<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(self, particle, u, v, w, modelTimestep, **kwargs):
# If the particle is settled, don't move it anywhere if particle.settled: return { 'u': 0, 'v': 0, 'w... |
""" I'm below my desired max depth, so i need to go down
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------------------------------- min
-------------------------------------- max
x me
_________________________... |
<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_relationship_aggregate(self, relationship):
""" Returns a new relationship aggregate for the given relationship. :param relationship: Instance of :class... |
if not self._session.IS_MANAGING_BACKREFERENCES:
relationship.direction &= ~RELATIONSHIP_DIRECTIONS.REVERSE
return RelationshipAggregate(self, relationship) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_new(self, entity_class, entity):
""" Registers the given entity for the given class as NEW. :raises ValueError: If the given entity already holds st... |
EntityState.manage(entity, self)
EntityState.get_state(entity).status = ENTITY_STATUS.NEW
self.__entity_set_map[entity_class].add(entity) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_clean(self, entity_class, entity):
""" Registers the given entity for the given class as CLEAN. :returns: Cloned entity. """ |
EntityState.manage(entity, self)
EntityState.get_state(entity).status = ENTITY_STATUS.CLEAN
self.__entity_set_map[entity_class].add(entity) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_deleted(self, entity_class, entity):
""" Registers the given entity for the given class as DELETED. :raises ValueError: If the given entity already ... |
EntityState.manage(entity, self)
EntityState.get_state(entity).status = ENTITY_STATUS.DELETED
self.__entity_set_map[entity_class].add(entity) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unregister(self, entity_class, entity):
""" Unregisters the given entity for the given class and discards its state information. """ |
EntityState.release(entity, self)
self.__entity_set_map[entity_class].remove(entity) |
<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_marked_new(self, entity):
""" Checks if the given entity is marked with status NEW. Returns `False` if the entity has no state information. """ |
try:
result = EntityState.get_state(entity).status == ENTITY_STATUS.NEW
except ValueError:
result = False
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 is_marked_deleted(self, entity):
""" Checks if the given entity is marked with status DELETED. Returns `False` if the entity has no state information. """ |
try:
result = EntityState.get_state(entity).status \
== ENTITY_STATUS.DELETED
except ValueError:
result = False
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 mark_clean(self, entity):
""" Marks the given entity as CLEAN. This is done when an entity is loaded fresh from the repository or after a commit. """ |
state = EntityState.get_state(entity)
state.status = ENTITY_STATUS.CLEAN
state.is_persisted = 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 iterator(self):
""" Returns an iterator over all entity states held by this Unit Of Work. """ |
# FIXME: There is no dependency tracking; objects are iterated in
# random order.
for ent_cls in list(self.__entity_set_map.keys()):
for ent in self.__entity_set_map[ent_cls]:
yield EntityState.get_state(ent) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_save(self, name, filename=None, folder="", keep_ext=True) -> bool:
""" Easy save of a file """ |
if name in self.files:
file_object = self.files[name]
clean_filename = secure_filename(file_object.filename)
if filename is not None and keep_ext:
clean_filename = filename + ".%s" % \
(clean_filename.rsplit('.', 1)[1].lower())
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, fail_callback=None):
""" Parse text fields and file fields for values and files """ |
# get text fields
for field in self.field_arguments:
self.values[field['name']] = self.__get_value(field['name'])
if self.values[field['name']] is None and field['required']:
if fail_callback is not None:
fail_callback()
... |
<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_value(self, field_name):
""" Get request Json value by field name """ |
value = request.values.get(field_name)
if value is None:
if self.json_form_data is None:
value = None
elif field_name in self.json_form_data:
value = self.json_form_data[field_name]
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 __get_file(self, file):
""" Get request file and do a security check """ |
file_object = None
if file['name'] in request.files:
file_object = request.files[file['name']]
clean_filename = secure_filename(file_object.filename)
if clean_filename == '':
return file_object
if file_object and self.__allowed_exte... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __allowed_extension(self, filename, extensions):
""" Check allowed file extensions """ |
allowed_extensions = current_app.config['UPLOADS']['EXTENSIONS']
if extensions is not None:
allowed_extensions = extensions
return '.' in filename and filename.rsplit('.', 1)[1].lower() in \
allowed_extensions |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __invalid_request(self, error):
""" Error response on failure """ |
# TODO: make this modifiable
error = {
'error': {
'message': error
}
}
abort(JsonResponse(status_code=400, data=error)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_field(self, offset, length, format):
"""Returns unpacked Python struct array. Args: offset (int):
offset to byte array within structure length (int):
h... |
return struct.unpack(format, self.data[offset:offset + length])[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export(self, filename, offset=0, length=None):
"""Exports byte array to specified destination Args: filename (str):
destination to output file offset (int):... |
self.__validate_offset(filename=filename, offset=offset, length=length)
with open(filename, 'w') as f:
if length is None:
length = len(self.data) - offset
if offset > 0:
output = self.data[offset:length]
else:
output ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tmpdir():
""" Create a tempdir context for the cwd and remove it after. """ |
target = None
try:
with _tmpdir_extant() as target:
yield target
finally:
if target is not None:
shutil.rmtree(target, ignore_errors=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 run(command, verbose=False):
""" Run a shell command. Capture the stdout and stderr as a single stream. Capture the status code. If verbose=True, then print ... |
def do_nothing(*args, **kwargs):
return None
v_print = print if verbose else do_nothing
p = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
)
v_print("run:", command)
def log_an... |
<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_lxc_version():
""" Asks the current host what version of LXC it has. Returns it as a string. If LXC is not installed, raises subprocess.CalledProcessErro... |
runner = functools.partial(
subprocess.check_output,
stderr=subprocess.STDOUT,
universal_newlines=True,
)
# Old LXC had an lxc-version executable, and prefixed its result with
# "lxc version: "
try:
result = runner(['lxc-version']).rstrip()
return parse_ver... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_qpimage(self, idx=0):
"""Return background-corrected QPImage""" |
if self._bgdata:
# The user has explicitly chosen different background data
# using `get_qpimage_raw`.
qpi = super(SingleHdf5Qpimage, self).get_qpimage()
else:
# We can use the background data stored in the qpimage hdf5 file
qpi = qpimage.QPIm... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simulate(s0, transmat, steps=1):
"""Simulate the next state Parameters s0 : ndarray Vector with state variables at t=0 transmat : ndarray The estimated trans... |
# Single-Step simulation
if steps == 1:
return np.dot(s0, transmat)
# Multi-Step simulation
out = np.zeros(shape=(steps + 1, len(s0)), order='C')
out[0, :] = s0
for i in range(1, steps + 1):
out[i, :] = np.dot(out[i - 1, :], transmat)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify(path):
"""Verify that `path` has a supported numpy file format""" |
path = pathlib.Path(path)
valid = False
if path.suffix == ".npy":
try:
nf = np.load(str(path), mmap_mode="r", allow_pickle=False)
except (OSError, ValueError, IsADirectoryError):
pass
else:
if len(nf.shape) == 2... |
<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_stem(self):
""" Return the name of the file without it's extension. """ |
filename = os.path.basename(self.src_path)
stem, ext = os.path.splitext(filename)
return "index" if stem in ("index", "README", "__init__") else stem |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def type_check(thetype, data, bindings = None):
""" Checks that a given bit of data conforms to the type provided """ |
if not bindings: bindings = Bindings()
if isinstance(thetype, core.RecordType):
for name,child in zip(thetype.child_names, thetype.child_types):
value = data[name]
type_check(child, value, bindings)
elif isinstance(thetype, core.TupleType):
assert isinstance(data, tu... |
<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_setup(filepath):
'''Get the kwargs from the setup function in setup.py'''
# TODO: Need to parse setup.cfg and merge with the data from below
# Monkey patch setuptools.setup to capture keyword arguments
setup_kwargs = {}
def setup_interceptor(**kwargs):
setup_kwargs.update(kwargs)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_console_scripts(setup_data):
'''Parse and return a list of console_scripts from setup_data'''
# TODO: support ini format of entry_points
# TODO: support setup.cfg entry_points as available in pbr
if 'entry_points' not in setup_data:
return []
console_scripts = setup_data['entry_po... |
<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_programmer(programmer_id, programmer_options, replace_existing=False):
"""install programmer in programmers.txt. :param programmer_id: string identif... |
doaction = 0
if programmer_id in programmers().keys():
log.debug('programmer already exists: %s', programmer_id)
if replace_existing:
log.debug('remove programmer: %s', programmer_id)
remove_programmer(programmer_id)
doaction = 1
else:
doaction = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule(self, job, when):
""" Schedule job to run at when nanoseconds since the UNIX epoch.""" |
pjob = pickle.dumps(job)
self._redis.zadd('ss:scheduled', when, pjob) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule_in(self, job, timedelta):
""" Schedule job to run at datetime.timedelta from now.""" |
now = long(self._now() * 1e6)
when = now + timedelta.total_seconds() * 1e6
self.schedule(job, when) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule_now(self, job):
""" Schedule job to run as soon as possible.""" |
now = long(self._now() * 1e6)
self.schedule(job, now) |
<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_aria_autocomplete(self, field):
""" Returns the appropriate value for attribute aria-autocomplete of field. :param field: The field. :type field: hatemi... |
tag_name = field.get_tag_name()
input_type = None
if field.has_attribute('type'):
input_type = field.get_attribute('type').lower()
if (
(tag_name == 'TEXTAREA')
or (
(tag_name == 'INPUT')
and (not (
... |
<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(self, field, list_attribute):
""" Validate the field when its value change. :param field: The field. :param list_attribute: The list attribute of f... |
if not self.scripts_added:
self._generate_validation_scripts()
self.id_generator.generate_id(field)
self.script_list_fields_with_validation.append_text(
'hatemileValidationList.'
+ list_attribute
+ '.push("'
+ field.get_attribute('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 remove(item):
""" Delete item, whether it's a file, a folder, or a folder full of other files and folders. """ |
if os.path.isdir(item):
shutil.rmtree(item)
else:
# Assume it's a file. error if not.
os.remove(item) |
<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_slugignores(root, fname='.slugignore'):
""" Given a root path, read any .slugignore file inside and return a list of patterns that should be removed prio... |
try:
with open(os.path.join(root, fname)) as f:
return [l.rstrip('\n') for l in f]
except IOError:
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_slug_dir(root):
""" Given a path, delete anything specified in .slugignore. """ |
if not root.endswith('/'):
root += '/'
for pattern in get_slugignores(root):
print("pattern", pattern)
remove_pattern(root, pattern) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export(self, folder_path, format=None):
""" General purpose export method, gets file type from filepath extension Valid output formats currently are: Trackli... |
if format is None:
raise ValueError("Must export to a specific format, no format specified.")
format = format.lower()
if format == "trackline" or format[-4:] == "trkl":
ex.Trackline.export(folder=folder_path, particles=self.particles, datetimes=self.datetimes)
... |
<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):
"""Parse passed arguments from shell.""" |
ordered = []
opt_full = dict()
opt_abbrev = dict()
args = args + [''] # Avoid out of range
i = 0
while i < len(args) - 1:
arg = args[i]
arg_next = args[i+1]
if arg.startswith('--'):
if arg_next.startswith('-'):
raise ValueError('{} lacks v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _construct_optional(params):
"""Construct optional args' key and abbreviated key from signature.""" |
args = []
filtered = {key: arg.default for key, arg in params.items() if arg.default != inspect._empty}
for key, default in filtered.items():
arg = OptionalArg(full=key, abbrev=key[0].lower(), default=default)
args.append(arg)
args_full, args_abbrev = dict(), dict()
# Resolve con... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _keyboard_access(self, element):
""" Provide keyboard access for element, if it not has. :param element: The element. :type element: hatemile.util.html.htmld... |
# pylint: disable=no-self-use
if not element.has_attribute('tabindex'):
tag = element.get_tag_name()
if (tag == 'A') and (not element.has_attribute('href')):
element.set_attribute('tabindex', '0')
elif (
(tag != 'A')
a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_event_in_element(self, element, event):
""" Add a type of event in element. :param element: The element. :type element: hatemile.util.html.htmldomelemen... |
if not self.main_script_added:
self._generate_main_scripts()
if self.script_list is not None:
self.id_generator.generate_id(element)
self.script_list.append_text(
event
+ "Elements.push('"
+ element.get_attribute('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 tee(process, filter):
"""Read lines from process.stdout and echo them to sys.stdout. Returns a list of lines read. Lines are not newline terminated. The 'fil... |
lines = []
while True:
line = process.stdout.readline()
if line:
if sys.version_info[0] >= 3:
line = decode(line)
stripped_line = line.rstrip()
if filter(stripped_line):
sys.stdout.write(line)
lines.append(stripped... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tee2(process, filter):
"""Read lines from process.stderr and echo them to sys.stderr. The 'filter' is a callable which is invoked for every line, receiving t... |
while True:
line = process.stderr.readline()
if line:
if sys.version_info[0] >= 3:
line = decode(line)
stripped_line = line.rstrip()
if filter(stripped_line):
sys.stderr.write(line)
elif process.returncode 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 run(args, echo=True, echo2=True, shell=False, cwd=None, env=None):
"""Run 'args' and return a two-tuple of exit code and lines read. If 'echo' is True, the s... |
if not callable(echo):
echo = On() if echo else Off()
if not callable(echo2):
echo2 = On() if echo2 else Off()
process = Popen(
args,
stdout=PIPE,
stderr=PIPE,
shell=shell,
cwd=cwd,
env=env
)
with background_thread(tee2, (process, 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 register_representer_class(self, representer_class):
""" Registers the given representer class with this registry, using its MIME content type as the key. ""... |
if representer_class in self.__rpr_classes.values():
raise ValueError('The representer class "%s" has already been '
'registered.' % representer_class)
self.__rpr_classes[representer_class.content_type] = representer_class
if issubclass(representer_class... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, resource_class, content_type, configuration=None):
""" Registers a representer factory for the given combination of resource class and content... |
if not issubclass(resource_class, Resource):
raise ValueError('Representers can only be registered for '
'resource classes (got: %s).' % resource_class)
if not content_type in self.__rpr_classes:
raise ValueError('No representer class has been regist... |
<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(self, resource_class, content_type):
""" Creates a representer for the given combination of resource and content type. This will also find representer... |
rpr_fac = self.__find_representer_factory(resource_class,
content_type)
if rpr_fac is None:
# Register a representer with default configuration on the fly
# and look again.
self.register(resource_class, content_type)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.