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(self):
"""Return the results now. :return: the membership request results :rtype: :class:`~groupy.api.memberships.MembershipResult.Results` :raises group... |
if self._expired_exception:
raise self._expired_exception
if self._not_ready_exception:
raise self._not_ready_exception
return self.results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list(self, page=1, per_page=10, omit=None):
"""List groups by page. The API allows certain fields to be excluded from the results so that very large groups c... |
return pagers.GroupList(self, self._raw_list, page=page,
per_page=per_page, omit=omit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_former(self):
"""List all former groups. :return: a list of groups :rtype: :class:`list` """ |
url = utils.urljoin(self.url, 'former')
response = self.session.get(url)
return [Group(self, **group) for group in response.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 get(self, id):
"""Get a single group by ID. :param str id: a group ID :return: a group :rtype: :class:`~groupy.api.groups.Group` """ |
url = utils.urljoin(self.url, id)
response = self.session.get(url)
return Group(self, **response.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(self, id, name=None, description=None, image_url=None, office_mode=None, share=None, **kwargs):
"""Update the details of a group. .. note:: There are ... |
path = '{}/update'.format(id)
url = utils.urljoin(self.url, path)
payload = {
'name': name,
'description': description,
'image_url': image_url,
'office_mode': office_mode,
'share': share,
}
payload.update(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 destroy(self, id):
"""Destroy a group. :param str id: a group ID :return: ``True`` if successful :rtype: bool """ |
path = '{}/destroy'.format(id)
url = utils.urljoin(self.url, path)
response = self.session.post(url)
return response.ok |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join(self, group_id, share_token):
"""Join a group using a share token. :param str group_id: the group_id of a group :param str share_token: the share token ... |
path = '{}/join/{}'.format(group_id, share_token)
url = utils.urljoin(self.url, path)
response = self.session.post(url)
group = response.data['group']
return Group(self, **group) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rejoin(self, group_id):
"""Rejoin a former group. :param str group_id: the group_id of a group :return: the group :rtype: :class:`~groupy.api.groups.Group` "... |
url = utils.urljoin(self.url, 'join')
payload = {'group_id': group_id}
response = self.session.post(url, json=payload)
return Group(self, **response.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 change_owners(self, group_id, owner_id):
"""Change the owner of a group. .. note:: you must be the owner to change owners :param str group_id: the group_id o... |
url = utils.urljoin(self.url, 'change_owners')
payload = {
'requests': [{
'group_id': group_id,
'owner_id': owner_id,
}],
}
response = self.session.post(url, json=payload)
result, = response.data['results'] # should be exa... |
<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(self, name=None, description=None, image_url=None, office_mode=None, share=None, **kwargs):
"""Update the details of the group. :param str name: group... |
# note we default to the current values for name and office_mode as a
# work-around for issues with the group update endpoint
if name is None:
name = self.name
if office_mode is None:
office_mode = self.office_mode
return self.manager.update(id=self.id, 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 refresh_from_server(self):
"""Refresh the group from the server in place.""" |
group = self.manager.get(id=self.id)
self.__init__(self.manager, **group.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 get_membership(self):
"""Get your membership. Note that your membership may not exist. For example, you do not have a membership in a former group. Also, the... |
user_id = self._user.me['user_id']
for member in self.members:
if member.user_id == user_id:
return member
raise exceptions.MissingMembershipError(self.group_id, user_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 urljoin(base, path=None):
"""Join a base url with a relative path.""" |
# /foo/bar + baz makes /foo/bar/baz instead of /foo/baz
if path is None:
url = base
else:
if not base.endswith('/'):
base += '/'
url = urllib.parse.urljoin(base, str(path))
return 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_rfc3339(when):
"""Return an RFC 3339 timestamp. :param datetime.datetime when: a datetime in UTC :return: RFC 3339 timestamp :rtype: str """ |
microseconds = format(when.microsecond, '04d')[:4]
rfc3339 = '%Y-%m-%dT%H:%M:%S.{}Z'
return when.strftime(rfc3339.format(microseconds)) |
<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_filter(**tests):
"""Create a filter from keyword arguments.""" |
tests = [AttrTest(k, v) for k, v in tests.items()]
return Filter(tests) |
<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(self, objects):
"""Find exactly one match in the list of objects. :param objects: objects to filter :type objects: :class:`list` :return: the one matchi... |
matches = list(self.__call__(objects))
if not matches:
raise exceptions.NoMatchesError(objects, self.tests)
elif len(matches) > 1:
raise exceptions.MultipleMatchesError(objects, self.tests,
matches=matches)
return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list(self):
"""Return a list of bots. :return: all of your bots :rtype: :class:`list` """ |
response = self.session.get(self.url)
return [Bot(self, **bot) for bot in response.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(self, bot_id, text, attachments=None):
"""Post a new message as a bot to its room. :param str bot_id: the ID of the bot :param str text: the text of the... |
url = utils.urljoin(self.url, 'post')
payload = dict(bot_id=bot_id, text=text)
if attachments:
payload['attachments'] = [a.to_json() for a in attachments]
response = self.session.post(url, json=payload)
return response.ok |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def destroy(self, bot_id):
"""Destroy a bot. :param str bot_id: the ID of the bot to destroy :return: ``True`` if successful :rtype: bool """ |
url = utils.urljoin(self.url, 'destroy')
payload = {'bot_id': bot_id}
response = self.session.post(url, json=payload)
return response.ok |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post(self, text, attachments=None):
"""Post a message as the bot. :param str text: the text of the message :param attachments: a list of attachments :type at... |
return self.manager.post(self.bot_id, text, attachments) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten_until(is_leaf, xs):
""" Flatten a nested sequence. A sequence could be a nested list of lists or tuples or a combination of both :param is_leaf: Pred... |
def _flatten_until(items):
if isinstance(Iterable, items) and not is_leaf(items):
for item in items:
for i in _flatten_until(item):
yield i
else:
yield items
return list(_flatten_until(xs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flip(f):
""" Calls the function f by flipping the first two positional arguments """ |
def wrapped(*args, **kwargs):
return f(*flip_first_two(args), **kwargs)
f_spec = make_func_curry_spec(f)
return curry_by_spec(f_spec, wrapped) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cachier(stale_after=None, next_time=False, pickle_reload=True, mongetter=None):
"""A persistent, stale-free memoization decorator. The positional and keyword... |
# print('Inside the wrapper maker')
# print('mongetter={}'.format(mongetter))
# print('stale_after={}'.format(stale_after))
# print('next_time={}'.format(next_time))
if mongetter:
core = _MongoCore(mongetter, stale_after, next_time)
else:
core = _PickleCore( # pylint: 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 defineID(defid):
"""Search for UD's definition ID and return list of UrbanDefinition objects. Keyword arguments: defid -- definition ID to search for (int or... |
json = _get_urban_json(UD_DEFID_URL + urlquote(str(defid)))
return _parse_urban_json(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 has_external_dependency(name):
'Check that a non-Python dependency is installed.'
for directory in os.environ['PATH'].split(':'):
if os.path.exists(os.path.join(directory, name)):
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 with_vtk(plot=True):
""" Tests VTK interface and mesh repair of Stanford Bunny Mesh """ |
mesh = vtki.PolyData(bunny_scan)
meshfix = pymeshfix.MeshFix(mesh)
if plot:
print('Plotting input mesh')
meshfix.plot()
meshfix.repair()
if plot:
print('Plotting repaired mesh')
meshfix.plot()
return meshfix.mesh |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_arrays(self, v, f):
"""Loads triangular mesh from vertex and face numpy arrays. Both vertex and face arrays should be 2D arrays with each vertex contain... |
# Check inputs
if not isinstance(v, np.ndarray):
try:
v = np.asarray(v, np.float)
if v.ndim != 2 and v.shape[1] != 3:
raise Exception('Invalid vertex format. Shape ' +
'should be (npoints, 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 mesh(self):
"""Return the surface mesh""" |
triangles = np.empty((self.f.shape[0], 4))
triangles[:, -3:] = self.f
triangles[:, 0] = 3
return vtki.PolyData(self.v, triangles, deep=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 plot(self, show_holes=True):
""" Plot the mesh. Parameters show_holes : bool, optional Shows boundaries. Default True """ |
if show_holes:
edges = self.mesh.extract_edges(boundary_edges=True,
feature_edges=False,
manifold_edges=False)
plotter = vtki.Plotter()
plotter.add_mesh(self.mesh, label='mesh')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def repair(self, verbose=False, joincomp=False, remove_smallest_components=True):
"""Performs mesh repair using MeshFix's default repair process. Parameters verb... |
assert self.f.shape[1] == 3, 'Face array must contain three columns'
assert self.f.ndim == 2, 'Face array must be 2D'
self.v, self.f = _meshfix.clean_from_arrays(self.v, self.f,
verbose, joincomp,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def scrape(url, params=None, user_agent=None):
'''
Scrape a URL optionally with parameters.
This is effectively a wrapper around urllib2.urlopen.
'''
headers = {}
if user_agent:
headers['User-Agent'] = user_agent
data = params and six.moves.urllib.parse.urlencode(params) or 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 pdftoxml(pdfdata, options=""):
"""converts pdf file to xml file""" |
pdffout = tempfile.NamedTemporaryFile(suffix='.pdf')
pdffout.write(pdfdata)
pdffout.flush()
xmlin = tempfile.NamedTemporaryFile(mode='r', suffix='.xml')
tmpxml = xmlin.name # "temph.xml"
cmd = 'pdftohtml -xml -nodrm -zoom 1.5 -enc UTF-8 -noframes %s "%s" "%s"' % (
options, pdffout.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 execute(query, data=None):
""" Execute an arbitrary SQL query given by query, returning any results as a list of OrderedDicts. A list of values can be suppli... |
connection = _State.connection()
_State.new_transaction()
if data is None:
data = []
result = connection.execute(query, data)
_State.table = None
_State.metadata = None
try:
del _State.table_pending
except AttributeError:
pass
if not result.returns_rows:
... |
<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_table(table_name):
""" Specify the table to work on. """ |
_State.connection()
_State.reflect_metadata()
_State.table = sqlalchemy.Table(table_name, _State.metadata,
extend_existing=True)
if list(_State.table.columns.keys()) == []:
_State.table_pending = True
else:
_State.table_pending = 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 show_tables():
""" Return the names of the tables currently in the database. """ |
_State.connection()
_State.reflect_metadata()
metadata = _State.metadata
response = select('name, sql from sqlite_master where type="table"')
return {row['name']: row['sql'] for row in response} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_var(name, value):
""" Save a variable to the table specified by _State.vars_table_name. Key is the name of the variable, and value is the value. """ |
connection = _State.connection()
_State.reflect_metadata()
vars_table = sqlalchemy.Table(
_State.vars_table_name, _State.metadata,
sqlalchemy.Column('name', sqlalchemy.types.Text, primary_key=True),
sqlalchemy.Column('value_blob', sqlalchemy.types.LargeBinary),
sqlalchemy.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 get_var(name, default=None):
""" Returns the variable with the provided key from the table specified by _State.vars_table_name. """ |
alchemytypes = {"text": lambda x: x.decode('utf-8'),
"big_integer": lambda x: int(x),
"date": lambda x: x.decode('utf-8'),
"datetime": lambda x: x.decode('utf-8'),
"float": lambda x: float(x),
"large_binary": lambda... |
<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_index(column_names, unique=False):
""" Create a new index of the columns in column_names, where column_names is a list of strings. If unique is True, ... |
connection = _State.connection()
_State.reflect_metadata()
table_name = _State.table.name
table = _State.table
index_name = re.sub(r'[^a-zA-Z0-9]', '', table_name) + '_'
index_name += '_'.join(re.sub(r'[^a-zA-Z0-9]', '', x)
for x in column_names)
if unique:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit_row(connection, row, unique_keys):
""" Takes a row and checks to make sure it fits in the columns of the current table. If it does not fit, adds the requ... |
new_columns = []
for column_name, column_value in list(row.items()):
new_column = sqlalchemy.Column(column_name,
get_column_type(column_value))
if not column_name in list(_State.table.columns.keys()):
new_columns.append(new_column)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_table(unique_keys):
""" Save the table currently waiting to be created. """ |
_State.new_transaction()
_State.table.create(bind=_State.engine, checkfirst=True)
if unique_keys != []:
create_index(unique_keys, unique=True)
_State.table_pending = False
_State.reflect_metadata() |
<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_column(connection, column):
""" Add a column to the current table. """ |
stmt = alembic.ddl.base.AddColumn(_State.table.name, column)
connection.execute(stmt)
_State.reflect_metadata() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drop():
""" Drop the current table if it exists """ |
# Ensure the connection is up
_State.connection()
_State.table.drop(checkfirst=True)
_State.metadata.remove(_State.table)
_State.table = None
_State.new_transaction() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attach_attrs_table(key, value, fmt, meta):
"""Extracts attributes and attaches them to element.""" |
# We can't use attach_attrs_factory() because Table is a block-level element
if key in ['Table']:
assert len(value) == 5
caption = value[0] # caption, align, x, head, body
# Set n to the index where the attributes start
n = 0
while n < len(caption) and not \
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_tables(key, value, fmt, meta):
"""Processes the attributed tables.""" |
global has_unnumbered_tables # pylint: disable=global-statement
# Process block-level Table elements
if key == 'Table':
# Inspect the table
if len(value) == 5: # Unattributed, bail out
has_unnumbered_tables = True
if fmt in ['latex']:
return [Raw... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(self, messages):
"""Send a SMS message, or an array of SMS messages""" |
tmpSms = SMS(to='', message='')
if str(type(messages)) == str(type(tmpSms)):
messages = [messages]
xml_root = self.__init_xml('Message')
wrapper_id = 0
for m in messages:
m.wrapper_id = wrapper_id
msg = self.__build_sms_data(m)
... |
<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_xml(self, rootElementTag):
"""Init a etree element and pop a key in there""" |
xml_root = etree.Element(rootElementTag)
key = etree.SubElement(xml_root, "Key")
key.text = self.apikey
return xml_root |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __build_sms_data(self, message):
"""Build a dictionary of SMS message elements""" |
attributes = {}
attributes_to_translate = {
'to' : 'To',
'message' : 'Content',
'client_id' : 'ClientID',
'concat' : 'Concat',
'from_name': 'From',
'invalid_char_option' : 'InvalidCharOption',
'truncate' : 'Truncate',... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pstats2entries(data):
"""Helper to convert serialized pstats back to a list of raw entries. Converse operation of cProfile.Profile.snapshot_stats() """ |
# Each entry's key is a tuple of (filename, line number, function name)
entries = {}
allcallers = {}
# first pass over stats to build the list of entry instances
for code_info, call_info in data.stats.items():
# build a fake code object
code = Code(*code_info)
# build a fa... |
<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_installed(prog):
"""Return whether or not a given executable is installed on the machine.""" |
with open(os.devnull, 'w') as devnull:
try:
if os.name == 'nt':
retcode = subprocess.call(['where', prog], stdout=devnull)
else:
retcode = subprocess.call(['which', prog], stdout=devnull)
except OSError as e:
# If where or which do... |
<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():
"""Execute the converter using parameters provided on the command line""" |
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--outfile', metavar='output_file_path',
help="Save calltree stats to <outfile>")
parser.add_argument('-i', '--infile', metavar='input_file_path',
help="Read Python stats from <infile>")
parser... |
<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(profiling_data, outputfile):
"""convert `profiling_data` to calltree format and dump it to `outputfile` `profiling_data` can either be: - a pstats.St... |
converter = CalltreeConverter(profiling_data)
if is_basestring(outputfile):
with open(outputfile, "w") as f:
converter.output(f)
else:
converter.output(outputfile) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def output(self, out_file):
"""Write the converted entries to out_file""" |
self.out_file = out_file
out_file.write('event: ns : Nanoseconds\n')
out_file.write('events: ns\n')
self._output_summary()
for entry in sorted(self.entries, key=_entry_sort_key):
self._output_entry(entry) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visualize(self):
"""Launch kcachegrind on the converted entries. One of the executables listed in KCACHEGRIND_EXECUTABLES must be present in the system path.... |
available_cmd = None
for cmd in KCACHEGRIND_EXECUTABLES:
if is_installed(cmd):
available_cmd = cmd
break
if available_cmd is None:
sys.stderr.write("Could not find kcachegrind. Tried: %s\n" %
", ".join(KCACHE... |
<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_app(self, app, **kwargs):
""" Initializes the Flask-Bouncer extension for the specified application. :param app: The application. """ |
self.app = app
self._init_extension()
self.app.before_request(self.check_implicit_rules)
if kwargs.get('ensure_authorization', False):
self.app.after_request(self.check_authorization) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_authorization(self, response):
"""checks that an authorization call has been made during the request""" |
if not hasattr(request, '_authorized'):
raise Unauthorized
elif not request._authorized:
raise Unauthorized
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_implicit_rules(self):
automatically check the permissions for you """ |
if not self.request_is_managed_by_flask_classy():
return
if self.method_is_explictly_overwritten():
return
class_name, action = request.endpoint.split(':')
clazz = [classy_class for classy_class in self.flask_classy_classes if classy_class.__name__ == class_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 rotate_texture(texture, rotation, x_offset=0.5, y_offset=0.5):
"""Rotates the given texture by a given angle. Args: texture (texture):
the texture to rotate... |
x, y = texture
x = x.copy() - x_offset
y = y.copy() - y_offset
angle = np.radians(rotation)
x_rot = x * np.cos(angle) + y * np.sin(angle)
y_rot = x * -np.sin(angle) + y * np.cos(angle)
return x_rot + x_offset, y_rot + y_offset |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def turtle_to_texture(turtle_program, turn_amount=DEFAULT_TURN, initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1):
"""Makes a texture from a turtle program. Arg... |
generator = branching_turtle_generator(
turtle_program, turn_amount, initial_angle, resolution)
return texture_from_generator(generator) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform_multiple(sequence, transformations, iterations):
"""Chains a transformation a given number of times. Args: sequence (str):
a string or generator o... |
for _ in range(iterations):
sequence = transform_sequence(sequence, transformations)
return sequence |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def l_system(axiom, transformations, iterations=1, angle=45, resolution=1):
"""Generates a texture by running transformations on a turtle program. First, the giv... |
turtle_program = transform_multiple(axiom, transformations, iterations)
return turtle_to_texture(turtle_program, angle, resolution=resolution) |
<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_path(self, i):
"""Returns the path corresponding to the node i.""" |
index = (i - 1) // 2
reverse = (i - 1) % 2
path = self.paths[index]
if reverse:
return path.reversed()
else:
return 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 cost(self, i, j):
"""Returns the distance between the end of path i and the start of path j.""" |
return dist(self.endpoints[i][1], self.endpoints[j][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 get_coordinates(self, i, end=False):
"""Returns the starting coordinates of node i as a pair, or the end coordinates iff end is True.""" |
if end:
endpoint = self.endpoints[i][1]
else:
endpoint = self.endpoints[i][0]
return (endpoint.real, endpoint.imag) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_plot(plot, width=PREVIEW_WIDTH, height=PREVIEW_HEIGHT):
"""Preview a plot in a jupyter notebook. Args: plot (list):
the plot to display (list of layers... |
return SVG(data=plot_to_svg(plot, width, height)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculate_view_box(layers, aspect_ratio, margin=DEFAULT_VIEW_BOX_MARGIN):
"""Calculates the size of the SVG viewBox to use. Args: layers (list):
the layers ... |
min_x = min(np.nanmin(x) for x, y in layers)
max_x = max(np.nanmax(x) for x, y in layers)
min_y = min(np.nanmin(y) for x, y in layers)
max_y = max(np.nanmax(y) for x, y in layers)
height = max_y - min_y
width = max_x - min_x
if height > width * aspect_ratio:
adj_height = height * (... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _layer_to_path_gen(layer):
"""Generates an SVG path from a given layer. Args: layer (layer):
the layer to convert Yields: str: the next component of the pat... |
draw = False
for x, y in zip(*layer):
if np.isnan(x) or np.isnan(y):
draw = False
elif not draw:
yield 'M {} {}'.format(x, y)
draw = True
else:
yield 'L {} {}'.format(x, y) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_plot(plot, filename, width=DEFAULT_PAGE_WIDTH, height=DEFAULT_PAGE_HEIGHT, unit=DEFAULT_PAGE_UNIT):
"""Writes a plot SVG to a file. Args: plot (list):
... |
svg = plot_to_svg(plot, width, height, unit)
with open(filename, 'w') as outfile:
outfile.write(svg) |
<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_layer(ax, layer):
"""Draws a layer on the given matplotlib axis. Args: ax (axis):
the matplotlib axis to draw on layer (layer):
the layers to plot """ |
ax.set_aspect('equal', 'datalim')
ax.plot(*layer)
ax.axis('off') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map_texture_to_surface(texture, surface):
"""Returns values on a surface for points on a texture. Args: texture (texture):
the texture to trace over the sur... |
texture_x, texture_y = texture
surface_h, surface_w = surface.shape
surface_x = np.clip(
np.int32(surface_w * texture_x - 1e-9), 0, surface_w - 1)
surface_y = np.clip(
np.int32(surface_h * texture_y - 1e-9), 0, surface_h - 1)
surface_z = surface[surface_y, surface_x]
return su... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_texture(texture_xy, texture_z, angle=DEFAULT_ANGLE):
"""Creates a texture by adding z-values to an existing texture and projecting. When working with... |
z_coef = np.sin(np.radians(angle))
y_coef = np.cos(np.radians(angle))
surface_x, surface_y = texture
return (surface_x, -surface_y * y_coef + surface_z * z_coef) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_surface(surface, angle=DEFAULT_ANGLE):
"""Returns the height of the surface when projected at the given angle. Args: surface (surface):
the surface ... |
z_coef = np.sin(np.radians(angle))
y_coef = np.cos(np.radians(angle))
surface_height, surface_width = surface.shape
slope = np.tile(np.linspace(0., 1., surface_height), [surface_width, 1]).T
return slope * y_coef + surface * z_coef |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_texture_on_surface(texture, surface, angle=DEFAULT_ANGLE):
"""Maps a texture onto a surface, then projects to 2D and returns a layer. Args: texture (... |
projected_surface = project_surface(surface, angle)
texture_x, _ = texture
texture_y = map_texture_to_surface(texture, projected_surface)
return texture_x, texture_y |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _remove_hidden_parts(projected_surface):
"""Removes parts of a projected surface that are not visible. Args: projected_surface (surface):
the surface to use... |
surface = np.copy(projected_surface)
surface[~_make_occlusion_mask(projected_surface)] = np.nan
return surface |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_and_occlude_texture(texture, surface, angle=DEFAULT_ANGLE):
"""Projects a texture onto a surface with occluded areas removed. Args: texture (texture)... |
projected_surface = project_surface(surface, angle)
projected_surface = _remove_hidden_parts(projected_surface)
texture_y = map_texture_to_surface(texture, projected_surface)
texture_x, _ = texture
return texture_x, texture_y |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_lines_texture(num_lines=10, resolution=50):
"""Makes a texture consisting of a given number of horizontal lines. Args: num_lines (int):
the number of l... |
x, y = np.meshgrid(
np.hstack([np.linspace(0, 1, resolution), np.nan]),
np.linspace(0, 1, num_lines),
)
y[np.isnan(x)] = np.nan
return x.flatten(), y.flatten() |
<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_grid_texture(num_h_lines=10, num_v_lines=10, resolution=50):
"""Makes a texture consisting of a grid of vertical and horizontal lines. Args: num_h_lines... |
x_h, y_h = make_lines_texture(num_h_lines, resolution)
y_v, x_v = make_lines_texture(num_v_lines, resolution)
return np.concatenate([x_h, x_v]), np.concatenate([y_h, y_v]) |
<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_spiral_texture(spirals=6.0, ccw=False, offset=0.0, resolution=1000):
"""Makes a texture consisting of a spiral from the origin. Args: spirals (float):
... |
dist = np.sqrt(np.linspace(0., 1., resolution))
if ccw:
direction = 1.
else:
direction = -1.
angle = dist * spirals * np.pi * 2. * direction
spiral_texture = (
(np.cos(angle) * dist / 2.) + 0.5,
(np.sin(angle) * dist / 2.) + 0.5
)
return spiral_texture |
<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_hex_texture(grid_size = 2, resolution=1):
"""Makes a texture consisting on a grid of hexagons. Args: grid_size (int):
the number of hexagons along each... |
grid_x, grid_y = np.meshgrid(
np.arange(grid_size),
np.arange(grid_size)
)
ROOT_3_OVER_2 = np.sqrt(3) / 2
ONE_HALF = 0.5
grid_x = (grid_x * np.sqrt(3) + (grid_y % 2) * ROOT_3_OVER_2).flatten()
grid_y = grid_y.flatten() * 1.5
grid_points = grid_x.shape[0]
x... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_noise_surface(dims=DEFAULT_DIMS, blur=10, seed=None):
"""Makes a surface by generating random noise and blurring it. Args: dims (pair):
the dimensions ... |
if seed is not None:
np.random.seed(seed)
return gaussian_filter(np.random.normal(size=dims), blur) |
<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_gradients(dims=DEFAULT_DIMS):
"""Makes a pair of gradients to generate textures from numpy primitives. Args: dims (pair):
the dimensions of the surface... |
return np.meshgrid(
np.linspace(0.0, 1.0, dims[0]),
np.linspace(0.0, 1.0, dims[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 make_sine_surface(dims=DEFAULT_DIMS, offset=0.5, scale=1.0):
"""Makes a surface from the 3D sine function. Args: dims (pair):
the dimensions of the surface ... |
gradients = (np.array(make_gradients(dims)) - offset) * scale * np.pi
return np.sin(np.linalg.norm(gradients, axis=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 make_bubble_surface(dims=DEFAULT_DIMS, repeat=3):
"""Makes a surface from the product of sine functions on each axis. Args: dims (pair):
the dimensions of t... |
gradients = make_gradients(dims)
return (
np.sin((gradients[0] - 0.5) * repeat * np.pi) *
np.sin((gradients[1] - 0.5) * repeat * np.pi)) |
<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_controller(url):
"""Initialize a controller. Provides a single global controller for applications that can't do this themselves """ |
# pylint: disable=global-statement
global _VERA_CONTROLLER
created = False
if _VERA_CONTROLLER is None:
_VERA_CONTROLLER = VeraController(url)
created = True
_VERA_CONTROLLER.start()
return [_VERA_CONTROLLER, created] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_request(self, payload, timeout=TIMEOUT):
"""Perform a data_request and return the result.""" |
request_url = self.base_url + "/data_request"
return requests.get(request_url, timeout=timeout, params=payload) |
<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_simple_devices_info(self):
"""Get basic device info from Vera.""" |
j = self.data_request({'id': 'sdata'}).json()
self.scenes = []
items = j.get('scenes')
for item in items:
self.scenes.append(VeraScene(item, self))
if j.get('temperature'):
self.temperature_units = j.get('temperature')
self.categories = {}
... |
<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_device_by_name(self, device_name):
"""Search the list of connected devices by name. device_name param is the string name of the device """ |
# Find the device for the vera device name we are interested in
found_device = None
for device in self.get_devices():
if device.name == device_name:
found_device = device
# found the first (and should be only) one so we will finish
break
... |
<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_device_by_id(self, device_id):
"""Search the list of connected devices by ID. device_id param is the integer ID of the device """ |
# Find the device for the vera device name we are interested in
found_device = None
for device in self.get_devices():
if device.device_id == device_id:
found_device = device
# found the first (and should be only) one so we will finish
break... |
<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_devices(self, category_filter=''):
"""Get list of connected devices. category_filter param is an array of strings """ |
# pylint: disable=too-many-branches
# the Vera rest API is a bit rough so we need to make 2 calls to get
# all the info e need
self.get_simple_devices_info()
j = self.data_request({'id': 'status', 'output_format': 'json'}).json()
self.devices = []
items = j.ge... |
<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_data(self):
"""Refresh data from Vera device.""" |
j = self.data_request({'id': 'sdata'}).json()
self.temperature_units = j.get('temperature', 'C')
self.model = j.get('model')
self.version = j.get('version')
self.serial_number = j.get('serial_number')
categories = {}
cats = j.get('categories')
for cat ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map_services(self):
"""Get full Vera device service info.""" |
# the Vera rest API is a bit rough so we need to make 2 calls
# to get all the info e need
self.get_simple_devices_info()
j = self.data_request({'id': 'status', 'output_format': 'json'}).json()
service_map = {}
items = j.get('devices')
for item in items:
... |
<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_changed_devices(self, timestamp):
"""Get data since last timestamp. This is done via a blocking call, pass NONE for initial state. """ |
if timestamp is None:
payload = {}
else:
payload = {
'timeout': SUBSCRIPTION_WAIT,
'minimumdelay': SUBSCRIPTION_MIN_WAIT
}
payload.update(timestamp)
# double the timeout here so requests doesn't timeout before vera
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vera_request(self, **kwargs):
"""Perfom a vera_request for this device.""" |
request_payload = {
'output_format': 'json',
'DeviceNum': self.device_id,
}
request_payload.update(kwargs)
return self.vera_controller.data_request(request_payload) |
<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_service_value(self, service_id, set_name, parameter_name, value):
"""Set a variable on the vera device. This will call the Vera api to change device stat... |
payload = {
'id': 'lu_action',
'action': 'Set' + set_name,
'serviceId': service_id,
parameter_name: value
}
result = self.vera_request(**payload)
logger.debug("set_service_value: "
"result of vera_request with payload %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 call_service(self, service_id, action):
"""Call a Vera service. This will call the Vera api to change device state. """ |
result = self.vera_request(id='action', serviceId=service_id,
action=action)
logger.debug("call_service: "
"result of vera_request with id %s: %s", service_id,
result.text)
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 set_cache_value(self, name, value):
"""Set a variable in the local state dictionary. This does not change the physical device. Useful if you want the device ... |
dev_info = self.json_state.get('deviceInfo')
if dev_info.get(name.lower()) is None:
logger.error("Could not set %s for %s (key does not exist).",
name, self.name)
logger.error("- dictionary %s", dev_info)
return
dev_info[name.lower()] = ... |
<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_cache_complex_value(self, name, value):
"""Set a variable in the local complex state dictionary. This does not change the physical device. Useful if you ... |
for item in self.json_state.get('states'):
if item.get('variable') == name:
item['value'] = str(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_complex_value(self, name):
"""Get a value from the service dictionaries. It's best to use get_value if it has the data you require since the vera subscri... |
for item in self.json_state.get('states'):
if item.get('variable') == name:
return item.get('value')
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_strict_value(self, name):
"""Get a case-sensitive keys value from the dev_info area. """ |
dev_info = self.json_state.get('deviceInfo')
return dev_info.get(name, 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 refresh_complex_value(self, name):
"""Refresh a value from the service dictionaries. It's best to use get_value / refresh if it has the data you need. """ |
for item in self.json_state.get('states'):
if item.get('variable') == name:
service_id = item.get('service')
result = self.vera_request(**{
'id': 'variableget',
'output_format': 'json',
'DeviceNum': self.dev... |
<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(self):
"""Refresh the dev_info data used by get_value. Only needed if you're not using subscriptions. """ |
j = self.vera_request(id='sdata', output_format='json').json()
devices = j.get('devices')
for device_data in devices:
if device_data.get('id') == self.device_id:
self.update(device_data) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.