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 clistream(reporter, *args, **kwargs):
""" Handle stream data on command line interface, and returns statistics of success, error, and total amount. More detailed information is available on underlying feature, :mod:`clitool.processor`. :param Handler: [DEPRECATED] Handler for file-like streams. (default: :class:`clitool.processor.CliHandler`) :type Handler: object which supports `handle` method. :param reporter: callback to report processed value :type reporter: callable :param delimiter: line delimiter [optional] :type delimiter: string :param args: functions to parse each item in the stream. :param kwargs: keywords, including ``files`` and ``input_encoding``. :rtype: list """ |
# Follow the rule of `parse_arguments()`
files = kwargs.get('files')
encoding = kwargs.get('input_encoding', DEFAULT_ENCODING)
processes = kwargs.get('processes')
chunksize = kwargs.get('chunksize')
from clitool.processor import CliHandler, Streamer
Handler = kwargs.get('Handler')
if Handler:
warnings.warn('"Handler" keyword will be removed from next release.',
DeprecationWarning)
else:
Handler = CliHandler
s = Streamer(reporter, processes=processes, *args)
handler = Handler(s, kwargs.get('delimiter'))
return handler.handle(files, encoding, chunksize) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def no_input(self):
"""Return whether the user wants to run in no-input mode. Enable this mode by adding a ``no-input`` option:: [zest.releaser] no-input = yes The default when this option has not been set is False. Standard config rules apply, so you can use upper or lower or mixed case and specify 0, false, no or off for boolean False, and 1, on, true or yes for boolean True. """ |
default = False
if self.config is None:
return default
try:
result = self.config.getboolean('zest.releaser', 'no-input')
except (NoSectionError, NoOptionError, ValueError):
return default
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def distutils_servers(self):
"""Return a list of known distutils servers for collective.dist. If the config has an old pypi config, remove the default pypi server from the list. """ |
if not multiple_pypi_support():
return []
try:
raw_index_servers = self.config.get('distutils', 'index-servers')
except (NoSectionError, NoOptionError):
return []
ignore_servers = ['']
if self.is_old_pypi_config():
# We have already asked about uploading to pypi using the normal
# upload.
ignore_servers.append('pypi')
# Yes, you can even have an old pypi config with a
# [distutils] server list.
index_servers = [
server.strip() for server in raw_index_servers.split('\n')
if server.strip() not in ignore_servers]
return index_servers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def want_release(self):
"""Does the user normally want to release this package. Some colleagues find it irritating to have to remember to answer the question "Check out the tag (for tweaks or pypi/distutils server upload)" with the non-default 'no' when in 99 percent of the cases they just make a release specific for a customer, so they always answer 'no' here. This is where an extra config option comes in handy: you can influence the default answer so you can just keep hitting 'Enter' until zest.releaser is done. Either in your ~/.pypirc or in a setup.cfg in a specific package, add this when you want the default answer to this question to be 'no': [zest.releaser] release = no The default when this option has not been set is True. Standard config rules apply, so you can use upper or lower or mixed case and specify 0, false, no or off for boolean False, and 1, on, true or yes for boolean True. """ |
default = True
if self.config is None:
return default
try:
result = self.config.getboolean('zest.releaser', 'release')
except (NoSectionError, NoOptionError, ValueError):
return default
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transpose_mat44(src_mat, transpose_mat=None):
"""Create a transpose of a matrix.""" |
if not transpose_mat:
transpose_mat = Matrix44()
for i in range(4):
for j in range(4):
transpose_mat.data[i][j] = src_mat.data[j][i]
return transpose_mat |
<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_affine_mat44(mat):
"""Return True if only tranlsate, rotate, and uniform scale components.""" |
# Ensure scale is uniform
if not (mat.data[0][0] == mat.data[1][1] == mat.data[2][2]):
return False
# Ensure row [3] is 0, 0, 0, 1
return (mat.data[0][3] == 0 and
mat.data[1][3] == 0 and
mat.data[2][3] == 0 and
mat.data[3][3] == 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 invert_affine_mat44(mat):
"""Assumes there is only rotate, translate, and uniform scale componenets to the matrix. """ |
inverted = Matrix44()
# Transpose the 3x3 rotation component
for i in range(3):
for j in range(3):
inverted.data[i][j] = mat.data[j][i]
# Set translation: inverted_trans_vec3 = -inv(rot_mat33) * trans_vec3
for row in range(3):
inverted.data[3][row] = (
-inverted.data[0][row] * mat.data[3][0] +
-inverted.data[1][row] * mat.data[3][1] +
-inverted.data[2][row] * mat.data[3][2])
return inverted |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def almost_equal(self, mat2, places=7):
"""Return True if the values in mat2 equal the values in this matrix. """ |
if not hasattr(mat2, "data"):
return False
for i in range(4):
if not (_float_almost_equal(self.data[i][0],
mat2.data[i][0], places) and
_float_almost_equal(self.data[i][1],
mat2.data[i][1], places) and
_float_almost_equal(self.data[i][2],
mat2.data[i][2], places) and
_float_almost_equal(self.data[i][3],
mat2.data[i][3], places)):
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 rot_from_vectors(start_vec, end_vec):
"""Return the rotation matrix to rotate from one vector to another.""" |
dot = start_vec.dot(end_vec)
# TODO: check if dot is a valid number
angle = math.acos(dot)
# TODO: check if angle is a valid number
cross = start_vec.cross(end_vec)
cross.normalize
rot_matrix = Matrix44.from_axis_angle(cross, angle)
# TODO: catch exception and return identity for invalid numbers
return rot_matrix |
<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_trans(self, out_vec=None):
"""Return the translation portion of the matrix as a vector. If out_vec is provided, store in out_vec instead of creating a new Vec3. """ |
if out_vec:
return out_vec.set(*self.data[3][:3])
return Vec3(*self.data[3][:3]) |
<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_trans(self, trans_vec):
"""Set the translation components of the matrix.""" |
# Column major, translation components in column 3.
self.data[3][0] = trans_vec[0]
self.data[3][1] = trans_vec[1]
self.data[3][2] = trans_vec[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 is_running(self):
""" True if the subprocess is running. If it's a zombie then we call :func:`desub.Desub.stop` to kill it with fire and return False. """ |
pp = self.pid
if pp:
try:
proc = psutil.Process(pp)
# Possible status:
# "STATUS_RUNNING", "STATUS_IDLE",
# "STATUS_SLEEPING", "STATUS_DISK_SLEEP",
# "STATUS_STOPPED", "STATUS_TRACING_STOP",
# "STATUS_ZOMBIE", "STATUS_DEAD",
# "STATUS_WAKING", "STATUS_LOCKED",
if proc.status in (psutil.STATUS_STOPPED,
psutil.STATUS_DEAD,
psutil.STATUS_ZOMBIE):
# The PID is still in the process table so call stop to
# remove the PID.
self.stop()
return False
else:
# OK, it's running.
return True
except psutil.NoSuchProcess:
pass
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 pid(self):
""" The integer PID of the subprocess or None. """ |
pf = self.path('cmd.pid')
if not os.path.exists(pf):
return None
with open(pf, 'r') as f:
return int(f.read()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
"""Start the subprocess.""" |
c_out, c_err = (open(self.path('cmd.stdout'), 'w'),
open(self.path('cmd.stderr'), 'w'))
kw = self.kw.copy()
kw['stdout'] = c_out
kw['stderr'] = c_err
if not kw.get('cwd', None):
kw['cwd'] = os.getcwd()
pr = subprocess.Popen(self.cmd_args, **kw)
with open(self.path('cmd.pid'), 'w') as f:
f.write(str(pr.pid)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self, timeout=15):
"""Stop the subprocess. Keyword Arguments **timeout** Time in seconds to wait for a process and its children to exit. """ |
pp = self.pid
if pp:
try:
kill_process_nicely(pp, timeout=timeout)
except psutil.NoSuchProcess:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_get_kb_by_type(kbtype):
"""Return a query to filter kb by type. :param kbtype: type to filter (e.g: taxonomy) :return: query to filter kb """ |
return models.KnwKB.query.filter_by(
kbtype=models.KnwKB.KNWKB_TYPES[kbtype]) |
<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_kb_mapping(kb_name="", key="", value="", match_type="e", default="", limit=None):
"""Get one unique mapping. If not found, return default. :param kb_name: the name of the kb :param key: include only lines matching this on left side in the results :param value: include only lines matching this on right side in the results :param match_type: s = substring match, e = exact match :param default: default value if no mapping is found :return: a mapping """ |
mappings = get_kb_mappings(kb_name, key=key, value=value,
match_type=match_type, limit=limit)
if len(mappings) == 0:
return default
else:
return mappings[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 add_kb_mapping(kb_name, key, value=""):
"""Add a new mapping to given kb. :param kb_name: the name of the kb where to insert the new value :param key: the key of the mapping :param value: the value of the mapping """ |
kb = get_kb_by_name(kb_name)
if key in kb.kbrvals:
# update
kb.kbrvals[key].m_value = value
else:
# insert
kb.kbrvals.set(models.KnwKBRVAL(m_key=key, m_value=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 update_kb_mapping(kb_name, old_key, key, value):
"""Update an existing kb mapping with key old_key with a new key and value. :param kb_name: the name of the kb where to insert the new value :param old_key: the key of the mapping in the kb :param key: the new key of the mapping :param value: the new value of the mapping """ |
db.session.query(models.KnwKBRVAL).join(models.KnwKB) \
.filter(models.KnwKB.name == kb_name,
models.KnwKBRVAL.m_key == old_key) \
.update({"m_key": key, "m_value": value}, synchronize_session=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 add_kb(kb_name=u"Untitled", kb_type=None, tries=10):
"""Add a new kb in database, return the id. Add a new kb in database, and returns its id The name of the kb will be 'Untitled#' such that it is unique. :param kb_name: the name of the kb :param kb_type: the type of the kb, incl 'taxonomy' and 'dynamic'. None for typical (leftside-rightside). :param tries: exit after <n> retry :return: the id of the newly created kb """ |
created = False
name = kb_name
i = 0
while(i < tries and created is False):
try:
kb = models.KnwKB(name=name, description="", kbtype=kb_type)
created = True
db.session.add(kb)
db.session.commit()
except IntegrityError:
db.session.rollback()
# get the highest id to calculate the new name
result = db.session.execute(
db.select([models.KnwKB.id])
.order_by(db.desc(models.KnwKB.id))
.limit(1)).first()
index = result[0] + 1 if result is not None else 1
name = kb_name + " " + str(index)
i = i + 1
created = False
except Exception:
db.session.rollback()
raise
if created is False:
# TODO raise the right exception
raise Exception(_("Can't create knowledge base \"%(name)s\".\n"
"Probabily the server is busy! "
"Try again later.", name=kb_name))
return kb.id |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_kb_dyn_config(kb_id, field, expression, collection=None):
"""Save a dynamic knowledge base configuration. :param kb_id: the id :param field: the field where values are extracted :param expression: ..using this expression :param collection: ..in a certain collection (default is all) """ |
# check that collection exists
if collection:
collection = Collection.query.filter_by(name=collection).one()
kb = get_kb_by_id(kb_id)
kb.set_dyn_config(field, expression, collection) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kb_mapping_exists(kb_name, key):
"""Return the information if a mapping exists. :param kb_name: knowledge base name :param key: left side (mapFrom) """ |
try:
kb = get_kb_by_name(kb_name)
except NoResultFound:
return False
return key in kb.kbrvals |
<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_kb(kb_name):
"""Delete given kb from database. :param kb_name: knowledge base name """ |
db.session.delete(models.KnwKB.query.filter_by(
name=kb_name).one()) |
<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_kba_values(kb_name, searchname="", searchtype="s"):
"""Return an array of values "authority file" type = just values. :param kb_name: name of kb :param searchname: get these values, according to searchtype :param searchtype: s=substring, e=exact, , sw=startswith """ |
if searchtype == 's' and searchname:
searchname = '%'+searchname+'%'
if searchtype == 'sw' and searchname: # startswith
searchname = searchname+'%'
if not searchname:
searchname = '%'
query = db.session.query(models.KnwKBRVAL).join(models.KnwKB) \
.filter(models.KnwKBRVAL.m_value.like(searchname),
models.KnwKB.name.like(kb_name))
return [(k.m_value,) for k in query.all()] |
<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_kbr_keys(kb_name, searchkey="", searchvalue="", searchtype='s'):
"""Return an array of keys. :param kb_name: the name of the knowledge base :param searchkey: search using this key :param searchvalue: search using this value :param searchtype: s = substring, e=exact """ |
if searchtype == 's' and searchkey:
searchkey = '%'+searchkey+'%'
if searchtype == 's' and searchvalue:
searchvalue = '%'+searchvalue+'%'
if searchtype == 'sw' and searchvalue: # startswith
searchvalue = searchvalue+'%'
if not searchvalue:
searchvalue = '%'
if not searchkey:
searchkey = '%'
query = db.session.query(models.KnwKBRVAL).join(models.KnwKB) \
.filter(models.KnwKBRVAL.m_key.like(searchkey),
models.KnwKBRVAL.m_value.like(searchvalue),
models.KnwKB.name.like(kb_name))
return [(k.m_key,) for k in query.all()] |
<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_kbr_values(kb_name, searchkey="", searchvalue="", searchtype='s', use_memoise=False):
"""Return a tuple of values from key-value mapping kb. :param kb_name: the name of the knowledge base :param searchkey: search using this key :param searchvalue: search using this value :param searchtype: s=substring; e=exact :param use_memoise: can we memoise while doing lookups? :type use_memoise: bool """ |
try:
if use_memoise:
kb = get_kb_by_name_memoised(kb_name)
else:
kb = get_kb_by_name(kb_name)
except NoResultFound:
return []
return list(kb.get_kbr_values(searchkey, searchvalue, searchtype)) |
<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_kbr_items(kb_name, searchkey="", searchvalue="", searchtype='s'):
"""Return a list of dictionaries that match the search. :param kb_name: the name of the knowledge base :param searchkey: search using this key :param searchvalue: search using this value :param searchtype: s = substring, e=exact :return: a list of dictionaries [{'key'=>x, 'value'=>y},..] """ |
kb = get_kb_by_name(kb_name)
return kb.get_kbr_items(searchkey, searchvalue, searchtype) |
<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_kbd_values_json(kbname, searchwith=""):
"""Return values from searching a dynamic kb as a json-formatted string. This IS probably the method you want. :param kbname: name of the knowledge base :param searchwith: a term to search with """ |
res = get_kbd_values(kbname, searchwith)
return json.dumps(res) |
<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_kbt_items(taxonomyfilename, templatefilename, searchwith=""):
""" Get items from taxonomy file using a templatefile. If searchwith is defined, return only items that match with it. :param taxonomyfilename: full path+name of the RDF file :param templatefile: full path+name of the XSLT file :param searchwith: a term to search with """ |
if processor_type == 1:
# lxml
doc = etree.XML(taxonomyfilename)
styledoc = etree.XML(templatefilename)
style = etree.XSLT(styledoc)
result = style(doc)
strres = str(result)
del result
del style
del styledoc
del doc
elif processor_type == 2:
# libxml2 & libxslt
styledoc = libxml2.parseFile(templatefilename)
style = libxslt.parseStylesheetDoc(styledoc)
doc = libxml2.parseFile(taxonomyfilename)
result = style.applyStylesheet(doc, None)
strres = style.saveResultToString(result)
style.freeStylesheet()
doc.freeDoc()
result.freeDoc()
else:
# no xml parser found
strres = ""
ritems = []
if len(strres) == 0:
return []
else:
lines = strres.split("\n")
for line in lines:
if searchwith:
if line.count(searchwith) > 0:
ritems.append(line)
else:
if len(line) > 0:
ritems.append(line)
return ritems |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_timestamp(dt):
"""Convert a datetime object to a unix timestamp. Note that unlike a typical unix timestamp, this is seconds since 1970 *local time*, not UTC. If the passed in object is already a timestamp, then that value is simply returned unmodified. """ |
if isinstance(dt, int):
return dt
return int(total_seconds(dt.replace(tzinfo=None) -
datetime.datetime(1970, 1, 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 fetch_token(self, **kwargs):
"""Fetch a new token using the supplied code. :param str code: A previously obtained auth code. """ |
if 'client_secret' not in kwargs:
kwargs.update(client_secret=self.client_secret)
return self.session.fetch_token(token_url, **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 refresh_token(self, **kwargs):
"""Refresh the authentication token. :param str refresh_token: The refresh token to use. May be empty if retrieved with ``fetch_token``. """ |
if 'client_secret' not in kwargs:
kwargs.update(client_secret=self.client_secret)
if 'client_id' not in kwargs:
kwargs.update(client_id=self.client_id)
return self.session.refresh_token(token_url, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_activity(self, id_num):
"""Return the activity with the given id. Note that this contains more detailed information than returned by `get_activities`. """ |
url = self._build_url('my', 'activities', id_num)
return self._json(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 get_activities(self, count=10, since=None, style='summary', limit=None):
"""Iterate over all activities, from newest to oldest. :param count: The number of results to retrieve per page. If set to ``None``, pagination is disabled. :param since: Return only activities since this date. Can be either a timestamp or a datetime object. :param style: The type of records to return. May be one of 'summary', 'briefs', 'ids', or 'extended'. :param limit: The maximum number of activities to return for the given query. """ |
params = {}
if since:
params.update(fromDate=to_timestamp(since))
parts = ['my', 'activities', 'search']
if style != 'summary':
parts.append(style)
url = self._build_url(*parts)
# TODO: return an Activity (or ActivitySummary?) class that can do
# things like convert date and time fields to proper datetime objects
return islice(self._iter(url, count, **params), 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 get_notables(self, id_num):
"""Return the notables of the activity with the given id. """ |
url = self._build_url('my', 'activities', id_num, 'notables')
return self._json(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 get_polyline(self, id_num, style='google'):
"""Return the polyline of the activity with the given id. :param style: The type of polyline to return. May be one of 'google', 'svg', or 'geojson'. """ |
parts = ['my', 'activities', id_num, 'polyline']
if style != 'google':
parts.append(style)
url = self._build_url(*parts)
return self._json(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 get_splits(self, id_num, unit='mi'):
"""Return the splits of the activity with the given id. :param unit: The unit to use for splits. May be one of 'mi' or 'km'. """ |
url = self._build_url('my', 'activities', id_num, 'splits', unit)
return self._json(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 get_stats(self, year=None, month=None):
"""Return stats for the given year and month.""" |
parts = ['my', 'stats']
if month and not year:
raise ValueError("month cannot be specified without year")
if year:
parts.append(year)
if month:
parts.append(year)
url = self._build_url(*parts)
return self._json(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 create_weight(self, weight, date=None):
"""Submit a new weight record. :param weight: The weight, in kilograms. :param date: The date the weight was recorded. If not specified, the current date will be used. """ |
url = self._build_url('my', 'body', 'weight')
data = {'weightInKilograms': weight}
if date:
if not date.is_aware():
raise ValueError("provided date is not timezone aware")
data.update(date=date.isoformat())
headers = {'Content-Type': 'application/json; charset=utf8'}
r = self.session.post(url, data=json.dumps(data), headers=headers)
r.raise_for_status()
return r |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
"""press to continue""" |
print('\n' + Fore.YELLOW + msg + Fore.RESET, end='')
input() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allow_origin_tween_factory(handler, registry):
"""Allow cross origin XHR requests """ |
def allow_origin_tween(request):
settings = request.registry.settings
request_origin = request.headers.get('origin')
def is_origin_allowed(origin):
allowed_origins = (
request.registry.settings.get('api.allowed_origins', [])
)
if isinstance(allowed_origins, str):
allowed_origins = allowed_origins.splitlines()
if not origin:
return False
for allowed_origin in allowed_origins:
if origin.lower().startswith(allowed_origin):
return True
return False
def allow_origin_callback(request, response):
"""Set access-control-allow-origin et. al headers
"""
allowed_methods = settings.get(
'api.allowed_methods',
str('GET, POST, PUT, DELETE, PATCH, OPTIONS'),
)
if callable(allowed_methods):
allowed_methods = allowed_methods(request)
allowed_headers = settings.get(
'api.allowed_headers',
str('Content-Type, Authorization, Range'),
)
if callable(allowed_headers):
allowed_headers = allowed_headers(request)
allowed_credentials = settings.get(
'api.allowed_credentials',
str('true'),
)
if callable(allowed_credentials):
allowed_credentials = allowed_credentials(request)
response.headers['Access-Control-Allow-Origin'] = request_origin
if allowed_credentials:
response.headers[str('Access-Control-Allow-Credentials')] = \
str(allowed_credentials)
if allowed_methods:
response.headers[str('Access-Control-Allow-Methods')] = str(
allowed_methods,
)
if allowed_headers:
response.headers[str('Access-Control-Allow-Headers')] = str(
allowed_headers,
)
if not is_origin_allowed(request_origin):
return handler(request)
request.add_response_callback(allow_origin_callback)
return handler(request)
return allow_origin_tween |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, dbsecgroup_id, source_cidr, port=3306):
""" Creates a security group rule. :param str dbsecgroup_id: The ID of the security group in which this rule should be created. :param str source_cidr: The source IP address range from which access should be allowed. :param int port: The port number used by db clients to connect to the db server. This would have been specified at db instance creation time. :rtype: :class:`DBSecurityGroupRule`. """ |
body = {
"security_group_rule": {
"security_group_id": dbsecgroup_id,
"cidr": source_cidr,
"from_port": port,
"to_port": port,
}
}
return self._create("/security-group-rules", body,
"security_group_rule") |
<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(filename1, filename2, recursive=False, backup=False,
suffix='~', *other_filenames):
'''An example copy script with some example parameters that might
be used in a file or directory copy command.
:param recursive: -r --recursive copy directories
recursively
:param backup: -b --backup backup any files you copy over
:param suffix: -S --suffix override the usual backup
suffix '''
filenames = [filename1, filename2] + list(other_filenames)
destination = filenames.pop()
print("You asked to move %s to %s" % (filenames, destination))
if recursive:
print("You asked to copy directories recursively.")
if backup:
print("You asked to backup any overwritten files.")
print("You would use the suffix %s" % suffix) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_date(my_date):
"""Parse a date into canonical format of datetime.dateime. :param my_date: Either datetime.datetime or string in '%Y-%m-%dT%H:%M:%SZ' format. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :return: A datetime.datetime. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- PURPOSE: Parse a date and make sure it has no time zone. """ |
if isinstance(my_date, datetime.datetime):
result = my_date
elif isinstance(my_date, str):
result = datetime.datetime.strptime(my_date, '%Y-%m-%dT%H:%M:%SZ')
else:
raise ValueError('Unexpected date format for "%s" of type "%s"' % (
str(my_date), type(my_date)))
assert result.tzinfo is None, 'Unexpected tzinfo for date %s' % (
result)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_thread_info(self, enforce_re=True, latest_date=None):
"""Return a json list with information about threads in the group. :param enforce_re=True: Whether to require titles to match regexp in self.topic_re. :param latest_date=None: Optional datetime.datetime for latest date to consider. Things past this are ignored. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :return: List of github items found. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- PURPOSE: Return a json list with information about threads in the group. Along with latest_date, this can be used to show issues. """ |
result = []
my_re = re.compile(self.topic_re)
url = '%s/issues?sort=updated' % (self.base_url)
latest_date = self.parse_date(latest_date) if latest_date else None
while url:
kwargs = {} if not self.gh_info.user else {'auth': (
self.gh_info.user, self.gh_info.token)}
my_req = requests.get(url, params=self.params, **kwargs)
my_json = my_req.json()
for item in my_json:
if (not enforce_re) or my_re.search(item['title']):
idate = self.parse_date(item['updated_at'])
if (latest_date is not None and idate > latest_date):
logging.debug('Skip %s since updated at %s > %s',
item['title'], idate, latest_date)
continue
result.append(item)
if self.max_threads is not None and len(
result) >= self.max_threads:
logging.debug('Stopping after max_threads=%i threads.',
len(result))
return result
url = None
if 'link' in my_req.headers:
link = my_req.headers['link'].split(',')
for thing in link:
potential_url, part = thing.split('; ')
if part == 'rel="next"':
url = potential_url.lstrip(' <').rstrip('> ')
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export(self, out_filename):
"""Export desired threads as a zipfile to out_filename. """ |
with zipfile.ZipFile(out_filename, 'w', zipfile.ZIP_DEFLATED) as arc:
id_list = list(self.get_thread_info())
for num, my_info in enumerate(id_list):
logging.info('Working on item %i : %s', num, my_info['number'])
my_thread = GitHubCommentThread(
self.gh_info.owner, self.gh_info.realm, my_info['title'],
self.gh_info.user, self.gh_info.token,
thread_id=my_info['number'])
csec = my_thread.get_comment_section()
cdict = [item.to_dict() for item in csec.comments]
my_json = json.dumps(cdict)
arc.writestr('%i__%s' % (my_info['number'], my_info['title']),
my_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 sleep_if_necessary(cls, user, token, endpoint='search', msg=''):
"""Sleep a little if hit github recently to honor rate limit. """ |
my_kw = {'auth': (user, token)} if user else {}
info = requests.get('https://api.github.com/rate_limit', **my_kw)
info_dict = info.json()
remaining = info_dict['resources'][endpoint]['remaining']
logging.debug('Search remaining on github is at %s', remaining)
if remaining <= 5:
sleep_time = 120
else:
sleep_time = 0
if sleep_time:
logging.warning('Sleep %i since github requests remaining = %i%s',
sleep_time, remaining, msg)
time.sleep(sleep_time)
return True
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 update_cache_key(cls, cache_key, item=None):
"""Get item in cache for cache_key and add item if item is not None. """ |
contents = cls.__thread_id_cache.get(cache_key, None)
if item is not None:
cls.__thread_id_cache[cache_key] = item
return contents |
<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_thread_id(self):
"""Lookup thread id as required by CommentThread.lookup_thread_id. This implementation will query GitHub with the required parameters to try and find the topic for the owner, realm, topic, etc., specified in init. """ |
query_string = 'in:title "%s" repo:%s/%s' % (
self.topic, self.owner, self.realm)
cache_key = (self.owner, self.realm, self.topic)
result = self.lookup_cache_key(cache_key)
if result is not None:
my_req = self.raw_pull(result)
if my_req.status_code != 200:
result = None # Cached item was no good
elif my_req.json()['title'] != self.topic:
logging.debug('Title must have changed; ignore cache')
result = None
else:
logging.debug('Using cached thread id %s for %s', str(result),
str(cache_key))
return result
data, dummy_hdr = self.raw_search(self.user, self.token, query_string)
if data['total_count'] == 1: # unique match
if data['items'][0]['title'] == self.topic:
result = data['items'][0]['number']
else:
result = None
elif data['total_count'] > 1: # multiple matches since github doesn't
searched_data = [ # have unique search we must filter
item for item in data['items'] if item['title'] == self.topic]
if not searched_data: # no matches
return None
elif len(searched_data) > 1:
raise yap_exceptions.UnableToFindUniqueTopic(
self.topic, data['total_count'], '')
else:
assert len(searched_data) == 1, (
'Confused searching for topic "%s"' % str(self.topic))
result = searched_data[0]['number']
else:
result = None
self.update_cache_key(cache_key, result)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raw_search(cls, user, token, query, page=0):
"""Do a raw search for github issues. :arg user: Username to use in accessing github. :arg token: Token to use in accessing github. :arg query: String query to use in searching github. :arg page=0: Number of pages to automatically paginate. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :returns: The pair (result, header) representing the result from github along with the header. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- PURPOSE: Search for issues on github. If page > 0 then we will pull out up to page more pages via automatic pagination. The best way to check if you got the full results is to check if results['total_count'] matches len(results['items']). """ |
page = int(page)
kwargs = {} if not user else {'auth': (user, token)}
my_url = cls.search_url
data = {'items': []}
while my_url:
cls.sleep_if_necessary(
user, token, msg='\nquery="%s"' % str(query))
my_req = requests.get(my_url, params={'q': query}, **kwargs)
if my_req.status_code != 200:
raise GitHubAngry(
'Bad status code %s finding query %s because %s' % (
my_req.status_code, query, my_req.reason))
my_json = my_req.json()
assert isinstance(my_json['items'], list)
data['items'].extend(my_json.pop('items'))
data.update(my_json)
my_url = None
if page and my_req.links.get('next', False):
my_url = my_req.links['next']['url']
if my_url:
page = page - 1
logging.debug(
'Paginating %s in raw_search (%i more pages allowed)',
my_req.links, page)
return data, my_req.headers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raw_pull(self, topic):
"""Do a raw pull of data for given topic down from github. :arg topic: String topic (i.e., issue title). ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :returns: Result of request data from github API. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- PURPOSE: Encapsulate call that gets raw data from github. """ |
assert topic is not None, 'A topic of None is not allowed'
kwargs = {} if not self.user else {'auth': (self.user, self.token)}
my_req = requests.get('%s/issues/%s' % (
self.base_url, topic), **kwargs)
return my_req |
<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_comment_list(self):
"""Lookup list of comments for an issue. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :returns: The pair (ISSUE, COMMENTS) where ISSUE is a dict for the main issue and COMMENTS is a list of comments on the issue. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- PURPOSE: Do the work of getting data from github, handling paging, and so on. """ |
if self.thread_id is None:
return None, None
# Just pulling a single issue here so pagination shouldn't be problem
my_req = self.raw_pull(self.thread_id)
if my_req.status_code != 200:
raise GitHubAngry('Bad status code %s because %s' % (
my_req.status_code, my_req.reason))
issue_json = my_req.json()
comments_url = issue_json['comments_url'] + self.url_extras
kwargs = {} if not self.user else {'auth': (self.user, self.token)}
comments_json = []
while comments_url:
logging.debug('Pulling comments URL: %s', comments_url)
c_req = requests.get(comments_url, **kwargs)
my_json = c_req.json()
assert isinstance(my_json, list)
comments_json.extend(my_json)
comments_url = None
if 'link' in c_req.headers: # need to handle pagination.
logging.debug('Paginating in lookup_comment_list')
link = c_req.headers['link'].split(',')
for thing in link:
potential_url, part = thing.split('; ')
if part == 'rel="next"':
comments_url = potential_url.lstrip(' <').rstrip('> ')
return issue_json, comments_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 add_comment(self, body, allow_create=False, allow_hashes=True, summary=None, hash_create=False):
"""Implement as required by CommentThread.add_comment. :arg body: String/text of comment to add. :arg allow_create=False: Whether to automatically create a new thread if a thread does not exist (usually by calling self.create_thread). :arg allow_hashes=True: Whether to support hashtag mentions of other topics and automatically insert comment in body into those topics as well. *IMPORTANT*: if you recursively call add_comment to insert the hashes, you should make sure to set this to False to prevent infinite hash processing loops. arg summary=None: Optional summary. If not given, we will extract one from body automatically if necessary. :arg hash_create=False: Whether to allow creating new threads via hash mentions. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :returns: Response object indicating whether added succesfully. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- PURPOSE: This uses the GitHub API to try to add the given comment to the desired thread. """ |
if self.thread_id is None:
self.thread_id = self.lookup_thread_id()
data = json.dumps({'body': body})
if self.thread_id is None:
if allow_create:
return self.create_thread(body)
else:
raise ValueError(
'Cannot find comment existing comment for %s' % self.topic)
result = requests.post('%s/issues/%s/comments' % (
self.base_url, self.thread_id), data, auth=(self.user, self.token))
if result.status_code != 201:
if result.reason == 'Not Found' and allow_create:
return self.create_thread(body)
else:
raise GitHubAngry(
'Bad status %s add_comment on %s because %s' % (
result.status_code, self.topic, result.reason))
if allow_hashes:
self.process_hashes(body, allow_create=hash_create)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_hashes(self, body, allow_create=False):
"""Process any hashes mentioned and push them to related topics. :arg body: Body of the comment to check for hashes and push out. :arg allow_create=False: Whether to allow creating new topics from hash tag mentions. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- PURPOSE: Look for hashtags matching self.hashtag_re and when found, add comment from body to those topics. """ |
hash_re = re.compile(self.hashtag_re)
hashes = hash_re.findall(body)
done = {self.topic.lower(): True}
for mention in hashes:
mention = mention.strip('#')
if mention.lower() in done:
continue # Do not duplicate hash mentions
new_thread = self.__class__(
owner=self.owner, realm=self.realm, topic=mention,
user=self.user, token=self.token)
my_comment = '# Hashtag copy from %s:\n%s' % (self.topic, body)
new_thread.add_comment(
my_comment, allow_create=allow_create,
allow_hashes=False) # allow_hashes=False to prevent inf loop
done[mention.lower()] = 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 upload_attachment(self, location, data):
"""Upload attachment as required by CommentThread class. See CommentThread.upload_attachment for details. """ |
self.validate_attachment_location(location)
content = data.read() if hasattr(data, 'read') else data
orig_content = content
if isinstance(content, bytes):
content = base64.b64encode(orig_content).decode('ascii')
else:
pass # Should be base64 encoded already
apath = '%s/%s' % (self.attachment_location, location)
url = '%s/contents/%s' % (self.base_url, apath)
result = requests.put(
url, auth=(self.user, self.token), data=json.dumps({
'message': 'file attachment %s' % location,
'content': content}))
if result.status_code != 201:
raise ValueError(
"Can't upload attachment %s due to error %s." % (
location, result.reason))
return '[%s](https://github.com/%s/%s/blob/master/%s)' % (
location, self.owner, self.realm, apath) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reconnect(self):
"""Closes the existing database connection and re-opens it.""" |
self.close()
self._db = psycopg2.connect(**self._db_args)
if self._search_path:
self.execute('set search_path=%s;' % self._search_path)
if self._timezone:
self.execute("set timezone='%s';" % self._timezone) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reregister_types(self):
"""Registers existing types for a new connection""" |
for _type in self._register_types:
psycopg2.extensions.register_type(psycopg2.extensions.new_type(*_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 register_type(self, oids, name, casting):
"""Callback to register data types when reconnect """ |
assert type(oids) is tuple
assert isinstance(name, basestring)
assert hasattr(casting, '__call__')
self._register_types.append((oids, name, casting))
psycopg2.extensions.register_type(psycopg2.extensions.new_type(oids, name, casting)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(self, query, *parameters, **kwargs):
"""Returns a row list for the given query and parameters.""" |
cursor = self._cursor()
try:
self._execute(cursor, query, parameters or None, kwargs)
if cursor.description:
column_names = [column.name for column in cursor.description]
res = [Row(zip(column_names, row)) for row in cursor.fetchall()]
cursor.close()
return res
except:
cursor.close()
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iter(self, query, *parameters, **kwargs):
"""Returns a generator for records from the query.""" |
cursor = self._cursor()
try:
self._execute(cursor, query, parameters or None, kwargs)
if cursor.description:
column_names = [column.name for column in cursor.description]
while True:
record = cursor.fetchone()
if not record:
break
yield Row(zip(column_names, record))
raise StopIteration
except:
cursor.close()
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, query, *parameters, **kwargs):
"""Same as query, but do not process results. Always returns `None`.""" |
cursor = self._cursor()
try:
self._execute(cursor, query, parameters, kwargs)
except:
raise
finally:
cursor.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, query, *parameters, **kwargs):
"""Returns the first row returned for the given query.""" |
rows = self.query(query, *parameters, **kwargs)
if not rows:
return None
elif len(rows) > 1:
raise ValueError('Multiple rows returned for get() query')
else:
return rows[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 executemany(self, query, *parameters):
"""Executes the given query against all the given param sequences. """ |
cursor = self._cursor()
try:
self._executemany(cursor, query, parameters)
if cursor.description:
column_names = [column.name for column in cursor.description]
res = [Row(zip(column_names, row)) for row in cursor.fetchall()]
cursor.close()
return res
except Exception: # pragma: no cover
cursor.close()
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install():
"""Install your package to all Python version you have installed on Windows. """ |
import os, shutil
_ROOT = os.getcwd()
_PACKAGE_NAME = os.path.basename(_ROOT)
print("Installing [%s] to all python version..." % _PACKAGE_NAME)
# find all Python release installed on this windows computer
installed_python_version = list()
for root, folder_list, _ in os.walk(r"C:\\"):
for folder in folder_list:
if folder.startswith("Python"):
if os.path.exists(os.path.join(root, folder, "pythonw.exe")):
installed_python_version.append(folder)
break
print("\tYou have installed: {0}".format(", ".join(installed_python_version)))
# remove __pycache__ folder and *.pyc file
print("\tRemoving *.pyc file ...")
pyc_folder_list = list()
for root, folder_list, _ in os.walk(_ROOT):
if os.path.basename(root) == "__pycache__":
pyc_folder_list.append(root)
for folder in pyc_folder_list:
shutil.rmtree(folder)
print("\t\tall *.pyc file has been removed.")
# install this package to all python version
for py_root in installed_python_version:
dst = os.path.join(r"C:\\", py_root, r"Lib\site-packages", _PACKAGE_NAME)
try:
shutil.rmtree(dst)
except:
pass
print("\tRemoved %s." % dst)
shutil.copytree(_ROOT, dst)
print("\tInstalled %s." % dst)
print("Complete!") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def namedtuple_asdict(obj):
""" Serializing a nested namedtuple into a Python dict """ |
if obj is None:
return obj
if hasattr(obj, "_asdict"): # detect namedtuple
return OrderedDict(zip(obj._fields, (namedtuple_asdict(item)
for item in obj)))
if isinstance(obj, str): # iterables - strings
return obj
if hasattr(obj, "keys"): # iterables - mapping
return OrderedDict(zip(obj.keys(), (namedtuple_asdict(item)
for item in obj.values())))
if hasattr(obj, "__iter__"): # iterables - sequence
return type(obj)((namedtuple_asdict(item) for item in obj))
# non-iterable cannot contain namedtuples
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_json(cls, json_dump):
""" How to get a context from a json dump """ |
context = cls()
if json_dump is None:
return None
ctxt = json.loads(json_dump)
for k in ctxt:
context[k] = ctxt[k]
return 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 find_tendril(cls, proto, addr):
""" Finds the tendril corresponding to the protocol and address tuple. Returns the Tendril object, or raises KeyError if the tendril is not tracked. The address tuple is the tuple of the local address and the remote address for the tendril. """ |
# First, normalize the proto
proto = proto.lower()
# Now, find and return the tendril
return cls._tendrils[proto][addr] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _track_tendril(self, tendril):
""" Adds the tendril to the set of tracked tendrils. """ |
self.tendrils[tendril._tendril_key] = tendril
# Also add to _tendrils
self._tendrils.setdefault(tendril.proto, weakref.WeakValueDictionary())
self._tendrils[tendril.proto][tendril._tendril_key] = tendril |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _untrack_tendril(self, tendril):
""" Removes the tendril from the set of tracked tendrils. """ |
try:
del self.tendrils[tendril._tendril_key]
except KeyError:
pass
# Also remove from _tendrils
try:
del self._tendrils[tendril.proto][tendril._tendril_key]
except KeyError:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_local_addr(self, timeout=None):
""" Retrieve the current local address. :param timeout: If not given or given as ``None``, waits until the local address is available. Otherwise, waits for as long as specified. If the local address is not set by the time the timeout expires, returns ``None``. """ |
# If we're not running, just return None
if not self.running:
return None
# OK, we're running; wait on the _local_addr_event
if not self._local_addr_event.wait(timeout):
# Still not set after timeout
return None
# We have a local address!
return self._local_addr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self, target, acceptor, wrapper=None):
""" Initiate a connection from the tendril manager's endpoint. Once the connection is completed, a Tendril object will be created and passed to the given acceptor. :param target: The target of the connection attempt. :param acceptor: A callable which will initialize the state of the new Tendril object. :param wrapper: A callable taking, as its first argument, a socket.socket object. The callable must return a valid proxy for the socket.socket object, which will subsequently be used to communicate on the connection. For passing extra arguments to the acceptor or the wrapper, see the ``TendrilPartial`` class; for chaining together multiple wrappers, see the ``WrapperChain`` class. """ |
if not self.running:
raise ValueError("TendrilManager not running")
# Check the target address
fam = utils.addr_info(target)
# Verify that we're in the right family
if self.addr_family != fam:
raise ValueError("address family mismatch") |
<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(self, *args, **kwargs):
"""Reads the node as a file """ |
with self.open('r') as f:
return f.read(*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 ls(self):
"""List the children entities of the directory. Raises exception if the object is a file. :return: """ |
if self.isfile():
raise NotDirectoryError('Cannot ls() on non-directory node: {path}'.format(path=self._pyerarchy_path))
return os.listdir(self._pyerarchy_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 mkdir(self, children, mode=0o0755, return_node=True):
"""Creates child entities in directory. Raises exception if the object is a file. :param children: The list of children to be created. :return: The child object, if one child is provided. None, otherwise. """ |
result = None
if isinstance(children, (str, unicode)):
if os.path.isabs(children):
raise BadValueError('Cannot mkdir an absolute path: {path}'.format(path=self._pyerarchy_path))
rel_path = os.path.join(self._pyerarchy_path, children)
os.makedirs(rel_path, mode)
if return_node:
result = Node(rel_path)
else:
for child in children:
self.mkdir(child, mode, False)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def capitalize( full_name, articles=None, separator_characters=None, ignore_worls=None, ):
"""Returns the correct writing of a compound name, respecting the first letters of the names in upper case.""" |
if articles is None:
articles = _ARTICLES
if separator_characters is None:
separator_characters = _SEPARATOR_CHARACTERS
if ignore_worls is None:
ignore_worls = _IGNORE_WORLS
new_full_name = full_name
if hasattr(new_full_name, 'strip'):
new_full_name = new_full_name.strip()
if not new_full_name:
return full_name
new_full_name = deep_unicode(new_full_name)
list_full_name = []
start_idx = 0
for step_idx, char in enumerate(list(new_full_name)):
if char in separator_characters:
list_full_name.extend(
[
_setting_word(
new_full_name[start_idx:step_idx],
separator_characters, ignore_worls,
articles if list_full_name else []
),
char
]
)
start_idx = step_idx + 1
list_full_name.append(
_setting_word(
new_full_name[start_idx:],
separator_characters, ignore_worls, articles
)
)
return ''.join(list_full_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 deep_unicode(s, encodings=None):
"""decode "DEEP" S using the codec registered for encoding.""" |
if encodings is None:
encodings = ['utf-8', 'latin-1']
if isinstance(s, (list, tuple)):
return [deep_unicode(i) for i in s]
if isinstance(s, dict):
return dict([
(deep_unicode(key), deep_unicode(s[key]))
for key in s
])
# in_dict = {}
# for key in s:
# in_dict[to_unicode(key)] = to_unicode(s[key])
# return in_dict
elif isinstance(s, str):
for encoding in encodings:
try:
return s.decode(encoding)
except:
pass
return 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 deep_encode(s, encoding='utf-8', errors='strict'):
"""Encode "DEEP" S using the codec registered for encoding.""" |
# encoding defaults to the default encoding. errors may be given to set
# a different error handling scheme. Default is 'strict' meaning
# that encoding errors raise
# a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
# 'xmlcharrefreplace' as well as any other name registered with
# codecs.register_error that can handle UnicodeEncodeErrors.
s = deep_encode(s)
if sys.version_info.major < 3 and isinstance(s, unicode):
return s.encode(encoding, errors)
if isinstance(s, (list, tuple)):
return [deep_encode(i, encoding=encoding, errors=errors) for i in s]
if isinstance(s, dict):
return dict([
(
deep_encode(key, encoding=encoding, errors=errors),
deep_encode(s[key], encoding=encoding, errors=errors)
) for key in s
])
# new_dict = {}
# for key in s:
# new_dict[
# to_encode(key, encoding=encoding, errors=errors)
# ] = to_encode(s[key], encoding=encoding, errors=errors)
# return new_dict
return 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 namespace(self, key, glob=False):
"""Return a namespace for keyring""" |
if not self.name:
self.name = os.environ['DJANGO_SETTINGS_MODULE']
ns = '.'.join([key, self._glob]) if glob else '.'.join([self.name, self._glob])
return ns |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, key, prompt_default='', prompt_help=''):
"""Return a value from the environ or keyring""" |
value = os.getenv(key)
if not value:
ns = self.namespace(key)
value = self.keyring.get_password(ns, key)
else:
ns = 'environ'
if not value:
ns = self.namespace(key, glob=True)
value = self.keyring.get_password(ns, key)
if not value:
ns = ''
if not value and self.prompt:
value = self._prompt_for_value(key, prompt_default, prompt_help)
if value:
self.set(key, value)
if ns:
self.kns[key] = ns
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, key, value, glob=False):
"""Set the key value pair in a local or global namespace""" |
ns = self.namespace(key, glob)
self.keyring.set_password(ns, key, 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 remove(self, key, glob=False):
"""Remove key value pair in a local or global namespace.""" |
ns = self.namespace(key, glob)
try:
self.keyring.delete_password(ns, key)
except PasswordDeleteError: # OSX and gnome have no delete method
self.set(key, '', glob) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, key, prompt_default='', prompt_help=''):
""" Return the value for key from the environment or keyring. The keyring value is resolved from a local namespace or a global one. """ |
value = super(DjSecret, self).get(key, prompt_default, prompt_help='')
if not value and self.raise_on_none:
error_msg = "The %s setting is undefined in the environment and djset %s" % (key, self._glob)
raise self.raise_on_none(error_msg)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw(self):
"""Draws the button in its current state.
Should be called every time through the main loop
""" |
if not self.visible:
return
# Blit the button's current appearance to the surface.
if self.isEnabled:
if self.mouseIsDown:
if self.mouseOverButton and self.lastMouseDownOverButton:
self.window.blit(self.surfaceDown, self.loc)
else:
self.window.blit(self.surfaceUp, self.loc)
else: # mouse is up
if self.mouseOverButton:
self.window.blit(self.surfaceOver, self.loc)
else:
self.window.blit(self.surfaceUp, self.loc)
else:
self.window.blit(self.surfaceDisabled, self.loc) |
<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):
"""This is just for debugging, so we can see what buttons would be drawn.
Not intended to be used in production.""" |
self.window.blit(self.surfaceUp, (self.loc[0], 10))
self.window.blit(self.surfaceOver, (self.loc[0], 60))
self.window.blit(self.surfaceDown, (self.loc[0], 110))
self.window.blit(self.surfaceDisabled, (self.loc[0], 160)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw(self):
"""Draws the checkbox.""" |
if not self.visible:
return
# Blit the current checkbox's image.
if self.isEnabled:
if self.mouseIsDown and self.lastMouseDownOverButton and self.mouseOverButton:
if self.value:
self.window.blit(self.surfaceOnDown, self.loc)
else:
self.window.blit(self.surfaceOffDown, self.loc)
else:
if self.value:
self.window.blit(self.surfaceOn, self.loc)
else:
self.window.blit(self.surfaceOff, self.loc)
else:
if self.value:
self.window.blit(self.surfaceOnDisabled, self.loc)
else:
self.window.blit(self.surfaceOffDisabled, self.loc) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getSelectedRadioButton(self):
"""Returns the nickname of the currently selected radio button.""" |
radioButtonListInGroup = PygWidgetsRadioButton.__PygWidgets__Radio__Buttons__Groups__Dicts__[self.group]
for radioButton in radioButtonListInGroup:
if radioButton.getValue():
selectedNickname = radioButton.getNickname()
return selectedNickname
raise Exception('No radio button was selected') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enableGroup(self):
"""Enables all radio buttons in the group.""" |
radioButtonListInGroup = PygWidgetsRadioButton.__PygWidgets__Radio__Buttons__Groups__Dicts__[self.group]
for radioButton in radioButtonListInGroup:
radioButton.enable() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disableGroup(self):
"""Disables all radio buttons in the group""" |
radioButtonListInGroup = PygWidgetsRadioButton.__PygWidgets__Radio__Buttons__Groups__Dicts__[self.group]
for radioButton in radioButtonListInGroup:
radioButton.disable() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw(self):
"""Draws the current text in the window""" |
if not self.visible:
return
self.window.blit(self.textImage, self.loc) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _updateImage(self):
"""Internal method to render text as an image.""" |
# Fill the background of the image
if self.backgroundColor is not None:
self.textImage.fill(self.backgroundColor)
# Render the text as a single line, and blit it onto the textImage surface
if self.mask is None:
lineSurface = self.font.render(self.text, True, self.textColor)
else:
nChars = len(self.text)
maskedText = self.mask * nChars
lineSurface = self.font.render(maskedText, True, self.textColor)
self.textImage.blit(lineSurface, (0, 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 draw(self):
"""Draws the Text in the window.""" |
if not self.visible:
return
# If this input text has focus, draw an outline around the text image
if self.focus:
pygame.draw.rect(self.window, self.focusColor, self.focusedImageRect, 1)
# Blit in the image of text (set earlier in _updateImage)
self.window.blit(self.textImage, self.loc)
# If this field has focus, see if it is time to blink the cursor
if self.focus:
self.cursorMsCounter = self.cursorMsCounter + self.clock.get_time()
if self.cursorMsCounter >= self.cursorSwitchMs:
self.cursorMsCounter = self.cursorMsCounter % self.cursorSwitchMs
self.cursorVisible = not self.cursorVisible
if self.cursorVisible:
cursorOffset = self.font.size(self.text[:self.cursorPosition])[0]
if self.cursorPosition > 0: # Try to get between characters
cursorOffset = cursorOffset - 1
if cursorOffset < self.width: # if the loc is within the text area, draw it
self.cursorLoc[0] = self.loc[0] + cursorOffset
self.window.blit(self.cursorSurface, self.cursorLoc)
self.clock.tick() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setValue(self, newText):
"""Sets new text into the field""" |
self.text = newText
self.cursorPosition = len(self.text)
self._updateImage() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clearText(self, keepFocus=False):
"""Clear the text in the field""" |
self.text = ''
self.focus = keepFocus
self._updateImage() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resetToPreviousLoc(self):
"""Resets the loc of the dragger to place where dragging started.
This could be used in a test situation if the dragger was dragged to an incorrect location.
""" |
self.rect.left = self.startDraggingX
self.rect.top = self.startDraggingY |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw(self):
"""Draws the dragger at the current mouse location.
Should be called in every frame.
""" |
if not self.visible:
return
if self.isEnabled:
# Draw the dragger's current appearance to the window.
if self.dragging:
self.window.blit(self.surfaceDown, self.rect)
else: # mouse is up
if self.mouseOver:
self.window.blit(self.surfaceOver, self.rect)
else:
self.window.blit(self.surfaceUp, self.rect)
else:
self.window.blit(self.surfaceDisabled, self.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 flipHorizontal(self):
""" flips an image object horizontally
""" |
self.flipH = not self.flipH
self._transmogrophy(self.angle, self.percent, self.scaleFromCenter, self.flipH, self.flipV) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flipVertical(self):
""" flips an image object vertically
""" |
self.flipV = not self.flipV
self._transmogrophy(self.angle, self.percent, self.scaleFromCenter, self.flipH, self.flipV) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _transmogrophy(self, angle, percent, scaleFromCenter, flipH, flipV):
'''
Internal method to scale and rotate
'''
self.angle = angle % 360
self.percent = percent
self.scaleFromCenter = scaleFromCenter
previousRect = self.rect
previousCenter = previousRect.center
previousX = previousRect.x
previousY = previousRect.y
# Rotate - pygame rotates in the opposite direction
pygameAngle = -self.angle
rotatedImage = pygame.transform.rotate(self.originalImage, pygameAngle)
rotatedRect = rotatedImage.get_rect()
rotatedWidth = rotatedRect.width
rotatedHeight = rotatedRect.height
# Scale
newWidth = int(rotatedWidth * .01 * self.percent)
newHeight = int(rotatedHeight * .01 * self.percent)
self.image = pygame.transform.scale(rotatedImage, (newWidth, newHeight))
# Flip
if flipH:
self.image = pygame.transform.flip(self.image, True, False)
if flipV:
self.image = pygame.transform.flip(self.image, False, True)
# Placement
self.rect = self.image.get_rect()
if self.scaleFromCenter:
self.rect.center = previousCenter
else: # use previous X, Y
self.rect.x = previousX
self.rect.y = previousY
self.setLoc((self.rect.left, self.rect.top)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw(self):
"""Draws the image at the given location.""" |
if not self.visible:
return
self.window.blit(self.image, self.loc) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def play(self):
"""Starts an animation playing.""" |
if self.state == PygAnimation.PLAYING:
pass # nothing to do
elif self.state == PygAnimation.STOPPED: # restart from beginning of animation
self.index = 0 # first image in list
self.elapsed = 0
self.playingStartTime = time.time()
self.elapsedStopTime = self.endTimesList[-1] # end of last animation image time
self.nextElapsedThreshold = self.endTimesList[0]
self.nIterationsLeft = self.nTimes # typically 1
elif self.state == PygAnimation.PAUSED: # restart where we left off
self.playingStartTime = time.time() - self.elapsedAtPause # recalc start time
self.elapsed = self.elapsedAtPause
self.elapsedStopTime = self.endTimesList[-1] # end of last animation image time
self.nextElapsedThreshold = self.endTimesList[self.index]
self.state = PygAnimation.PLAYING |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.