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 coerce(self, other, is_positive=True):
""" Only copies a pointer to the new domain's cell """ |
if hasattr(other, 'get_domain') and hasattr(other, 'lower') and hasattr(other, 'upper'):
if self.is_domain_equal(other):
return other
else:
msg = "Cannot merge partial orders with different domains!"
raise CellConstructionFailure(msg)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_refinement_options(self):
""" Returns possible specializations for the upper values in the taxonomy """ |
domain = self.get_domain()
for upper_value in self.upper:
for suc in domain.successors(upper_value):
yield suc |
<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_relaxation_options(self):
""" Returns possible generalizations for the upper values in the taxonomy """ |
domain = self.get_domain()
for upper_value in self.upper:
for suc in domain.predecessors(upper_value):
yield suc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dotfile(self):
""" Writes a DOT graphviz file of the domain structure, and returns the filename""" |
domain = self.get_domain()
filename = "%s.dot" % (self.__class__.__name__)
nx.write_dot(domain, filename)
return 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 error_handler_404(request):
""" 500 error handler which includes ``request`` in the context. Templates: `500.html` Context: None """ |
from django.template import Context, loader
from django.http import HttpResponseServerError
t = loader.get_template('404.html')
return HttpResponseServerError(t.render(Context({
'request': request,
'settings': settings,
}))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_redirect_url(self, **kwargs):
""" Redirect to request parameter 'next' or to referrer if url is not defined. """ |
if self.request.REQUEST.has_key('next'):
return self.request.REQUEST.get('next')
url = RedirectView.get_redirect_url(self, **kwargs)
if url:
return url
return self.request.META.get('HTTP_REFERER') |
<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_to_response(self, context, **response_kwargs):
""" Returns a response, using the `response_class` for this view, with a template rendered with the giv... |
return HttpResponse(json.dumps(context, cls=JSON_ENCODER),
content_type='application/json',
**response_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 clean(self):
"""Verified value is derived from whether user has a verification hash""" |
result = super(User, self).clean()
result['verified'] = 'verification_hash' not in self._resource
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 check_unique(self):
"""Check the user's email is unique""" |
emails = yield self.view.values(key=self.email)
user_id = getattr(self, 'id', None)
users = {x for x in emails if x != user_id and x}
if users:
raise exceptions.ValidationError(
"User with email '{}' already exists".format(self.email)) |
<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_admin(cls, email, password, **kwargs):
""" Create an approved 'global' administrator :param email: the user's email address :param password: the user'... |
data = {
'email': email,
'password': cls.hash_password(password),
'has_agreed_to_terms': True,
'state': State.approved,
'role': cls.roles.administrator.value,
'organisations': {}
}
data.update(**kwargs)
user = 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 hash_password(plain_text):
"""Hash a plain text password""" |
# NOTE: despite the name this is a one-way hash not a reversible cypher
hashed = pbkdf2_sha256.encrypt(plain_text, rounds=8000, salt_size=10)
return unicode(hashed) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def change_password(self, previous, new_password):
""" Change the user's password and save to the database :param previous: plain text previous password :param n... |
if not self.verify_password(previous):
raise exceptions.Unauthorized('Incorrect password')
if len(new_password) < options.min_length_password:
msg = ('Passwords must be at least {} characters'
.format(options.min_length_password))
raise exceptions... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(cls, email, password):
""" Log in a user :param email: the user's email address :param password: the user's password :returns: (User, token) :raises: S... |
try:
doc = yield cls.view.first(key=email, include_docs=True)
except couch.NotFound:
raise exceptions.Unauthorized('Unknown email address')
user = cls(**doc['doc'])
verified = user.verify_password(password)
if not verified:
raise exceptions.... |
<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(cls, user_id, verification_hash):
""" Verify a user using the verification hash The verification hash is removed from the user once verified :param us... |
user = yield cls.get(user_id)
# If user does not have verification hash then this means they have already been verified
if 'verification_hash' not in user._resource:
raise Return(user)
if user.verification_hash != verification_hash:
raise exceptions.ValidationE... |
<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_admin(self):
"""Is the user a system administrator""" |
return self.role == self.roles.administrator.value and self.state == State.approved |
<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_reseller(self):
"""is the user a reseller""" |
return self.role == self.roles.reseller.value and self.state == State.approved |
<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_org_admin(self, organisation_id):
"""Is the user authorized to administrate the organisation""" |
return (self._has_role(organisation_id, self.roles.administrator) or
self.is_admin()) |
<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_user(self, organisation_id):
"""Is the user valid and approved in this organisation""" |
return (self._has_role(organisation_id, self.roles.user) or
self.is_org_admin(organisation_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 _has_role(self, organisation_id, role):
"""Check the user's role for the organisation""" |
if organisation_id is None:
return False
try:
org = self.organisations.get(organisation_id, {})
user_role = org.get('role')
state = org.get('state')
except AttributeError:
return False
return user_role == role.value and state... |
<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_organisation_from_all(cls, organisation_id):
"""Remove an organisation from all users""" |
users = yield views.organisation_members.get(key=organisation_id,
include_docs=True)
users = [x['doc'] for x in users['rows']]
for user in users:
user['organisations'][organisation_id]['state'] = State.deactivated.name
db... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def valid(cls, token, **kwargs):
""" Check if a token exists and has not expired :param token: the token :return: bool """ |
try:
token = yield cls.get(token)
except couch.NotFound:
raise Return(False)
raise Return(token.ttl >= datetime.utcnow()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plant(self, *seeds, **arguments):
"""Applys seeds and arguments to the garden for use during the harvest """ |
map(self._clean, seeds)
self.network_kwargs.update(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 _clean(self, seed):
"""Takes a seed and applies it to the garden """ |
seed = deepcopy(seed)
# inherit any other figures
self._inherit(*array(get(seed, 'inherit', [])))
# merge the seed arguments
if '&arguments' in seed:
self.arguments = merge(self.arguments, seed.pop('&arguments'))
elif 'arguments' in seed:
self.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 _generate_base_mimetypes(self):
""" Generate the base mimetypes as described by non customized document types. """ |
for t in self.type_instances:
if t.custom_mime:
continue
yield t.mime, (t, None, 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 crossvalidation_stats(errors1, errors2):
"""Paired difference test of the CV errors of two models Parameters: errors1 : ndarray The CV errors model 1 errors2... |
# load modules
import numpy as np
import scipy.stats
import warnings
# Number of blocks
K = errors1.shape[0]
# display warnings
if K < 30:
warnings.warn((
"The number of blocks is K<30 what is insufficient "
"for conducting a t-Test to compare both mode... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def badRequestMethod(self, environ, start_response):
""" Return HTTP 400 Bad Request. """ |
response = "400 Bad Request\n\nTo access this PyAMF gateway you " \
"must use POST requests (%s received)" % environ['REQUEST_METHOD']
start_response('400 Bad Request', [
('Content-Type', 'text/plain'),
('Content-Length', str(len(response))),
('Server', ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collect(self):
""" Walks self.migration_home and load all potential migration modules """ |
for root, dirname, files in walk(self.migration_home):
for file_name in file_filter(files, "*.py"):
file_name = file_name.replace('.py', '')
file = None
try:
if file_name == '__init__':
continue
... |
<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_all(self, direction):
""" Runs all registered migrations :param direction: Can be on of two values, UP or DOWN """ |
for key in sorted(migration_registry.keys):
self.run(key, direction) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self, migration_name, direction):
""" Asserts an engine is configured and runs the registered migration in the given direction :param migration_name: key... |
if not self.engine:
raise AttributeError("No engine configured for MigrationManager")
connection = self.engine.connect()
trans = connection.begin()
try:
migration = migration_registry[migration_name]()
if migration.preflight():
trans ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def maven_url(self):
'''
Download-URL from Maven
'''
return '{prefix}/{path}/{artifact}/{version}/{filename}'.format(
prefix = MAVEN_PREFIX,
path = '/'.join(self.group.split('.')),
artifact = self.artifact,
version = self.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 download_to(self, folder):
'''
Download into a folder
'''
urlretrieve(self.maven_url, os.path.join(folder, self.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 radar_factory(num_vars, frame='circle'):
"""Create a radar chart with `num_vars` axes. This function creates a RadarAxes projection and registers it. Paramet... |
# calculate evenly-spaced axis angles
theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)
# rotate theta such that the first axis is at the top
theta += np.pi/2
def draw_poly_patch(self):
verts = unit_poly_verts(theta)
return plt.Polygon(verts, closed=True, edgecolor='k')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unit_poly_verts(theta):
"""Return vertices of polygon for subplot axes. This polygon is circumscribed by a unit circle centered at (0.5, 0.5) """ |
x0, y0, r = [0.5] * 3
verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta]
return verts |
<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_logging_factories(loader):
""" Registers default factories for logging standard package. :param loader: Loader where you want register default loggi... |
loader.register_factory(logging.Logger, LoggerFactory)
loader.register_factory(logging.Handler, LoggingHandlerFactory) |
<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_subscription(self, channel, callback_function):
""" Add a channel to subscribe to and a callback function to run when the channel receives an update. If ... |
if channel not in CHANNELS:
CHANNELS.append(channel)
SUBSCRIPTIONS[channel] = [callback_function]
else:
SUBSCRIPTIONS[channel].append(callback_function)
# If a channel gets added after subscription has already been called
# call subscribe on the indiv... |
<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_keep_alive(self):
""" Start a new thread timer to keep the keep_alive_function running every keep_alive seconds. """ |
threading.Timer(self._keep_alive, self._run_keep_alive).start()
_LOGGER.info("Polling the API")
# This may or may not return something
self._keep_alive_function() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unsubscribe(self):
""" Completly stop all pubnub operations. """ |
_LOGGER.info("PubNub unsubscribing")
self._pubnub.unsubscribe_all()
self._pubnub.stop()
self._pubnub = 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 _subscribe(self):
""" Start the subscription to the channel list. If self._keep_alive_function isn't None start timer thread to run self._keep_alive_function... |
_LOGGER.info("PubNub subscribing")
self._pubnub.subscribe().channels(CHANNELS).execute()
if self._keep_alive_function is not None:
threading.Timer(self._keep_alive, self._run_keep_alive).start()
self._subscribed = 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 status(self, pubnub, status):
""" Things to do on different status updates. """ |
if status.operation == PNOperationType.PNSubscribeOperation \
or status.operation == PNOperationType.PNUnsubscribeOperation:
if status.category == PNStatusCategory.PNConnectedCategory:
# This is expected for a subscribe, this means there is no error or issue whatsoever
... |
<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, klass=None, memo=None, **kwargs):
""" Creates a copy of the current instance. The 'kwargs' parameter can be used by clients to update attributes ... |
obj = Empty()
obj.__class__ = klass or self.__class__
obj.resource = self.resource
obj.filters = self.filters.copy()
obj.order_by = self.order_by
obj.low_mark = self.low_mark
obj.high_mark = self.high_mark
obj.__dict__.update(kwargs)
return 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 results(self, limit=100):
""" Yields the results from the API, efficiently handling the pagination and properly passing all paramaters. """ |
limited = True if self.high_mark is not None else False
rmax = self.high_mark - self.low_mark if limited else None
rnum = 0
params = self.get_params()
params["offset"] = self.low_mark
params["limit"] = limit
while not limited and rmax is None or rnum < rmax:
... |
<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):
""" Deletes the results of this query, it first fetches all the items to be deletes and then issues a PATCH against the list uri of the resourc... |
uris = [obj["resource_uri"] for obj in self.results()]
data = self.resource._meta.api.resource_serialize({"objects": [], "deleted_objects": uris})
self.resource._meta.api.http_resource("PATCH", self.resource._meta.resource_name, data=data)
return len(uris) |
<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_count(self):
""" Gets the total_count using the current filter constraints. """ |
params = self.get_params()
params["offset"] = self.low_mark
params["limit"] = 1
r = self.resource._meta.api.http_resource("GET", self.resource._meta.resource_name, params=params)
data = self.resource._meta.api.resource_deserialize(r.text)
number = data["meta"]["total_c... |
<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):
""" An iterator over the results from applying this QuerySet to the api. """ |
for item in self.query.results():
obj = self.resource(**item)
yield obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count(self):
""" Returns the number of records as an integer. If the QuerySet is already fully cached this simply returns the length of the cached results se... |
if self._result_cache is not None and not self._iter:
return len(self._result_cache)
return self.query.get_count() |
<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, **kwargs):
""" Creates a new object with the given kwargs, saving it to the api and returning the created object. """ |
obj = self.resource(**kwargs)
obj.save(force_insert=True)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exclude(source, keys, *, transform=None):
"""Returns a dictionary excluding keys from a source dictionary. :source: a dictionary :keys: a set of keys, or a p... |
check = keys if callable(keys) else lambda key: key in keys
return {key: transform(source[key]) if transform else source[key]
for key in source if not check(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 pick(source, keys, *, transform=None):
"""Returns a dictionary including only specified keys from a source dictionary. :source: a dictionary :keys: a set of ... |
check = keys if callable(keys) else lambda key: key in keys
return {key: transform(source[key]) if transform else source[key]
for key in source if check(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 json_default(obj):
"""Convert an object to JSON, via the defaults set with register_json_default. :obj: the object to convert """ |
for default in _JSON_DEFAULTS:
if default[0](obj):
return default[1](obj)
raise TypeError(repr(obj) + " is not JSON serializable") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_json(obj, pretty=False):
"""Converts an object to JSON, using the defaults specified in register_json_default. :obj: the object to convert to JSON :pretty... |
sort_keys = False
indent = None
separators = (",", ":")
if isinstance(pretty, tuple):
sort_keys, indent, separators = pretty
elif pretty is True:
sort_keys = True
indent = 2
separators = (", ", ": ")
return json.dumps(obj, sort_keys=sort_keys, indent=indent, separators=separators,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_value(obj, name):
"""A flexible method for getting values from objects by name. returns: - obj is None: (False, None) - obj is dict: (name in obj, obj.ge... |
if obj is None:
return (False, None)
elif isinstance(obj, dict):
return (name in obj, obj.get(name))
elif hasattr(obj, name):
return (True, getattr(obj, name))
elif hasattr(obj, "__getitem__") and hasattr(obj, "__contains__") and name in obj:
return (True, obj[name])
else:
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 set_value(obj, name, value):
"""A flexible method for setting a value on an object. If the object implements __setitem__ (such as a dict) performs obj[name] ... |
if hasattr(obj, "__setitem__"):
obj[name] = value
else:
setattr(obj, 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 with_defaults(method, nparams, defaults=None):
"""Call method with nparams positional parameters, all non-specified defaults are passed None. :method: the me... |
args = [None] * nparams if not defaults else defaults + max(nparams - len(defaults), 0) * [None]
return method(*args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delegate(from_owner, to_owner, methods):
"""Creates methods on from_owner to call through to methods on to_owner. :from_owner: the object to delegate to :to_... |
for method in methods:
_delegate(from_owner, to_owner, method) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _delegate(from_owner, to_owner, method):
"""Creates a method on from_owner to calls through to the same method on to_owner. :from_owner: the object to delega... |
dgate = lambda self, *args, **kwargs: getattr(getattr(self, to_owner), method)(*args, **kwargs)
dgate.__name__ = method
dgate.__doc__ = "Delegates to {0}.{1}: {2}".format(to_owner, method, method.__doc__)
setattr(from_owner, method, dgate) |
<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_methods(extension_name):
""" Return all methods in extension that have nago_access set """ |
extension = get_extension(extension_name)
methods = {}
for name, i in inspect.getmembers(extension):
if hasattr(i, 'nago_access'):
api_name = i.nago_name
methods[api_name] = i
return methods |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def column_converter(string):
""" Converts column arguments to integers. - Accepts columns in form of INT, or the range INT-INT. - Returns a list of one or more ... |
column = string.strip(',')
if '-' in column:
column_range = map(int, column.split('-'))
# For decreasing ranges, increment the larger value, reverse the
# passing to range (so it will accept the input), and finally
# reverse the output ([::-1])
if column_range[0] > colum... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_columns(column, line, columns):
""" Make sure the column is the minimum between the largest column asked for and the max column available in the line. ... |
return column <= min(len(line), max(columns)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def panic(self, *args):
""" Creates a fatal error and exit """ |
self._err("fatal", *args)
if self.test_errs_mode is False: # pragma: no cover
sys.exit(1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def warning(self, *args) -> "Err": """ Creates a warning message """ |
error = self._create_err("warning", *args)
print(self._errmsg(error))
return error |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def info(self, *args) -> "Err": """ Creates an info message """ |
error = self._create_err("info", *args)
print(self._errmsg(error))
return error |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def debug(self, *args) -> "Err": """ Creates a debug message """ |
error = self._create_err("debug", *args)
print(self._errmsg(error))
return error |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_err(self, errclass: str, *args) -> "Err": """ Create an error """ |
error = self._new_err(errclass, *args)
self._add(error)
return error |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _err(self, errclass: str="error", *args) -> "Err": """ Creates an error """ |
error = self._new_err(errclass, *args)
if self.log_errs is True:
sep = " "
if self.log_format == "csv":
sep = ","
msg = str(datetime.now()) + sep + \
self._errmsg(error, msgformat=self.log_format)
self.logger.error(msg)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _headline(self, error, i: int) -> str: """ Format the error message's headline """ |
msgs = Msg()
# get the error title
if error.errclass == "fatal":
msg = msgs.fatal(i)
elif error.errclass == "warning":
msg = msgs.warning(i)
elif error.errclass == "info":
msg = msgs.info(i)
elif error.errclass == "debug":
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _errmsg(self, error: "Err", tb: bool=False, i: int=None, msgformat: str="terminal") -> str: """ Get the error message """ |
if msgformat == "terminal":
msg = self._headline(error, i)
if error.ex is not None:
msg += "\n" + "line " + colors.bold(str(error.line))
msg += ": " + colors.yellow(error.code)
msg += "\n" + str(error.file)
if self.errs_tra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _print_errs(self):
""" Prints the errors trace with tracebacks """ |
i = 0
for error in self.errors:
print(self._errmsg(error, tb=True, i=i))
# for spacing
if self.errs_traceback is False:
print()
i += 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add(self, error: "Err"):
""" Adds an error to the trace if required """ |
if self.trace_errs is True:
self.errors.append(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_caller(self, callers: List[str], function: str) -> str: """ Get the caller function from the provided function """ |
is_next = False
for c in callers:
if is_next is True:
return c
if function == c:
is_next = 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 _get_args(self, *args) -> (Exception, str):
""" Returns exception and message from the provided arguments """ |
ex = None
msg = None
for arg in args:
if isinstance(arg, str):
msg = arg
elif isinstance(arg, Exception):
ex = arg
return ex, msg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trace(self):
""" Print the errors trace if there are some errors """ |
if len(self.errors) > 0:
numerrs = len(self.errors)
print("========= Trace (" + str(numerrs) + ") =========")
self._print_errs()
self.errors = [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def via(self, *args):
""" Creates an empty error to record in the stack trace """ |
error = None
if len(self.errors) > 0:
error = self._err("via", *args)
return error |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __create_translation_migration(self):
""" Create an empty migration """ |
migrations_dir = os.path.join(self.BASE_DIR, self.app_name + "/migrations/")
dependency_migration = os.path.basename(max(glob.iglob(migrations_dir + '*.py'), key=os.path.getctime)).replace(
".py", "")
"""
If there's no migration before this, which is unlikely to happen, then... |
<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_local_path(directory, create_dir=False):
""" sets path for local saving of information if create is true we will create the folder even if it doesnt exis... |
if not os.path.exists(directory) and create_dir is True:
os.makedirs(directory)
if not os.path.exists(directory) and create_dir is False:
raise AttributeError("Path '%s' does not exist, to make it pass create_dir=True to rinocloud.set_local_path" % directory)
if os.path.isdir(directory):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def task(name=None, t=INFO, *args, **kwargs):
""" This decorator modifies current function such that its start, end, and duration is logged in console. If the ta... |
def c_run(name, f, t, args, kwargs):
def run(*largs, **lkwargs):
thread = __get_current_thread()
old_name = __THREAD_PARAMS[thread][__THREAD_PARAMS_FNAME_KEY]
__THREAD_PARAMS[thread][__THREAD_PARAMS_FNAME_KEY] = name
r = log(name, f, t, largs, lkwargs, *arg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def progress_task(name=None, t=INFO, max_value=100, *args, **kwargs):
""" This decorator extends the basic @task decorator by allowing users to display some form... |
return task(name=name, t=t, init_progress=True, max_value=max_value,
*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 current_kv_names(self):
"""Return set of string names of current available Splunk KV collections""" |
return current_kv_names(self.sci, self.username, self.appname, request=self._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 get(self, CachableItem):
"""Returns current ICachedItem for ICachableItem or None if not cached""" |
cached_item = self.mapper.get(CachableItem)
r = self.request('get',
self.url+"storage/collections/data/"+self.collname+'/'+cached_item.getId(),
data={'output_mode': 'json'})
if r.ok:
# we need to update the object with the values found in the cache area
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isDirty(self, CachableItem):
"""True if cached information requires update for ICachableItem""" |
_cachedItem = self.get(CachableItem)
if not _cachedItem:
return True
_newCacheItem = self.mapper.get(CachableItem)
return False if _cachedItem == _newCacheItem else 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 cache(self, CachableItem):
"""Updates caches area with latest item information returning ICachedItem if cache updates were required. Issues ICacheObjectCreat... |
_cachedItem = self.get(CachableItem)
if not _cachedItem:
_cachedItem = self.mapper.get(CachableItem)
self._add(_cachedItem)
logger.debug("new cachable item added to Splunk KV cache area {id: %s, type: %s}", str(_cachedItem.getId()), str(_cachedItem.__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 run_model(t_output_every, output_dir=None, m=None, force_resume=True, **iterate_args):
"""Convenience function to combine making a Runner object, and running... |
r = runner.Runner(output_dir, m, force_resume)
print(r)
r.iterate(t_output_every=t_output_every, **iterate_args)
return r |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resume_runs(dirnames, t_output_every, t_upto, parallel=False):
"""Resume many models, and run. Parameters dirnames: list[str] List of output directory paths ... |
run_model_partial = partial(run_model, t_output_every, force_resume=True,
t_upto=t_upto)
run_func(run_model_partial, dirnames, parallel) |
<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_kwarg_scan(ModelClass, model_kwarg_sets, t_output_every, t_upto, force_resume=True, parallel=False):
"""Run many models with the same parameters but vari... |
task_runner = _TaskRunner(ModelClass, t_output_every, t_upto, force_resume)
run_func(task_runner, model_kwarg_sets, parallel) |
<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_field_scan(ModelClass, model_kwargs, t_output_every, t_upto, field, vals, force_resume=True, parallel=False):
"""Run many models with a range of paramete... |
model_kwarg_sets = [dict(model_kwargs, field=val) for val in vals]
run_kwarg_scan(ModelClass, model_kwarg_sets,
t_output_every, t_upto, force_resume, parallel) |
<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(logger=None):
"""Pass stump a logger to use. If no logger is supplied, a basic logger of level INFO will print to stdout. """ |
global LOGGER
if logger is None:
LOGGER = logging.basicConfig(stream=sys.stdout, level=logging.INFO)
else:
LOGGER = logger |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _stump(f, *args, **kwargs):
"""Worker for the common actions of all stump methods, aka the secret sauce. *Keyword parameters* - log :: integer - Specifies a ... |
global LOGGER
def aux(*xs, **kws):
f_kws = kws.copy()
f_kws.update(dict(zip(inspect.getfullargspec(f).args, xs)))
level = kwargs.get('log', logging.INFO)
post = kwargs.get('postfix_only', False)
pre = kwargs.get('prefix_only', False)
print_return = kwargs.get('... |
<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_full_name(self):
""" Returns the first_name plus the last_name, with a space in between. """ |
full_name = '{first_name} {last_name}'.format(first_name=self.first_name, last_name=self.last_name)
return full_name.strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
""" Main function for this module """ |
sandbox = create_sandbox()
directory = download_package_to_sandbox(
sandbox,
'https://pypi.python.org/packages/source/c/checkmyreqs/checkmyreqs-0.1.6.tar.gz'
)
print(directory)
destroy_sandbox(sandbox) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_map(uri, url_root):
""" return a tuple of the rule and kw. """ |
# TODO: Building the Map each time this is called seems like it could be more effiecent.
result = []
try:
result = db.execute(text(fetch_query_string('select_route_where_dynamic.sql'))).fetchall()
except OperationalError as err:
current_app.logger.error("OperationalError: %s", err)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def route_handler(context, content, pargs, kwargs):
""" Route shortcode works a lot like rendering a page based on the url or route. This allows inserting in ren... |
(node, rule_kw) = node_from_uri(pargs[0])
if node == None:
return u"<!-- 404 '{0}' -->".format(pargs[0])
rule_kw.update( node )
values = rule_kw
values.update( request.form.to_dict(flat=True) )
values.update( request.args.to_dict(flat=True) )
values['method'] = request.method
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def page_uri_handler(context, content, pargs, kwargs):
""" Shortcode for getting the link to internal pages using the flask `url_for` method. Activate with 'shor... |
uri = pargs[0]
return url_for('.page_uri', uri=uri) |
<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, uri=''):
"For sql queries that start with 'SELECT ...'"
(node, rule_kw) = node_from_uri(uri)
if node == None:
abort(404)
rule_kw.update( node )
values = rule_kw
xhr_data = request.get_json()
if xhr_data:
values.update( xhr_da... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def post(self, uri=''):
"For sql queries that start with 'INSERT ...'"
# get node...
(node, rule_kw) = node_from_uri(uri, method=request.method)
rule_kw.update( node )
values = rule_kw
xhr_data = request.get_json()
if xhr_data:
values.update( xhr_dat... |
<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_aliyun_config(name, default=None):
'''
Get configuration variable from environment variable or
or django settings.py
'''
config = os.environ.get(name, getattr(settings, name, default))
if config is not None:
if isinstance(config, str):
return config.strip()
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 tweets_for(query_type, args, per_user=None):
""" Retrieve tweets for a user, list or search term. The optional ``per_user`` arg limits the number of tweets p... |
lookup = {"query_type": query_type, "value": args[0]}
try:
tweets = Tweet.objects.get_for(**lookup)
except TwitterQueryException:
return []
if per_user is not None:
_tweets = defaultdict(list)
for tweet in tweets:
if len(_tweets[tweet.user_name]) < per_user:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tweets_default(*args):
""" Tweets for the default settings. """ |
query_type = settings.TWITTER_DEFAULT_QUERY_TYPE
args = (settings.TWITTER_DEFAULT_QUERY,
settings.TWITTER_DEFAULT_NUM_TWEETS)
per_user = None
if query_type == QUERY_TYPE_LIST:
per_user = 1
return tweets_for(query_type, args, per_user=per_user) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_cli_arg(arg):
""" Turn a bytestring provided by `argparse` into unicode. :param arg: The bytestring to decode. :return: The argument as a unicode obje... |
if arg is None:
raise ValueError('Argument cannot be None')
if sys.version_info.major == 3:
# already decoded
return arg
return arg.decode(sys.getfilesystemencoding()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_level_from_vebosity(verbosity):
""" Get the `logging` module log level from a verbosity. :param verbosity: The number of times the `-v` option was specif... |
if verbosity == 0:
return logging.WARNING
if verbosity == 1:
return logging.INFO
return logging.DEBUG |
<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_cursor_position():
"""Write an escape sequence to ask for the current cursor position. Since the result is written on the standard input, this function s... |
# "cursor position report" in ECMA-48.
it = get_char(u'\x1b[6n')
sequence = consume_escape_sequence(it, next(it))
# sequence format is \x1b[<row>;<col>R
return tuple(int(x) for x in sequence[2:-1].split(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 get_template(self, path):
""" Load and compile template. """ |
if self.options['debug'] and self.options['cache_size']:
return self.cache.get(path, self.cache_template(path))
return self.load_template(path) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.