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 _generate_constructor(cls, names):
"""Get a hopefully cache constructor""" |
cache = cls._constructors
if names in cache:
return cache[names]
elif len(cache) > 3:
cache.clear()
func = generate_constructor(cls, names)
cache[names] = func
return func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _take_ownership(self):
"""Make the Python instance take ownership of the GIBaseInfo. i.e. unref if the python instance gets gc'ed. """ |
if self:
ptr = cast(self.value, GIBaseInfo)
_UnrefFinalizer.track(self, ptr)
self.__owns = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cast(cls, base_info, take_ownership=True):
"""Casts a GIBaseInfo instance to the right sub type. The original GIBaseInfo can't have ownership. Will take own... |
type_value = base_info.type.value
try:
new_obj = cast(base_info, cls.__types[type_value])
except KeyError:
new_obj = base_info
if take_ownership:
assert not base_info.__owns
new_obj._take_ownership()
return new_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 decode_return(codec="ascii"):
"""Decodes the return value of it isn't None""" |
def outer(f):
def wrap(*args, **kwargs):
res = f(*args, **kwargs)
if res is not None:
return res.decode(codec)
return res
return wrap
return outer |
<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_ctypes_library(name):
"""Takes a library name and calls find_library in case loading fails, since some girs don't include the real .so name. Raises OSEr... |
try:
return cdll.LoadLibrary(name)
except OSError:
name = find_library(name)
if name is None:
raise
return cdll.LoadLibrary(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 cache_return(func):
"""Cache the return value of a function without arguments""" |
_cache = []
def wrap():
if not _cache:
_cache.append(func())
return _cache[0]
return wrap |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lookup_name_fast(self, name):
"""Might return a struct""" |
if name in self.__names:
return self.__names[name]
count = self.__get_count_cached()
lo = 0
hi = count
while lo < hi:
mid = (lo + hi) // 2
if self.__get_name_cached(mid) < name:
lo = mid + 1
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _new_type(cls, args):
"""Creates a new class similar to namedtuple. Pass a list of field names or None for no field name. ResultTuple(1, bar=3) """ |
fformat = ["%r" if f is None else "%s=%%r" % f for f in args]
fformat = "(%s)" % ", ".join(fformat)
class _ResultTuple(cls):
__slots__ = ()
_fformat = fformat
if args:
for i, a in enumerate(args):
if a is not 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 signal_list_names(type_):
"""Returns a list of signal names for the given type :param type\\_: :type type\\_: :obj:`GObject.GType` :returns: A list of signal... |
ids = signal_list_ids(type_)
return tuple(GObjectModule.signal_name(i) for i in ids) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def track(cls, obj, ptr):
""" Track an object which needs destruction when it is garbage collected. """ |
cls._objects.add(cls(obj, ptr)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _unpack_result(klass, result):
'''Convert a D-BUS return variant into an appropriate return value'''
result = result.unpack()
# to be compatible with standard Python behaviour, unbox
# single-element tuples and return None for empty result tuples
if len(result) == 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 load_overrides(introspection_module):
"""Loads overrides for an introspection module. Either returns the same module again in case there are no overrides or ... |
namespace = introspection_module.__name__.rsplit(".", 1)[-1]
module_keys = [prefix + "." + namespace for prefix in const.PREFIX]
# We use sys.modules so overrides can import from gi.repository
# but restore everything at the end so this doesn't have any side effects
for module_key in module_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 override(klass):
"""Takes a override class or function and assigns it dunder arguments form the overidden one. """ |
namespace = klass.__module__.rsplit(".", 1)[-1]
mod_name = const.PREFIX[-1] + "." + namespace
module = sys.modules[mod_name]
if isinstance(klass, types.FunctionType):
def wrap(wrapped):
setattr(module, klass.__name__, wrapped)
return wrapped
return wrap
ol... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deprecated(function, instead):
"""Mark a function deprecated so calling it issues a warning""" |
# skip for classes, breaks doc generation
if not isinstance(function, types.FunctionType):
return function
@wraps(function)
def wrap(*args, **kwargs):
warnings.warn("Deprecated, use %s instead" % instead,
PyGIDeprecationWarning)
return function(*args, **k... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deprecated_attr(namespace, attr, replacement):
"""Marks a module level attribute as deprecated. Accessing it will emit a PyGIDeprecationWarning warning. e.g.... |
_deprecated_attrs.setdefault(namespace, []).append((attr, replacement)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strip_boolean_result(method, exc_type=None, exc_str=None, fail_ret=None):
"""Translate method's return value for stripping off success flag. There are a lot ... |
@wraps(method)
def wrapped(*args, **kwargs):
ret = method(*args, **kwargs)
if ret[0]:
if len(ret) == 2:
return ret[1]
else:
return ret[1:]
else:
if exc_type:
raise exc_type(exc_str or 'call failed')
... |
<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_param_type(self, index):
"""Returns a ReturnValue instance for param type 'index'""" |
assert index in (0, 1)
type_info = self.type.get_param_type(index)
type_cls = get_return_class(type_info)
instance = type_cls(None, type_info, [], self.backend)
instance.setup()
return instance |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request_name(self, name):
"""Request a name, might return the name or a similar one if already used or reserved """ |
while name in self._blacklist:
name += "_"
self._blacklist.add(name)
return 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 add_dependency(self, name, obj):
"""Add a code dependency so it gets inserted into globals""" |
if name in self._deps:
if self._deps[name] is obj:
return
raise ValueError(
"There exists a different dep with the same name : %r" % name)
self._deps[name] = 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 write_into(self, block, level=0):
"""Append this block to another one, passing all dependencies""" |
for line, l in self._lines:
block.write_line(line, level + l)
for name, obj in _compat.iteritems(self._deps):
block.add_dependency(name, 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 write_lines(self, lines, level=0):
"""Append multiple new lines""" |
for line in lines:
self.write_line(line, level) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile(self, **kwargs):
"""Execute the python code and returns the global dict. kwargs can contain extra dependencies that get only used at compile time. ""... |
code = compile(str(self), "<string>", "exec")
global_dict = dict(self._deps)
global_dict.update(kwargs)
_compat.exec_(code, global_dict)
return global_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pprint(self, file_=sys.stdout):
"""Print the code block to stdout. Does syntax highlighting if possible. """ |
code = []
if self._deps:
code.append("# dependencies:")
for k, v in _compat.iteritems(self._deps):
code.append("# %s: %r" % (k, v))
code.append(str(self))
code = "\n".join(code)
if file_.isatty():
try:
from pygments... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def may_be_null_is_nullable():
"""If may_be_null returns nullable or if NULL can be passed in. This can still be wrong if the specific typelib is older than the ... |
repo = GIRepository()
repo.require("GLib", "2.0", 0)
info = repo.find_by_name("GLib", "spawn_sync")
# this argument is (allow-none) and can never be (nullable)
return not info.get_arg(8).may_be_null |
<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_type_name(type_):
"""Gives a name for a type that is suitable for a docstring. int -> "int" Gtk.Window -> "Gtk.Window" [int] -> "[int]" {int: Gtk.Button}... |
if type_ is None:
return ""
if isinstance(type_, string_types):
return type_
elif isinstance(type_, list):
assert len(type_) == 1
return "[%s]" % get_type_name(type_[0])
elif isinstance(type_, dict):
assert len(type_) == 1
key, value = list(type_.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 generate_function(info, method=False):
"""Creates a Python callable for a GIFunctionInfo instance""" |
assert isinstance(info, GIFunctionInfo)
arg_infos = list(info.get_args())
arg_types = [a.get_type() for a in arg_infos]
return_type = info.get_return_type()
func = None
messages = []
for backend in list_backends():
instance = backend()
try:
func = _generate_fu... |
<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_enum_class(ffi, type_name, prefix, flags=False):
"""Returns a new shiny class for the given enum type""" |
class _template(int):
_map = {}
@property
def value(self):
return int(self)
def __str__(self):
return self._map.get(self, "Unknown")
def __repr__(self):
return "%s.%s" % (type(self).__name__, str(self))
class _template_flags(int):... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fixup_cdef_enums(string, reg=re.compile(r"=\s*(\d+)\s*<<\s*(\d+)")):
"""Converts some common enum expressions to constants""" |
def repl_shift(match):
shift_by = int(match.group(2))
value = int(match.group(1))
int_value = ctypes.c_int(value << shift_by).value
return "= %s" % str(int_value)
return reg.sub(repl_shift, 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 unpack_glist(g, type_, transfer_full=True):
"""Takes a glist, copies the values casted to type_ in to a list and frees all items and the list. """ |
values = []
item = g
while item:
ptr = item.contents.data
value = cast(ptr, type_).value
values.append(value)
if transfer_full:
free(ptr)
item = item.next()
if transfer_full:
g.free()
return values |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unpack_nullterm_array(array):
"""Takes a null terminated array, copies the values into a list and frees each value and the list. """ |
addrs = cast(array, POINTER(ctypes.c_void_p))
l = []
i = 0
value = array[i]
while value:
l.append(value)
free(addrs[i])
i += 1
value = array[i]
free(addrs)
return l |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_version(namespace, version):
"""Set a version for the namespace to be loaded. This needs to be called before importing the namespace or any namespace... |
global _versions
repo = GIRepository()
namespaces = repo.get_loaded_namespaces()
if namespace in namespaces:
loaded_version = repo.get_version(namespace)
if loaded_version != version:
raise ValueError('Namespace %s is already loaded with version %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 unpack_glist(glist_ptr, cffi_type, transfer_full=True):
"""Takes a glist ptr, copies the values casted to type_ in to a list and frees all items and the list... |
current = glist_ptr
while current:
yield ffi.cast(cffi_type, current.data)
if transfer_full:
free(current.data)
current = current.next
if transfer_full:
lib.g_list_free(glist_ptr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unpack_zeroterm_array(ptr):
"""Converts a zero terminated array to a list and frees each element and the list itself. If an item is returned all yielded befo... |
assert ptr
index = 0
current = ptr[index]
while current:
yield current
free(ffi.cast("gpointer", current))
index += 1
current = ptr[index]
free(ffi.cast("gpointer", ptr)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def StructureAttribute(struct_info):
"""Creates a new struct class.""" |
# Copy the template and add the gtype
cls_dict = dict(_Structure.__dict__)
cls = type(struct_info.name, _Structure.__bases__, cls_dict)
cls.__module__ = struct_info.namespace
cls.__gtype__ = PGType(struct_info.g_type)
cls._size = struct_info.size
cls._is_gtype_struct = struct_info.is_gtype... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _from_gerror(cls, error, own=True):
"""Creates a GError exception and takes ownership if own is True""" |
if not own:
error = error.copy()
self = cls()
self._error = error
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_version(version):
"""Takes a version string or tuple and raises ValueError in case the passed version is newer than the current version of pgi. Keep in... |
if isinstance(version, string_types):
version = tuple(map(int, version.split(".")))
if version > version_info:
str_version = ".".join(map(str, version))
raise ValueError("pgi version '%s' requested, '%s' available" %
(str_version, __version__)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_as_gi():
"""Call before the first gi import to redirect gi imports to pgi""" |
import sys
# check if gi has already been replaces
if "gi.repository" in const.PREFIX:
return
# make sure gi isn't loaded first
for mod in iterkeys(sys.modules):
if mod == "gi" or mod.startswith("gi."):
raise AssertionError("pgi has to be imported before gi")
# r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_panel_to_edit_handler(model, panel_cls, heading, index=None):
""" Adds specified panel class to model class. :param model: the model class. :param panel_... |
from wagtail.wagtailadmin.views.pages import get_page_edit_handler
edit_handler = get_page_edit_handler(model)
panel_instance = ObjectList(
[panel_cls(),],
heading = heading
).bind_to_model(model)
if index:
edit_handler.children.insert(index, panel_instance)
else:
... |
<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_ordering(self):
""" Returns ordering value for list. :rtype: str. """ |
#noinspection PyUnresolvedReferences
ordering = self.request.GET.get('ordering', None)
if ordering not in ['title', '-created_at']:
ordering = '-created_at'
return ordering |
<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_queryset(self):
""" Returns queryset instance. :rtype: django.db.models.query.QuerySet. """ |
queryset = super(IndexView, self).get_queryset()
search_form = self.get_search_form()
if search_form.is_valid():
query_str = search_form.cleaned_data.get('q', '').strip()
queryset = self.model.objects.search(query_str)
return queryset |
<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_search_form(self):
""" Returns search form instance. :rtype: django.forms.ModelForm. """ |
#noinspection PyUnresolvedReferences
if 'q' in self.request.GET:
#noinspection PyUnresolvedReferences
return self.search_form_class(self.request.GET)
else:
return self.search_form_class(placeholder=_(u'Search')) |
<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_template_names(self):
""" Returns a list of template names for the view. :rtype: list. """ |
#noinspection PyUnresolvedReferences
if self.request.is_ajax():
template_name = '/results.html'
else:
template_name = '/index.html'
return ['{0}{1}'.format(self.template_dir, template_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 paginate_queryset(self, queryset, page_size):
""" Returns tuple containing paginator instance, page instance, object list, and whether there are other pages.... |
paginator = self.get_paginator(
queryset,
page_size,
orphans = self.get_paginate_orphans(),
allow_empty_first_page = self.get_allow_empty()
)
page_kwarg = self.page_kwarg
#noinspection PyUnresolvedReferences
page... |
<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_success_url(self):
""" Returns redirect URL for valid form submittal. :rtype: str. """ |
if self.success_url:
url = force_text(self.success_url)
else:
url = reverse('{0}:index'.format(self.url_namespace))
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 delete(self, request, *args, **kwargs):
""" Processes deletion of the specified instance. :param request: the request instance. :rtype: django.http.HttpRespo... |
#noinspection PyAttributeOutsideInit
self.object = self.get_object()
success_url = self.get_success_url()
meta = getattr(self.object, '_meta')
self.object.delete()
messages.success(
request,
_(u'{0} "{1}" deleted.').format(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chunked(iterable, n):
"""Returns chunks of n length of iterable If len(iterable) % n != 0, then the last chunk will have length less than n. Example: [(1, 2)... |
iterable = iter(iterable)
while 1:
t = tuple(islice(iterable, n))
if t:
yield t
else:
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 format_explanation(explanation, indent=' ', indent_level=0):
"""Return explanation in an easier to read format Easier to read for me, at least. """ |
if not explanation:
return ''
# Note: This is probably a crap implementation, but it's an
# interesting starting point for a better formatter.
line = ('%s%s %2.4f' % ((indent * indent_level),
explanation['description'],
explanation['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_es(**overrides):
"""Return a elasticsearch Elasticsearch object using settings from ``settings.py``. :arg overrides: Allows you to override defaults to c... |
defaults = {
'urls': settings.ES_URLS,
'timeout': getattr(settings, 'ES_TIMEOUT', 5)
}
defaults.update(overrides)
return base_get_es(**defaults) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def es_required(fun):
"""Wrap a callable and return None if ES_DISABLED is False. This also adds an additional `es` argument to the callable giving you an Elasti... |
@wraps(fun)
def wrapper(*args, **kw):
if getattr(settings, 'ES_DISABLED', False):
log.debug('Search disabled for %s.' % fun)
return
return fun(*args, es=get_es(), **kw)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_es(self, default_builder=get_es):
"""Returns the elasticsearch Elasticsearch object to use. This uses the django get_es builder by default which takes in... |
return super(S, self).get_es(default_builder=default_builder) |
<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_indexes(self, default_indexes=None):
"""Returns the list of indexes to act on based on ES_INDEXES setting """ |
doctype = self.type.get_mapping_type_name()
indexes = (settings.ES_INDEXES.get(doctype) or
settings.ES_INDEXES['default'])
if isinstance(indexes, six.string_types):
indexes = [indexes]
return super(S, self).get_indexes(default_indexes=indexes) |
<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_index(cls):
"""Gets the index for this model. The index for this model is specified in `settings.ES_INDEXES` which is a dict of mapping type -> index nam... |
indexes = settings.ES_INDEXES
index = indexes.get(cls.get_mapping_type_name()) or indexes['default']
if not (isinstance(index, six.string_types)):
# FIXME - not sure what to do here, but we only want one
# index and somehow this isn't one index.
index = 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 get_indexable(cls):
"""Returns the queryset of ids of all things to be indexed. Defaults to:: cls.get_model().objects.order_by('id').values_list( 'id', flat=... |
model = cls.get_model()
return model.objects.order_by('id').values_list('id', flat=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_es(urls=None, timeout=DEFAULT_TIMEOUT, force_new=False, **settings):
"""Create an elasticsearch `Elasticsearch` object and return it. This will aggressiv... |
# Cheap way of de-None-ifying things
urls = urls or DEFAULT_URLS
# v0.7: Check for 'hosts' instead of 'urls'. Take this out in v1.0.
if 'hosts' in settings:
raise DeprecationWarning('"hosts" is deprecated in favor of "urls".')
if not force_new:
key = _build_key(urls, timeout, **se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _facet_counts(items):
"""Returns facet counts as dict. Given the `items()` on the raw dictionary from Elasticsearch this processes it and returns the counts ... |
facets = {}
for name, data in items:
facets[name] = FacetResult(name, data)
return facets |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _boosted_value(name, action, key, value, boost):
"""Boost a value if we should in _process_queries""" |
if boost is not None:
# Note: Most queries use 'value' for the key name except
# Match queries which use 'query'. So we have to do some
# switcheroo for that.
value_key = 'query' if action in MATCH_ACTIONS else 'value'
return {name: {'boost': boost, value_key: value}}
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decorate_with_metadata(obj, result):
"""Return obj decorated with es_meta object""" |
# Create es_meta object with Elasticsearch metadata about this
# search result
obj.es_meta = Metadata(
# Elasticsearch id
id=result.get('_id', 0),
# Source data
source=result.get('_source', {}),
# The search result score
score=result.get('_score', 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 _combine(self, other, conn='and'):
""" OR and AND will create a new F, with the filters from both F objects combined with the connector `conn`. """ |
f = F()
self_filters = copy.deepcopy(self.filters)
other_filters = copy.deepcopy(other.filters)
if not self.filters:
f.filters = other_filters
elif not other.filters:
f.filters = self_filters
elif conn in self.filters[0]:
f.filters =... |
<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_python(self, obj):
"""Converts strings in a data structure to Python types It converts datetime-ish things to Python datetimes. Override if you want somet... |
if isinstance(obj, string_types):
if len(obj) == 26:
try:
return datetime.strptime(obj, '%Y-%m-%dT%H:%M:%S.%f')
except (TypeError, ValueError):
pass
elif len(obj) == 19:
try:
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(self, *queries, **kw):
""" Return a new S instance with query args combined with existing set in a must boolean query. :arg queries: instances of Q :ar... |
q = Q()
for query in queries:
q += query
if 'or_' in kw:
# Backwards compatibile with pre-0.7 version.
or_query = kw.pop('or_')
# or_query here is a dict of key/val pairs. or_ indicates
# they're in a should clause, so we generate th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter(self, *filters, **kw):
""" Return a new S instance with filter args combined with existing set with AND. :arg filters: this will be instances of F :ar... |
items = kw.items()
if six.PY3:
items = list(items)
return self._clone(
next_step=('filter', list(filters) + 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 boost(self, **kw):
""" Return a new S instance with field boosts. ElasticUtils allows you to specify query-time field boosts with ``.boost()``. It takes a se... |
new = self._clone()
new.field_boosts.update(kw)
return new |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def demote(self, amount_, *queries, **kw):
""" Returns a new S instance with boosting query and demotion. You can demote documents that match query criteria:: q ... |
q = Q()
for query in queries:
q += query
q += Q(**kw)
return self._clone(next_step=('demote', (amount_, q))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def facet_raw(self, **kw):
""" Return a new S instance with raw facet args combined with existing set. """ |
items = kw.items()
if six.PY3:
items = list(items)
return self._clone(next_step=('facet_raw', 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 suggest(self, name, term, **kwargs):
"""Set suggestion options. :arg name: The name to use for the suggestions. :arg term: The term to suggest similar lookin... |
return self._clone(next_step=('suggest', (name, term, 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 extra(self, **kw):
""" Return a new S instance with extra args combined with existing set. """ |
new = self._clone()
actions = ['values_list', 'values_dict', 'order_by', 'query',
'filter', 'facet']
for key, vals in kw.items():
assert key in actions
if hasattr(vals, 'items'):
new.steps.append((key, vals.items()))
else:
... |
<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_highlight(self, fields, options):
"""Return the portion of the query that controls highlighting.""" |
ret = {'fields': dict((f, {}) for f in fields),
'order': 'score'}
ret.update(options)
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 _process_filters(self, filters):
"""Takes a list of filters and returns ES JSON API :arg filters: list of F, (key, val) tuples, or dicts :returns: list of ES... |
rv = []
for f in filters:
if isinstance(f, F):
if f.filters:
rv.extend(self._process_filters(f.filters))
continue
elif isinstance(f, dict):
if six.PY3:
key = list(f.keys())[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 _process_queries(self, queries):
"""Takes a list of queries and returns query clause value :arg queries: list of Q instances :returns: dict which is the quer... |
# First, let's mush everything into a single Q. Then we can
# parse that into bits.
new_q = Q()
for query in queries:
new_q += query
# Now we have a single Q that needs to be processed.
should_q = [self._process_query(query) for query in new_q.should_q]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_search(self):
""" Perform the search, then convert that raw format into a SearchResults instance and return it. """ |
if self._results_cache is None:
response = self.raw()
ResultsClass = self.get_results_class()
results = self.to_python(response.get('hits', {}).get('hits', []))
self._results_cache = ResultsClass(
self.type, response, results, self.fields)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_es(self, default_builder=get_es):
"""Returns the Elasticsearch object to use. :arg default_builder: The function that takes a bunch of arguments and gene... |
# .es() calls are incremental, so we go through them all and
# update bits that are specified.
args = {}
for action, value in self.steps:
if action == 'es':
args.update(**value)
# TODO: store the Elasticsearch on the S if we've already
# crea... |
<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_indexes(self, default_indexes=DEFAULT_INDEXES):
"""Returns the list of indexes to act on.""" |
for action, value in reversed(self.steps):
if action == 'indexes':
return list(value)
if self.type is not None:
indexes = self.type.get_index()
if isinstance(indexes, string_types):
indexes = [indexes]
return indexes
... |
<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_doctypes(self, default_doctypes=DEFAULT_DOCTYPES):
"""Returns the list of doctypes to use.""" |
for action, value in reversed(self.steps):
if action == 'doctypes':
return list(value)
if self.type is not None:
return [self.type.get_mapping_type_name()]
return default_doctypes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_es(self):
"""Returns an `Elasticsearch`. * If there's an s, then it returns that `Elasticsearch`. * If the es was provided in the constructor, then it re... |
if self.s:
return self.s.get_es()
return self.es or get_es() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_search(self):
""" Perform the mlt call, then convert that raw format into a SearchResults instance and return it. """ |
if self._results_cache is None:
response = self.raw()
results = self.to_python(response.get('hits', {}).get('hits', []))
self._results_cache = DictSearchResults(
self.type, response, results, None)
return self._results_cache |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index(cls, document, id_=None, overwrite_existing=True, es=None, index=None):
"""Adds or updates a document to the index :arg document: Python dict of key/va... |
if es is None:
es = cls.get_es()
if index is None:
index = cls.get_index()
kw = {}
if not overwrite_existing:
kw['op_type'] = 'create'
es.index(index=index, doc_type=cls.get_mapping_type_name(),
body=document, id=id_, **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 bulk_index(cls, documents, id_field='id', es=None, index=None):
"""Adds or updates a batch of documents. :arg documents: List of Python dicts representing in... |
if es is None:
es = cls.get_es()
if index is None:
index = cls.get_index()
documents = (dict(d, _id=d[id_field]) for d in documents)
bulk_index(
es,
documents,
index=index,
doc_type=cls.get_mapping_type_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 unindex(cls, id_, es=None, index=None):
"""Removes a particular item from the search index. :arg id_: The Elasticsearch id for the document to remove from th... |
if es is None:
es = cls.get_es()
if index is None:
index = cls.get_index()
es.delete(index=index, doc_type=cls.get_mapping_type_name(), id=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 refresh_index(cls, es=None, index=None):
"""Refreshes the index. Elasticsearch will update the index periodically automatically. If you need to see the docum... |
if es is None:
es = cls.get_es()
if index is None:
index = cls.get_index()
es.indices.refresh(index=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 monkeypatch_es():
"""Monkey patch for elasticsearch-py 1.0+ to make it work with ES 0.90 1. tweaks elasticsearch.client.bulk to normalize return status codes... |
if _monkeypatched_es:
return
def normalize_bulk_return(fun):
"""Set's "ok" based on "status" if "status" exists"""
@wraps(fun)
def _fixed_bulk(self, *args, **kwargs):
def fix_item(item):
# Go through all the possible sections of item looking
... |
<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_context_data(self, **kwargs):
""" Returns view context dictionary. :rtype: dict. """ |
kwargs.update({
'entries': Entry.objects.get_for_tag(
self.kwargs.get('slug', 0)
)
})
return super(EntriesView, self).get_context_data(**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 _ensure_file_path(self):
""" Ensure the storage path exists. If it doesn't, create it with "go-rwx" permissions. """ |
storage_root = os.path.dirname(self.file_path)
needs_storage_root = storage_root and not os.path.isdir(storage_root)
if needs_storage_root: # pragma: no cover
os.makedirs(storage_root)
if not os.path.isfile(self.file_path):
# create the file without group/world ... |
<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_relationship_panels(self):
"""
Add edit handler that includes "related" panels to applicable
model classes that don't explicitly define their own edit... |
from wagtailplus.utils.edit_handlers import add_panel_to_edit_handler
from wagtailplus.wagtailrelations.edit_handlers import RelatedPanel
for model in self.applicable_models:
add_panel_to_edit_handler(model, RelatedPanel, _(u'Related')) |
<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_relationship_methods(self):
"""
Adds relationship methods to applicable model classes.
""" |
Entry = apps.get_model('wagtailrelations', 'Entry')
@cached_property
def related(instance):
return instance.get_related()
@cached_property
def related_live(instance):
return instance.get_related_live()
@cached_property
def r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_rollback_panels(self):
"""
Adds rollback panel to applicable model class's edit handlers.
""" |
from wagtailplus.utils.edit_handlers import add_panel_to_edit_handler
from wagtailplus.wagtailrollbacks.edit_handlers import HistoryPanel
for model in self.applicable_models:
add_panel_to_edit_handler(model, HistoryPanel, _(u'History')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_rollback_methods():
"""
Adds rollback methods to applicable model classes.
""" |
# Modified Page.save_revision method.
def page_rollback(instance, revision_id, user=None, submitted_for_moderation=False, approved_go_live_at=None, changed=True):
old_revision = instance.revisions.get(pk=revision_id)
new_revision = instance.revisions.create(
... |
<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_related(page):
""" Returns list of related Entry instances for specified page. :param page: the page instance. :rtype: list. """ |
related = []
entry = Entry.get_for_model(page)
if entry:
related = entry.related
return related |
<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_related_entry_admin_url(entry):
""" Returns admin URL for specified entry instance. :param entry: the entry instance. :return: str. """ |
namespaces = {
Document: 'wagtaildocs:edit',
Link: 'wagtaillinks:edit',
Page: 'wagtailadmin_pages:edit',
}
for cls, url in namespaces.iteritems():
if issubclass(entry.content_type.model_class(), cls):
return urlresolvers.reverse(url, args=(entry.ob... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand_db_attributes(attrs, for_editor):
""" Given a dictionary of attributes, find the corresponding link instance and return its HTML representation. :para... |
try:
editor_attrs = ''
link = Link.objects.get(id=attrs['id'])
if for_editor:
editor_attrs = 'data-linktype="link" data-id="{0}" '.format(
link.id
)
return '<a {0}href="{1}" title="{2}">'.format(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crypter(self):
"""The actual keyczar crypter""" |
if not hasattr(self, '_crypter'):
# initialise the Keyczar keysets
if not self.keyset_location:
raise ValueError('No encrypted keyset location!')
reader = keyczar.readers.CreateReader(self.keyset_location)
if self.encrypting_keyset_location:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index_objects(mapping_type, ids, chunk_size=100, es=None, index=None):
"""Index documents of a specified mapping type. This allows for asynchronous indexing.... |
if settings.ES_DISABLED:
return
log.debug('Indexing objects {0}-{1}. [{2}]'.format(
ids[0], ids[-1], len(ids)))
# Get the model this mapping type is based on.
model = mapping_type.get_model()
# Retrieve all the objects that we're going to index and do it in
# bulk.
fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unindex_objects(mapping_type, ids, es=None, index=None):
"""Remove documents of a specified mapping_type from the index. This allows for asynchronous deletin... |
if settings.ES_DISABLED:
return
for id_ in ids:
mapping_type.unindex(id_, es=es, index=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 get_json(self, link):
""" Returns specified link instance as JSON. :param link: the link instance. :rtype: JSON. """ |
return json.dumps({
'id': link.id,
'title': link.title,
'url': link.get_absolute_url(),
'edit_link': reverse(
'{0}:edit'.format(self.url_namespace),
kwargs = {'pk': link.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 _create_cipher(self, password, salt, IV):
""" Create the cipher object to encrypt or decrypt a payload. """ |
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Cipher import AES
pw = PBKDF2(password, salt, dkLen=self.block_size)
return AES.new(pw[:self.block_size], AES.MODE_CFB, IV) |
<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_file(self):
""" Initialize a new password file and set the reference password. """ |
self.keyring_key = self._get_new_password()
# set a reference password, used to check that the password provided
# matches for subsequent checks.
self.set_password('keyring-setting',
'password reference',
'password reference 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 _check_file(self):
""" Check if the file exists and has the expected password reference. """ |
if not os.path.exists(self.file_path):
return False
self._migrate()
config = configparser.RawConfigParser()
config.read(self.file_path)
try:
config.get(
escape_for_ini('keyring-setting'),
escape_for_ini('password reference'... |
<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_version(self, config):
""" check for a valid version an existing scheme implies an existing version as well return True, if version is valid, and Fals... |
try:
self.file_version = config.get(
escape_for_ini('keyring-setting'),
escape_for_ini('version'),
)
except (configparser.NoSectionError, configparser.NoOptionError):
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unlock(self):
""" Unlock this keyring by getting the password for the keyring from the user. """ |
self.keyring_key = getpass.getpass(
'Please enter password for encrypted keyring: ')
try:
ref_pw = self.get_password('keyring-setting', 'password reference')
assert ref_pw == 'password reference value'
except AssertionError:
self._lock()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _escape_char(c):
"Single char escape. Return the char, escaped if not already legal"
if isinstance(c, int):
c = _unichr(c)
return c if c in LEGAL_CHARS else ESCAPE_FMT % ord(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 _safe_string(self, source, encoding='utf-8'):
"""Convert unicode to string as gnomekeyring barfs on unicode""" |
if not isinstance(source, str):
return source.encode(encoding)
return str(source) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.