text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user_shakes(self):
""" Get a list of Shake objects for the currently authenticated user. Returns: A list of Shake objects. """ |
endpoint = '/api/shakes'
data = self._make_request(verb="GET", endpoint=endpoint)
shakes = [Shake.NewFromJSON(shk) for shk in data['shakes']]
return shakes |
<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_shared_files_from_shake(self, shake_id=None, before=None, after=None):
""" Returns a list of SharedFile objects from a particular shake. Args: shake_id (... |
if before and after:
raise Exception("You cannot specify both before and after keys")
endpoint = '/api/shakes'
if shake_id:
endpoint += '/{0}'.format(shake_id)
if before:
endpoint += '/before/{0}'.format(before)
elif after:
endp... |
<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_shared_file(self, sharekey=None):
""" Returns a SharedFile object given by the sharekey. Args: sharekey (str):
Sharekey of the SharedFile you want to re... |
if not sharekey:
raise Exception("You must specify a sharekey.")
endpoint = '/api/sharedfile/{0}'.format(sharekey)
data = self._make_request('GET', endpoint)
return SharedFile.NewFromJSON(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def like_shared_file(self, sharekey=None):
""" 'Like' a SharedFile. mlkshk doesn't allow you to unlike a sharedfile, so this is ~~permanent~~. Args: sharekey (st... |
if not sharekey:
raise Exception(
"You must specify a sharekey of the file you"
"want to 'like'.")
endpoint = '/api/sharedfile/{sharekey}/like'.format(sharekey=sharekey)
data = self._make_request("POST", endpoint=endpoint, data=None)
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 save_shared_file(self, sharekey=None):
""" Save a SharedFile to your Shake. Args: sharekey (str):
Sharekey for the file to save. Returns: SharedFile saved t... |
endpoint = '/api/sharedfile/{sharekey}/save'.format(sharekey=sharekey)
data = self._make_request("POST", endpoint=endpoint, data=None)
try:
sf = SharedFile.NewFromJSON(data)
sf.saved = True
return sf
except:
raise Exception("{0}".format(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_friends_shake(self, before=None, after=None):
""" Contrary to the endpoint naming, this resource is for a list of SharedFiles from your friends on mlkshk... |
if before and after:
raise Exception("You cannot specify both before and after keys")
endpoint = '/api/friends'
if before:
endpoint += '/before/{0}'.format(before)
elif after:
endpoint += '/after/{0}'.format(after)
data = self._make_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_comments(self, sharekey=None):
""" Retrieve comments on a SharedFile Args: sharekey (str):
Sharekey for the file from which you want to return the set o... |
if not sharekey:
raise Exception(
"You must specify a sharekey of the file you"
"want to 'like'.")
endpoint = '/api/sharedfile/{0}/comments'.format(sharekey)
data = self._make_request("GET", endpoint=endpoint)
return [Comment.NewFromJSON(c)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_comment(self, sharekey=None, comment=None):
""" Post a comment on behalf of the current user to the SharedFile with the given sharekey. Args: sharekey (... |
endpoint = '/api/sharedfile/{0}/comments'.format(sharekey)
post_data = {'body': comment}
data = self._make_request("POST", endpoint=endpoint, data=post_data)
return Comment.NewFromJSON(data) |
<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_shared_file(self, image_file=None, source_link=None, shake_id=None, title=None, description=None):
""" Upload an image. TODO: Don't have a pro account t... |
if image_file and source_link:
raise Exception('You can only specify an image file or '
'a source link, not both.')
if not image_file and not source_link:
raise Exception('You must specify an image file or a source link')
content_type = self.... |
<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_edge(self, u, v, **attr):
"""
Add an edge between vertices u and v and update edge attributes
""" |
if u not in self.vertices:
self.vertices[u] = []
if v not in self.vertices:
self.vertices[v] = []
vertex = (u, v)
self.edges[vertex] = {}
if attr:
self.edges[vertex].update(attr)
self.vertices[u].append(v)
self.vertic... |
<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_edge(self, u, v):
"""
Remove the edge between vertices u and v
""" |
try:
self.edges.pop((u, v))
except KeyError:
raise GraphInsertError("Edge %s-%s doesn't exist." % (u, v))
self.vertices[u].remove(v)
self.vertices[v].remove(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 degree(self, vertex):
"""
Return the degree of a vertex
""" |
try:
return len(self.vertices[vertex])
except KeyError:
raise GraphInsertError("Vertex %s doesn't exist." % (vertex,)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli_certify_core_integer( config, min_value, max_value, value, ):
"""Console script for certify_int""" |
def parser(v):
# Attempt a json/pickle decode:
try:
v = load_json_pickle(v, config)
except Exception:
pass
# Attempt a straight conversion to integer:
try:
return int(v)
except Exception as err:
six.raise_from(
... |
<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_dupkey(self, k):
""" Really odd function - used to help ensure we actually warn for duplicate keys. """ |
if self._privflags & PYCBC_CONN_F_WARNEXPLICIT:
warnings.warn_explicit(
'Found duplicate keys! {0}'.format(k), RuntimeWarning,
__file__, -1, module='couchbase_ffi.bucket', registry={})
else:
warnings.warn('Found duplicate keys!', RuntimeWarning) |
<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_text(self, xml, name):
""" Gets the element's text value from the XML object provided. """ |
nodes = xml.getElementsByTagName("wp:comment_" + name)[0].childNodes
accepted_types = [Node.CDATA_SECTION_NODE, Node.TEXT_NODE]
return "".join([n.data for n in nodes if n.nodeType in accepted_types]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_import(self, options):
""" Gets the posts from either the provided URL or the path if it is local. """ |
url = options.get("url")
if url is None:
raise CommandError("Usage is import_wordpress %s" % self.args)
try:
import feedparser
except ImportError:
raise CommandError("Could not import the feedparser library.")
feed = feedparser.parse(url)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wp_caption(self, post):
""" Filters a Wordpress Post for Image Captions and renders to match HTML. """ |
for match in re.finditer(r"\[caption (.*?)\](.*?)\[/caption\]", post):
meta = '<div '
caption = ''
for imatch in re.finditer(r'(\w+)="(.*?)"', match.group(1)):
if imatch.group(1) == 'id':
meta += 'id="%s" ' % imatch.group(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 read_emote_mappings(json_obj_files=[]):
""" Reads the contents of a list of files of json objects and combines them into one large json object. """ |
super_json = {}
for fname in json_obj_files:
with open(fname) as f:
super_json.update(json.loads(f.read().decode('utf-8')))
return super_json |
<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_tls_property(default=None):
"""Creates a class-wide instance property with a thread-specific value.""" |
class TLSProperty(object):
def __init__(self):
from threading import local
self.local = local()
def __get__(self, instance, cls):
if not instance:
return self
return self.value
def __set__(self, instance, 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 lookup(self):
""" The meat of this middleware. Returns None and sets settings.SITE_ID if able to find a Site object by domain and its subdomain is valid. Ret... |
# check to see if this hostname is actually a env hostname
if self.domain:
if self.subdomain:
self.domain_unsplit = '%s.%s' % (self.subdomain, self.domain)
else:
self.domain_unsplit = self.domain
self.domain_requested = self.domain_un... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def theme_lookup(self):
""" Returns theme based on site Returns None and sets settings.THEME if able to find a theme object by site. Otherwise, returns False. ""... |
# check cache
cache_key = 'theme:%s' % self.domain_unsplit
theme = cache.get(cache_key)
if theme:
THEME.value = theme
return None
# check database
if hasattr(self.site, 'themes'):
try:
themes = [theme.name for theme i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def age(self, as_at_date=None):
""" Compute the person's age """ |
if self.date_of_death != None or self.is_deceased == True:
return None
as_at_date = date.today() if as_at_date == None else as_at_date
if self.date_of_birth != None:
if (as_at_date.month >= self.date_of_birth.month) and (as_at_date.day >= self.date_of_birth.day... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def name(self):
""" Return the person's name. If we have special titles, use them, otherwise, don't include the title. """ |
if self.title in ["DR", "SIR", "LORD"]:
return "%s %s %s" % (self.get_title_display(), self.first_name, self.last_name)
else:
return "%s %s" % (self.first_name, self.last_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 full_name(self):
""" Return the title and full name """ |
return "%s %s %s %s" % (self.get_title_display(),
self.first_name,
self.other_names.replace(",", ""),
self.last_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 save(self, *args, **kwargs):
""" If date of death is specified, set is_deceased to true """ |
if self.date_of_death != None:
self.is_deceased = True
# Since we often copy and paste names from strange sources, do some basic cleanup
self.first_name = self.first_name.strip()
self.last_name = self.last_name.strip()
self.other_names = self.other_names... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def storedata(filename=None):
"""Store the state of the current credolib workspace in a pickle file.""" |
if filename is None:
filename = 'credolib_state.pickle'
ns = get_ipython().user_ns
with open(filename, 'wb') as f:
d = {}
for var in ['_headers', '_loaders', '_data1d', '_data2d', '_data1dunited',
'allsamplenames', '_headers_sample', 'badfsns', '_rowavg',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restoredata(filename=None):
"""Restore the state of the credolib workspace from a pickle file.""" |
if filename is None:
filename = 'credolib_state.pickle'
ns = get_ipython().user_ns
with open(filename, 'rb') as f:
d = pickle.load(f)
for k in d.keys():
ns[k] = d[k] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autocorrect(query, possibilities, delta=0.75):
"""Attempts to figure out what possibility the query is This autocorrect function is rather simple right now w... |
# TODO: Make this way more robust and awesome using probability, n-grams?
possibilities = [possibility.lower() for possibility in possibilities]
# Don't waste time for exact matches
if query in possibilities:
return query
# Complete query as much as possible
options = [word for word... |
<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(self, overwrite):
"""Generate service files. This exposes several comforts. `self.files` is a list into which all generated file paths will be appen... |
self.files = []
tmp = utils.get_tmp_dir(self.init_system, self.name)
self.templates = os.path.join(os.path.dirname(__file__), 'templates')
self.template_prefix = self.init_system
self.generate_into_prefix = os.path.join(tmp, self.name)
self.overwrite = overwrite |
<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, **kwargs):
"""Retrieve the status of a service `name` or all services for the current init system. """ |
self.services = dict(
init_system=self.init_system,
services=[]
) |
<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_file_from_template(self, template, destination):
"""Generate a file from a Jinja2 `template` and writes it to `destination` using `params`. `overwri... |
# We cast the object to a string before passing it on as py3.x
# will fail on Jinja2 if there are ints/bytes (not strings) in the
# template which will not allow `env.from_string(template)` to
# take place.
templates = str(pkgutil.get_data(__name__, os.path.join(
'te... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_value_to_es(value, ranges, obj, method=None):
""" Takes an value and converts it to an elasticsearch representation args: value: the value to convert... |
def sub_convert(val):
"""
Returns the json value for a simple datatype or the subject uri if the
value is a rdfclass
args:
val: the value to convert
"""
if isinstance(val, BaseRdfDataType):
return val.to_json
elif isinstance(value, _... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_idx_types(rng_def, ranges):
""" Returns the elasticsearch index types for the obj args: rng_def: the range defintion dictionay ranges: rdfproperty ranges... |
idx_types = rng_def.get('kds_esIndexType', []).copy()
if not idx_types:
nested = False
for rng in ranges:
if range_is_obj(rng, __MODULE__.rdfclass):
nested = True
if nested:
idx_types.append('es_Nested')
return idx_types |
<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_prop_range_defs(class_names, def_list):
""" Filters the range defitions based on the bound class args: obj: the rdffroperty instance """ |
try:
cls_options = set(class_names + ['kdr_AllClasses'])
return [rng_def for rng_def in def_list \
if not isinstance(rng_def, BlankNode) \
and cls_options.difference(\
set(rng_def.get('kds_appliesToClass', []))) < \
cl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def range_is_obj(rng, rdfclass):
""" Test to see if range for the class should be an object or a litteral """ |
if rng == 'rdfs_Literal':
return False
if hasattr(rdfclass, rng):
mod_class = getattr(rdfclass, rng)
for item in mod_class.cls_defs['rdf_type']:
try:
if issubclass(getattr(rdfclass, item),
rdfclass.rdfs_Literal):
... |
<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_es_value(obj, def_obj):
""" Returns the value for an object that goes into the elacticsearch 'value' field args: obj: data object to update def_obj: the ... |
def get_dict_val(item):
"""
Returns the string representation of the dict item
"""
if isinstance(item, dict):
return str(item.get('value'))
return str(item)
value_flds = []
if def_obj.es_defs.get('kds_esValue'):
value_flds = def_obj.es_defs['kds_... |
<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_es_label(obj, def_obj):
""" Returns object with label for an object that goes into the elacticsearch 'label' field args: obj: data object to update def_o... |
label_flds = LABEL_FIELDS
if def_obj.es_defs.get('kds_esLabel'):
label_flds = def_obj.es_defs['kds_esLabel'] + LABEL_FIELDS
try:
for label in label_flds:
if def_obj.cls_defs.get(label):
obj['label'] = def_obj.cls_defs[label][0]
break
if ... |
<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_es_ids(obj, def_obj):
""" Returns the object updated with the 'id' and 'uri' fields for the elasticsearch document args: obj: data object to update def_o... |
try:
path = ""
for base in [def_obj.__class__] + list(def_obj.__class__.__bases__):
if hasattr(base, 'es_defs') and base.es_defs:
path = "%s/%s/" % (base.es_defs['kds_esIndex'][0],
base.es_defs['kds_esDocType'][0])
cont... |
<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_es_id(uri):
""" Creates the id based off of the uri value Args: ----- uri: the uri to conver to an elasticsearch id """ |
try:
uri = uri.clean_uri
except AttributeError:
pass
return sha1(uri.encode()).hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gp_norm(infile):
"""indentify normalization region""" |
inDir, outDir = getWorkDirs()
data, titles = [], []
for eidx,energy in enumerate(['19', '27', '39', '62']):
file_url = os.path.realpath(os.path.join(
inDir, 'rawdata', energy, 'pt-integrated', infile+'.dat'
))
data_import = np.loadtxt(open(file_url, 'rb'))
data_i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_version():
""" Get the version from the source, but without importing. """ |
with open('sj.py') as source:
for node in ast.walk(ast.parse(source.read(), 'sj.py')):
if node.__class__.__name__ == 'Assign' and \
node.targets[0].__class__.__name__ == 'Name' and \
node.targets[0].id == '__version__':
return node.value.s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_field(self, setting, field_class, name, code=None):
""" Initialize a field whether it is built with a custom name for a specific translation language o... |
kwargs = {
"label": setting["label"] + ":",
"required": setting["type"] in (int, float),
"initial": getattr(settings, name),
"help_text": self.format_help(setting["description"]),
}
if setting["choices"]:
field_class = forms.ChoiceFiel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self):
""" Save each of the settings to the DB. """ |
active_language = get_language()
for (name, value) in self.cleaned_data.items():
if name not in registry:
name, code = name.rsplit('_modeltranslation_', 1)
else:
code = None
setting_obj, created = Setting.objects.get_or_create(name=nam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_help(self, description):
""" Format the setting's description into HTML. """ |
for bold in ("``", "*"):
parts = []
if description is None:
description = ""
for i, s in enumerate(description.split(bold)):
parts.append(s if i % 2 == 0 else "<b>%s</b>" % s)
description = "".join(parts)
description = urli... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bestfit_func(self, bestfit_x):
""" Returns bestfit_y value args: bestfit_x: scalar, array_like x value return: scalar, array_like bestfit y value """ |
bestfit_x = np.array(bestfit_x)
if not self.done_bestfit:
raise KeyError("Do do_bestfit first")
bestfit_y = 0
for idx, val in enumerate(self.fit_args):
bestfit_y += val * (bestfit_x **
(self.args.get("degree", 1) - idx))
re... |
<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(request, template="accounts/account_login.html", form_class=LoginForm, extra_context=None):
""" Login form. """ |
form = form_class(request.POST or None)
if request.method == "POST" and form.is_valid():
authenticated_user = form.save()
info(request, _("Successfully logged in"))
auth_login(request, authenticated_user)
return login_redirect(request)
context = {"form": form, "title": _("Lo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def signup(request, template="accounts/account_signup.html", extra_context=None):
""" Signup form. """ |
profile_form = get_profile_form()
form = profile_form(request.POST or None, request.FILES or None)
if request.method == "POST" and form.is_valid():
new_user = form.save()
if not new_user.is_active:
if settings.ACCOUNTS_APPROVAL_REQUIRED:
send_approve_mail(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 signup_verify(request, uidb36=None, token=None):
""" View for the link in the verification email sent to a new user when they create an account and ``ACCOUNT... |
user = authenticate(uidb36=uidb36, token=token, is_active=False)
if user is not None:
user.is_active = True
user.save()
auth_login(request, user)
info(request, _("Successfully signed up"))
return login_redirect(request)
else:
error(request, _("The link you cl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def profile(request, username, template="accounts/account_profile.html", extra_context=None):
""" Display a profile. """ |
lookup = {"username__iexact": username, "is_active": True}
context = {"profile_user": get_object_or_404(User, **lookup)}
context.update(extra_context or {})
return TemplateResponse(request, template, context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def profile_update(request, template="accounts/account_profile_update.html", extra_context=None):
""" Profile update form. """ |
profile_form = get_profile_form()
form = profile_form(request.POST or None, request.FILES or None,
instance=request.user)
if request.method == "POST" and form.is_valid():
user = form.save()
info(request, _("Profile updated"))
try:
return redirect(... |
<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_branch_sha(profile, name):
"""Get the SHA a branch's HEAD points to. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such... |
ref = "heads/" + name
data = refs.get_ref(profile, ref)
head = data.get("head")
sha = head.get("sha")
return sha |
<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_branch(profile, name):
"""Fetch a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module ... |
ref = "heads/" + name
data = refs.get_ref(profile, ref)
return data |
<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_branch(profile, name, branch_off):
"""Create a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles t... |
branch_off_sha = get_branch_sha(profile, branch_off)
ref = "heads/" + name
data = refs.create_ref(profile, ref, branch_off_sha)
return data |
<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_branch(profile, name, sha):
"""Move a branch's HEAD to a new SHA. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such... |
ref = "heads/" + name
data = refs.update_ref(profile, ref, sha)
return data |
<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_branch(profile, name):
"""Delete a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this mod... |
ref = "heads/" + name
data = refs.delete_ref(profile, ref)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(profile, branch, merge_into):
"""Merge a branch into another branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Su... |
data = merges.merge(profile, branch, merge_into)
return data |
<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_callbacks(self, name):
""" Returns True if there are callbacks attached to the specified event name. Returns False if not """ |
r = self.event_listeners.get(name)
if not r:
return False
return len(r) > 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 on(self, name, callback, once=False):
""" Adds a callback to the event specified by name once <bool> if True the callback will be removed once it's been trig... |
if name not in self.event_listeners:
self.event_listeners[name] = []
self.event_listeners[name].append((callback, once)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def off(self, name, callback, once=False):
""" Removes callback to the event specified by name """ |
if name not in self.event_listeners:
return
self.event_listeners[name].remove((callback, once)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trigger(self, name, *args, **kwargs):
""" Triggers the event specified by name and passes self in keyword argument "event_origin" All additional arguments an... |
mark_remove = []
for callback, once in self.event_listeners.get(name, []):
callback(event_origin=self, *args, **kwargs)
if once:
mark_remove.append( (callback, once) )
for callback, once in mark_remove:
self.off(name, callback, once=once) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def get_final_destination(self):
"""Get a list of final destinations for a stop.""" |
dest = []
await self.get_departures()
for departure in self._departures:
dep = {}
dep['line'] = departure.get('line')
dep['destination'] = departure.get('destination')
dest.append(dep)
return [dict(t) for t in {tuple(d.items()) for d in de... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_name(name, module=None):
"""Resolve a dotted name to a module and its parts. This is stolen wholesale from unittest.TestLoader.loadTestByName. """ |
parts = name.split('.')
parts_copy = parts[:]
if module is None:
while parts_copy: # pragma: no cover
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_cop... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_mobile(view):
"""View Decorator that adds a "mobile" attribute to the request which is True or False depending on whether the request should be consid... |
@wraps(view)
def detected(request, *args, **kwargs):
MobileDetectionMiddleware.process_request(request)
return view(request, *args, **kwargs)
detected.__doc__ = '%s\n[Wrapped by detect_mobile which detects if the request is from a phone]' % view.__doc__
return detected |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def masked(a, b):
"""Return a numpy array with values from a where elements in b are not False. Populate with numpy.nan where b is False. When plotting, those el... |
if np.any([a.dtype.kind.startswith(c) for c in ['i', 'u', 'f', 'c']]):
n = np.array([np.nan for i in range(len(a))])
else:
n = np.array([None for i in range(len(a))])
# a = a.astype(object)
return np.where(b, a, 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 duration_bool(b, rule, samplerate=None):
""" Mask the parts in b being True but does not meet the duration rules. Return an updated copy of b. b: 1d array wi... |
if rule is None:
return b
slicelst = slicelist(b)
b2 = np.array(b)
if samplerate is None:
samplerate = 1.0
for sc in slicelst:
dur = (sc.stop - sc.start) / samplerate # NOQA
if not eval(rule):
b2[sc] = False
return b2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def startstop_bool(pack):
"""Make a bool array based on start and stop conditions. pack: pack.ChannelPack instance If there is start conditions but no stop condi... |
b_TRUE = np.ones(pack.rec_cnt) == True # NOQA
start_list = pack.conconf.conditions_list('startcond')
stop_list = pack.conconf.conditions_list('stopcond')
# Pre-check:
runflag = 'startstop'
if not start_list and not stop_list:
return b_TRUE
elif not start_list:
runflag = '... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _startstop_bool(startb, stopb, runflag, stopextend):
"""Return boolean array based on start and stop conditions. startb, stopb: Numpy 1D arrays of the same l... |
# All false at start
res = np.zeros(len(startb)) == True # NOQA
start_slices = slicelist(startb)
stop_slices = slicelist(stopb)
# Special case when there is a start but no stop slice or vice versa:
# if start_slices and not stop_slices:
if runflag == 'startonly':
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 slicelist(b):
"""Produce a list of slices given the boolean array b. Start and stop in each slice describe the True sections in b.""" |
slicelst = []
started = False
for i, e in enumerate(b):
if e and not started:
start = i
started = True
elif not e and started:
slicelst.append(slice(start, i))
started = False
if e:
slicelst.append(slice(start, i + 1)) # True in... |
<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_archive(archive):
""" Save `archive` into database and into proper indexes. Attr: archive (obj):
Instance of the :class:`.DBArchive`. Returns: obj: :cl... |
_assert_obj_type(archive, obj_type=DBArchive)
_get_handler().store_object(archive)
return archive.to_comm(light_request=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 main(argv):
""" Basic command line script for testing library. """ |
# Parse command line arguments
parser = argparse.ArgumentParser(
description="LifeSOSpy v{} - {}".format(
PROJECT_VERSION, PROJECT_DESCRIPTION))
parser.add_argument(
'-H', '--host',
help="Hostname/IP Address for the LifeSOS server, if we are to run as a client.",
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def datetime(self):
"""Return `datetime` object""" |
return dt.datetime(
self.year(), self.month(), self.day(),
self.hour(), self.minute(), self.second(),
int(self.millisecond() * 1e3)) |
<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_command(self, name):
"""Wrap command class in constructor.""" |
def command(options):
client = ZookeeperClient(
"%s:%d" % (options.pop('host'), options.pop('port')),
session_timeout=1000
)
path = options.pop('path_prefix')
force = options.pop('force')
extra = options.pop('extr... |
<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_installed_version(vcs):
"""Get the installed version for this project. Args: vcs (easyci.vcs.base.Vcs) Returns: str - version number Raises: VersionNotIn... |
version_path = _get_version_path(vcs)
if not os.path.exists(version_path):
raise VersionNotInstalledError
with open(version_path, 'r') as f:
return f.read().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 set_installed_version(vcs, version):
"""Set the installed version for this project. Args: vcs (easyci.vcs.base.Vcs) version (str) """ |
version_path = _get_version_path(vcs)
with open(version_path, 'w') as f:
f.write(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 get_urls(self, **kwargs):
""" Ensure the correct host by injecting the current site. """ |
kwargs["site"] = Site.objects.get(id=current_site_id())
return super(DisplayableSitemap, self).get_urls(**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 usernames(urls):
'''Take an iterable of `urls` of normalized URL or file paths and
attempt to extract usernames. Returns a list.
'''
usernames = StringCounter()
for url, count in urls.items():
uparse = urlparse(url)
path = uparse.path
hostname = uparse.hostname
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleaned_data(self):
""" When cleaned_data is initially accessed, we want to ensure the form gets validated which has the side effect of setting cleaned_data ... |
if not hasattr(self, "_cleaned_data"):
self._cleaned_data = {}
self.is_valid()
return self._cleaned_data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self):
""" This should return an elasticsearch-DSL Search instance, list or queryset based on the values in self.cleaned_data. """ |
results = self.index.objects.all()
# reduce the results based on the q field
if self.cleaned_data.get("q"):
results = results.query(
"multi_match",
query=self.cleaned_data['q'],
fields=self.get_fields(),
# this prevents... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def on(message):
'''Decorator that register a class method as callback for a message.'''
def decorator(function):
try:
function._callback_messages.append(message)
except AttributeError:
function._callback_messages = [message]
return function
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def plug(self):
'''Add the actor's methods to the callback registry.'''
if self.__plugged:
return
for _, method in inspect.getmembers(self, predicate=inspect.ismethod):
if hasattr(method, '_callback_messages'):
for message in method._callback_messages:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unplug(self):
'''Remove the actor's methods from the callback registry.'''
if not self.__plugged:
return
members = set([method for _, method
in inspect.getmembers(self, predicate=inspect.ismethod)])
for message in global_callbacks:
global... |
<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):
'''Run until there are no events to be processed.'''
# We left-append rather than emit (right-append) because some message
# may have been already queued for execution before the director runs.
global_event_queue.appendleft((INITIATE, self, (), {}))
while global_ev... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def halt(self, message, emitter, *args, **kwargs):
'''Halt the execution of the loop.'''
self.process_event((FINISH, self, (), {}))
global_event_queue.clear() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create_injector(param_name, fun_param_value):
'''Dependency injection with Bottle.
This creates a simple dependency injector that will map
``param_name`` in routes to the value ``fun_param_value()``
each time the route is invoked.
``fun_param_value`` is a closure so that it is lazily evaluated... |
<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_app(self):
'''Eliminate the builder by producing a new Bottle application.
This should be the final call in your method chain. It uses all
of the built up options to create a new Bottle application.
:rtype: :class:`bottle.Bottle`
'''
if self.config is 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 add_search_engine(self, name, engine):
'''Adds a search engine with the given name.
``engine`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.SearchEngine`, which should provide a means
of obtaining recommendations... |
<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_filter(self, name, filter):
'''Adds a filter with the given name.
``filter`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.Filter`, which should provide a means
of creating a predicate function.
The `... |
<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_routes(self, routes):
'''Merges a Bottle application into this one.
:param routes: A Bottle application or a sequence of routes.
:type routes: :class:`bottle.Bottle` or `[bottle route]`.
:rtype: :class:`WebBuilder`
'''
# Basically the same as `self.app.merge(rout... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def enable_cors(self):
'''Enables Cross Origin Resource Sharing.
This makes sure the necessary headers are set so that this
web application's routes can be accessed from other origins.
:rtype: :class:`WebBuilder`
'''
def access_control_headers():
bottle.resp... |
<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_properties(self) -> 'PygalleBaseClass': """ Initialize the Pigalle properties. # Returns: PygalleBaseClass: The current instance. """ |
self._pigalle = {
PygalleBaseClass.__KEYS.INTERNALS: dict(),
PygalleBaseClass.__KEYS.PUBLIC: dict()
}
return self |
<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(self, key: str, value: Any) -> 'PygalleBaseClass': """ Define a public property. :param key: :param value: :return: """ |
self.public()[key] = value
return self |
<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_category(self, category: str = None) -> 'PygalleBaseClass': """ Define the category of the class. # Arguments category: The name of category. # Returns: P... |
return self.set_internal(PygalleBaseClass.__KEYS.CATEGORY, category) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instance_of(self, kls: Any) -> bool: """ Return true if the current object is an instance of passed type. # Arguments kls: The class. # Returns: bool: * Retur... |
if not kls:
raise ValueError
return isinstance(self, kls) |
<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_pigalle_class(kls: ClassVar) -> bool: """ Return true if the passed object as argument is a class being to the Pigalle framework. # Arguments kls: The clas... |
return (kls is PygalleBaseClass) or (issubclass(type(kls), PygalleBaseClass)) |
<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_pigalle(obj: Any) -> bool: """ Return true if the passed object as argument is a class or an instance of class being to the Pigalle framework. # Arguments ... |
return PygalleBaseClass.is_pigalle_class(obj) or PygalleBaseClass.is_pigalle_instance(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 has_method(self, key: str) -> bool: """ Return if a method exists for the current instance. # Arguments key: The method name. # Returns: bool: * True if the c... |
return hasattr(self.__class__, key) and callable(getattr(self.__class__, 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 extract_context(tex_file, extracted_image_data):
"""Extract context. Given a .tex file and a label name, this function will extract the text before and after... |
if os.path.isdir(tex_file) or not os.path.exists(tex_file):
return []
lines = "".join(get_lines_from_file(tex_file))
# Generate context for each image and its assoc. labels
for data in extracted_image_data:
context_list = []
# Generate a list of index tuples for all matches
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def intelligently_find_filenames(line, TeX=False, ext=False, commas_okay=False):
"""Intelligently find filenames. Find the filename in the line. We don't support... |
files_included = ['ERROR']
if commas_okay:
valid_for_filename = '\\s*[A-Za-z0-9\\-\\=\\+/\\\\_\\.,%#]+'
else:
valid_for_filename = '\\s*[A-Za-z0-9\\-\\=\\+/\\\\_\\.%#]+'
if ext:
valid_for_filename += '\.e*ps[texfi2]*'
if TeX:
valid_for_filename += '[\.latex]*'
... |
<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_lines_from_file(filepath, encoding="UTF-8"):
"""Return an iterator over lines.""" |
try:
fd = codecs.open(filepath, 'r', encoding)
lines = fd.readlines()
except UnicodeDecodeError:
# Fall back to 'ISO-8859-1'
fd = codecs.open(filepath, 'r', 'ISO-8859-1')
lines = fd.readlines()
finally:
fd.close()
return lines |
<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_request(self, conf, post_params={}):
"""Make a request to the API and return data in a pythonic object""" |
endpoint, requires_auth = conf
# setup the url and the request objects
url = '%s%s.php' % (self.api_url, endpoint)
log.debug('Setting url to %s' % url)
request = urllib2.Request(url)
# tack on authentication if needed
log.debug('Post params: %s' % post_params)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.