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)
if isinstance(other, LinearOrderedCell):
# convert other's domain to a chain/dag
# first ensure domain has same size and elements
raise NotImplemented("Please Implement me!")
domain = self.get_domain()
if other in domain:
c = self.__class__()
if not is_positive:
# add value to lower (negative example)
c.lower = set([other])
c.upper = set()
else:
# add value to upper (positive example)
c.upper = set([other])
c.lower = set()
return c
else:
raise CellConstructionFailure("Could not coerce value that is"+
" outside order's domain . (Other = %s) " % (str(other),)) |
<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 given context. If any keyword arguments are provided, they will be passed to the constructor of the response class. """ |
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's plain text password :returns: a 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(**data)
yield user._save()
raise Return(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 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 new_password: plain text new password :raises: ValidationError """ |
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.ValidationError(msg)
if len(new_password) > options.max_length_password:
msg = ('Passwords must be at no more than {} characters'
.format(options.max_length_password))
raise exceptions.ValidationError(msg)
self.password = self.hash_password(new_password)
yield self._save() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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: SocketError, CouchException """ |
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.Unauthorized('Invalid password')
token = yield Token.create(user)
raise Return((user, token.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 verify(cls, user_id, verification_hash):
""" Verify a user using the verification hash The verification hash is removed from the user once verified :param user_id: the user ID :param verification_hash: the verification hash :returns: a User instance """ |
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.ValidationError('Invalid verification hash')
del user.verification_hash
yield user._save()
raise Return(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 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 == State.approved.name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 = cls.db_client()
yield db.save_docs(users) |
<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.arguments = seed.pop('arguments')
# append the seed
self.seeds.append(seed) |
<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 : ndarray The CV errors model 2 Returns: -------- pvalue : float Two-sided P-value if the differences between err1 and err2 are significant tscore : float t-statistics se : float Standard Error of the CV-Error-Difference mu : float The average difference between err1 and err2 """ |
# 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 models! "
"K=40 is suggested."))
# difference between errors
delta = errors1 - errors2
# the average difference
mu = np.mean(delta)
# Standard Error of the CV-Error-Difference
# se = np.sqrt(np.sum((delta-np.mean(delta))**2)/K)
se = np.std(delta)
# t-statistics
tscore = mu / se
# Two-sided P-value
pvalue = scipy.stats.t.sf(np.abs(tscore), K - 1) * 2
# done
return pvalue, tscore, se, mu |
<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', gateway.SERVER_NAME),
])
return [response] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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
file, pathname, description = find_module(
file_name, [root])
load_module(file_name, file, pathname, description)
finally:
if file is not None:
file.close() |
<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 to a registered class in the `migration_registry` :param direction: Can be on of two values, UP or DOWN """ |
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 = connection.begin()
if direction == Direction.UP:
migration.up(connection)
elif direction == Direction.DOWN:
migration.down(connection)
else:
raise UnknowDirectionError
if migration.check():
trans.commit()
else:
raise MigrationError("Migration failed consistency checks")
except Exception, e:
trans.rollback()
#XXX:dc: do more to introspect why we failed
raise e |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def 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,
filename = 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 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. Parameters num_vars : int Number of variables for radar chart. frame : {'circle' | 'polygon'} Shape of frame surrounding axes. """ |
# 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')
def draw_circle_patch(self):
# unit circle centered on (0.5, 0.5)
return plt.Circle((0.5, 0.5), 0.5)
patch_dict = {'polygon': draw_poly_patch, 'circle': draw_circle_patch}
if frame not in patch_dict:
raise ValueError('unknown value for `frame`: %s' % frame)
class RadarAxes(PolarAxes):
name = 'radar'
# use 1 line segment to connect specified points
RESOLUTION = 1
# define draw_frame method
draw_patch = patch_dict[frame]
def fill(self, *args, **kwargs):
"""Override fill so that line is closed by default"""
closed = kwargs.pop('closed', True)
return super(RadarAxes, self).fill(closed=closed, *args, **kwargs)
def plot(self, *args, **kwargs):
"""Override plot so that line is closed by default"""
lines = super(RadarAxes, self).plot(*args, **kwargs)
for line in lines:
self._close_line(line)
def _close_line(self, line):
x, y = line.get_data()
# FIXME: markers at x[0], y[0] get doubled-up
if x[0] != x[-1]:
x = np.concatenate((x, [x[0]]))
y = np.concatenate((y, [y[0]]))
line.set_data(x, y)
def set_varlabels(self, labels):
self.set_thetagrids(np.degrees(theta), labels)
def _gen_axes_patch(self):
return self.draw_patch()
def _gen_axes_spines(self):
if frame == 'circle':
return PolarAxes._gen_axes_spines(self)
# The following is a hack to get the spines (i.e. the axes frame)
# to draw correctly for a polygon frame.
# spine_type must be 'left', 'right', 'top', 'bottom', or `circle`.
spine_type = 'circle'
verts = unit_poly_verts(theta)
# close off polygon by repeating first vertex
verts.append(verts[0])
path = Path(verts)
spine = Spine(self, spine_type, path)
spine.set_transform(self.transAxes)
return {'polar': spine}
register_projection(RadarAxes)
return theta |
<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 logging factories """ |
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 channel already exists, create a new "subscription" and append another callback function. Args: channel (str):
The channel to add a subscription too. callback_function (func):
The function to run on an update to the passed in channel. """ |
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 individual channel, here.
if self._subscribed:
_LOGGER.info("New channel added after main subscribe call.")
self._pubnub.subscribe().channels(channel).execute() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _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 every self._keep_alive amount of seconds. """ |
_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
_LOGGER.info("PubNub connected")
elif status.category == PNStatusCategory.PNReconnectedCategory:
# This usually occurs if subscribe temporarily fails but reconnects. This means
# there was an error but there is no longer any issue
_LOGGER.info("PubNub reconnected")
elif status.category == PNStatusCategory.PNDisconnectedCategory:
# This is the expected category for an unsubscribe. This means there
# was no error in unsubscribing from everything
_LOGGER.info("PubNub unsubscribed")
elif status.category == PNStatusCategory.PNUnexpectedDisconnectCategory:
# This is usually an issue with the internet connection, this is an error, handle appropriately
# retry will be called automatically
_LOGGER.info("PubNub disconnected (lost internet?)")
else:
# This is usually an issue with the internet connection, this is an error, handle appropriately
# retry will be called automatically
_LOGGER.info("PubNub disconnected (lost internet?)")
elif status.operation == PNOperationType.PNHeartbeatOperation:
# Heartbeat operations can in fact have errors, so it is important to check first for an error.
# For more information on how to configure heartbeat notifications through the status
# PNObjectEventListener callback, consult <link to the PNCONFIGURATION heartbeart config>
if status.is_error():
# There was an error with the heartbeat operation, handle here
_LOGGER.info("PubNub failed heartbeat")
else:
# Heartbeat operation was successful
_LOGGER.info("PubNub heartbeat")
else:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 after copying has taken place. """ |
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 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 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:
if limited or rmax is not None:
rleft = rmax - rnum
params["limit"] = rleft if rleft < limit else limit
r = self.resource._meta.api.http_resource("GET", self.resource._meta.resource_name, params=params)
data = self.resource._meta.api.resource_deserialize(r.text)
if not limited:
rmax = data["meta"]["total_count"]
if data["meta"]["total_count"] < rmax:
rmax = data["meta"]["total_count"]
params["offset"] = data["meta"]["offset"] + data["meta"]["limit"]
for item in data["objects"]:
rnum += 1
yield 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 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 resource. """ |
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_count"]
# Apply offset and limit constraints manually, since using limit/offset
# in the API doesn't change the total_count output.
number = max(0, number - self.low_mark)
if self.high_mark is not None:
number = min(number, self.high_mark - self.low_mark)
return number |
<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 set to avoid an api call. """ |
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 predicate function that accepting a key :transform: a function that transforms the values """ |
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 keys, or a predicate function that accepting a key :transform: a function that transforms the values """ |
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: if True, extra whitespace is added to make the output easier to read """ |
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,
default=json_default) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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.get(name)) - obj hasattr(name):
(True, getattr(obj, name)) - else: (False, None) :obj: the object to pull values from :name: the name to use when getting the value """ |
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, 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 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] = value, else performs setattr(obj, name, value). :obj: the object to set the value on :name: the name to assign the value to :value: the value to assign """ |
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 method to call :nparams: the number of parameters the function expects :defaults: the default values to pass in for the last len(defaults) params """ |
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_owner: the owner on which to delegate from :methods: a list of methods to delegate """ |
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 delegate to :to_owner: the owner on which to delegate from :methods: the method to delegate """ |
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 integers. """ |
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] > column_range[1]:
column_range[0] += 1
return [i for i in range(*column_range[::-1])][::-1]
# For normal ranges, increment the larger value.
column_range[1] += 1
return [i for i in range(*column_range)]
if ',' in column:
columns = column.split(',')
return map(int, columns)
return [int(column)] |
<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)
print(self._errmsg(error))
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 _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":
msg = msgs.debug(i)
elif error.errclass == "via":
msg = msgs.via(i)
else:
msg = msgs.error(i)
# function name
if error.function is not None:
msg += " from " + colors.bold(error.function)
if error.caller is not None:
msg += " called from " + colors.bold(error.caller)
if error.caller_msg is not None:
msg += "\n" + error.caller_msg
if error.function is not None and error.msg is not None:
msg += ": "
else:
msg = msg + " "
if error.errtype is not None:
msg += error.errtype + " : "
if error.msg is not None:
msg += error.msg
return 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 _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_traceback is True or tb is True:
if error.tb is not None:
msg += "\n" + error.tb
elif msgformat == "csv":
sep = ","
msg = error.msg + sep
msg += str(error.line) + sep + error.code + sep
msg += str(error.file)
elif msgformat == "text":
sep = ","
msg = error.msg
if error.ex is not None:
msg += sep + str(error.line) + sep + error.code + sep
msg += str(error.file) + sep
if self.errs_traceback is True or tb is True:
if error.tb is not None:
msg += sep + error.tb
elif msgformat == "dict":
msg = {"date": datetime.now()}
if error.ex is not None:
msg["msg"] = error.msg
msg["line"] = error.line
msg["code"] = error.code
msg["file"] = error.file
if self.errs_traceback is True or tb is True:
if error.tb is not None:
msg["traceback"] = error.tb
return 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 _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 create a migration without dependencies
"""
if "__init__" in dependency_migration:
dependency_migration = ""
""" Make an empty migration """
call_command('makemigrations', self.app_name, "--empty")
""" Get last migration name and edit it, adding the new code """
last_migration_file = max(glob.iglob(migrations_dir + '*.py'), key=os.path.getctime)
new_lines = self.__create_translation_lines()
translation_type_lines = self.__create_translation_type_lines()
if len(dependency_migration) > 0:
dependency_string = "('%(app_name)s', '%(dependency)s')," % {'app_name': self.app_name,
'dependency': dependency_migration}
else:
dependency_string = ""
try:
if len(new_lines) > 0:
with open(last_migration_file, 'w+') as file:
file.write(self.migration_string % {
'django_version': django.get_version(),
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'translation_strings': "\n".join(new_lines),
'tags_to_remove': ", ".join('"{0}"'.format(tag) for tag in self.updated_translations),
'dependency_string': dependency_string,
'app_name': 'translation_server',
'translation_type_strings': "\n".join(translation_type_lines),
'translation_types_to_remove': ", ".join(
'"{0}"'.format(tag) for tag in self.updated_translation_types),
})
else:
os.remove(last_migration_file)
self.stdout.write(self.style.NOTICE("There was no new translations to make migrations"))
return
except Exception as error:
os.remove(last_migration_file)
raise error
else:
self.__update_translation()
self.stdout.write(self.style.SUCCESS("Translation migration file create successfully"))
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 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 exist """ |
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):
rinocloud.path = directory
return 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 task name is not given, it will attempt to infer it from the function name. Optionally, the decorator can log information into files. """ |
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, *args, **kwargs)
__THREAD_PARAMS[thread][__THREAD_PARAMS_FNAME_KEY] = old_name
return r
return run
if callable(name):
f = name
name = f.__name__
return c_run(name, f, t, args, kwargs)
if name == None:
def wrapped(f):
name = f.__name__
return c_run(name, f, t, args, kwargs)
return wrapped
else:
return lambda f: c_run(name, f, t, 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 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 of progress on the console. The module can receive an increment in the progress through "tick_progress". """ |
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
data = r.json()
for name in self.mapper.mapper:
setattr(cached_item, name, data[name])
return cached_item
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 ICacheObjectCreatedEvent, and ICacheObjectModifiedEvent for ICacheArea/ICachableItem combo. """ |
_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__))
notify(CacheObjectCreatedEvent(_cachedItem, self))
return _cachedItem
else:
_newCacheItem = self.mapper.get(CachableItem)
if _cachedItem != _newCacheItem:
logger.debug("Cachable item modified in Splunk KV cache area {id: %s, type: %s}", str(_newCacheItem.getId()), str(_newCacheItem.__class__))
self._update(_newCacheItem)
notify(CacheObjectModifiedEvent(_newCacheItem, self))
return _newCacheItem
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 it for some time. Parameters m: Model Model to run. iterate_args: Arguments to pass to :meth:`Runner.iterate`. Others: see :class:`Runner`. Returns ------- r: Runner runner object after it has finished running for the required time. """ |
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 from which to resume. output_every: int see :class:`Runner`. t_upto: float Run each model until the time is equal to this parallel: bool Whether or not to run the models in parallel, using the Multiprocessing library. If `True`, the number of concurrent tasks will be equal to one less than the number of available cores detected. """ |
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 variable `field`. For each `val` in `vals`, a new model will be made, and run up to a time. The output directory is automatically generated from the model arguments. Parameters ModelClass: type A class or factory function that returns a model object by calling `ModelClass(model_kwargs)` model_kwarg_sets: list[dict] List of argument sets, each of which can instantiate a model. t_output_every: float see :class:`Runner`. t_upto: float Run each model until the time is equal to this parallel: bool Whether or not to run the models in parallel, using the Multiprocessing library. If `True`, the number of concurrent tasks will be equal to one less than the number of available cores detected. """ |
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 parameter sets. Parameters ModelClass: callable A class or factory function that returns a model object by calling `ModelClass(model_kwargs)` model_kwargs: dict See `ModelClass` explanation. t_output_every: float see :class:`Runner`. t_upto: float Run each model until the time is equal to this field: str The name of the field to be varied, whose values are in `vals`. vals: array_like Iterable of values to use to instantiate each Model object. parallel: bool Whether or not to run the models in parallel, using the Multiprocessing library. If `True`, the number of concurrent tasks will be equal to one less than the number of available cores detected. """ |
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 custom level of logging to pass to the active logger. - Default: INFO - print_time :: bool - Include timestamp in message - print_return :: bool - include the return value in the functions exit message - postfix_only :: bool - omit the functions entering message - prefix_only :: bool - omit the functions exiting message *Exceptions:* - IndexError and ValueError - will be returned if *args contains a string that does not correspond to a parameter name of the decorated function, or if there are more '{}'s than there are *args. """ |
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('print_return', False)
print_time = kwargs.get('print_time', False)
# prepare locals for later uses in string interpolation
fn = f.__name__
timestr = '%s:' % _timestr() if print_time else ''
# get message
try:
message = list(args).pop(0)
timestr = ':' + timestr
except IndexError:
message = fn
fn = ''
# format message
try:
report = '{fn}{timestr}{arg}'.format(**locals(),
arg=message.format(**f_kws))
except KeyError:
report = '{fn}{timestr}{error}'.\
format(**locals(), error='KeyError in decorator usage')
if not post:
LOGGER.log(level, '%s...', report)
try:
ret = f(*xs, **kws)
except Exception as e:
try:
with_message = ' with message %s' % str(e)
if str(e) == '':
raise Exception() # use default value
except:
with_message = ''
LOGGER.log(level, '%s...threw exception %s%s',
report, type(e).__name__, with_message)
raise
if not pre:
if print_return:
LOGGER.log(level, '%s...done (returning %s)', report, ret)
else:
LOGGER.log(level, '%s...done', report)
return ret
return aux |
<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)
return (None, None)
if result:
#routes = result.as_dict()
#(routes, col_names) = rowify(result, c.description)
#current_app.logger.debug( [x['rule'] for x in routes] )
rules = map( lambda r: Rule(r['rule'], endpoint='dynamic'), result )
d_map = Map( rules )
map_adapter = d_map.bind(url_root)
#current_app.logger.debug(uri)
try:
(rule, rule_kw) = map_adapter.match(path_info=uri, return_rule=True)
#current_app.logger.debug(rule)
return (str(rule), rule_kw)
except HTTPException:
pass
return (None, {}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 rendered HTML within another page. Activate it with the 'shortcodes' template filter. Within the content use the chill route shortcode: "[chill route /path/to/something/]" where the '[chill' and ']' are the shortcode starting and ending tags. And 'route' is this route handler that takes one argument which is the url. """ |
(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
noderequest = values.copy()
noderequest.pop('node_id')
noderequest.pop('name')
noderequest.pop('value')
rendered = render_node(node['id'], noderequest=noderequest, **values)
if rendered:
if not isinstance(rendered, (str, unicode, int, float)):
# return a json string
return encoder.encode(rendered)
return rendered
# Nothing to show, so nothing found
return "<!-- 404 '{0}' -->".format(pargs[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 page_uri_handler(context, content, pargs, kwargs):
""" Shortcode for getting the link to internal pages using the flask `url_for` method. Activate with 'shortcodes' template filter. Within the content use the chill page_uri shortcode: "[chill page_uri idofapage]". The argument is the 'uri' for a page that chill uses. Does not verify the link to see if it's valid. """ |
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_data )
values.update( request.form.to_dict(flat=True) )
values.update( request.args.to_dict(flat=True) )
values.update( request.cookies )
values['method'] = request.method
noderequest = values.copy()
noderequest.pop('node_id')
noderequest.pop('name')
noderequest.pop('value')
current_app.logger.debug("get kw: %s", values)
rendered = render_node(node['id'], noderequest=noderequest, **values)
current_app.logger.debug("rendered: %s", rendered)
if rendered:
if not isinstance(rendered, (str, unicode, int, float)):
# return a json string
return encoder.encode(rendered)
return rendered
# Nothing to show, so nothing found
abort(404) |
<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_data )
values.update( request.form.to_dict(flat=True) )
values.update( request.args.to_dict(flat=True) )
values['method'] = request.method
# Execute the sql query with the data
_query(node['id'], **values)
response = make_response('ok', 201)
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def 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()
else:
return config
else:
raise ImproperlyConfigured(
'Can not get config for {} either in environment'
'variable or in settings.py'.format(name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 per user, for example to allow a fair spread of tweets per user for a list. """ |
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:
_tweets[tweet.user_name].append(tweet)
tweets = sum(_tweets.values(), [])
tweets.sort(key=lambda t: t.created_at, reverse=True)
if len(args) > 1 and str(args[-1]).isdigit():
tweets = tweets[:int(args[-1])]
return tweets |
<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 object. :raises ValueError: If arg is None. """ |
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 specified. :return: The corresponding log level. """ |
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 should not be used if you expect that your input has been pasted, because the characters in the buffer would be read before the answer about the cursor.""" |
# "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.