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 ownership. """
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 OSError like LoadLibrary if loading fails. e.g. javascriptcoregtk-3.0 should be libjavascriptcoregtk-3.0.so on unix """
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: hi = mid if lo != count and self.__get_name_cached(lo) == name: return self.__get_info_cached(lo)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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: vars()[a] = property(itemgetter(i)) del i, a return _ResultTuple
<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 names :rtype: :obj:`list` """
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: result = result[0] elif len(result) == 0: result = None return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_overrides(introspection_module): """Loads overrides for an introspection module. Either returns the same module again in case there are no overrides or a proxy module including overrides. Doesn't cache the result. """
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: has_old = module_key in sys.modules old_module = sys.modules.get(module_key) # Create a new sub type, so we can separate descriptors like # _DeprecatedAttribute for each namespace. proxy_type = type(namespace + "ProxyModule", (OverridesProxyModule, ), {}) proxy = proxy_type(introspection_module) for module_key in module_keys: sys.modules[module_key] = proxy try: override_package_name = 'pgi.overrides.' + namespace # http://bugs.python.org/issue14710 try: override_loader = get_loader(override_package_name) except AttributeError: override_loader = None # Avoid checking for an ImportError, an override might # depend on a missing module thus causing an ImportError if override_loader is None: return introspection_module override_mod = importlib.import_module(override_package_name) finally: for module_key in module_keys: del sys.modules[module_key] if has_old: sys.modules[module_key] = old_module override_all = [] if hasattr(override_mod, "__all__"): override_all = override_mod.__all__ for var in override_all: try: item = getattr(override_mod, var) except (AttributeError, TypeError): # Gedit puts a non-string in __all__, so catch TypeError here continue # make sure new classes have a proper __module__ try: if item.__module__.split(".")[-1] == namespace: item.__module__ = namespace except AttributeError: pass setattr(proxy, var, item) # Replace deprecated module level attributes with a descriptor # which emits a warning when accessed. for attr, replacement in _deprecated_attrs.pop(namespace, []): try: value = getattr(proxy, attr) except AttributeError: raise AssertionError( "%s was set deprecated but wasn't added to __all__" % attr) delattr(proxy, attr) deprecated_attr = _DeprecatedAttribute( namespace, attr, value, replacement) setattr(proxy_type, attr, deprecated_attr) return proxy
<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 old_klass = klass.__mro__[1] name = old_klass.__name__ klass.__name__ = name klass.__module__ = old_klass.__module__ setattr(module, name, klass) return klass
<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, **kwargs) 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 deprecated_attr(namespace, attr, replacement): """Marks a module level attribute as deprecated. Accessing it will emit a PyGIDeprecationWarning warning. e.g. for ``deprecated_attr("GObject", "STATUS_FOO", "GLib.Status.FOO")`` accessing GObject.STATUS_FOO will emit: "GObject.STATUS_FOO is deprecated; use GLib.Status.FOO instead" :param str namespace: The namespace of the override this is called in. :param str namespace: The attribute name (which gets added to __all__). :param str replacement: The replacement text which will be included in the warning. """
_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 of methods which return a "success" boolean and have several out arguments. Translate such a method to return the out arguments on success and None on failure. """
@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') return fail_ret return wrapped
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 import highlight from pygments.lexers import PythonLexer from pygments.formatters import TerminalFormatter except ImportError: pass else: formatter = TerminalFormatter(bg="dark") lexer = PythonLexer() file_.write(highlight(code, lexer, formatter)) return file_.write(code + "\n")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 linked libgirepository. https://bugzilla.gnome.org/show_bug.cgi?id=660879#c47 """
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} -> "{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())[0] return "{%s: %s}" % (get_type_name(key), get_type_name(value)) elif type_.__module__ in ("__builtin__", "builtins"): return type_.__name__ else: return "%s.%s" % (type_.__module__, 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 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_function(instance, info, arg_infos, arg_types, return_type, method) except NotImplementedError: messages.append("%s: %s" % (backend.NAME, traceback.format_exc())) else: break if func: return func raise NotImplementedError("\n".join(messages))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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): _map = {} @property def value(self): return int(self) def __str__(self): names = [] val = int(self) for flag, name in self._map.items(): if val & flag: names.append(name) val &= ~flag if val: names.append(str(val)) return " | ".join(sorted(names or ["Unknown"])) def __repr__(self): return "%s(%s)" % (type(self).__name__, str(self)) if flags: template = _template_flags else: template = _template cls = type(type_name, template.__bases__, dict(template.__dict__)) prefix_len = len(prefix) for value, name in ffi.typeof(type_name).elements.items(): assert name[:prefix_len] == prefix name = name[prefix_len:] setattr(cls, name, cls(value)) cls._map[value] = name return cls
<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 that depends on it. """
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' % (namespace, loaded_version)) if namespace in _versions and _versions[namespace] != version: raise ValueError('Namespace %s already requires version %s' % (namespace, _versions[namespace])) available_versions = repo.enumerate_versions(namespace) if not available_versions: raise ValueError('Namespace %s not available' % namespace) if version not in available_versions: raise ValueError('Namespace %s not available for version %s' % (namespace, version)) _versions[namespace] = 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 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. If an item is returned all yielded before are invalid. """
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 before are invalid. """
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_struct # Add methods for method_info in struct_info.get_methods(): add_method(method_info, cls) # Add fields for field_info in struct_info.get_fields(): field_name = escape_identifier(field_info.name) attr = FieldAttribute(field_name, field_info) setattr(cls, field_name, attr) return cls
<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 mind that the pgi version is different from the pygobject one. """
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") # replace and tell the import hook import pgi import pgi.repository sys.modules["gi"] = pgi sys.modules["gi.repository"] = pgi.repository const.PREFIX.append("gi.repository")
<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_cls: the panel class. :param heading: the panel heading. :param index: the index position to insert at. """
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: edit_handler.children.append(panel_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 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. :param queryset: the queryset instance to paginate. :param page_size: the number of instances per page. :rtype: tuple. """
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_num = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 # Default to a valid page. try: page = paginator.page(page_num) except PageNotAnInteger: page = paginator.page(1) except EmptyPage: page = paginator.page(paginator.num_pages) #noinspection PyRedundantParentheses return (paginator, page, page.object_list, page.has_other_pages())
<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.HttpResponse. """
#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( meta.verbose_name.lower(), str(self.object) ) ) return redirect(success_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 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), (3, 4), (5,)] """
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'])) if 'details' in explanation: details = '\n'.join( [format_explanation(subtree, indent, indent_level + 1) for subtree in explanation['details']]) return line + '\n' + details return line
<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 create the ElasticSearch object. You can override any of the arguments isted in :py:func:`elasticutils.get_es`. For example, if you wanted to create an ElasticSearch with a longer timeout to a different cluster, you'd do: """
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 ElasticSearch instance to use. """
@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 into account settings in ``settings.py``. """
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 name. By default, this uses `.get_mapping_type()` to determine the mapping and returns the value in `settings.ES_INDEXES` for that or ``settings.ES_INDEXES['default']``. Override this to compute it differently. :returns: index name to use """
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[0] return 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=True) :returns: iterable of ids of objects to be indexed """
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 aggressively re-use `Elasticsearch` objects with the following rules: 1. if you pass the same argument values to `get_es()`, then it will return the same `Elasticsearch` object 2. if you pass different argument values to `get_es()`, then it will return different `Elasticsearch` object 3. it caches each `Elasticsearch` object that gets created 4. if you pass in `force_new=True`, then you are guaranteed to get a fresh `Elasticsearch` object AND that object will not be cached :arg urls: list of uris; Elasticsearch hosts to connect to, defaults to ``['http://localhost:9200']`` :arg timeout: int; the timeout in seconds, defaults to 5 :arg force_new: Forces get_es() to generate a new Elasticsearch object rather than pulling it from cache. :arg settings: other settings to pass into Elasticsearch constructor; See `<http://elasticsearch-py.readthedocs.org/>`_ for more details. Examples:: # Returns cached Elasticsearch object es = get_es() # Returns a new Elasticsearch object es = get_es(force_new=True) es = get_es(urls=['localhost']) es = get_es(urls=['localhost:9200'], timeout=10, max_retries=3) """
# 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, **settings) if key in _cached_elasticsearch: return _cached_elasticsearch[key] es = Elasticsearch(urls, timeout=timeout, **settings) if not force_new: # We don't need to rebuild the key here since we built it in # the previous if block, so it's in the namespace. Having said # that, this is a little ew. _cached_elasticsearch[key] = es return 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 _facet_counts(items): """Returns facet counts as dict. Given the `items()` on the raw dictionary from Elasticsearch this processes it and returns the counts keyed on the facet name provided in the original query. """
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}} return {name: 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 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), # The document type type=result.get('_type', None), # Explanation of score explanation=result.get('_explanation', {}), # Highlight bits highlight=result.get('highlight', {}) ) # Put the id on the object for convenience obj._id = result.get('_id', 0) 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 _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 = self_filters f.filters[0][conn].extend(other_filters) elif conn in other.filters[0]: f.filters = other_filters f.filters[0][conn].extend(self_filters) else: f.filters = [{conn: self_filters + other_filters}] return f
<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 something different. :arg obj: Python datastructure :returns: Python datastructure with strings converted to Python types .. Note:: This does the conversion in-place! """
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: return datetime.strptime(obj, '%Y-%m-%dT%H:%M:%S') except (TypeError, ValueError): pass elif len(obj) == 10: try: return datetime.strptime(obj, '%Y-%m-%d') except (TypeError, ValueError): pass elif isinstance(obj, dict): for key, val in obj.items(): obj[key] = self.to_python(val) elif isinstance(obj, list): return [self.to_python(item) for item in obj] 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 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 :arg kw: queries in the form of ``field__action=value`` There are three special flags you can use: * ``must=True``: Specifies that the queries and kw queries **must match** in order for a document to be in the result. If you don't specify a special flag, this is the default. * ``should=True``: Specifies that the queries and kw queries **should match** in order for a document to be in the result. * ``must_not=True``: Specifies the queries and kw queries **must not match** in order for a document to be in the result. These flags work by putting those queries in the appropriate clause of an Elasticsearch boolean query. Examples: Notes: 1. Don't specify multiple special flags, but if you did, `should` takes precedence. 2. If you don't specify any, it defaults to `must`. 3. You can specify special flags in the :py:class:`elasticutils.Q`, too. If you're building your query incrementally, using :py:class:`elasticutils.Q` helps a lot. See the documentation on :py:class:`elasticutils.Q` for more details on composing queries with Q. See the documentation on :py:class:`elasticutils.S` for more details on adding support for more query types. """
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 the # equivalent Q and then add it in. or_query['should'] = True q += Q(**or_query) q += Q(**kw) return self._clone(next_step=('query', 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 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 :arg kw: this will be in the form of ``field__action=value`` Examples: By default, everything is combined using AND. If you provide multiple filters in a single filter call, those are ANDed together. If you provide multiple filters in multiple filter calls, those are ANDed together. If you want something different, use the F class which supports ``&`` (and), ``|`` (or) and ``~`` (not) operators. Then call filter once with the resulting F instance. See the documentation on :py:class:`elasticutils.F` for more details on composing filters with F. See the documentation on :py:class:`elasticutils.S` for more details on adding support for new filter types. """
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 set of arguments where the keys are either field names or field name + ``__`` + field action. Examples:: q = (S().query(title='taco trucks', description__match='awesome') .boost(title=4.0, description__match=2.0)) If the key is a field name, then the boost will apply to all query bits that have that field name. For example:: q = (S().query(title='trucks', title__prefix='trucks', title__fuzzy='trucks') .boost(title=4.0)) applies a 4.0 boost to all three query bits because all three query bits are for the title field name. If the key is a field name and field action, then the boost will apply only to that field name and field action. For example:: q = (S().query(title='trucks', title__prefix='trucks', title__fuzzy='trucks') .boost(title__prefix=4.0)) will only apply the 4.0 boost to title__prefix. Boosts are relative to one another and all boosts default to 1.0. For example, if you had:: qs = (S().boost(title=4.0, summary=2.0) .query(title__match=value, summary__match=value, content__match=value, should=True)) ``title__match`` would be boosted twice as much as ``summary__match`` and ``summary__match`` twice as much as ``content__match``. """
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 = (S().query(title='trucks') .demote(0.5, description__match='gross')) q = (S().query(title='trucks') .demote(0.5, Q(description__match='gross'))) This is implemented using the boosting query in Elasticsearch. Anything you specify with ``.query()`` goes into the positive section. The negative query and negative boost portions are specified as the first and second arguments to ``.demote()``. .. Note:: Calling this again will overwrite previous ``.demote()`` calls. """
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 looking terms for. Additional keyword options: * ``field`` -- The field to base suggestions upon, defaults to _all Results will have a ``_suggestions`` property containing the suggestions for all terms. .. Note:: Suggestions are only supported since Elasticsearch 0.90. Calling this multiple times will add multiple suggest clauses to the query. """
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: new.steps.append((key, vals)) 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 _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 JSON API filters """
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] else: key = f.keys()[0] val = f[key] key = key.strip('_') if key not in ('or', 'and', 'not', 'filter'): raise InvalidFieldActionError( '%s is not a valid connector' % f.keys()[0]) if 'filter' in val: filter_filters = self._process_filters(val['filter']) if len(filter_filters) == 1: filter_filters = filter_filters[0] rv.append({key: {'filter': filter_filters}}) else: rv.append({key: self._process_filters(val)}) else: key, val = f key, field_action = split_field_action(key) handler_name = 'process_filter_{0}'.format(field_action) if field_action and hasattr(self, handler_name): rv.append(getattr(self, handler_name)( key, val, field_action)) elif key.strip('_') in ('or', 'and', 'not'): connector = key.strip('_') rv.append({connector: self._process_filters(val.items())}) elif field_action is None: if val is None: rv.append({'missing': { 'field': key, "null_value": True}}) else: rv.append({'term': {key: val}}) elif field_action in ('startswith', 'prefix'): rv.append({'prefix': {key: val}}) elif field_action == 'in': rv.append({'in': {key: val}}) elif field_action in RANGE_ACTIONS: rv.append({'range': {key: {field_action: val}}}) elif field_action == 'range': lower, upper = val rv.append({'range': {key: {'gte': lower, 'lte': upper}}}) elif field_action == 'distance': distance, latitude, longitude = val rv.append({ 'geo_distance': { 'distance': distance, key: [longitude, latitude] } }) else: raise InvalidFieldActionError( '%s is not a valid field action' % field_action) return rv
<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 query clause value """
# 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] must_q = [self._process_query(query) for query in new_q.must_q] must_not_q = [self._process_query(query) for query in new_q.must_not_q] if len(must_q) > 1 or (len(should_q) + len(must_not_q) > 0): # If there's more than one must_q or there are must_not_q # or should_q, then we need to wrap the whole thing in a # boolean query. bool_query = {} if must_q: bool_query['must'] = must_q if should_q: bool_query['should'] = should_q if must_not_q: bool_query['must_not'] = must_not_q return {'bool': bool_query} if must_q: # There's only one must_q query and that's it, so we hoist # that. return must_q[0] 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 _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) 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 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 generates a elasticsearch Elasticsearch object. .. Note:: If you desire special behavior regarding building the Elasticsearch object for this S, subclass S and override this method. """
# .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 # created one since we don't need to do it multiple times. return default_builder(**args)
<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 return default_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 returns that `Elasticsearch`. * Otherwise, it creates a new `Elasticsearch` and returns that. Override this if that behavior isn't correct for you. """
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/value pairs representing the document .. Note:: This must be serializable into JSON. :arg id_: the id of the document .. Note:: If you don't provide an ``id_``, then Elasticsearch will make up an id for your document and it'll look like a character name from a Lovecraft novel. :arg overwrite_existing: if ``True`` overwrites existing documents of the same ID and doctype :arg es: The `Elasticsearch` to use. If you don't specify an `Elasticsearch`, it'll use `cls.get_es()`. :arg index: The name of the index to use. If you don't specify one it'll use `cls.get_index()`. .. Note:: If you need the documents available for searches immediately, make sure to refresh the index by calling ``refresh_index()``. """
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 individual documents to be added to the index .. Note:: This must be serializable into JSON. :arg id_field: The name of the field to use as the document id. This defaults to 'id'. :arg es: The `Elasticsearch` to use. If you don't specify an `Elasticsearch`, it'll use `cls.get_es()`. :arg index: The name of the index to use. If you don't specify one it'll use `cls.get_index()`. .. Note:: If you need the documents available for searches immediately, make sure to refresh the index by calling ``refresh_index()``. """
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(), raise_on_error=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 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 the index. :arg es: The `Elasticsearch` to use. If you don't specify an `Elasticsearch`, it'll use `cls.get_es()`. :arg index: The name of the index to use. If you don't specify one it'll use `cls.get_index()`. """
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 documents you just indexed in your search results right now, you should call `refresh_index` as soon as you're done indexing. This is particularly helpful for unit tests. :arg es: The `Elasticsearch` to use. If you don't specify an `Elasticsearch`, it'll use `cls.get_es()`. :arg index: The name of the index to use. If you don't specify one it'll use `cls.get_index()`. """
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 .. Note:: We can nix this whe we drop support for ES 0.90. """
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 # for 'ok' and adding an additional 'status'. for key, val in item.items(): if 'ok' in val: val['status'] = 201 return item ret = fun(self, *args, **kwargs) if 'items' in ret: ret['items'] = [fix_item(item) for item in ret['items']] return ret return _fixed_bulk Elasticsearch.bulk = normalize_bulk_return(Elasticsearch.bulk)
<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 permissions with open(self.file_path, 'w'): pass user_read_write = 0o600 os.chmod(self.file_path, user_read_write)
<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 handler. """
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 related_with_scores(instance): return instance.get_related_with_scores() def get_related(instance): entry = Entry.objects.get_for_model(instance)[0] return entry.get_related() def get_related_live(instance): entry = Entry.objects.get_for_model(instance)[0] return entry.get_related_live() def get_related_with_scores(instance): try: entry = Entry.objects.get_for_model(instance)[0] return entry.get_related_with_scores() except IntegrityError: return [] for model in self.applicable_models: model.add_to_class( 'get_related', get_related ) model.add_to_class( 'get_related_live', get_related_live ) model.add_to_class( 'get_related_with_scores', get_related_with_scores ) model.add_to_class( 'related', related ) model.add_to_class( 'related_live', related_live ) model.add_to_class( 'related_with_scores', related_with_scores )
<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( content_json = old_revision.content_json, user = user, submitted_for_moderation = submitted_for_moderation, approved_go_live_at = approved_go_live_at ) update_fields = [] instance.latest_revision_created_at = new_revision.created_at update_fields.append('latest_revision_created_at') if changed: instance.has_unpublished_changes = True update_fields.append('has_unpublished_changes') if update_fields: instance.save(update_fields=update_fields) logger.info( "Page edited: \"%s\" id=%d revision_id=%d", instance.title, instance.id, new_revision.id ) if submitted_for_moderation: logger.info( "Page submitted for moderation: \"%s\" id=%d revision_id=%d", instance.title, instance.id, new_revision.id ) return new_revision Page = apps.get_model('wagtailcore', 'Page') Page.add_to_class('rollback', page_rollback)
<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.object_id,)) 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 expand_db_attributes(attrs, for_editor): """ Given a dictionary of attributes, find the corresponding link instance and return its HTML representation. :param attrs: dictionary of link attributes. :param for_editor: whether or not HTML is for editor. :rtype: str. """
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( editor_attrs, escape(link.get_absolute_url()), link.title ) except Link.DoesNotExist: return '<a>'
<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: encrypting_keyczar = keyczar.Crypter.Read( self.encrypting_keyset_location) reader = keyczar.readers.EncryptedReader(reader, encrypting_keyczar) self._crypter = keyczar.Crypter(reader) return self._crypter
<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 a mapping_type extends Indexable, you can add a ``post_save`` hook for the model that it's based on like this:: @receiver(dbsignals.post_save, sender=MyModel) def update_in_index(sender, instance, **kw): from elasticutils.contrib.django import tasks tasks.index_objects.delay(MyMappingType, [instance.id]) :arg mapping_type: the mapping type for these ids :arg ids: the list of ids of things to index :arg chunk_size: the size of the chunk for bulk indexing .. Note:: The default chunk_size is 100. The number of documents you can bulk index at once depends on the size of the documents. :arg es: The `Elasticsearch` to use. If you don't specify an `Elasticsearch`, it'll use `mapping_type.get_es()`. :arg index: The name of the index to use. If you don't specify one it'll use `mapping_type.get_index()`. """
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. for id_list in chunked(ids, chunk_size): documents = [] for obj in model.objects.filter(id__in=id_list): try: documents.append(mapping_type.extract_document(obj.id, obj)) except Exception as exc: log.exception('Unable to extract document {0}: {1}'.format( obj, repr(exc))) if documents: mapping_type.bulk_index(documents, id_field='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 unindex_objects(mapping_type, ids, es=None, index=None): """Remove documents of a specified mapping_type from the index. This allows for asynchronous deleting. If a mapping_type extends Indexable, you can add a ``pre_delete`` hook for the model that it's based on like this:: @receiver(dbsignals.pre_delete, sender=MyModel) def remove_from_index(sender, instance, **kw): from elasticutils.contrib.django import tasks tasks.unindex_objects.delay(MyMappingType, [instance.id]) :arg mapping_type: the mapping type for these ids :arg ids: the list of ids of things to remove :arg es: The `Elasticsearch` to use. If you don't specify an `Elasticsearch`, it'll use `mapping_type.get_es()`. :arg index: The name of the index to use. If you don't specify one it'll use `mapping_type.get_index()`. """
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') self._write_config_value('keyring-setting', 'scheme', self.scheme) self._write_config_value('keyring-setting', 'version', self.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 _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'), ) except (configparser.NoSectionError, configparser.NoOptionError): return False try: self._check_scheme(config) except AttributeError: # accept a missing scheme return True return self._check_version(config)
<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 False otherwise """
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() raise ValueError("Incorrect Password")
<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)