Search is not available for this dataset
text
stringlengths
75
104k
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.wagta...
def get_context_data(self, **kwargs): """ Returns context dictionary for view. :rtype: dict. """ #noinspection PyUnresolvedReferences query_str = self.request.GET.get('q', None) queryset = kwargs.pop('object_list', self.object_list) c...
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...
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_...
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) ...
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' ...
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. :rtyp...
def form_invalid(self, form): """ Processes an invalid form submittal. :param form: the form instance. :rtype: django.http.HttpResponse. """ meta = getattr(self.model, '_meta') #noinspection PyUnresolvedReferences messages.error( self.request...
def form_valid(self, form): """ Processes a valid form submittal. :param form: the form instance. :rtype: django.http.HttpResponse. """ #noinspection PyAttributeOutsideInit self.object = form.save() meta = getattr(self.object, '_meta') # I...
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
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 = se...
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: >>> chunked([1, 2, 3, 4, 5], 2) [(1, 2), (3, 4), (5,)] """ iterable = iter(iterable) while 1: t = tuple(islice(iterab...
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 ...
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, i...
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): lo...
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)
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(index...
def get_doctypes(self, default_doctypes=None): """Returns the doctypes (or mapping type names) to use.""" doctypes = self.type.get_mapping_type_name() if isinstance(doctypes, six.string_types): doctypes = [doctypes] return super(S, self).get_doctypes(default_doctypes=doctypes...
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...
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() ...
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 retur...
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] = FacetResu...
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 = 'qu...
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('_sou...
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...
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 ...
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: * ``...
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: >>> s = S().filter(foo='bar') ...
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:: ...
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(ti...
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))
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 ...
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(): asse...
def build_search(self): """Builds the Elasticsearch search body represented by this S. Loop over self.steps to build the search body that will be sent to Elasticsearch. This returns a Python dict. If you want the JSON that actually gets sent, then pass the return value through ...
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
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.filter...
def _process_query(self, query): """Takes a key/val pair and returns the Elasticsearch code for it""" key, val = query field_name, field_action = split_field_action(key) # Boost by name__action overrides boost by name. boost = self.field_boosts.get(key) if boost is None:...
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. ...
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(r...
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 bu...
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() ...
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(...
def raw(self): """ Build query and passes to Elasticsearch, then returns the raw format returned. """ qs = self.build_search() es = self.get_es() index = self.get_indexes() doc_type = self.get_doctypes() if doc_type and not index: rai...
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. Overr...
def raw(self): """ Build query and passes to `Elasticsearch`, then returns the raw format returned. """ es = self.get_es() params = dict(self.query_params) mlt_fields = self.mlt_fields or params.pop('mlt_fields', []) body = self.s.build_search() if self....
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', [])) ...
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. ...
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. :...
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(...
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 indexin...
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_ret...
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...
def get_password(self, service, username): """ Read the password from the file. """ assoc = self._generate_assoc(service, username) service = escape_for_ini(service) username = escape_for_ini(username) # load the passwords from the file config = configpar...
def set_password(self, service, username, password): """Write the password in the file. """ if not username: # https://github.com/jaraco/keyrings.alt/issues/21 raise ValueError("Username cannot be blank.") if not isinstance(password, string_types): rai...
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: # ...
def delete_password(self, service, username): """Delete the password for the username of the service. """ service = escape_for_ini(service) username = escape_for_ini(username) config = configparser.RawConfigParser() if os.path.exists(self.file_path): config.re...
def applicable_models(self): """ Returns a list of model classes that subclass Page and include a "tags" field. :rtype: list. """ Page = apps.get_model('wagtailcore', 'Page') applicable = [] for model in apps.get_models(): ...
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.wagtail...
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 ready(self): """ Finalizes application configuration. """ import wagtailplus.wagtailrelations.signals.handlers self.add_relationship_panels() self.add_relationship_methods() super(WagtailRelationsAppConfig, self).ready()
def applicable_models(self): """ Returns a list of model classes that subclass Page. :rtype: list. """ Page = apps.get_model('wagtailcore', 'Page') applicable = [] for model in apps.get_models(): if issubclass(model, Page): ...
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.applic...
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...
def ready(self): """ Finalizes application configuration. """ self.add_rollback_panels() self.add_rollback_methods() super(WagtailRollbacksAppConfig, self).ready()
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
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', } ...
def get_related_with_scores(page): """ Returns list of related tuples (Entry instance, score) for specified page. :param page: the page instance. :rtype: list. """ related = [] entry = Entry.get_for_model(page) if entry: related = entry.related_with_scores return rel...
def get_password(self, service, username): """Get password of the username for the service """ init_part = self._keyring.get_password(service, username) if init_part: parts = [init_part] i = 1 while True: next_part = self._keyring.get_p...
def set_password(self, service, username, password): """Set password for the username of the service """ segments = range(0, len(password), self._max_password_size) password_parts = [ password[i:i + self._max_password_size] for i in segments] for i, password_part in e...
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. ...
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_loca...
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(dbsign...
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(dbs...
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(), ...
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_si...
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('keyri...
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: ...
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-setti...
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 ...
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)
def unescape(value): """ Inverse of escape. """ pattern = ESCAPE_FMT.replace('%02X', '(?P<code>[0-9A-Fa-f]{2})') # the pattern must be bytes to operate on bytes pattern_bytes = pattern.encode('ascii') re_esc = re.compile(pattern_bytes) return re_esc.sub(_unescape_code, value.encode('asci...
def _find_passwords(self, service, username, deleting=False): """Get password of the username for the service """ passwords = [] service = self._safe_string(service) username = self._safe_string(username) for attrs_tuple in (('username', 'service'), ('user', 'domain')): ...
def get_password(self, service, username): """Get password of the username for the service """ items = self._find_passwords(service, username) if not items: return None secret = items[0].secret return ( secret if isinstance(secret, six...
def set_password(self, service, username, password): """Set password for the username of the service """ service = self._safe_string(service) username = self._safe_string(username) password = self._safe_string(password) attrs = GnomeKeyring.Attribute.list_new() Gn...
def delete_password(self, service, username): """Delete the password for the username of the service. """ items = self._find_passwords(service, username, deleting=True) if not items: raise PasswordDeleteError("Password not found") for current in items: res...
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)
def get_context_data(self, **kwargs): """ Returns context dictionary for view. :rtype: dict. """ kwargs.update({ 'view': self, 'email_form': EmailLinkForm(), 'external_form': ExternalLinkForm(), 'type_email': ...
def post(self, request, *args, **kwargs): """ Returns POST response. :param request: the request instance. :rtype: django.http.HttpResponse. """ form = None link_type = int(request.POST.get('link_type', 0)) if link_type == Link.LINK_TYPE_EMAIL: ...
def get_form_class(self): """ Returns form class to use in the view. :rtype: django.forms.ModelForm. """ if self.object.link_type == Link.LINK_TYPE_EMAIL: return EmailLinkForm elif self.object.link_type == Link.LINK_TYPE_EXTERNAL: return ExternalL...
def get_password(self, service, username): """Get password of the username for the service """ try: # fetch the password key = self._key_for_service(service) hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key) password_saved = winreg.QueryValueEx(...
def set_password(self, service, username, password): """Write the password to the registry """ # encrypt the password password_encrypted = _win_crypto.encrypt(password.encode('utf-8')) # encode with base64 password_base64 = base64.encodestring(password_encrypted) ...
def delete_password(self, service, username): """Delete the password for the username of the service. """ try: key_name = self._key_for_service(service) hkey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, key_name, 0, winreg.KEY_ALL_ACCESS) ...
def encrypt(self, password): """Encrypt the password. """ if not password or not self._crypter: return password or b'' return self._crypter.encrypt(password)
def decrypt(self, password_encrypted): """Decrypt the password. """ if not password_encrypted or not self._crypter: return password_encrypted or b'' return self._crypter.decrypt(password_encrypted)
def _open(self, mode='r'): """Open the password file in the specified mode """ open_file = None writeable = 'w' in mode or 'a' in mode or '+' in mode try: # NOTE: currently the MemOpener does not split off any filename # which causes errors on close(...
def config(self): """load the passwords from the config file """ if not hasattr(self, '_config'): raw_config = configparser.RawConfigParser() f = self._open() if f: raw_config.readfp(f) f.close() self._config = raw_c...
def get_password(self, service, username): """Read the password from the file. """ service = escape_for_ini(service) username = escape_for_ini(username) # fetch the password try: password_base64 = self.config.get(service, username).encode() # deco...
def set_password(self, service, username, password): """Write the password in the file. """ service = escape_for_ini(service) username = escape_for_ini(username) # encrypt the password password = password or '' password_encrypted = self.encrypt(password.encode('u...
def get_queryset(self): """ Returns queryset limited to categories with live Entry instances. :rtype: django.db.models.query.QuerySet. """ queryset = super(LiveEntryCategoryManager, self).get_queryset() return queryset.filter(tag__in=[ entry_tag.tag ...
def get_for_model(self, model): """ Returns tuple (Entry instance, created) for specified model instance. :rtype: wagtailplus.wagtailrelations.models.Entry. """ return self.get_or_create( content_type = ContentType.objects.get_for_model(model), ...