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 load(self, value):
""" enforce env > value when loading from file """ |
self.reset(
value,
validator=self.__dict__.get('validator'),
env=self.__dict__.get('env'),
) |
<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_img_path(instance, filename):
""" Sets upload_to dynamically """ |
upload_path = '/'.join(
['img', instance._meta.app_label, str(now.year), str(now.month), filename]
)
return upload_path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, *args, **kwargs):
""" Clean text and save formatted version. """ |
self.text = clean_text(self.text)
self.text_formatted = format_text(self.text)
super(BaseUserContentModel, self).save(*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 enqueue(self, job):
"""Enqueue a job for later processing, returns the new length of the queue """ |
if job.queue_name():
raise EnqueueError("job %s already queued!" % job.job_id)
new_len = self.redis.lpush(self.queue_name, job.serialize())
job.notify_queued(self)
return new_len |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next_job(self, timeout_seconds=None):
"""Retuns the next job in the queue, or None if is nothing there """ |
if timeout_seconds is not None:
timeout = timeout_seconds
else:
timeout = BLOCK_SECONDS
response = self.lua_next(keys=[self.queue_name])
if not response:
return
job = Job.from_serialized(response)
if not job:
self.log.warn("could not deserialize job from: %s", serializ... |
<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_headline_from_description(sender, instance, *args, **kwargs):
'''
Auto generate the headline of the node from the first lines of the description.
'''
lines = instance.description.split('\n')
headline = truncatewords(lines[0], 20)
if headline[:-3] == '...':
headline = truncat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def story_root_for_new_outline(sender, instance, created, *args, **kwargs):
'''
If a new instance of a Outline is created, also create
the root node of the story tree.
'''
if created and isinstance(instance, Outline):
streeroot = StoryElementNode.add_root(outline=instance, story_element_type... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def story_node_add_arc_element_update_characters_locations(sender, instance, created, *args, **kwargs):
'''
If an arc element is added to a story element node, add any missing elements or locations.
'''
arc_node = ArcElementNode.objects.get(pk=instance.pk)
logger.debug('Scanning arc_node %s' % arc_n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def validate_arc_links_same_outline(sender, instance, *args, **kwargs):
'''
Evaluates attempts to link an arc to a story node from another outline.
'''
if instance.story_element_node:
if instance.story_element_node.outline != instance.parent_outline:
raise IntegrityError(_('An arc ca... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def validate_character_instance_valid_for_arc(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Evaluate attempts to assign a character instance to ensure it is from same
outline.
'''
if action == 'pre_add':
if reverse:
# Fetch arc definition through link.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def validate_location_instance_valid_for_arc(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Evaluates attempts to add location instances to arc, ensuring they are from same outline.
'''
if action == 'pre_add':
if reverse:
# Fetch arc definition through link.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def validate_character_for_story_element(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Validates that character is from the same outline as the story node.
'''
if action == 'pre_add':
if reverse:
for spk in pk_set:
story_node = StoryElementNode.obje... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def validate_location_for_story_element(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Validates that location is from same outline as story node.
'''
if action == 'pre_add':
if reverse:
for spk in pk_set:
story_node = StoryElementNode.objects.get(pk... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def options(self, request, *args, **kwargs):
""" Handles responding to requests for the OPTIONS HTTP verb """ |
response = HttpResponse()
response['Allow'] = ', '.join(self.allowed_methods)
response['Content-Length'] = 0
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 is_python2_identifier(possible_identifier):
""" Returns `True` if the given `possible_identifier` can be used as an identifier in Python 2. """ |
match = _python2_identifier_re.match(possible_identifier)
return bool(match) and not iskeyword(possible_identifier) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_python3_identifier(possible_identifier):
""" Returns `True` if the given `possible_identifier` can be used as an identifier in Python 3. """ |
possible_identifier = unicodedata.normalize('NFKC', possible_identifier)
return (
bool(possible_identifier) and
_is_in_id_start(possible_identifier[0]) and
all(map(_is_in_id_continue, possible_identifier[1:]))
) and not iskeyword(possible_identifier) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unique(iterable):
""" Returns an iterator that yields the first occurence of a hashable item in `iterable`. """ |
seen = set()
for obj in iterable:
if obj not in seen:
yield obj
seen.add(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 contains(self, x, y) -> bool: """" Checks if the given x, y position is within the area of this region. """ |
if x < self._left or x > self._right or y < self._top or y > self._bottom:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_in_bounds(self, width, height) -> bool: """ Check if this entire region is contained within the bounds of a given stage size.""" |
if self._top < 0 \
or self._bottom > height \
or self._left < 0 \
or self._right > width:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def canvas_resize(self, scale):
""" Resize this region against the entire axis space. """ |
self._top *= scale
self._bottom *= scale
self._left *= scale
self._right *= scale
self._calibrate_to_rect() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def distance(r1: 'Region', r2: 'Region'):
""" Calculate distance between the x and y of the two regions.""" |
return math.sqrt((r2.x - r1.x) ** 2 + (r2.y - r1.y) ** 2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fast_distance(r1: 'Region', r2: 'Region'):
""" A quicker way of calculating approximate distance. Lower accuracy but faster results.""" |
return abs(r1.x - r2.x) + abs(r1.y - r2.y) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rms(x):
""""Root Mean Square" Arguments: x (seq of float):
A sequence of numerical values Returns: The square root of the average of the squares of the valu... |
try:
return (np.array(x) ** 2).mean() ** 0.5
except:
x = np.array(dropna(x))
invN = 1.0 / len(x)
return (sum(invN * (x_i ** 2) for x_i in x)) ** .5 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rmse(target, prediction, relative=False, percent=False):
"""Root Mean Square Error This seems like a simple formula that you'd never need to create a functio... |
relative = relative or percent
prediction = pd.np.array(prediction)
target = np.array(target)
err = prediction - target
if relative:
denom = target
# Avoid ZeroDivisionError: divide by prediction rather than target where target==0
denom[denom == 0] = prediction[denom == 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 pandas_mesh(df):
"""Create numpy 2-D "meshgrid" from 3+ columns in a Pandas DataFrame Arguments: df (DataFrame):
Must have 3 or 4 columns of numerical data ... |
xyz = [df[c].values for c in df.columns]
index = pd.MultiIndex.from_tuples(zip(xyz[0], xyz[1]), names=['x', 'y'])
# print(index)
series = [pd.Series(values, index=index) for values in xyz[2:]]
# print(series)
X, Y = np.meshgrid(sorted(list(set(xyz[0]))), sorted(list(set(xyz[1]))))
N, M = X.... |
<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_integrator(integrator):
"""Return the scipy.integrator indicated by an index, name, or integrator_function >> get_integrator(0) """ |
integrator_types = set(['trapz', 'cumtrapz', 'simps', 'romb'])
integrator_funcs = [integrate.trapz, integrate.cumtrapz, integrate.simps, integrate.romb]
if isinstance(integrator, int) and 0 <= integrator < len(integrator_types):
integrator = integrator_types[integrator]
if isinstance(integrato... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def square_off(series, time_delta=None, transition_seconds=1):
"""Insert samples in regularly sampled data to produce stairsteps from ramps when plotted. New sam... |
if time_delta:
# int, float means delta is in seconds (not years!)
if isinstance(time_delta, (int, float)):
time_delta = datetime.timedelta(0, time_delta)
new_times = series.index + time_delta
else:
diff = np.diff(series.index)
time_delta = np.append(diff, [d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join_time_series(serieses, ignore_year=False, T_s=None, aggregator='mean'):
"""Combine a dict of pd.Series objects into a single pd.DataFrame with optional d... |
if ignore_year:
df = pd.DataFrame()
for name, ts in serieses.iteritems():
# FIXME: deal with leap years
sod = np.array(map(lambda x: (x.hour * 3600 + x.minute * 60 + x.second),
ts.index.time))
# Coerce soy to an integer so that merge/jo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def smooth(x, window_len=11, window='hanning', fill='reflect'):
"""smooth the data using a window with requested size. Convolve a normalized window with the sign... |
# force window_len to be an odd integer so it can be symmetrically applied
window_len = int(window_len)
window_len += int(not (window_len % 2))
half_len = (window_len - 1) / 2
if x.ndim != 1:
raise ValueError("smooth only accepts 1 dimension arrays.")
if x.size < window_len:
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 fuzzy_index_match(possiblities, label, **kwargs):
"""Find the closest matching column label, key, or integer indexed value Returns: type(label):
sequence of... |
possibilities = list(possiblities)
if isinstance(label, basestring):
return fuzzy_get(possibilities, label, **kwargs)
if isinstance(label, int):
return possibilities[label]
if isinstance(label, list):
return [fuzzy_get(possibilities, lbl) for lbl in label] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_dataframe(obj, columns=None, exclude=None, limit=1e8):
"""Coerce an iterable, queryset, list or rows, dict of columns, etc into a Pandas DataFrame""" |
try:
obj = obj.objects.all()[:limit]
except:
pass
if isinstance(obj, (pd.Series, list, tuple)):
return make_dataframe(pd.DataFrame(obj), columns, exclude, limit)
# if the obj is a named tuple, DataFrame, dict of columns, django QuerySet, sql alchemy query result
# retrieve t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter(self, destination_object=None, source_object=None, **kwargs):
""" See ``QuerySet.filter`` for full documentation This adds support for ``destination_o... |
if destination_object:
kwargs.update({
"destination_id": destination_object.pk,
"destination_type": get_for_model(destination_object),
})
if source_object:
kwargs.update({
"source_id": source_object.pk,
... |
<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_module_names_for_sphinx(modules: List, new_name: str):
""" Trick sphinx into displaying the desired module in these objects' documentation. """ |
for obj in modules:
obj.__module__ = new_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 run_skeleton(skeleton_path, tasks, watch=True):
"""loads and executes tasks from a given skeleton file skeleton_path: path to the skeleton file tasks: a list... |
build_context = load_context_from_skeleton(skeleton_path);
# for t in build_context.tasks:
# print t, str(build_context.tasks[t])
for task in tasks:
build_context.build_task(task)
# print json.dumps(
# dict((name,
# str(task.value)[0:100] + "..."
# ... |
<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_fresh_content(top=4, additional=10, featured=False):
""" Requires articles, photos and video packages to be installed. Returns published *Featured* conte... |
from articles.models import Article
from photos.models import Gallery
from video.models import Video
articles = Article.published.only('title', 'summary', 'slug', 'created')
galleries = Gallery.published.only('title', 'summary', 'slug', 'created')
videos = Video.published.only('title', 'summar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def markdown(value, arg=''):
""" Runs Markdown over a given value, optionally using various extensions python-markdown supports. Derived from django.contrib.mark... |
import warnings
warnings.warn('The markdown filter has been deprecated',
category=DeprecationWarning)
try:
import markdown
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError(
"Error in 'markdown' filter: The Python mar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_path(self):
""" The path to the file where passwords are stored. This property may be overridden by the subclass or at the instance level. """ |
return os.path.join(keyring.util.platform.data_root(), 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 account(self, account=None):
''' Fetches account information and stores the
result in a class variable. Returns that variable
if the account has not changed.
'''
for num_of_retries in range(default.max_retry):
if account is None:
account = self.mai... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def steem_instance(self):
''' Returns the steem instance if it already exists
otherwise uses the goodnode method to fetch a node
and instantiate the Steem class.
'''
if self.s:
return self.s
for num_of_retries in range(default.max_retry):
node = se... |
<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_key (self, acctname=None, tokenkey=None):
''' This can be used to verify either a private
posting key or to verify a steemconnect refresh
token and retreive the access token.
'''
if (re.match( r'^[A-Za-z0-9]+$', tokenkey)
and tokenkey is not Non... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reward_pool_balances(self):
''' Fetches and returns the 3 values
needed to calculate the reward pool
and other associated values such as rshares.
Returns the reward balance, all recent claims
and the current price of steem.
'''
if self.reward_balance > 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 rshares_to_steem (self, rshares):
''' Gets the reward pool balances
then calculates rshares to steem
'''
self.reward_pool_balances()
return round(
rshares
* self.reward_balance
/ self.recent_claims
* self.base, 4) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def global_props(self):
''' Retrieves the global properties
used to determine rates used for calculations
in converting steempower to vests etc.
Stores these in the Utilities class as that
is where the conversions take place, however
SimpleSteem is the class that contains... |
<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_vote_value(self, **kwargs):
''' Ensures the needed variables are
created and set to defaults although
a variable number of variables are given.
'''
try:
kwargs.items()
except:
pass
else:
for key, value in kwargs.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 check_balances(self, account=None):
''' Fetches an account balance and makes
necessary conversions
'''
a = self.account(account)
if a is not False and a is not None:
self.sbdbal = Amount(a['sbd_balance']).amount
self.steembal = Amount(a['balance']).amo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def transfer_funds(self, to, amount, denom, msg):
''' Transfer SBD or STEEM to the given account
'''
try:
self.steem_instance().commit.transfer(to,
float(amount), denom, msg, self.mainaccount)
except Exception as e:
self.msg.error_message(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 get_my_history(self, account=None, limit=10000):
''' Fetches the account history from
most recent back
'''
if not account:
account = self.mainaccount
try:
h = self.steem_instance().get_account_history(
account, -1, limit)
except... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reply(self, permlink, msgbody):
''' Used for creating a reply to a
post. Waits 20 seconds
after posting as that is the required
amount of time between posting.
'''
for num_of_retries in range(default.max_retry):
try:
self.steem_instance(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def follow(self, author):
''' Follows the given account
'''
try:
self.steem_instance().commit.follow(author,
['blog'], self.mainaccount)
except Exception as e:
self.msg.error_message(e)
return False
else:
return Tru... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def following(self, account=None, limit=100):
''' Gets a list of all the followers
of a given account. If no account is given
the followers of the mainaccount are
returned.
'''
if not account:
account = self.mainaccount
followingnames = []
try:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def vote_history(self, permlink, author=None):
''' Returns the raw vote history of a
given post from a given account
'''
if author is None:
author = self.mainaccount
return self.steem_instance().get_active_votes(author, permlink) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dex_ticker(self):
''' Simply grabs the ticker using the
steem_instance method and adds it
to a class variable.
'''
self.dex = Dex(self.steem_instance())
self.ticker = self.dex.get_ticker();
return self.ticker |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def steem_to_sbd(self, steemamt=0, price=0, account=None):
''' Uses the ticker to get the highest bid
and moves the steem at that price.
'''
if not account:
account = self.mainaccount
if self.check_balances(account):
if steemamt == 0:
steem... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sbd_to_steem(self, sbd=0, price=0, account=None):
''' Uses the ticker to get the lowest ask
and moves the sbd at that price.
'''
if not account:
account = self.mainaccount
if self.check_balances(account):
if sbd == 0:
sbd = self.sbdbal
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def vote_witness(self, witness, account=None):
''' Uses the steem_instance method to
vote on a witness.
'''
if not account:
account = self.mainaccount
try:
self.steem_instance().approve_witness(witness, account=account)
except Exception as 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 unvote_witness(self, witness, account=None):
''' Uses the steem_instance method to
unvote a witness.
'''
if not account:
account = self.mainaccount
try:
self.steem_instance().disapprove_witness(witness, account=account)
except Exception as 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 voted_me_witness(self, account=None, limit=100):
''' Fetches all those a given account is
following and sees if they have voted that
account as witness.
'''
if not account:
account = self.mainaccount
self.has_voted = []
self.has_not_voted = []
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def muted_me(self, account=None, limit=100):
''' Fetches all those a given account is
following and sees if they have muted that
account.
'''
self.has_muted = []
if account is None:
account = self.mainaccount
following = self.following(account, limit)
... |
<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(self, to, steempower):
''' Delegates based on Steem Power rather
than by vests.
'''
self.global_props()
vests = self.util.sp_to_vests(steempower)
strvests = str(vests)
strvests = strvests + " VESTS"
try:
self.steem_instance().commi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def start_logging(gconfig, logpath):
'''Turn on logging and set up the global config.
This expects the :mod:`yakonfig` global configuration to be unset,
and establishes it. It starts the log system via the :mod:`dblogger`
setup. In addition to :mod:`dblogger`'s defaults, if `logpath` is
provided,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def start_worker(which_worker, config={}):
'''Start some worker class.
:param str which_worker: name of the worker
:param dict config: ``rejester`` config block
'''
if which_worker == 'multi_worker':
cls = MultiWorker
elif which_worker == 'fork_worker':
cls = ForkWorker
els... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def go(gconfig, args):
'''Actually run the worker.
This does some required housekeeping, like setting up logging for
:class:`~rejester.workers.MultiWorker` and establishing the global
:mod:`yakonfig` configuration. This expects to be called with the
:mod:`yakonfig` configuration unset.
:param... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def fork_worker(gconfig, args):
'''Run the worker as a daemon process.
This uses :mod:`daemon` to run the standard double-fork, so it can
return immediately and successfully in the parent process having forked.
:param dict gconfig: the :mod:`yakonfig` global configuration
:param args: command-line... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transient_change_detect(self, *class_build_args, **class_build_kwargs):
""" This should be called when we want to detect a change in the status of the system... |
transient_detected = set(self.get_transients_available())
#TODO : unify that last_got_set with the *_available. they are essentially the same
tst_gone = self.last_transients_detected - transient_detected
# print("INTERFACING + {transient_detected}".format(**locals()))
# print(... |
<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_function_doc(function, config=default_config):
"""Return doc for a function.""" |
if config.exclude_function:
for ex in config.exclude_function:
if ex.match(function.__name__):
return None
return _doc_object(function, 'function', config=config) |
<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_class_doc(klass, config=default_config):
"""Return doc for a class.""" |
if config.exclude_class:
for ex in config.exclude_class:
if ex.match(klass.__name__):
return None
nested_doc = []
class_dict = klass.__dict__
for item in dir(klass):
if item in class_dict.keys():
appended = None
if isinstance(class_d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_module_doc(module, config=default_config, already_met=None):
"""Return doc for a module.""" |
# Avoid recursion loops (init)
if already_met is None:
already_met = set()
if config.exclude_module:
for ex in config.exclude_module:
if ex.match(module.__name__):
return None
# Force load submodules into module's dict
if hasattr(module, '__path__'):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match(self, name):
""" Check if given name matches. Args: name (str):
name to check. Returns: bool: matches name. """ |
if self.method == Ex.Method.PREFIX:
return name.startswith(self.value)
elif self.method == Ex.Method.SUFFIX:
return name.endswith(self.value)
elif self.method == Ex.Method.CONTAINS:
return self.value in name
elif self.method == Ex.Method.EXACT:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autocommand(func):
""" A simplified decorator for making a single function a Command instance. In the future this will leverage PEP0484 to do really smart fu... |
name = func.__name__
title, desc = command.parse_docstring(func)
if not title:
title = 'Auto command for: %s' % name
if not desc:
# Prevent Command from using docstring of AutoCommand
desc = ' '
return AutoCommand(title=title, desc=desc, name=name, func=func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self, args):
""" Convert the unordered args into function arguments. """ |
args = vars(args)
positionals = []
keywords = {}
for action in self.argparser._actions:
if not hasattr(action, 'label'):
continue
if action.label == 'positional':
positionals.append(args[action.dest])
elif action.label ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _save_to(self, im, path, format=None):
"""Save the image for testing. """ |
format = format or im.format
if not format:
_, format = splitext(path)
format = format[1:]
im.format = format.lower()
im.save(filename=path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions """ |
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message) |
<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, message, *args, **kwargs):
"""Debug level to use and abuse when coding """ |
self._log(logging.DEBUG, message, *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 warn(self, message, *args, **kwargs):
""" |
self._log(logging.WARNING, message, *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 warning(self, message, *args, **kwargs):
"""Alias to warn """ |
self._log(logging.WARNING, message, *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 error(self, message, *args, **kwargs):
""" |
self._log(logging.ERROR, message, *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 init_logger(self):
"""Create configuration for the root logger.""" |
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._creat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration """ |
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset_formatter(self):
"""Rebuild formatter for all handlers.""" |
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter) |
<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_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers.""" |
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level) |
<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_min_level_to_print(self, level):
"""Allow to change print level after creation """ |
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level) |
<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_min_level_to_save(self, level):
"""Allow to change save level after creation """ |
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level) |
<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_min_level_to_mail(self, level):
"""Allow to change mail level after creation """ |
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level) |
<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_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation """ |
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level) |
<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_handler(self, handler_class):
"""Return an existing class of handler.""" |
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger.""" |
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_handler(self, handler_class, level):
"""Update the level of an handler.""" |
handler = self._get_handler(handler_class)
handler.setLevel(level) |
<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_handler(self, handler_class, level):
"""Create an handler for at specific level.""" |
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.ha... |
<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_formatter(self, handler):
""" Return formatters according to handler. All handlers are the same format, except syslog. We omit time when syslogging. """ |
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def version_control():
"""Return an object that provides the version control interface based on the detected version control system.""" |
curdir_contents = os.listdir('.')
if '.hg' in curdir_contents:
return hg.Hg()
elif '.git' in curdir_contents:
return git.Git()
else:
logger.critical('No version control system detected.')
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 package_in_pypi(package):
"""Check whether the package is registered on pypi""" |
url = 'http://pypi.python.org/simple/%s' % package
try:
urllib.request.urlopen(url)
return True
except urllib.error.HTTPError as e:
logger.debug("Package not found on pypi: %s", e)
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 _grab_version(self):
"""Set the version to a non-development version.""" |
original_version = self.vcs.version
logger.debug("Extracted version: %s", original_version)
if original_version is None:
logger.critical('No version found.')
sys.exit(1)
suggestion = utils.cleanup_version(original_version)
new_version = utils.ask_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 _write_history(self):
"""Write previously-calculated history lines back to the file""" |
if self.data['history_file'] is None:
return
contents = '\n'.join(self.data['history_lines'])
history = self.data['history_file']
open(history, 'w').write(contents)
logger.info("History file %s updated.", history) |
<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_if_tag_already_exists(self):
"""Check if tag already exists and show the difference if so""" |
version = self.data['new_version']
if self.vcs.tag_exists(version):
return True
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 _release(self):
"""Upload the release, when desired""" |
pypiconfig = pypi.PypiConfig()
# Does the user normally want a real release? We are
# interested in getting a sane default answer here, so you can
# override it in the exceptional case but just hit Enter in
# the usual case.
main_files = os.listdir(self.data['workingd... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_version(self):
"""Ask for and store a new dev version string.""" |
#current = self.vcs.version
current = self.data['new_version']
# Clean it up to a non-development version.
current = utils.cleanup_version(current)
# Try to make sure that the suggestion for next version after
# 1.1.19 is not 1.1.110, but 1.1.20.
current_split =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_history(self):
"""Update the history file""" |
version = self.data['new_version']
history = self.vcs.history_file()
if not history:
logger.warn("No history file found")
return
history_lines = open(history).read().split('\n')
headings = utils.extract_headings_from_history(history_lines)
if not ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _push(self):
"""Offer to push changes, if needed.""" |
push_cmds = self.vcs.push_commands()
if not push_cmds:
return
if utils.ask("OK to push commits to the server?"):
for push_cmd in push_cmds:
output = utils.system(push_cmd)
logger.info(output) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user(user, driver):
# noqa: E501 """Retrieve a user Retrieve a user # noqa: E501 :param user: Get user with this name :type user: str :param driver: The ... |
response = ApitaxResponse()
driver: Driver = LoadedDrivers.getDriver(driver)
user: User = driver.getApitaxUser(User(username=user))
response.body.add({'user': {'username': user.username, 'role': user.role}})
return Response(status=200, body=response.getResponseBody()) |
<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(path_dir, requirements_name):
"""Console script for imports.""" |
click.echo("\nWARNING: Uninstall libs it's at your own risk!")
click.echo('\nREMINDER: After uninstall libs, update your requirements '
'file.\nUse the `pip freeze > requirements.txt` command.')
click.echo('\n\nList of installed libs and your dependencies added on '
'project\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.