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 loads(astring):
"""Decompress and deserialize string into a Python object via pickle.""" |
try:
return pickle.loads(lzma.decompress(astring))
except lzma.LZMAError as e:
raise SerializerError(
'Cannot decompress object ("{}")'.format(str(e))
)
except pickle.UnpicklingError as e:
raise SerializerError(
'Cannot restore object ("{}")'.format(str(e))
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self, path_expression, mode=UXP, values=None, ifunc=lambda x: x):
""" find matches for the given path expression in the data :param path_expression: path tuple or string :return: """ |
# keys = path_expression if isinstance(path_expression, six.string_types) else path_expression[-1]
path_and_value_list = iterutils.search(
self.data,
path_expression=path_expression,
required_values=values,
exact=(mode[1] == "x"))
return self.__return_value(path_and_value_list, mode, ifunc) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __visit_index_path(self, src, p, k, v):
""" Called during processing of source data """ |
cp = p + (k,)
self.path_index[cp] = self.indexed_obj_factory(p, k, v, self.path_index.get(cp))
if cp in self.path_index:
# if self.path_index[cp].assert_val_equals(v):
# raise ValueError('unexpected value change at path_index[{}]'.format(cp))
self.path_index[cp].add_src(src)
else:
self.path_index[cp] = Flobject(val=v, path=cp, srcs=set([src])) |
<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_default_data_path(*args, module=None, class_=None, flag_raise=True):
""" Returns path to default data directory Arguments 'module' and 'class' give the chance to return path relative to package other than f311.filetypes Args: module: Python module object. It is expected that this module has a sub-subdirectory named 'data/default' class_: Python class object to extract path information from. If this argument is used, it will be expected that the class "root" package will have a sub-subdirectory named 'data/default'. Argument 'class_' **has precedence over argument 'module'** flag_raise: raises error if file is not found. This can be turned off for whichever purpose """ |
if module is None:
module = __get_filetypes_module()
if class_ is not None:
pkgname = class_.__module__
mseq = pkgname.split(".")
if len(mseq) < 2 or mseq[1] != "filetypes":
raise ValueError("Invalid module name for class '{}': '{}' "
"(must be '(...).filetypes[.(...)]')".format(class_.__name__, pkgname))
# gets "root" module object
# For example, if pkgname is "pyfant.filetypes.filemain", module below will be
# the "pyfant" module object
module = sys.modules[mseq[0]]
module_path = os.path.split(module.__file__)[0]
p = os.path.abspath(os.path.join(module_path, "data", "default", *args))
if flag_raise:
if not os.path.isfile(p):
raise RuntimeError("Path not found '{}'".format(p))
return p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_default_data_file(filename, module=None):
"""Copies file from default data directory to local directory.""" |
if module is None:
module = __get_filetypes_module()
fullpath = get_default_data_path(filename, module=module)
shutil.copy(fullpath, ".") |
<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_display(self):
""" Find a usable display, which doesn't have an existing Xvfb file """ |
self.display_num = 2
while os.path.isdir(XVFB_PATH % (self.display_num,)):
self.display_num += 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 comments(recid):
"""Display comments.""" |
from invenio_access.local_config import VIEWRESTRCOLL
from invenio_access.mailcookie import \
mail_cookie_create_authorize_action
from .api import check_user_can_view_comments
auth_code, auth_msg = check_user_can_view_comments(current_user, recid)
if auth_code and current_user.is_guest:
cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {
'collection': g.collection})
url_args = {'action': cookie, 'ln': g.ln, 'referer': request.referrer}
flash(_("Authorization failure"), 'error')
return redirect(url_for('webaccount.login', **url_args))
elif auth_code:
flash(auth_msg, 'error')
abort(401)
# FIXME check restricted discussion
comments = CmtRECORDCOMMENT.query.filter(db.and_(
CmtRECORDCOMMENT.id_bibrec == recid,
CmtRECORDCOMMENT.in_reply_to_id_cmtRECORDCOMMENT == 0,
CmtRECORDCOMMENT.star_score == 0
)).order_by(CmtRECORDCOMMENT.date_creation).all()
return render_template('comments/comments.html', comments=comments,
option='comments') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getattr(self, key, default=None, callback=None):
u"""Getting the attribute of an element. 'text' 'TEXT' 'default' """ |
value = self._xml.text if key == 'text' else self._xml.get(key, default)
return callback(value) if callback else 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 setattr(self, key, value):
u"""Sets an attribute on a node. 'text2' 'val' """ |
if key == 'text':
self._xml.text = str(value)
else:
self._xml.set(key, 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(self, default=None, callback=None):
u"""Returns leaf's value.""" |
value = self._xml.text if self._xml.text else default
return callback(value) if callback else 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 to_str(self, pretty_print=False, encoding=None, **kw):
u"""Converts a node with all of it's children to a string. Remaining arguments are passed to etree.tostring as is. kwarg without_comments: bool because it works only in C14N flags: 'pretty print' and 'encoding' are ignored. :param bool pretty_print: whether to format the output :param str encoding: which encoding to use (ASCII by default) :rtype: str :returns: node's representation as a string """ |
if kw.get('without_comments') and not kw.get('method'):
kw.pop('without_comments')
kw['method'] = 'c14n'
kw['with_comments'] = False
return etree.tostring(
self._xml,
pretty_print=pretty_print,
encoding=encoding,
**kw
) |
<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_children(self, key=None):
u"""Iterates over children. :param key: A key for filtering children by tagname. """ |
tag = None
if key:
tag = self._get_aliases().get(key)
if not tag:
raise KeyError(key)
for child in self._xml.iterchildren(tag=tag):
if len(child):
yield self.__class__(child)
else:
yield Literal(child) |
<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, **kwargs):
u"""Updating or creation of new simple nodes. Each dict key is used as a tagname and value as text. """ |
for key, value in kwargs.items():
helper = helpers.CAST_DICT.get(type(value), str)
tag = self._get_aliases().get(key, key)
elements = list(self._xml.iterchildren(tag=tag))
if elements:
for element in elements:
element.text = helper(value)
else:
element = etree.Element(key)
element.text = helper(value)
self._xml.append(element)
self._aliases = 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 sget(self, path, default=NONE_NODE):
u"""Enables access to nodes if one or more of them don't exist. Example: text value 'attr text' 'text value' NONE_NODE Accessing nonexistent path returns None-like object with mocked converting functions which returns None: True """ |
attrs = str(path).split(".")
text_or_attr = None
last_attr = attrs[-1]
# Case of getting text or attribute
if last_attr == '#text' or last_attr.startswith('@'):
# #text => text, @attr => attr
text_or_attr = last_attr[1:]
attrs = attrs[:-1]
# When getting #text and @attr we want default value to be None.
if default is NONE_NODE:
default = None
my_object = self
for attr in attrs:
try:
if isinstance(my_object, (list, tuple)) and re.match('^\-?\d+$', attr):
my_object_next = my_object[int(attr)]
else:
my_object_next = getattr(my_object, attr)
my_object = my_object_next
except (AttributeError, KeyError, IndexError):
return default
# Return #text or @attr
if text_or_attr:
try:
return my_object.getattr(text_or_attr)
except AttributeError:
# myObject can be a list.
return None
else:
return my_object |
<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, tag, value):
u"""Creates a node, if it doesn't exist yet. Unlike attribute access, this allows to pass a node's name with hyphens. Those hyphens will be normalized automatically. In case the required element already exists, raises an exception. Updating/overwriting should be done using `update``. """ |
child_tags = {child.tag for child in self._xml}
if tag in child_tags:
raise KeyError('Node {} already exists in XML tree.'.format(tag))
self.set(tag, 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, name, value):
u"""Assigns a new XML structure to the node. A literal value, dict or list can be passed in. Works for all nested levels. Dictionary: '<head><a>A</a><b attr="val">B</b></head>' List: '<head><a>A</a><a>B</a><a>C</a></head>' Literals: 'A' """ |
try:
# Searches for a node to assign to.
element = next(self._xml.iterchildren(tag=name))
except StopIteration:
# There is no such node in the XML tree. We create a new one
# with current root as parent (self._xml).
element = etree.SubElement(self._xml, name)
if isinstance(value, dict):
self.assign_dict(element, value)
elif isinstance(value, (list, tuple, set)):
self.assign_sequence_or_set(element, value)
else:
# Literal value.
self.assign_literal(element, value)
# Clear the aliases.
self._aliases = 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 assign_dict(self, node, xml_dict):
"""Assigns a Python dict to a ``lxml`` node. :param node: A node to assign the dict to. :param xml_dict: The dict with attributes/children to use. """ |
new_node = etree.Element(node.tag)
# Replaces the previous node with the new one
self._xml.replace(node, new_node)
# Copies #text and @attrs from the xml_dict
helpers.dict_to_etree(xml_dict, new_node) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assign_literal(element, value):
u"""Assigns a literal. If a given node doesn't exist, it will be created. :param etree.Element element: element to which we assign. :param value: the value to assign """ |
# Searches for a conversion method specific to the type of value.
helper = helpers.CAST_DICT.get(type(value), str)
# Removes all children and attributes.
element.clear()
element.text = helper(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 to_dict(self, **kw):
u"""Converts the lxml object to a dict. possible kwargs: without_comments: bool """ |
_, value = helpers.etree_to_dict(self._xml, **kw).popitem()
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 _get_aliases(self):
u"""Creates a dict with aliases. The key is a normalized tagname, value the original tagname. """ |
if self._aliases is None:
self._aliases = {}
if self._xml is not None:
for child in self._xml.iterchildren():
self._aliases[helpers.normalize_tag(child.tag)] = child.tag
return self._aliases |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xpath( self, path, namespaces=None, regexp=False, smart_strings=True, single_use=False, ):
u"""Executes XPath query on the ``lxml`` object and returns a correct object. :param str path: XPath string e.g., 'cars'/'car' :param str/dict namespaces: e.g., 'exslt', 're' or ``{'re': "http://exslt.org/regular-expressions"}`` :param bool regexp: if ``True`` and no namespaces is provided, it will use ``exslt`` namespace :param bool smart_strings: :param bool single_use: faster method for using only once. Does not create ``XPathEvaluator`` instance. "//*[re:test(., '^abc$', 'i')]", namespaces='exslt', regexp=True, ) """ |
if (
namespaces in ['exslt', 're'] or
(regexp and not namespaces)
):
namespaces = {'re': "http://exslt.org/regular-expressions"}
if single_use:
node = self._xml.xpath(path)
else:
xpe = self.xpath_evaluator(
namespaces=namespaces,
regexp=regexp,
smart_strings=smart_strings
)
node = xpe(path)
if len(node) == 1:
node = node[0]
if len(node):
return self.__class__(node)
else:
return Literal(node)
return node |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xpath_evaluator(self, namespaces=None, regexp=False, smart_strings=True):
u"""Creates an XPathEvaluator instance for an ElementTree or an Element. :returns: ``XPathEvaluator`` instance """ |
return etree.XPathEvaluator(
self._xml,
namespaces=namespaces,
regexp=regexp,
smart_strings=smart_strings
) |
<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_last_modified_date(*args, **kwargs):
"""Returns the date of the last modified Note or Release. For use with Django's last_modified decorator. """ |
try:
latest_note = Note.objects.latest()
latest_release = Release.objects.latest()
except ObjectDoesNotExist:
return None
return max(latest_note.modified, latest_release.modified) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def using_ios_stash():
''' returns true if sys path hints the install is running on ios '''
print('detected install path:')
print(os.path.dirname(__file__))
module_names = set(sys.modules.keys())
return 'stash' in module_names or 'stash.system' in module_names |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_partition_scores(image, min_w=1, min_h=1):
"""Return list of best to worst binary splits along the x and y axis.
""" |
h, w = image.shape[:2]
if w == 0 or h == 0:
return []
area = h * w
cnz = numpy.count_nonzero
total = cnz(image)
if total == 0 or area == total:
return []
if h < min_h * 2:
y_c = []
else:
y_c = [(-abs((count / ((h - y) * w)) - ((total - count) / (y * w))),
y, 0)
for count, y in ((cnz(image[y:]), y)
for y in range(min_h, image.shape[0] - min_h))]
if w < min_w * 2:
x_c = []
else:
x_c = [(-abs((count / (h * (w - x))) - ((total - count) / (h * x))),
x, 1)
for count, x in ((cnz(image[:, x:]), x)
for x in range(min_w, image.shape[1] - min_w))]
return sorted(x_c + y_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 __init_defaults(self, config):
"""Initializes the default connection settings.""" |
provider = self.__provider
if provider == 'sqlite':
config.setdefault('dbname', ':memory:')
config.setdefault('create_db', True)
elif provider == 'mysql':
config.setdefault('port', 3306)
config.setdefault('charset', 'utf8')
elif provider == 'postgres':
config.setdefault('port', 5432)
elif provider == 'oracle':
config.setdefault('port', 1521)
else:
raise ValueError('Unsupported provider "{}"'.format(provider))
if provider != 'sqlite':
config.setdefault('host', 'localhost')
config.setdefault('user', None)
config.setdefault('password', None)
config.setdefault('dbname', None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def newnations(self, root):
"""Most recently founded nations, from newest. Returns ------- an :class:`ApiQuery` of a list of :class:`Nation` """ |
return [aionationstates.Nation(n)
for n in root.find('NEWNATIONS').text.split(',')] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def regions(self, root):
"""List of all the regions, seemingly in order of creation. Returns ------- an :class:`ApiQuery` of a list of :class:`Region` """ |
return [aionationstates.Region(r)
for r in root.find('REGIONS').text.split(',')] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def regionsbytag(self, *tags):
"""All regions with any of the named tags. Parameters *tags : str Regional tags. Can be preceded by a ``-`` to select regions without that tag. Returns ------- an :class:`ApiQuery` of a list of :class:`Region` """ |
if len(tags) > 10:
raise ValueError('You can specify up to 10 tags')
if not tags:
raise ValueError('No tags specified')
# We don't check for invalid tags here because the behaviour is
# fairly intuitive - quering for a non-existent tag returns no
# regions, excluding it returns all of them.
@api_query('regionsbytag', tags=','.join(tags))
async def result(_, root):
text = root.find('REGIONS').text
return ([aionationstates.Region(r) for r in text.split(',')]
if text else [])
return result(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch(self, id):
"""Dispatch by id. Parameters id : int Dispatch id. Returns ------- an :class:`ApiQuery` of :class:`Dispatch` Raises ------ :class:`NotFound` If a dispatch with the requested id doesn't exist. """ |
@api_query('dispatch', dispatchid=str(id))
async def result(_, root):
elem = root.find('DISPATCH')
if not elem:
raise NotFound(f'No dispatch found with id {id}')
return Dispatch(elem)
return result(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatchlist(self, *, author=None, category=None, subcategory=None, sort='new'):
"""Find dispatches by certain criteria. Parameters author : str Name of the nation authoring the dispatch. category : str Dispatch's primary category. subcategory : str Dispatch's secondary category. sort : str Sort order, 'new' or 'best'. Returns ------- an :class:`ApiQuery` of a list of :class:`DispatchThumbnail` """ |
params = {'sort': sort}
if author:
params['dispatchauthor'] = author
# Here we do need to ensure that our categories are valid, cause
# NS just ignores the categories it doesn't recognise and returns
# whatever it feels like.
if category and subcategory:
if (category not in dispatch_categories or
subcategory not in dispatch_categories[category]):
raise ValueError('Invalid category/subcategory')
params['dispatchcategory'] = f'{category}:{subcategory}'
elif category:
if category not in dispatch_categories:
raise ValueError('Invalid category')
params['dispatchcategory'] = category
else:
raise ValueError('Cannot request subcategory without category')
@api_query('dispatchlist', **params)
async def result(_, root):
return [
DispatchThumbnail._from_elem(elem)
for elem in root.find('DISPATCHLIST')
]
return result(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def poll(self, id):
"""Poll with a given id. Parameters id : int Poll id. Returns ------- an :class:`ApiQuery` of :class:`Poll` Raises ------ :class:`NotFound` If a poll with the requested id doesn't exist. """ |
@api_query('poll', pollid=str(id))
async def result(_, root):
elem = root.find('POLL')
if not elem:
raise NotFound(f'No poll found with id {id}')
return Poll(elem)
return result(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def banner(self, *ids, _expand_macros=None):
"""Get data about banners by their ids. Macros in banners' names and descriptions are not expanded. Parameters *ids : str Banner ids. Returns ------- an :class:`ApiQuery` of a list of :class:`Banner` Raises ------ :class:`NotFound` If any of the provided ids is invalid. """ |
async def noop(s):
return s
_expand_macros = _expand_macros or noop
@api_query('banner', banner=','.join(ids))
async def result(_, root):
banners = [await Banner(elem, _expand_macros)
for elem in root.find('BANNERS')]
if not len(banners) == len(ids):
raise NotFound('one of the banner ids provided is invalid')
return banners
return result(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def send_telegram(self, *, client_key, telegram_id, telegram_key, recepient):
"""A basic interface to the Telegrams API. Parameters client_key : str Telegrams API Client Key. telegram_id : int or str Telegram id. telegram_key : str Telegram key. recepient : str Name of the nation you want to telegram. Returns ------- an awaitable """ |
params = {
'a': 'sendTG',
'client': client_key,
'tgid': str(telegram_id),
'key': telegram_key,
'to': recepient
}
return await self._call_api(params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def happenings(self, *, nations=None, regions=None, filters=None, beforeid=None, beforetime=None):
"""Iterate through happenings from newest to oldest. Parameters nations : iterable of str Nations happenings of which will be requested. Cannot be specified at the same time with ``regions``. regions : iterable of str Regions happenings of which will be requested. Cannot be specified at the same time with ``nations``. filters : iterable of str Categories to request happenings by. Available filters are: ``law``, ``change``, ``dispatch``, ``rmb``, ``embassy``, ``eject``, ``admin``, ``move``, ``founding``, ``cte``, ``vote``, ``resolution``, ``member``, and ``endo``. beforeid : int Only request happenings before this id. beforetime : :class:`datetime.datetime` Only request happenings that were emitted before this moment. Returns ------- an asynchronous iterator yielding any of the classes from \ the :mod:`~aionationstates.happenings` module """ |
while True:
happening_bunch = await self._get_happenings(
nations=nations, regions=regions, filters=filters,
beforeid=beforeid, beforetime=beforetime
)
for happening in happening_bunch:
yield happening
if len(happening_bunch) < 100:
break
beforeid = happening_bunch[-1].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 find_potential_match_regions(template, transformed_array, method='correlation', raw_tolerance=0.666):
"""To prevent prohibitively slow calculation of normalisation coefficient at each point in image find potential match points, and normalise these only these. This function uses the definitions of the matching functions to calculate the expected match value and finds positions in the transformed array matching these- normalisation will then eliminate false positives """ |
if method == 'correlation':
match_value = np.sum(template**2) # this will be the value of the match in the
elif method == 'squared difference':
match_value = 0
elif method == 'correlation coefficient':
temp_minus_mean = template - np.mean(template)
match_value = np.sum(temp_minus_mean**2)
else:
raise ValueError('Matching method not implemented')
condition = ((np.round(transformed_array, decimals=3)>=match_value*raw_tolerance) &
(np.round(transformed_array, decimals=3)<=match_value*(1./raw_tolerance)))
return np.transpose(condition.nonzero()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalise_correlation(image_tile_dict, transformed_array, template, normed_tolerance=1):
"""Calculates the normalisation coefficients of potential match positions Then normalises the correlation at these positions, and returns them if they do indeed constitute a match """ |
template_norm = np.linalg.norm(template)
image_norms = {(x,y):np.linalg.norm(image_tile_dict[(x,y)])*template_norm for (x,y) in image_tile_dict.keys()}
match_points = image_tile_dict.keys()
# for correlation, then need to transofrm back to get correct value for division
h, w = template.shape
#points_from_transformed_array = [(match[0] + h - 1, match[1] + w - 1) for match in match_points]
image_matches_normalised = {match_points[i]:transformed_array[match_points[i][0], match_points[i][1]]/image_norms[match_points[i]] for i in range(len(match_points))}
result = {key:value for key, value in image_matches_normalised.items() if np.round(value, decimals=3) >= normed_tolerance}
return result.keys() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalise_correlation_coefficient(image_tile_dict, transformed_array, template, normed_tolerance=1):
"""As above, but for when the correlation coefficient matching method is used """ |
template_mean = np.mean(template)
template_minus_mean = template - template_mean
template_norm = np.linalg.norm(template_minus_mean)
image_norms = {(x,y):np.linalg.norm(image_tile_dict[(x,y)]- np.mean(image_tile_dict[(x,y)]))*template_norm for (x,y) in image_tile_dict.keys()}
match_points = image_tile_dict.keys()
# for correlation, then need to transofrm back to get correct value for division
h, w = template.shape
image_matches_normalised = {match_points[i]:transformed_array[match_points[i][0], match_points[i][1]]/image_norms[match_points[i]] for i in range(len(match_points))}
normalised_matches = {key:value for key, value in image_matches_normalised.items() if np.round(value, decimals=3) >= normed_tolerance}
return normalised_matches.keys() |
<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_squared_differences(image_tile_dict, transformed_array, template, sq_diff_tolerance=0.1):
"""As above, but for when the squared differences matching method is used """ |
template_norm_squared = np.sum(template**2)
image_norms_squared = {(x,y):np.sum(image_tile_dict[(x,y)]**2) for (x,y) in image_tile_dict.keys()}
match_points = image_tile_dict.keys()
# for correlation, then need to transofrm back to get correct value for division
h, w = template.shape
image_matches_normalised = {match_points[i]:-2*transformed_array[match_points[i][0], match_points[i][1]] + image_norms_squared[match_points[i]] + template_norm_squared for i in range(len(match_points))}
#print image_matches_normalised
cutoff = h*w*255**2*sq_diff_tolerance
normalised_matches = {key:value for key, value in image_matches_normalised.items() if np.round(value, decimals=3) <= cutoff}
return normalised_matches.keys() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def post(self):
"""Get the message lodged. Returns ------- an :class:`aionationstates.ApiQuery` of :class:`aionationstates.Post` """ |
post = (await self.region._get_messages(
fromid=self._post_id, limit=1))[0]
assert post.id == self._post_id
return post |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def resolution(self):
"""Get the resolution voted on. Returns ------- awaitable of :class:`aionationstates.ResolutionAtVote` The resolution voted for. Raises ------ aionationstates.NotFound If the resolution has since been passed or defeated. """ |
resolutions = await asyncio.gather(
aionationstates.ga.resolution_at_vote,
aionationstates.sc.resolution_at_vote,
)
for resolution in resolutions:
if (resolution is not None
and resolution.name == self.resolution_name):
return resolution
raise aionationstates.NotFound |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def proposal(self):
"""Get the proposal in question. Actually just the first proposal with the same name, but the chance of a collision is tiny. Returns ------- awaitable of :class:`aionationstates.Proposal` The proposal submitted. Raises ------ aionationstates.NotFound If the proposal has since been withdrawn or promoted. """ |
proposals = await aionationstates.wa.proposals()
for proposal in proposals:
if (proposal.name == self.proposal_name):
return proposal
raise aionationstates.NotFound |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def append(self, electrode_id):
'''
Append the specified electrode to the route.
The route is not modified (i.e., electrode is not appended) if
electrode is not connected to the last electrode in the existing route.
Parameters
----------
electrode_id : str
Electrode identifier.
'''
do_append = False
if not self.electrode_ids:
do_append = True
elif self.device.shape_indexes.shape[0] > 0:
source = self.electrode_ids[-1]
target = electrode_id
if not (source == target):
source_id, target_id = self.device.shape_indexes[[source,
target]]
try:
if self.device.adjacency_matrix[source_id, target_id]:
# Electrodes are connected, so append target to current
# route.
do_append = True
except IndexError:
logger.warning('Electrodes `%s` and `%s` are not '
'connected.', source, target)
if do_append:
self.electrode_ids.append(electrode_id)
return do_append |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def insert_surface(self, position, name, surface, alpha=1.):
'''
Insert Cairo surface as new layer.
Args
----
position (int) : Index position to insert layer at.
name (str) : Name of layer.
surface (cairo.Context) : Surface to render.
alpha (float) : Alpha/transparency level in the range `[0, 1]`.
'''
if name in self.df_surfaces.index:
raise NameError('Surface already exists with `name="{}"`.'
.format(name))
self.df_surfaces.loc[name] = surface, alpha
# Reorder layers such that the new surface is placed at the specified
# layer position (relative to the background surface).
surfaces_order = self.df_surfaces.index.values.tolist()
surfaces_order.remove(name)
base_index = surfaces_order.index('background') + 1
if position < 0:
position = len(surfaces_order) + position
surfaces_order.insert(base_index + position, name)
self.reorder_surfaces(surfaces_order) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def append_surface(self, name, surface, alpha=1.):
'''
Append Cairo surface as new layer on top of existing layers.
Args
----
name (str) : Name of layer.
surface (cairo.ImageSurface) : Surface to render.
alpha (float) : Alpha/transparency level in the range `[0, 1]`.
'''
self.insert_surface(position=self.df_surfaces.index.shape[0],
name=name, surface=surface, alpha=alpha) |
<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_surface(self, name):
'''
Remove layer from rendering stack and flatten remaining layers.
Args
----
name (str) : Name of layer.
'''
self.df_surfaces.drop(name, axis=0, inplace=True)
# Order of layers may have changed after removing a layer. Trigger
# refresh of surfaces.
self.reorder_surfaces(self.df_surfaces.index) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def clone_surface(self, source_name, target_name, target_position=-1,
alpha=1.):
'''
Clone surface from existing layer to a new name, inserting new surface
at specified position.
By default, new surface is appended as the top surface layer.
Args
----
source_name (str) : Name of layer to clone.
target_name (str) : Name of new layer.
'''
source_surface = self.df_surfaces.surface.ix[source_name]
source_width = source_surface.get_width()
source_height = source_surface.get_height()
source_format = source_surface.get_format()
target_surface = cairo.ImageSurface(source_format, source_width,
source_height)
target_cairo_context = cairo.Context(target_surface)
target_cairo_context.set_source_surface(source_surface, 0, 0)
target_cairo_context.paint()
self.insert_surface(target_position, target_name, target_surface,
alpha) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def render_electrode_shapes(self, df_shapes=None, shape_scale=0.8,
fill=(1, 1, 1)):
'''
Render electrode state shapes.
By default, draw each electrode shape filled white.
See also :meth:`render_shapes()`.
Parameters
----------
df_shapes = : pandas.DataFrame
.. versionadded:: 0.12
'''
surface = self.get_surface()
if df_shapes is None:
if hasattr(self.canvas, 'df_canvas_shapes'):
df_shapes = self.canvas.df_canvas_shapes
else:
return surface
if 'x_center' not in df_shapes or 'y_center' not in df_shapes:
# No center points have been computed for shapes.
return surface
cairo_context = cairo.Context(surface)
df_shapes = df_shapes.copy()
# Scale shapes to leave shape edges uncovered.
df_shapes[['x', 'y']] = (df_shapes[['x_center', 'y_center']] +
df_shapes[['x_center_offset',
'y_center_offset']].values *
shape_scale)
for path_id, df_path_i in (df_shapes.groupby(self.canvas
.shape_i_columns)[['x',
'y']]):
# Use attribute lookup for `x` and `y`, since it is considerably
# faster than `get`-based lookup using columns name strings.
vertices_x = df_path_i.x.values
vertices_y = df_path_i.y.values
cairo_context.move_to(vertices_x[0], vertices_y[0])
for x, y in itertools.izip(vertices_x[1:], vertices_y[1:]):
cairo_context.line_to(x, y)
cairo_context.close_path()
# Draw filled shape to indicate actuated electrode state.
cairo_context.set_source_rgba(*fill)
cairo_context.fill()
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 render_registration(self):
'''
Render pinned points on video frame as red rectangle.
'''
surface = self.get_surface()
if self.canvas is None or self.df_canvas_corners.shape[0] == 0:
return surface
corners = self.df_canvas_corners.copy()
corners['w'] = 1
transform = self.canvas.shapes_to_canvas_transform
canvas_corners = corners.values.dot(transform.T.values).T
points_x = canvas_corners[0]
points_y = canvas_corners[1]
cairo_context = cairo.Context(surface)
cairo_context.move_to(points_x[0], points_y[0])
for x, y in zip(points_x[1:], points_y[1:]):
cairo_context.line_to(x, y)
cairo_context.line_to(points_x[0], points_y[0])
cairo_context.set_source_rgb(1, 0, 0)
cairo_context.stroke()
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 draw_route(self, df_route, cr, color=None, line_width=None):
'''
Draw a line between electrodes listed in a route.
Arguments
---------
- `df_route`:
* A `pandas.DataFrame` containing a column named `electrode_i`.
* For each row, `electrode_i` corresponds to the integer index of
the corresponding electrode.
- `cr`: Cairo context.
- `color`: Either a RGB or RGBA tuple, with each color channel in the
range [0, 1]. If `color` is `None`, the electrode color is set to
white.
'''
df_route_centers = (self.canvas.df_shape_centers
.ix[df_route.electrode_i][['x_center',
'y_center']])
df_endpoint_marker = (.6 * self.get_endpoint_marker(df_route_centers)
+ df_route_centers.iloc[-1].values)
# Save cairo context to restore after drawing route.
cr.save()
if color is None:
# Colors from ["Show me the numbers"][1].
#
# [1]: http://blog.axc.net/its-the-colors-you-have/
# LiteOrange = rgb(251,178,88);
# MedOrange = rgb(250,164,58);
# LiteGreen = rgb(144,205,151);
# MedGreen = rgb(96,189,104);
color_rgb_255 = np.array([96,189,104, .8 * 255])
color = (color_rgb_255 / 255.).tolist()
if len(color) < 4:
color += [1.] * (4 - len(color))
cr.set_source_rgba(*color)
cr.move_to(*df_route_centers.iloc[0])
for electrode_i, center_i in df_route_centers.iloc[1:].iterrows():
cr.line_to(*center_i)
if line_width is None:
line_width = np.sqrt((df_endpoint_marker.max().values -
df_endpoint_marker.min().values).prod()) * .1
cr.set_line_width(4)
cr.stroke()
cr.move_to(*df_endpoint_marker.iloc[0])
for electrode_i, center_i in df_endpoint_marker.iloc[1:].iterrows():
cr.line_to(*center_i)
cr.close_path()
cr.set_source_rgba(*color)
cr.fill()
# Restore cairo context after drawing route.
cr.restore() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def on_widget__button_press_event(self, widget, event):
'''
Called when any mouse button is pressed.
.. versionchanged:: 0.11
Do not trigger `route-electrode-added` event if `ALT` key is
pressed.
'''
if self.mode == 'register_video' and event.button == 1:
self.start_event = event.copy()
return
elif self.mode == 'control':
shape = self.canvas.find_shape(event.x, event.y)
if shape is None: return
state = event.get_state()
if event.button == 1:
# Start a new route.
self._route = Route(self.device)
self._route.append(shape)
self.last_pressed = shape
if not (state & gtk.gdk.MOD1_MASK):
# `<Alt>` key is not held down.
self.emit('route-electrode-added', shape) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def on_widget__button_release_event(self, widget, event):
'''
Called when any mouse button is released.
.. versionchanged:: 0.11.3
Always reset pending route, regardless of whether a route was
completed. This includes a) removing temporary routes from routes
table, and b) resetting the state of the current route electrode
queue. This fixes
https://github.com/sci-bots/microdrop/issues/256.
'''
event = event.copy()
if self.mode == 'register_video' and (event.button == 1 and
self.start_event is not None):
self.emit('point-pair-selected', {'start_event': self.start_event,
'end_event': event.copy()})
self.start_event = None
return
elif self.mode == 'control':
# XXX Negative `route_i` corresponds to temporary route being
# drawn. Since release of mouse button terminates route drawing,
# clear any rows corresponding to negative `route_i` values from
# the routes table.
self.df_routes = self.df_routes.loc[self.df_routes.route_i >=
0].copy()
shape = self.canvas.find_shape(event.x, event.y)
if shape is not None:
electrode_data = {'electrode_id': shape, 'event': event.copy()}
if event.button == 1:
if gtk.gdk.BUTTON1_MASK == event.get_state():
if self._route.append(shape):
self.emit('route-electrode-added', shape)
if len(self._route.electrode_ids) == 1:
# Single electrode, so select electrode.
self.emit('electrode-selected', electrode_data)
else:
# Multiple electrodes, so select route.
route = self._route
self.emit('route-selected', route)
elif (event.get_state() == (gtk.gdk.MOD1_MASK |
gtk.gdk.BUTTON1_MASK) and
self.last_pressed != shape):
# `<Alt>` key was held down.
self.emit('electrode-pair-selected',
{'source_id': self.last_pressed,
'target_id': shape, 'event': event.copy()})
self.last_pressed = None
elif event.button == 3:
# Create right-click pop-up menu.
menu = self.create_context_menu(event, shape)
# Display menu popup
menu.popup(None, None, None, event.button, event.time)
# Clear route.
self._route = 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 on_widget__motion_notify_event(self, widget, event):
'''
Called when mouse pointer is moved within drawing area.
.. versionchanged:: 0.11
Do not trigger `route-electrode-added` event if `ALT` key is
pressed.
'''
if self.canvas is None:
# Canvas has not been initialized. Nothing to do.
return
elif event.is_hint:
pointer = event.window.get_pointer()
x, y, mod_type = pointer
else:
x = event.x
y = event.y
shape = self.canvas.find_shape(x, y)
# Grab focus to [enable notification on key press/release events][1].
#
# [1]: http://mailman.daa.com.au/cgi-bin/pipermail/pygtk/2003-August/005770.html
self.widget.grab_focus()
if shape != self.last_hovered:
if self.last_hovered is not None:
# Leaving shape
self.emit('electrode-mouseout', {'electrode_id':
self.last_hovered,
'event': event.copy()})
self.last_hovered = None
elif shape is not None:
# Entering shape
self.last_hovered = shape
if self._route is not None:
if self._route.append(shape) and not (event.get_state() &
gtk.gdk.MOD1_MASK):
# `<Alt>` key was not held down.
self.emit('route-electrode-added', shape)
self.emit('electrode-mouseover', {'electrode_id':
self.last_hovered,
'event': event.copy()}) |
<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_electrode_command(self, command, title=None, group=None):
'''
Register electrode command.
Add electrode plugin command to context menu.
'''
commands = self.electrode_commands.setdefault(group, OrderedDict())
if title is None:
title = (command[:1].upper() + command[1:]).replace('_', ' ')
commands[command] = title |
<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_route_command(self, command, title=None, group=None):
'''
Register route command.
Add route plugin command to context menu.
'''
commands = self.route_commands.setdefault(group, OrderedDict())
if title is None:
title = (command[:1].upper() + command[1:]).replace('_', ' ')
commands[command] = title |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def after(self):
""" Return a deferred that will fire after the request is finished. Returns: Deferred: a new deferred that will fire appropriately """ |
d = Deferred()
self._after_deferreds.append(d)
return d.chain |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def after_response(self, request, fn, *args, **kwargs):
""" Call the given callable after the given request has its response. Arguments: request: the request to piggyback fn (callable):
a callable that takes at least two arguments, the request and the response (in that order), along with any additional positional and keyword arguments passed to this function which will be passed along. If the callable returns something other than ``None``, it will be used as the new response. """ |
self._requests[id(request)]["callbacks"].append((fn, 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 plot_degbandshalffill():
"""Plot of Quasiparticle weight for degenerate half-filled bands, showing the Mott transition""" |
ulim = [3.45, 5.15, 6.85, 8.55]
bands = range(1, 5)
for band, u_int in zip(bands, ulim):
name = 'Z_half_'+str(band)+'band'
dop = [0.5]
data = ssplt.calc_z(band, dop, np.arange(0, u_int, 0.1),0., name)
plt.plot(data['u_int'], data['zeta'][0, :, 0], label='$N={}$'.format(str(band)))
ssplt.label_saves('Z_half_multiorb.png') |
<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_dop(bands, int_max, dop, hund_cu, name):
"""Plot of Quasiparticle weight for N degenerate bands under selected doping shows transition only at half-fill the rest are metallic states""" |
data = ssplt.calc_z(bands, dop, np.arange(0, int_max, 0.1), hund_cu, name)
ssplt.plot_curves_z(data, 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 plot_dop_phase(bands, int_max, hund_cu):
"""Phase plot of Quasiparticle weight for N degenerate bands under doping shows transition only at interger filling the rest are metallic states""" |
name = 'Z_dop_phase_'+str(bands)+'bands_U'+str(int_max)+'J'+str(hund_cu)
dop = np.sort(np.hstack((np.linspace(0.01,0.99,50),
np.arange(1./2./bands, 1, 1/2/bands))))
data = ssplt.calc_z(bands, dop, np.arange(0, int_max, 0.1), hund_cu, name)
ssplt.imshow_z(data, name)
ssplt.surf_z(data, 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 _register_extensions(self, namespace):
"""Register any extensions under the given namespace.""" |
# Register any extension classes for this class.
extmanager = ExtensionManager(
'extensions.classes.{}'.format(namespace),
propagate_map_exceptions=True
)
if extmanager.extensions:
extmanager.map(util.register_extension_class, base=self)
# Register any extension methods for this class.
extmanager = ExtensionManager(
'extensions.methods.{}'.format(namespace),
propagate_map_exceptions=True
)
if extmanager.extensions:
extmanager.map(util.register_extension_method, base=self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acls(self):
"""The instance bound ACLs operations layer.""" |
if self._acls is None:
self._acls = InstanceAcls(instance=self)
return self._acls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self):
"""Get all ACLs for this instance.""" |
return self._instance._client.acls.all(self._instance.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 create(self, cidr_mask, description, **kwargs):
"""Create an ACL for this instance. See :py:meth:`Acls.create` for call signature. """ |
return self._instance._client.acls.create(
self._instance.name,
cidr_mask,
description,
**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(self, acl):
"""Get the ACL specified by ID belonging to this instance. See :py:meth:`Acls.get` for call signature. """ |
return self._instance._client.acls.get(self._instance.name, acl) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _VarintEncoder():
"""Return an encoder for a basic varint value.""" |
local_chr = chr
def EncodeVarint(write, value):
bits = value & 0x7f
value >>= 7
while value:
write(0x80|bits)
bits = value & 0x7f
value >>= 7
return write(bits)
return EncodeVarint |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _SignedVarintEncoder():
"""Return an encoder for a basic signed varint value.""" |
local_chr = chr
def EncodeSignedVarint(write, value):
if value < 0:
value += (1 << 64)
bits = value & 0x7f
value >>= 7
while value:
write(0x80|bits)
bits = value & 0x7f
value >>= 7
return write(bits)
return EncodeSignedVarint |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match(value, query):
""" Determine whether a value satisfies a query. """ |
if type(query) in [str, int, float, type(None)]:
return value == query
elif type(query) == dict and len(query.keys()) == 1:
for op in query:
if op == "$eq": return value == query[op]
elif op == "$lt": return value < query[op]
elif op == "$lte": return value <= query[op]
elif op == "$gt": return value > query[op]
elif op == "$gte": return value >= query[op]
elif op == "$ne": return value != query[op]
elif op == "$in": return value in query[op]
elif op == "$nin": return value not in query[op]
else: GeoQLError("Not a valid query operator: " + op)
else:
raise GeoQLError("Not a valid query: " + str(query)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def features_tags_parse_str_to_dict(obj):
""" Parse tag strings of all features in the collection into a Python dictionary, if possible. """ |
features = obj['features']
for i in tqdm(range(len(features))):
tags = features[i]['properties'].get('tags')
if tags is not None:
try:
tags = json.loads("{" + tags.replace("=>", ":") + "}")
except:
try:
tags = eval("{" + tags.replace("=>", ":") + "}")
except:
tags = None
if type(tags) == dict:
features[i]['properties']['tags'] = {k:tags[k] for k in tags}
elif tags is None and 'tags' in features[i]['properties']:
del features[i]['properties']['tags']
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 features_keep_by_property(obj, query):
""" Filter all features in a collection by retaining only those that satisfy the provided query. """ |
features_keep = []
for feature in tqdm(obj['features']):
if all([match(feature['properties'].get(prop), qry) for (prop, qry) in query.items()]):
features_keep.append(feature)
obj['features'] = features_keep
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 features_keep_within_radius(obj, center, radius, units):
""" Filter all features in a collection by retaining only those that fall within the specified radius. """ |
features_keep = []
for feature in tqdm(obj['features']):
if all([getattr(geopy.distance.vincenty((lat,lon), center), units) < radius for (lon,lat) in geojson.utils.coords(feature)]):
features_keep.append(feature)
obj['features'] = features_keep
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 features_keep_using_features(obj, bounds):
""" Filter all features in a collection by retaining only those that fall within the features in the second collection. """ |
# Build an R-tree index of bound features and their shapes.
bounds_shapes = [
(feature, shapely.geometry.shape(feature['geometry']))
for feature in tqdm(bounds['features'])
if feature['geometry'] is not None
]
index = rtree.index.Index()
for i in tqdm(range(len(bounds_shapes))):
(feature, shape) = bounds_shapes[i]
index.insert(i, shape.bounds)
features_keep = []
for feature in tqdm(obj['features']):
if 'geometry' in feature and 'coordinates' in feature['geometry']:
coordinates = feature['geometry']['coordinates']
if any([
shape.contains(shapely.geometry.Point(lon, lat))
for (lon, lat) in coordinates
for (feature, shape) in [bounds_shapes[i]
for i in index.nearest((lon,lat,lon,lat), 1)]
]):
features_keep.append(feature)
continue
obj['features'] = features_keep
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 features_node_edge_graph(obj):
""" Transform the features into a more graph-like structure by appropriately splitting LineString features into two-point "edges" that connect Point "nodes". """ |
points = {}
features = obj['features']
for feature in tqdm(obj['features']):
for (lon, lat) in geojson.utils.coords(feature):
points.setdefault((lon, lat), 0)
points[(lon, lat)] += 1
points = [p for (p, c) in points.items() if c > 1]
features = [geojson.Point(p) for p in points]
# For each feature, split it into "edge" features
# that occur between every point.
for f in tqdm(obj['features']):
seqs = []
seq = []
for point in geojson.utils.coords(f):
if len(seq) > 0:
seq.append(point)
if point in points:
seq.append(point)
if len(seq) > 1 and seq[0] in points:
seqs.append(seq)
seq = [point]
for seq in seqs:
features.append(geojson.Feature(geometry={"coordinates":seq, "type":f['geometry']['type']}, properties=f['properties'], type=f['type']))
obj['features'] = features
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 get_table_info(conn, tablename):
"""Returns TableInfo object""" |
r = conn.execute("pragma table_info('{}')".format(tablename))
ret = TableInfo(((row["name"], row) for row in r))
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def early_warning(iterable, name='this generator'):
''' This function logs an early warning that the generator is empty.
This is handy for times when you're manually playing with generators and
would appreciate the console warning you ahead of time that your generator
is now empty, instead of being surprised with a StopIteration or
GeneratorExit exception when youre trying to test something. '''
nxt = None
prev = next(iterable)
while 1:
try:
nxt = next(iterable)
except:
warning(' {} is now empty'.format(name))
yield prev
break
else:
yield prev
prev = nxt |
<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, data, request, id):
""" Create a new resource using POST """ |
if id:
# can't post to individual user
raise errors.MethodNotAllowed()
user = self._dict_to_model(data)
user.save()
# according to REST, return 201 and Location header
return Response(201, None, {
'Location': '%s%d' % (reverse('user'), user.pk)}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, request, id):
""" Get one user or all users """ |
if id:
return self._get_one(id)
else:
return self._get_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 put(self, data, request, id):
""" Update a single user. """ |
if not id:
# can't update the whole container
raise errors.MethodNotAllowed()
userdata = self._dict_to_model(data)
userdata.pk = id
try:
userdata.save(force_update=True)
except DatabaseError:
# can't udpate non-existing user
raise errors.NotFound() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, request, id):
""" Delete a single user. """ |
if not id:
# can't delete the whole container
raise errors.MethodNotAllowed()
try:
models.User.objects.get(pk=id).delete()
except models.User.DoesNotExist:
# we never had it, so it's definitely deleted
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_one(self, id):
""" Get one user from db and turn into dict """ |
try:
return self._to_dict(models.User.objects.get(pk=id))
except models.User.DoesNotExist:
raise errors.NotFound() |
<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_all(self):
""" Get all users from db and turn into list of dicts """ |
return [self._to_dict(row) for row in models.User.objects.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 _dict_to_model(self, data):
""" Create new user model instance based on the received data. Note that the created user is not saved into database. """ |
try:
# we can do this because we have same fields
# in the representation and in the model:
user = models.User(**data)
except TypeError:
# client sent bad data
raise errors.BadRequest()
else:
return user |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def captures(self, uuid, withTitles=False):
"""Return the captures for a given uuid optional value withTitles=yes""" |
picker = lambda x: x.get('capture', [])
return self._get((uuid,), picker, withTitles='yes' if withTitles else 'no') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uuid(self, type, val):
"""Return the item-uuid for a identifier""" |
picker = lambda x: x.get('uuid', x)
return self._get((type, val), picker) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mods(self, uuid):
"""Return a mods record for a given uuid""" |
picker = lambda x: x.get('mods', {})
return self._get(('mods', uuid), picker) |
<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_i18n_day_name(day_nb, display='short', ln=None):
"""Get the string representation of a weekday, internationalized @param day_nb: number of weekday UNIX like. => 0=Sunday @param ln: language for output @return: the string representation of the day """ |
ln = default_ln(ln)
_ = gettext_set_language(ln)
if display == 'short':
days = {0: _("Sun"),
1: _("Mon"),
2: _("Tue"),
3: _("Wed"),
4: _("Thu"),
5: _("Fri"),
6: _("Sat")}
else:
days = {0: _("Sunday"),
1: _("Monday"),
2: _("Tuesday"),
3: _("Wednesday"),
4: _("Thursday"),
5: _("Friday"),
6: _("Saturday")}
return days[day_nb] |
<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_i18n_month_name(month_nb, display='short', ln=None):
"""Get a non-numeric representation of a month, internationalized. @param month_nb: number of month, (1 based!) =>1=jan,..,12=dec @param ln: language for output @return: the string representation of month """ |
ln = default_ln(ln)
_ = gettext_set_language(ln)
if display == 'short':
months = {0: _("Month"),
1: _("Jan"),
2: _("Feb"),
3: _("Mar"),
4: _("Apr"),
5: _("May"),
6: _("Jun"),
7: _("Jul"),
8: _("Aug"),
9: _("Sep"),
10: _("Oct"),
11: _("Nov"),
12: _("Dec")}
else:
months = {0: _("Month"),
1: _("January"),
2: _("February"),
3: _("March"),
4: _("April"),
5: _("May "), # trailing space distinguishes short/long form
6: _("June"),
7: _("July"),
8: _("August"),
9: _("September"),
10: _("October"),
11: _("November"),
12: _("December")}
return months[month_nb].strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_month_selectbox(name, selected_month=0, ln=None):
"""Creates an HTML menu for month selection. Value of selected field is numeric. @param selected_month: preselect a month. use 0 for the Label 'Month' @param ln: language of the menu @return: html as string """ |
ln = default_ln(ln)
out = "<select name=\"%s\">\n" % name
for i in range(0, 13):
out += "<option value=\"%i\"" % i
if (i == selected_month):
out += " selected=\"selected\""
out += ">%s</option>\n" % get_i18n_month_name(i, ln)
out += "</select>\n"
return out |
<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_runtime_limit(value, now=None):
"""Parsing CLI option for runtime limit, supplied as VALUE. Value could be something like: Sunday 23:00-05:00, the format being [Wee[kday]] [hh[:mm][-hh[:mm]]]. The function will return two valid time ranges. The first could be in the past, containing the present or in the future. The second is always in the future. """ |
def extract_time(value):
value = _RE_RUNTIMELIMIT_HOUR.search(value).groupdict()
return timedelta(hours=int(value['hours']),
minutes=int(value['minutes']))
def extract_weekday(value):
key = value[:3].lower()
try:
return {
'mon': 0,
'tue': 1,
'wed': 2,
'thu': 3,
'fri': 4,
'sat': 5,
'sun': 6,
}[key]
except KeyError:
raise ValueError("%s is not a good weekday name." % value)
if now is None:
now = datetime.now()
today = now.date()
g = _RE_RUNTIMELIMIT_FULL.search(value)
if not g:
raise ValueError('"%s" does not seem to be correct format for '
'parse_runtime_limit() '
'[Wee[kday]] [hh[:mm][-hh[:mm]]]).' % value)
pieces = g.groupdict()
if pieces['weekday_begin'] is None:
# No weekday specified. So either today or tomorrow
first_occasion_day = timedelta(days=0)
next_occasion_delta = timedelta(days=1)
else:
# If given 'Mon' then we transform it to 'Mon-Mon'
if pieces['weekday_end'] is None:
pieces['weekday_end'] = pieces['weekday_begin']
# Day range
weekday_begin = extract_weekday(pieces['weekday_begin'])
weekday_end = extract_weekday(pieces['weekday_end'])
if weekday_begin <= today.weekday() <= weekday_end:
first_occasion_day = timedelta(days=0)
else:
days = (weekday_begin - today.weekday()) % 7
first_occasion_day = timedelta(days=days)
weekday = (now + first_occasion_day).weekday()
if weekday < weekday_end:
# Fits in the same week
next_occasion_delta = timedelta(days=1)
else:
# The week after
days = weekday_begin - weekday + 7
next_occasion_delta = timedelta(days=days)
if pieces['hour_begin'] is None:
pieces['hour_begin'] = '00:00'
if pieces['hour_end'] is None:
pieces['hour_end'] = '00:00'
beginning_time = extract_time(pieces['hour_begin'])
ending_time = extract_time(pieces['hour_end'])
if not ending_time:
ending_time = beginning_time + timedelta(days=1)
elif beginning_time and ending_time and beginning_time > ending_time:
ending_time += timedelta(days=1)
start_time = real_datetime.combine(today, real_time(hour=0, minute=0))
current_range = (
start_time + first_occasion_day + beginning_time,
start_time + first_occasion_day + ending_time
)
if now > current_range[1]:
current_range = tuple(t + next_occasion_delta for t in current_range)
future_range = (
current_range[0] + next_occasion_delta,
current_range[1] + next_occasion_delta
)
return current_range, future_range |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def guess_datetime(datetime_string):
"""Try to guess the datetime contained in a string of unknow format. @param datetime_string: the datetime representation. @type datetime_string: string @return: the guessed time. @rtype: L{time.struct_time} @raises ValueError: in case it's not possible to guess the time. """ |
if CFG_HAS_EGENIX_DATETIME:
try:
return Parser.DateTimeFromString(datetime_string).timetuple()
except ValueError:
pass
else:
for format in (None, '%x %X', '%X %x', '%Y-%M-%dT%h:%m:%sZ'):
try:
return time.strptime(datetime_string, format)
except ValueError:
pass
raise ValueError("It is not possible to guess the datetime format of %s" %
datetime_string) |
<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_dst(date_obj):
"""Determine if dst is locally enabled at this time""" |
dst = 0
if date_obj.year >= 1900:
tmp_date = time.mktime(date_obj.timetuple())
# DST is 1 so reduce time with 1 hour.
dst = time.localtime(tmp_date)[-1]
return dst |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def utc_to_localtime( date_str, fmt="%Y-%m-%d %H:%M:%S", input_fmt="%Y-%m-%dT%H:%M:%SZ"):
""" Convert UTC to localtime Reference: - (1) http://www.openarchives.org/OAI/openarchivesprotocol.html#Dates - (2) http://www.w3.org/TR/NOTE-datetime This function works only with dates complying with the "Complete date plus hours, minutes and seconds" profile of ISO 8601 defined by (2), and linked from (1). Eg: 1994-11-05T13:15:30Z """ |
date_struct = datetime.strptime(date_str, input_fmt)
date_struct += timedelta(hours=get_dst(date_struct))
date_struct -= timedelta(seconds=time.timezone)
return strftime(fmt, date_struct) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_call(self, actual_call, stubbed_call):
"""Extends Stub call handling behavior to be callable by default.""" |
self._actual_calls.append(actual_call)
use_call = stubbed_call or actual_call
return use_call.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 formatted_args(self):
"""Format call arguments as a string. This is used to make test failure messages more helpful by referring to calls using a string that matches how they were, or should have been called. "('arg1', 'arg2', kwarg='kwarg')" """ |
arg_reprs = list(map(repr, self.args))
kwarg_reprs = ['%s=%s' % (k, repr(v)) for k, v in self.kwargs.items()]
return '(%s)' % ', '.join(arg_reprs + kwarg_reprs) |
<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(self):
""" Check if data and third party tools are available :raises: RuntimeError """ |
#for path in self.path.values():
# if not os.path.exists(path):
# raise RuntimeError("File '{}' is missing".format(path))
for tool in ('cd-hit', 'prank', 'hmmbuild', 'hmmpress', 'hmmscan', 'phmmer', 'mafft', 'meme'):
if not self.pathfinder.exists(tool):
raise RuntimeError("Dependency {} is missing".format(tool)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_non_rabs(self):
""" Shrink the non-Rab DB size by reducing sequence redundancy. """ |
logging.info('Building non-Rab DB')
run_cmd([self.pathfinder['cd-hit'], '-i', self.path['non_rab_db'], '-o', self.output['non_rab_db'],
'-d', '100', '-c', str(config['param']['non_rab_db_identity_threshold']), '-g', '1', '-T', self.cpu])
os.remove(self.output['non_rab_db'] + '.clstr') |
<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_duration(duration):
"""Attepmts to parse an ISO8601 formatted ``duration``. Returns a ``datetime.timedelta`` object. """ |
duration = str(duration).upper().strip()
elements = ELEMENTS.copy()
for pattern in (SIMPLE_DURATION, COMBINED_DURATION):
if pattern.match(duration):
found = pattern.match(duration).groupdict()
del found['time']
elements.update(dict((k, int(v or 0))
for k, v
in found.items()))
return datetime.timedelta(days=(elements['days'] +
_months_to_days(elements['months']) +
_years_to_days(elements['years'])),
hours=elements['hours'],
minutes=elements['minutes'],
seconds=elements['seconds'])
return ParseError() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def skin_details(skin_id, lang="en"):
"""This resource returns details about a single skin. :param skin_id: The skin to query for. :param lang: The language to display the texts in. The response is an object with at least the following properties. Note that the availability of some properties depends on the type of item the skin applies to. skin_id (number):
The skin id. name (string):
The name of the skin. type (string):
The type of item the skin applies to. One of ``Armor``, ``Back`` or ``Weapon``. flags (list):
Skin flags. Currently known skin flags are ``ShowInWardrobe``, ``HideIfLocked`` and ``NoCost``. restrictions (list):
Race restrictions: ``Asura``, ``Charr``, ``Human``, ``Norn`` and ``Sylvari``. icon_file_id (string):
The icon file id to be used with the render service. icon_file_signature (string):
The icon file signature to be used with the render service. """ |
params = {"skin_id": skin_id, "lang": lang}
cache_name = "skin_details.%(skin_id)s.%(lang)s.json" % params
return get_cached("skin_details.json", cache_name, params=params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bubble_to_gexf(bblfile:str, gexffile:str=None, oriented:bool=False):
"""Write in bblfile a graph equivalent to those depicted in bubble file""" |
tree = BubbleTree.from_bubble_file(bblfile, oriented=bool(oriented))
gexf_converter.tree_to_file(tree, gexffile)
return gexffile |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bubble_to_js(bblfile:str, jsdir:str=None, oriented:bool=False, **style):
"""Write in jsdir a graph equivalent to those depicted in bubble file""" |
js_converter.bubble_to_dir(bblfile, jsdir, oriented=bool(oriented), **style)
return jsdir |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.