repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
mozilla/elasticutils | elasticutils/__init__.py | _boosted_value | 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} | python | 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} | [
"def",
"_boosted_value",
"(",
"name",
",",
"action",
",",
"key",
",",
"value",
",",
"boost",
")",
":",
"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",
"}"
] | Boost a value if we should in _process_queries | [
"Boost",
"a",
"value",
"if",
"we",
"should",
"in",
"_process_queries"
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L397-L405 | train |
mozilla/elasticutils | elasticutils/__init__.py | decorate_with_metadata | 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 | python | 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 | [
"def",
"decorate_with_metadata",
"(",
"obj",
",",
"result",
")",
":",
"# 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"
] | Return obj decorated with es_meta object | [
"Return",
"obj",
"decorated",
"with",
"es_meta",
"object"
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1918-L1938 | train |
mozilla/elasticutils | elasticutils/__init__.py | F._combine | 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 | python | 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 | [
"def",
"_combine",
"(",
"self",
",",
"other",
",",
"conn",
"=",
"'and'",
")",
":",
"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"
] | OR and AND will create a new F, with the filters from both F
objects combined with the connector `conn`. | [
"OR",
"and",
"AND",
"will",
"create",
"a",
"new",
"F",
"with",
"the",
"filters",
"from",
"both",
"F",
"objects",
"combined",
"with",
"the",
"connector",
"conn",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L277-L300 | train |
mozilla/elasticutils | elasticutils/__init__.py | PythonMixin.to_python | 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 | python | 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 | [
"def",
"to_python",
"(",
"self",
",",
"obj",
")",
":",
"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"
] | 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! | [
"Converts",
"strings",
"in",
"a",
"data",
"structure",
"to",
"Python",
"types"
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L410-L451 | train |
mozilla/elasticutils | elasticutils/__init__.py | S.query | 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:
>>> s = S().query(foo='bar')
>>> s = S().query(Q(foo='bar'))
>>> s = S().query(foo='bar', bat__match='baz')
>>> s = S().query(foo='bar', should=True)
>>> s = S().query(foo='bar', should=True).query(baz='bat', must=True)
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)) | python | 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:
>>> s = S().query(foo='bar')
>>> s = S().query(Q(foo='bar'))
>>> s = S().query(foo='bar', bat__match='baz')
>>> s = S().query(foo='bar', should=True)
>>> s = S().query(foo='bar', should=True).query(baz='bat', must=True)
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)) | [
"def",
"query",
"(",
"self",
",",
"*",
"queries",
",",
"*",
"*",
"kw",
")",
":",
"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",
")",
")"
] | 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:
>>> s = S().query(foo='bar')
>>> s = S().query(Q(foo='bar'))
>>> s = S().query(foo='bar', bat__match='baz')
>>> s = S().query(foo='bar', should=True)
>>> s = S().query(foo='bar', should=True).query(baz='bat', must=True)
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. | [
"Return",
"a",
"new",
"S",
"instance",
"with",
"query",
"args",
"combined",
"with",
"existing",
"set",
"in",
"a",
"must",
"boolean",
"query",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L694-L759 | train |
mozilla/elasticutils | elasticutils/__init__.py | S.filter | 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')
>>> s = S().filter(F(foo='bar'))
>>> s = S().filter(foo='bar', bat='baz')
>>> s = S().filter(foo='bar').filter(bat='baz')
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)) | python | 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')
>>> s = S().filter(F(foo='bar'))
>>> s = S().filter(foo='bar', bat='baz')
>>> s = S().filter(foo='bar').filter(bat='baz')
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)) | [
"def",
"filter",
"(",
"self",
",",
"*",
"filters",
",",
"*",
"*",
"kw",
")",
":",
"items",
"=",
"kw",
".",
"items",
"(",
")",
"if",
"six",
".",
"PY3",
":",
"items",
"=",
"list",
"(",
"items",
")",
"return",
"self",
".",
"_clone",
"(",
"next_step",
"=",
"(",
"'filter'",
",",
"list",
"(",
"filters",
")",
"+",
"items",
")",
")"
] | 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')
>>> s = S().filter(F(foo='bar'))
>>> s = S().filter(foo='bar', bat='baz')
>>> s = S().filter(foo='bar').filter(bat='baz')
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. | [
"Return",
"a",
"new",
"S",
"instance",
"with",
"filter",
"args",
"combined",
"with",
"existing",
"set",
"with",
"AND",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L782-L817 | train |
mozilla/elasticutils | elasticutils/__init__.py | S.boost | 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 | python | 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 | [
"def",
"boost",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"new",
"=",
"self",
".",
"_clone",
"(",
")",
"new",
".",
"field_boosts",
".",
"update",
"(",
"kw",
")",
"return",
"new"
] | 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``. | [
"Return",
"a",
"new",
"S",
"instance",
"with",
"field",
"boosts",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L839-L897 | train |
mozilla/elasticutils | elasticutils/__init__.py | S.demote | 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))) | python | 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))) | [
"def",
"demote",
"(",
"self",
",",
"amount_",
",",
"*",
"queries",
",",
"*",
"*",
"kw",
")",
":",
"q",
"=",
"Q",
"(",
")",
"for",
"query",
"in",
"queries",
":",
"q",
"+=",
"query",
"q",
"+=",
"Q",
"(",
"*",
"*",
"kw",
")",
"return",
"self",
".",
"_clone",
"(",
"next_step",
"=",
"(",
"'demote'",
",",
"(",
"amount_",
",",
"q",
")",
")",
")"
] | 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. | [
"Returns",
"a",
"new",
"S",
"instance",
"with",
"boosting",
"query",
"and",
"demotion",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L899-L928 | train |
mozilla/elasticutils | elasticutils/__init__.py | S.facet_raw | 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)) | python | 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",
"facet_raw",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"items",
"=",
"kw",
".",
"items",
"(",
")",
"if",
"six",
".",
"PY3",
":",
"items",
"=",
"list",
"(",
"items",
")",
"return",
"self",
".",
"_clone",
"(",
"next_step",
"=",
"(",
"'facet_raw'",
",",
"items",
")",
")"
] | Return a new S instance with raw facet args combined with
existing set. | [
"Return",
"a",
"new",
"S",
"instance",
"with",
"raw",
"facet",
"args",
"combined",
"with",
"existing",
"set",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L944-L952 | train |
mozilla/elasticutils | elasticutils/__init__.py | S.suggest | 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))) | python | 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))) | [
"def",
"suggest",
"(",
"self",
",",
"name",
",",
"term",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_clone",
"(",
"next_step",
"=",
"(",
"'suggest'",
",",
"(",
"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. | [
"Set",
"suggestion",
"options",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1019-L1039 | train |
mozilla/elasticutils | elasticutils/__init__.py | S.extra | 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 | python | 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 | [
"def",
"extra",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"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"
] | Return a new S instance with extra args combined with existing
set. | [
"Return",
"a",
"new",
"S",
"instance",
"with",
"extra",
"args",
"combined",
"with",
"existing",
"set",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1041-L1055 | train |
mozilla/elasticutils | elasticutils/__init__.py | S.build_search | 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 :py:func:`elasticutils.utils.to_json`.
:returns: a Python dict
"""
filters = []
filters_raw = None
queries = []
query_raw = None
sort = []
dict_fields = set()
list_fields = set()
facets = {}
facets_raw = {}
demote = None
highlight_fields = set()
highlight_options = {}
suggestions = {}
explain = False
as_list = as_dict = False
search_type = None
for action, value in self.steps:
if action == 'order_by':
sort = []
for key in value:
if isinstance(key, string_types) and key.startswith('-'):
sort.append({key[1:]: 'desc'})
else:
sort.append(key)
elif action == 'values_list':
if not value:
list_fields = set()
else:
list_fields |= set(value)
as_list, as_dict = True, False
elif action == 'values_dict':
if not value:
dict_fields = set()
else:
dict_fields |= set(value)
as_list, as_dict = False, True
elif action == 'explain':
explain = value
elif action == 'query':
queries.append(value)
elif action == 'query_raw':
query_raw = value
elif action == 'demote':
# value here is a tuple of (negative_boost, query)
demote = value
elif action == 'filter':
filters.extend(self._process_filters(value))
elif action == 'filter_raw':
filters_raw = value
elif action == 'facet':
# value here is a (args, kwargs) tuple
facets.update(_process_facets(*value))
elif action == 'facet_raw':
facets_raw.update(dict(value))
elif action == 'highlight':
if value[0] == (None,):
highlight_fields = set()
else:
highlight_fields |= set(value[0])
highlight_options.update(value[1])
elif action == 'search_type':
search_type = value
elif action == 'suggest':
suggestions[value[0]] = (value[1], value[2])
elif action in ('es', 'indexes', 'doctypes', 'boost'):
# Ignore these--we use these elsewhere, but want to
# make sure lack of handling it here doesn't throw an
# error.
pass
else:
raise NotImplementedError(action)
qs = {}
# If there's a filters_raw, we use that.
if filters_raw:
qs['filter'] = filters_raw
else:
if len(filters) > 1:
qs['filter'] = {'and': filters}
elif filters:
qs['filter'] = filters[0]
# If there's a query_raw, we use that. Otherwise we use
# whatever we got from query and demote.
if query_raw:
qs['query'] = query_raw
else:
pq = self._process_queries(queries)
if demote is not None:
qs['query'] = {
'boosting': {
'negative': self._process_queries([demote[1]]),
'negative_boost': demote[0]
}
}
if pq:
qs['query']['boosting']['positive'] = pq
elif pq:
qs['query'] = pq
if as_list:
fields = qs['fields'] = list(list_fields) if list_fields else ['*']
elif as_dict:
fields = qs['fields'] = list(dict_fields) if dict_fields else ['*']
else:
fields = set()
if facets:
qs['facets'] = facets
# Hunt for `facet_filter` shells and update those. We use
# None as a shell, so if it's explicitly set to None, then
# we update it.
for facet in facets.values():
if facet.get('facet_filter', 1) is None and 'filter' in qs:
facet['facet_filter'] = qs['filter']
if facets_raw:
qs.setdefault('facets', {}).update(facets_raw)
if sort:
qs['sort'] = sort
if self.start:
qs['from'] = self.start
if self.stop is not None:
qs['size'] = self.stop - self.start
if highlight_fields:
qs['highlight'] = self._build_highlight(
highlight_fields, highlight_options)
if explain:
qs['explain'] = True
for suggestion, (term, kwargs) in six.iteritems(suggestions):
qs.setdefault('suggest', {})[suggestion] = {
'text': term,
'term': {
'field': kwargs.get('field', '_all'),
},
}
self.fields, self.as_list, self.as_dict = fields, as_list, as_dict
self.search_type = search_type
return qs | python | 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 :py:func:`elasticutils.utils.to_json`.
:returns: a Python dict
"""
filters = []
filters_raw = None
queries = []
query_raw = None
sort = []
dict_fields = set()
list_fields = set()
facets = {}
facets_raw = {}
demote = None
highlight_fields = set()
highlight_options = {}
suggestions = {}
explain = False
as_list = as_dict = False
search_type = None
for action, value in self.steps:
if action == 'order_by':
sort = []
for key in value:
if isinstance(key, string_types) and key.startswith('-'):
sort.append({key[1:]: 'desc'})
else:
sort.append(key)
elif action == 'values_list':
if not value:
list_fields = set()
else:
list_fields |= set(value)
as_list, as_dict = True, False
elif action == 'values_dict':
if not value:
dict_fields = set()
else:
dict_fields |= set(value)
as_list, as_dict = False, True
elif action == 'explain':
explain = value
elif action == 'query':
queries.append(value)
elif action == 'query_raw':
query_raw = value
elif action == 'demote':
# value here is a tuple of (negative_boost, query)
demote = value
elif action == 'filter':
filters.extend(self._process_filters(value))
elif action == 'filter_raw':
filters_raw = value
elif action == 'facet':
# value here is a (args, kwargs) tuple
facets.update(_process_facets(*value))
elif action == 'facet_raw':
facets_raw.update(dict(value))
elif action == 'highlight':
if value[0] == (None,):
highlight_fields = set()
else:
highlight_fields |= set(value[0])
highlight_options.update(value[1])
elif action == 'search_type':
search_type = value
elif action == 'suggest':
suggestions[value[0]] = (value[1], value[2])
elif action in ('es', 'indexes', 'doctypes', 'boost'):
# Ignore these--we use these elsewhere, but want to
# make sure lack of handling it here doesn't throw an
# error.
pass
else:
raise NotImplementedError(action)
qs = {}
# If there's a filters_raw, we use that.
if filters_raw:
qs['filter'] = filters_raw
else:
if len(filters) > 1:
qs['filter'] = {'and': filters}
elif filters:
qs['filter'] = filters[0]
# If there's a query_raw, we use that. Otherwise we use
# whatever we got from query and demote.
if query_raw:
qs['query'] = query_raw
else:
pq = self._process_queries(queries)
if demote is not None:
qs['query'] = {
'boosting': {
'negative': self._process_queries([demote[1]]),
'negative_boost': demote[0]
}
}
if pq:
qs['query']['boosting']['positive'] = pq
elif pq:
qs['query'] = pq
if as_list:
fields = qs['fields'] = list(list_fields) if list_fields else ['*']
elif as_dict:
fields = qs['fields'] = list(dict_fields) if dict_fields else ['*']
else:
fields = set()
if facets:
qs['facets'] = facets
# Hunt for `facet_filter` shells and update those. We use
# None as a shell, so if it's explicitly set to None, then
# we update it.
for facet in facets.values():
if facet.get('facet_filter', 1) is None and 'filter' in qs:
facet['facet_filter'] = qs['filter']
if facets_raw:
qs.setdefault('facets', {}).update(facets_raw)
if sort:
qs['sort'] = sort
if self.start:
qs['from'] = self.start
if self.stop is not None:
qs['size'] = self.stop - self.start
if highlight_fields:
qs['highlight'] = self._build_highlight(
highlight_fields, highlight_options)
if explain:
qs['explain'] = True
for suggestion, (term, kwargs) in six.iteritems(suggestions):
qs.setdefault('suggest', {})[suggestion] = {
'text': term,
'term': {
'field': kwargs.get('field', '_all'),
},
}
self.fields, self.as_list, self.as_dict = fields, as_list, as_dict
self.search_type = search_type
return qs | [
"def",
"build_search",
"(",
"self",
")",
":",
"filters",
"=",
"[",
"]",
"filters_raw",
"=",
"None",
"queries",
"=",
"[",
"]",
"query_raw",
"=",
"None",
"sort",
"=",
"[",
"]",
"dict_fields",
"=",
"set",
"(",
")",
"list_fields",
"=",
"set",
"(",
")",
"facets",
"=",
"{",
"}",
"facets_raw",
"=",
"{",
"}",
"demote",
"=",
"None",
"highlight_fields",
"=",
"set",
"(",
")",
"highlight_options",
"=",
"{",
"}",
"suggestions",
"=",
"{",
"}",
"explain",
"=",
"False",
"as_list",
"=",
"as_dict",
"=",
"False",
"search_type",
"=",
"None",
"for",
"action",
",",
"value",
"in",
"self",
".",
"steps",
":",
"if",
"action",
"==",
"'order_by'",
":",
"sort",
"=",
"[",
"]",
"for",
"key",
"in",
"value",
":",
"if",
"isinstance",
"(",
"key",
",",
"string_types",
")",
"and",
"key",
".",
"startswith",
"(",
"'-'",
")",
":",
"sort",
".",
"append",
"(",
"{",
"key",
"[",
"1",
":",
"]",
":",
"'desc'",
"}",
")",
"else",
":",
"sort",
".",
"append",
"(",
"key",
")",
"elif",
"action",
"==",
"'values_list'",
":",
"if",
"not",
"value",
":",
"list_fields",
"=",
"set",
"(",
")",
"else",
":",
"list_fields",
"|=",
"set",
"(",
"value",
")",
"as_list",
",",
"as_dict",
"=",
"True",
",",
"False",
"elif",
"action",
"==",
"'values_dict'",
":",
"if",
"not",
"value",
":",
"dict_fields",
"=",
"set",
"(",
")",
"else",
":",
"dict_fields",
"|=",
"set",
"(",
"value",
")",
"as_list",
",",
"as_dict",
"=",
"False",
",",
"True",
"elif",
"action",
"==",
"'explain'",
":",
"explain",
"=",
"value",
"elif",
"action",
"==",
"'query'",
":",
"queries",
".",
"append",
"(",
"value",
")",
"elif",
"action",
"==",
"'query_raw'",
":",
"query_raw",
"=",
"value",
"elif",
"action",
"==",
"'demote'",
":",
"# value here is a tuple of (negative_boost, query)",
"demote",
"=",
"value",
"elif",
"action",
"==",
"'filter'",
":",
"filters",
".",
"extend",
"(",
"self",
".",
"_process_filters",
"(",
"value",
")",
")",
"elif",
"action",
"==",
"'filter_raw'",
":",
"filters_raw",
"=",
"value",
"elif",
"action",
"==",
"'facet'",
":",
"# value here is a (args, kwargs) tuple",
"facets",
".",
"update",
"(",
"_process_facets",
"(",
"*",
"value",
")",
")",
"elif",
"action",
"==",
"'facet_raw'",
":",
"facets_raw",
".",
"update",
"(",
"dict",
"(",
"value",
")",
")",
"elif",
"action",
"==",
"'highlight'",
":",
"if",
"value",
"[",
"0",
"]",
"==",
"(",
"None",
",",
")",
":",
"highlight_fields",
"=",
"set",
"(",
")",
"else",
":",
"highlight_fields",
"|=",
"set",
"(",
"value",
"[",
"0",
"]",
")",
"highlight_options",
".",
"update",
"(",
"value",
"[",
"1",
"]",
")",
"elif",
"action",
"==",
"'search_type'",
":",
"search_type",
"=",
"value",
"elif",
"action",
"==",
"'suggest'",
":",
"suggestions",
"[",
"value",
"[",
"0",
"]",
"]",
"=",
"(",
"value",
"[",
"1",
"]",
",",
"value",
"[",
"2",
"]",
")",
"elif",
"action",
"in",
"(",
"'es'",
",",
"'indexes'",
",",
"'doctypes'",
",",
"'boost'",
")",
":",
"# Ignore these--we use these elsewhere, but want to",
"# make sure lack of handling it here doesn't throw an",
"# error.",
"pass",
"else",
":",
"raise",
"NotImplementedError",
"(",
"action",
")",
"qs",
"=",
"{",
"}",
"# If there's a filters_raw, we use that.",
"if",
"filters_raw",
":",
"qs",
"[",
"'filter'",
"]",
"=",
"filters_raw",
"else",
":",
"if",
"len",
"(",
"filters",
")",
">",
"1",
":",
"qs",
"[",
"'filter'",
"]",
"=",
"{",
"'and'",
":",
"filters",
"}",
"elif",
"filters",
":",
"qs",
"[",
"'filter'",
"]",
"=",
"filters",
"[",
"0",
"]",
"# If there's a query_raw, we use that. Otherwise we use",
"# whatever we got from query and demote.",
"if",
"query_raw",
":",
"qs",
"[",
"'query'",
"]",
"=",
"query_raw",
"else",
":",
"pq",
"=",
"self",
".",
"_process_queries",
"(",
"queries",
")",
"if",
"demote",
"is",
"not",
"None",
":",
"qs",
"[",
"'query'",
"]",
"=",
"{",
"'boosting'",
":",
"{",
"'negative'",
":",
"self",
".",
"_process_queries",
"(",
"[",
"demote",
"[",
"1",
"]",
"]",
")",
",",
"'negative_boost'",
":",
"demote",
"[",
"0",
"]",
"}",
"}",
"if",
"pq",
":",
"qs",
"[",
"'query'",
"]",
"[",
"'boosting'",
"]",
"[",
"'positive'",
"]",
"=",
"pq",
"elif",
"pq",
":",
"qs",
"[",
"'query'",
"]",
"=",
"pq",
"if",
"as_list",
":",
"fields",
"=",
"qs",
"[",
"'fields'",
"]",
"=",
"list",
"(",
"list_fields",
")",
"if",
"list_fields",
"else",
"[",
"'*'",
"]",
"elif",
"as_dict",
":",
"fields",
"=",
"qs",
"[",
"'fields'",
"]",
"=",
"list",
"(",
"dict_fields",
")",
"if",
"dict_fields",
"else",
"[",
"'*'",
"]",
"else",
":",
"fields",
"=",
"set",
"(",
")",
"if",
"facets",
":",
"qs",
"[",
"'facets'",
"]",
"=",
"facets",
"# Hunt for `facet_filter` shells and update those. We use",
"# None as a shell, so if it's explicitly set to None, then",
"# we update it.",
"for",
"facet",
"in",
"facets",
".",
"values",
"(",
")",
":",
"if",
"facet",
".",
"get",
"(",
"'facet_filter'",
",",
"1",
")",
"is",
"None",
"and",
"'filter'",
"in",
"qs",
":",
"facet",
"[",
"'facet_filter'",
"]",
"=",
"qs",
"[",
"'filter'",
"]",
"if",
"facets_raw",
":",
"qs",
".",
"setdefault",
"(",
"'facets'",
",",
"{",
"}",
")",
".",
"update",
"(",
"facets_raw",
")",
"if",
"sort",
":",
"qs",
"[",
"'sort'",
"]",
"=",
"sort",
"if",
"self",
".",
"start",
":",
"qs",
"[",
"'from'",
"]",
"=",
"self",
".",
"start",
"if",
"self",
".",
"stop",
"is",
"not",
"None",
":",
"qs",
"[",
"'size'",
"]",
"=",
"self",
".",
"stop",
"-",
"self",
".",
"start",
"if",
"highlight_fields",
":",
"qs",
"[",
"'highlight'",
"]",
"=",
"self",
".",
"_build_highlight",
"(",
"highlight_fields",
",",
"highlight_options",
")",
"if",
"explain",
":",
"qs",
"[",
"'explain'",
"]",
"=",
"True",
"for",
"suggestion",
",",
"(",
"term",
",",
"kwargs",
")",
"in",
"six",
".",
"iteritems",
"(",
"suggestions",
")",
":",
"qs",
".",
"setdefault",
"(",
"'suggest'",
",",
"{",
"}",
")",
"[",
"suggestion",
"]",
"=",
"{",
"'text'",
":",
"term",
",",
"'term'",
":",
"{",
"'field'",
":",
"kwargs",
".",
"get",
"(",
"'field'",
",",
"'_all'",
")",
",",
"}",
",",
"}",
"self",
".",
"fields",
",",
"self",
".",
"as_list",
",",
"self",
".",
"as_dict",
"=",
"fields",
",",
"as_list",
",",
"as_dict",
"self",
".",
"search_type",
"=",
"search_type",
"return",
"qs"
] | 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 :py:func:`elasticutils.utils.to_json`.
:returns: a Python dict | [
"Builds",
"the",
"Elasticsearch",
"search",
"body",
"represented",
"by",
"this",
"S",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1067-L1227 | train |
mozilla/elasticutils | elasticutils/__init__.py | S._build_highlight | 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 | python | 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",
"_build_highlight",
"(",
"self",
",",
"fields",
",",
"options",
")",
":",
"ret",
"=",
"{",
"'fields'",
":",
"dict",
"(",
"(",
"f",
",",
"{",
"}",
")",
"for",
"f",
"in",
"fields",
")",
",",
"'order'",
":",
"'score'",
"}",
"ret",
".",
"update",
"(",
"options",
")",
"return",
"ret"
] | Return the portion of the query that controls highlighting. | [
"Return",
"the",
"portion",
"of",
"the",
"query",
"that",
"controls",
"highlighting",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1229-L1234 | train |
mozilla/elasticutils | elasticutils/__init__.py | S._process_filters | 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 | python | 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 | [
"def",
"_process_filters",
"(",
"self",
",",
"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"
] | 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 | [
"Takes",
"a",
"list",
"of",
"filters",
"and",
"returns",
"ES",
"JSON",
"API"
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1236-L1318 | train |
mozilla/elasticutils | elasticutils/__init__.py | S._process_query | 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:
boost = self.field_boosts.get(field_name)
handler_name = 'process_query_{0}'.format(field_action)
if field_action and hasattr(self, handler_name):
return getattr(self, handler_name)(field_name, val, field_action)
elif field_action in QUERY_ACTION_MAP:
return {
QUERY_ACTION_MAP[field_action]: _boosted_value(
field_name, field_action, key, val, boost)
}
elif field_action == 'query_string':
# query_string has different syntax, so it's handled
# differently.
#
# Note: query_string queries are not boosted with
# .boost()---they're boosted in the query text itself.
return {
'query_string': {'default_field': field_name, 'query': val}
}
elif field_action in RANGE_ACTIONS:
# Ranges are special and have a different syntax, so
# we handle them separately.
return {
'range': {field_name: _boosted_value(
field_action, field_action, key, val, boost)}
}
elif field_action == 'range':
lower, upper = val
value = {
'gte': lower,
'lte': upper,
}
if boost:
value['boost'] = boost
return {'range': {field_name: value}}
raise InvalidFieldActionError(
'%s is not a valid field action' % field_action) | python | 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:
boost = self.field_boosts.get(field_name)
handler_name = 'process_query_{0}'.format(field_action)
if field_action and hasattr(self, handler_name):
return getattr(self, handler_name)(field_name, val, field_action)
elif field_action in QUERY_ACTION_MAP:
return {
QUERY_ACTION_MAP[field_action]: _boosted_value(
field_name, field_action, key, val, boost)
}
elif field_action == 'query_string':
# query_string has different syntax, so it's handled
# differently.
#
# Note: query_string queries are not boosted with
# .boost()---they're boosted in the query text itself.
return {
'query_string': {'default_field': field_name, 'query': val}
}
elif field_action in RANGE_ACTIONS:
# Ranges are special and have a different syntax, so
# we handle them separately.
return {
'range': {field_name: _boosted_value(
field_action, field_action, key, val, boost)}
}
elif field_action == 'range':
lower, upper = val
value = {
'gte': lower,
'lte': upper,
}
if boost:
value['boost'] = boost
return {'range': {field_name: value}}
raise InvalidFieldActionError(
'%s is not a valid field action' % field_action) | [
"def",
"_process_query",
"(",
"self",
",",
"query",
")",
":",
"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",
":",
"boost",
"=",
"self",
".",
"field_boosts",
".",
"get",
"(",
"field_name",
")",
"handler_name",
"=",
"'process_query_{0}'",
".",
"format",
"(",
"field_action",
")",
"if",
"field_action",
"and",
"hasattr",
"(",
"self",
",",
"handler_name",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"handler_name",
")",
"(",
"field_name",
",",
"val",
",",
"field_action",
")",
"elif",
"field_action",
"in",
"QUERY_ACTION_MAP",
":",
"return",
"{",
"QUERY_ACTION_MAP",
"[",
"field_action",
"]",
":",
"_boosted_value",
"(",
"field_name",
",",
"field_action",
",",
"key",
",",
"val",
",",
"boost",
")",
"}",
"elif",
"field_action",
"==",
"'query_string'",
":",
"# query_string has different syntax, so it's handled",
"# differently.",
"#",
"# Note: query_string queries are not boosted with",
"# .boost()---they're boosted in the query text itself.",
"return",
"{",
"'query_string'",
":",
"{",
"'default_field'",
":",
"field_name",
",",
"'query'",
":",
"val",
"}",
"}",
"elif",
"field_action",
"in",
"RANGE_ACTIONS",
":",
"# Ranges are special and have a different syntax, so",
"# we handle them separately.",
"return",
"{",
"'range'",
":",
"{",
"field_name",
":",
"_boosted_value",
"(",
"field_action",
",",
"field_action",
",",
"key",
",",
"val",
",",
"boost",
")",
"}",
"}",
"elif",
"field_action",
"==",
"'range'",
":",
"lower",
",",
"upper",
"=",
"val",
"value",
"=",
"{",
"'gte'",
":",
"lower",
",",
"'lte'",
":",
"upper",
",",
"}",
"if",
"boost",
":",
"value",
"[",
"'boost'",
"]",
"=",
"boost",
"return",
"{",
"'range'",
":",
"{",
"field_name",
":",
"value",
"}",
"}",
"raise",
"InvalidFieldActionError",
"(",
"'%s is not a valid field action'",
"%",
"field_action",
")"
] | Takes a key/val pair and returns the Elasticsearch code for it | [
"Takes",
"a",
"key",
"/",
"val",
"pair",
"and",
"returns",
"the",
"Elasticsearch",
"code",
"for",
"it"
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1320-L1371 | train |
mozilla/elasticutils | elasticutils/__init__.py | S._process_queries | 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 {} | python | 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 {} | [
"def",
"_process_queries",
"(",
"self",
",",
"queries",
")",
":",
"# 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",
"{",
"}"
] | Takes a list of queries and returns query clause value
:arg queries: list of Q instances
:returns: dict which is the query clause value | [
"Takes",
"a",
"list",
"of",
"queries",
"and",
"returns",
"query",
"clause",
"value"
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1373-L1411 | train |
mozilla/elasticutils | elasticutils/__init__.py | S._do_search | 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 | python | 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 | [
"def",
"_do_search",
"(",
"self",
")",
":",
"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"
] | Perform the search, then convert that raw format into a
SearchResults instance and return it. | [
"Perform",
"the",
"search",
"then",
"convert",
"that",
"raw",
"format",
"into",
"a",
"SearchResults",
"instance",
"and",
"return",
"it",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1426-L1437 | train |
mozilla/elasticutils | elasticutils/__init__.py | S.get_es | 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) | python | 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) | [
"def",
"get_es",
"(",
"self",
",",
"default_builder",
"=",
"get_es",
")",
":",
"# .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",
")"
] | 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. | [
"Returns",
"the",
"Elasticsearch",
"object",
"to",
"use",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1439-L1462 | train |
mozilla/elasticutils | elasticutils/__init__.py | S.get_indexes | 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 | python | 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 | [
"def",
"get_indexes",
"(",
"self",
",",
"default_indexes",
"=",
"DEFAULT_INDEXES",
")",
":",
"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"
] | Returns the list of indexes to act on. | [
"Returns",
"the",
"list",
"of",
"indexes",
"to",
"act",
"on",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1464-L1476 | train |
mozilla/elasticutils | elasticutils/__init__.py | S.get_doctypes | 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 | python | 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 | [
"def",
"get_doctypes",
"(",
"self",
",",
"default_doctypes",
"=",
"DEFAULT_DOCTYPES",
")",
":",
"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"
] | Returns the list of doctypes to use. | [
"Returns",
"the",
"list",
"of",
"doctypes",
"to",
"use",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1478-L1487 | train |
mozilla/elasticutils | elasticutils/__init__.py | S.raw | 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:
raise BadSearch(
'You must specify an index if you are specifying doctypes.')
extra_search_kwargs = {}
if self.search_type:
extra_search_kwargs['search_type'] = self.search_type
hits = es.search(body=qs,
index=self.get_indexes(),
doc_type=self.get_doctypes(),
**extra_search_kwargs)
log.debug('[%s] %s' % (hits['took'], qs))
return hits | python | 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:
raise BadSearch(
'You must specify an index if you are specifying doctypes.')
extra_search_kwargs = {}
if self.search_type:
extra_search_kwargs['search_type'] = self.search_type
hits = es.search(body=qs,
index=self.get_indexes(),
doc_type=self.get_doctypes(),
**extra_search_kwargs)
log.debug('[%s] %s' % (hits['took'], qs))
return hits | [
"def",
"raw",
"(",
"self",
")",
":",
"qs",
"=",
"self",
".",
"build_search",
"(",
")",
"es",
"=",
"self",
".",
"get_es",
"(",
")",
"index",
"=",
"self",
".",
"get_indexes",
"(",
")",
"doc_type",
"=",
"self",
".",
"get_doctypes",
"(",
")",
"if",
"doc_type",
"and",
"not",
"index",
":",
"raise",
"BadSearch",
"(",
"'You must specify an index if you are specifying doctypes.'",
")",
"extra_search_kwargs",
"=",
"{",
"}",
"if",
"self",
".",
"search_type",
":",
"extra_search_kwargs",
"[",
"'search_type'",
"]",
"=",
"self",
".",
"search_type",
"hits",
"=",
"es",
".",
"search",
"(",
"body",
"=",
"qs",
",",
"index",
"=",
"self",
".",
"get_indexes",
"(",
")",
",",
"doc_type",
"=",
"self",
".",
"get_doctypes",
"(",
")",
",",
"*",
"*",
"extra_search_kwargs",
")",
"log",
".",
"debug",
"(",
"'[%s] %s'",
"%",
"(",
"hits",
"[",
"'took'",
"]",
",",
"qs",
")",
")",
"return",
"hits"
] | Build query and passes to Elasticsearch, then returns the raw
format returned. | [
"Build",
"query",
"and",
"passes",
"to",
"Elasticsearch",
"then",
"returns",
"the",
"raw",
"format",
"returned",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1489-L1514 | train |
mozilla/elasticutils | elasticutils/__init__.py | MLT.get_es | 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() | python | 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() | [
"def",
"get_es",
"(",
"self",
")",
":",
"if",
"self",
".",
"s",
":",
"return",
"self",
".",
"s",
".",
"get_es",
"(",
")",
"return",
"self",
".",
"es",
"or",
"get_es",
"(",
")"
] | 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. | [
"Returns",
"an",
"Elasticsearch",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1721-L1736 | train |
mozilla/elasticutils | elasticutils/__init__.py | MLT.raw | 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.s else ''
hits = es.mlt(
index=self.index, doc_type=self.doctype, id=self.id,
mlt_fields=mlt_fields, body=body, **params)
log.debug(hits)
return hits | python | 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.s else ''
hits = es.mlt(
index=self.index, doc_type=self.doctype, id=self.id,
mlt_fields=mlt_fields, body=body, **params)
log.debug(hits)
return hits | [
"def",
"raw",
"(",
"self",
")",
":",
"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",
".",
"s",
"else",
"''",
"hits",
"=",
"es",
".",
"mlt",
"(",
"index",
"=",
"self",
".",
"index",
",",
"doc_type",
"=",
"self",
".",
"doctype",
",",
"id",
"=",
"self",
".",
"id",
",",
"mlt_fields",
"=",
"mlt_fields",
",",
"body",
"=",
"body",
",",
"*",
"*",
"params",
")",
"log",
".",
"debug",
"(",
"hits",
")",
"return",
"hits"
] | Build query and passes to `Elasticsearch`, then returns the raw
format returned. | [
"Build",
"query",
"and",
"passes",
"to",
"Elasticsearch",
"then",
"returns",
"the",
"raw",
"format",
"returned",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1738-L1756 | train |
mozilla/elasticutils | elasticutils/__init__.py | MLT._do_search | 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 | python | 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 | [
"def",
"_do_search",
"(",
"self",
")",
":",
"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"
] | Perform the mlt call, then convert that raw format into a
SearchResults instance and return it. | [
"Perform",
"the",
"mlt",
"call",
"then",
"convert",
"that",
"raw",
"format",
"into",
"a",
"SearchResults",
"instance",
"and",
"return",
"it",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L1758-L1768 | train |
mozilla/elasticutils | elasticutils/__init__.py | Indexable.index | 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) | python | 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) | [
"def",
"index",
"(",
"cls",
",",
"document",
",",
"id_",
"=",
"None",
",",
"overwrite_existing",
"=",
"True",
",",
"es",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"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",
")"
] | 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()``. | [
"Adds",
"or",
"updates",
"a",
"document",
"to",
"the",
"index"
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L2182-L2227 | train |
mozilla/elasticutils | elasticutils/__init__.py | Indexable.bulk_index | 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
) | python | 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
) | [
"def",
"bulk_index",
"(",
"cls",
",",
"documents",
",",
"id_field",
"=",
"'id'",
",",
"es",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"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",
")"
] | 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()``. | [
"Adds",
"or",
"updates",
"a",
"batch",
"of",
"documents",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L2230-L2270 | train |
mozilla/elasticutils | elasticutils/__init__.py | Indexable.unindex | 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_) | python | 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_) | [
"def",
"unindex",
"(",
"cls",
",",
"id_",
",",
"es",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"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_",
")"
] | 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()`. | [
"Removes",
"a",
"particular",
"item",
"from",
"the",
"search",
"index",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L2273-L2292 | train |
mozilla/elasticutils | elasticutils/__init__.py | Indexable.refresh_index | 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) | python | 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) | [
"def",
"refresh_index",
"(",
"cls",
",",
"es",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"if",
"es",
"is",
"None",
":",
"es",
"=",
"cls",
".",
"get_es",
"(",
")",
"if",
"index",
"is",
"None",
":",
"index",
"=",
"cls",
".",
"get_index",
"(",
")",
"es",
".",
"indices",
".",
"refresh",
"(",
"index",
"=",
"index",
")"
] | 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()`. | [
"Refreshes",
"the",
"index",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L2295-L2317 | train |
mozilla/elasticutils | elasticutils/monkeypatch.py | monkeypatch_es | 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) | python | 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) | [
"def",
"monkeypatch_es",
"(",
")",
":",
"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",
")"
] | 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. | [
"Monkey",
"patch",
"for",
"elasticsearch",
"-",
"py",
"1",
".",
"0",
"+",
"to",
"make",
"it",
"work",
"with",
"ES",
"0",
".",
"90"
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/monkeypatch.py#L9-L40 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/views.py | EntriesView.get_context_data | 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) | python | 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) | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'entries'",
":",
"Entry",
".",
"objects",
".",
"get_for_tag",
"(",
"self",
".",
"kwargs",
".",
"get",
"(",
"'slug'",
",",
"0",
")",
")",
"}",
")",
"return",
"super",
"(",
"EntriesView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")"
] | Returns view context dictionary.
:rtype: dict. | [
"Returns",
"view",
"context",
"dictionary",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/views.py#L28-L40 | train |
jaraco/keyrings.alt | keyrings/alt/file_base.py | Keyring.get_password | 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 = configparser.RawConfigParser()
if os.path.exists(self.file_path):
config.read(self.file_path)
# fetch the password
try:
password_base64 = config.get(service, username).encode()
# decode with base64
password_encrypted = decodebytes(password_base64)
# decrypt the password with associated data
try:
password = self.decrypt(password_encrypted, assoc).decode(
'utf-8')
except ValueError:
# decrypt the password without associated data
password = self.decrypt(password_encrypted).decode('utf-8')
except (configparser.NoOptionError, configparser.NoSectionError):
password = None
return password | python | 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 = configparser.RawConfigParser()
if os.path.exists(self.file_path):
config.read(self.file_path)
# fetch the password
try:
password_base64 = config.get(service, username).encode()
# decode with base64
password_encrypted = decodebytes(password_base64)
# decrypt the password with associated data
try:
password = self.decrypt(password_encrypted, assoc).decode(
'utf-8')
except ValueError:
# decrypt the password without associated data
password = self.decrypt(password_encrypted).decode('utf-8')
except (configparser.NoOptionError, configparser.NoSectionError):
password = None
return password | [
"def",
"get_password",
"(",
"self",
",",
"service",
",",
"username",
")",
":",
"assoc",
"=",
"self",
".",
"_generate_assoc",
"(",
"service",
",",
"username",
")",
"service",
"=",
"escape_for_ini",
"(",
"service",
")",
"username",
"=",
"escape_for_ini",
"(",
"username",
")",
"# load the passwords from the file",
"config",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"file_path",
")",
":",
"config",
".",
"read",
"(",
"self",
".",
"file_path",
")",
"# fetch the password",
"try",
":",
"password_base64",
"=",
"config",
".",
"get",
"(",
"service",
",",
"username",
")",
".",
"encode",
"(",
")",
"# decode with base64",
"password_encrypted",
"=",
"decodebytes",
"(",
"password_base64",
")",
"# decrypt the password with associated data",
"try",
":",
"password",
"=",
"self",
".",
"decrypt",
"(",
"password_encrypted",
",",
"assoc",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"ValueError",
":",
"# decrypt the password without associated data",
"password",
"=",
"self",
".",
"decrypt",
"(",
"password_encrypted",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"(",
"configparser",
".",
"NoOptionError",
",",
"configparser",
".",
"NoSectionError",
")",
":",
"password",
"=",
"None",
"return",
"password"
] | Read the password from the file. | [
"Read",
"the",
"password",
"from",
"the",
"file",
"."
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/file_base.py#L96-L123 | train |
jaraco/keyrings.alt | keyrings/alt/file_base.py | Keyring.set_password | 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):
raise TypeError("Password should be a unicode string, not bytes.")
assoc = self._generate_assoc(service, username)
# encrypt the password
password_encrypted = self.encrypt(password.encode('utf-8'), assoc)
# encode with base64 and add line break to untangle config file
password_base64 = '\n' + encodebytes(password_encrypted).decode()
self._write_config_value(service, username, password_base64) | python | 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):
raise TypeError("Password should be a unicode string, not bytes.")
assoc = self._generate_assoc(service, username)
# encrypt the password
password_encrypted = self.encrypt(password.encode('utf-8'), assoc)
# encode with base64 and add line break to untangle config file
password_base64 = '\n' + encodebytes(password_encrypted).decode()
self._write_config_value(service, username, password_base64) | [
"def",
"set_password",
"(",
"self",
",",
"service",
",",
"username",
",",
"password",
")",
":",
"if",
"not",
"username",
":",
"# https://github.com/jaraco/keyrings.alt/issues/21",
"raise",
"ValueError",
"(",
"\"Username cannot be blank.\"",
")",
"if",
"not",
"isinstance",
"(",
"password",
",",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"Password should be a unicode string, not bytes.\"",
")",
"assoc",
"=",
"self",
".",
"_generate_assoc",
"(",
"service",
",",
"username",
")",
"# encrypt the password",
"password_encrypted",
"=",
"self",
".",
"encrypt",
"(",
"password",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"assoc",
")",
"# encode with base64 and add line break to untangle config file",
"password_base64",
"=",
"'\\n'",
"+",
"encodebytes",
"(",
"password_encrypted",
")",
".",
"decode",
"(",
")",
"self",
".",
"_write_config_value",
"(",
"service",
",",
"username",
",",
"password_base64",
")"
] | Write the password in the file. | [
"Write",
"the",
"password",
"in",
"the",
"file",
"."
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/file_base.py#L125-L139 | train |
jaraco/keyrings.alt | keyrings/alt/file_base.py | Keyring._ensure_file_path | 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) | python | 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) | [
"def",
"_ensure_file_path",
"(",
"self",
")",
":",
"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",
")"
] | Ensure the storage path exists.
If it doesn't, create it with "go-rwx" permissions. | [
"Ensure",
"the",
"storage",
"path",
"exists",
".",
"If",
"it",
"doesn",
"t",
"create",
"it",
"with",
"go",
"-",
"rwx",
"permissions",
"."
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/file_base.py#L167-L181 | train |
jaraco/keyrings.alt | keyrings/alt/file_base.py | Keyring.delete_password | 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.read(self.file_path)
try:
if not config.remove_option(service, username):
raise PasswordDeleteError("Password not found")
except configparser.NoSectionError:
raise PasswordDeleteError("Password not found")
# update the file
with open(self.file_path, 'w') as config_file:
config.write(config_file) | python | 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.read(self.file_path)
try:
if not config.remove_option(service, username):
raise PasswordDeleteError("Password not found")
except configparser.NoSectionError:
raise PasswordDeleteError("Password not found")
# update the file
with open(self.file_path, 'w') as config_file:
config.write(config_file) | [
"def",
"delete_password",
"(",
"self",
",",
"service",
",",
"username",
")",
":",
"service",
"=",
"escape_for_ini",
"(",
"service",
")",
"username",
"=",
"escape_for_ini",
"(",
"username",
")",
"config",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"file_path",
")",
":",
"config",
".",
"read",
"(",
"self",
".",
"file_path",
")",
"try",
":",
"if",
"not",
"config",
".",
"remove_option",
"(",
"service",
",",
"username",
")",
":",
"raise",
"PasswordDeleteError",
"(",
"\"Password not found\"",
")",
"except",
"configparser",
".",
"NoSectionError",
":",
"raise",
"PasswordDeleteError",
"(",
"\"Password not found\"",
")",
"# update the file",
"with",
"open",
"(",
"self",
".",
"file_path",
",",
"'w'",
")",
"as",
"config_file",
":",
"config",
".",
"write",
"(",
"config_file",
")"
] | Delete the password for the username of the service. | [
"Delete",
"the",
"password",
"for",
"the",
"username",
"of",
"the",
"service",
"."
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/file_base.py#L183-L198 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/apps.py | WagtailRelationsAppConfig.applicable_models | 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():
meta = getattr(model, '_meta')
fields = meta.get_all_field_names()
if issubclass(model, Page) and 'tags' in fields:
applicable.append(model)
return applicable | python | 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():
meta = getattr(model, '_meta')
fields = meta.get_all_field_names()
if issubclass(model, Page) and 'tags' in fields:
applicable.append(model)
return applicable | [
"def",
"applicable_models",
"(",
"self",
")",
":",
"Page",
"=",
"apps",
".",
"get_model",
"(",
"'wagtailcore'",
",",
"'Page'",
")",
"applicable",
"=",
"[",
"]",
"for",
"model",
"in",
"apps",
".",
"get_models",
"(",
")",
":",
"meta",
"=",
"getattr",
"(",
"model",
",",
"'_meta'",
")",
"fields",
"=",
"meta",
".",
"get_all_field_names",
"(",
")",
"if",
"issubclass",
"(",
"model",
",",
"Page",
")",
"and",
"'tags'",
"in",
"fields",
":",
"applicable",
".",
"append",
"(",
"model",
")",
"return",
"applicable"
] | Returns a list of model classes that subclass Page
and include a "tags" field.
:rtype: list. | [
"Returns",
"a",
"list",
"of",
"model",
"classes",
"that",
"subclass",
"Page",
"and",
"include",
"a",
"tags",
"field",
".",
":",
"rtype",
":",
"list",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/apps.py#L17-L34 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/apps.py | WagtailRelationsAppConfig.add_relationship_panels | 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')) | python | 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')) | [
"def",
"add_relationship_panels",
"(",
"self",
")",
":",
"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'",
")",
")"
] | Add edit handler that includes "related" panels to applicable
model classes that don't explicitly define their own edit handler. | [
"Add",
"edit",
"handler",
"that",
"includes",
"related",
"panels",
"to",
"applicable",
"model",
"classes",
"that",
"don",
"t",
"explicitly",
"define",
"their",
"own",
"edit",
"handler",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/apps.py#L36-L45 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/apps.py | WagtailRelationsAppConfig.add_relationship_methods | 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
) | python | 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
) | [
"def",
"add_relationship_methods",
"(",
"self",
")",
":",
"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",
")"
] | Adds relationship methods to applicable model classes. | [
"Adds",
"relationship",
"methods",
"to",
"applicable",
"model",
"classes",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/apps.py#L47-L104 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/apps.py | WagtailRelationsAppConfig.ready | def ready(self):
"""
Finalizes application configuration.
"""
import wagtailplus.wagtailrelations.signals.handlers
self.add_relationship_panels()
self.add_relationship_methods()
super(WagtailRelationsAppConfig, self).ready() | python | def ready(self):
"""
Finalizes application configuration.
"""
import wagtailplus.wagtailrelations.signals.handlers
self.add_relationship_panels()
self.add_relationship_methods()
super(WagtailRelationsAppConfig, self).ready() | [
"def",
"ready",
"(",
"self",
")",
":",
"import",
"wagtailplus",
".",
"wagtailrelations",
".",
"signals",
".",
"handlers",
"self",
".",
"add_relationship_panels",
"(",
")",
"self",
".",
"add_relationship_methods",
"(",
")",
"super",
"(",
"WagtailRelationsAppConfig",
",",
"self",
")",
".",
"ready",
"(",
")"
] | Finalizes application configuration. | [
"Finalizes",
"application",
"configuration",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/apps.py#L106-L114 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrollbacks/apps.py | WagtailRollbacksAppConfig.applicable_models | 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):
applicable.append(model)
return applicable | python | 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):
applicable.append(model)
return applicable | [
"def",
"applicable_models",
"(",
"self",
")",
":",
"Page",
"=",
"apps",
".",
"get_model",
"(",
"'wagtailcore'",
",",
"'Page'",
")",
"applicable",
"=",
"[",
"]",
"for",
"model",
"in",
"apps",
".",
"get_models",
"(",
")",
":",
"if",
"issubclass",
"(",
"model",
",",
"Page",
")",
":",
"applicable",
".",
"append",
"(",
"model",
")",
"return",
"applicable"
] | Returns a list of model classes that subclass Page.
:rtype: list. | [
"Returns",
"a",
"list",
"of",
"model",
"classes",
"that",
"subclass",
"Page",
".",
":",
"rtype",
":",
"list",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrollbacks/apps.py#L20-L33 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrollbacks/apps.py | WagtailRollbacksAppConfig.add_rollback_panels | 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')) | python | 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')) | [
"def",
"add_rollback_panels",
"(",
"self",
")",
":",
"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'",
")",
")"
] | Adds rollback panel to applicable model class's edit handlers. | [
"Adds",
"rollback",
"panel",
"to",
"applicable",
"model",
"class",
"s",
"edit",
"handlers",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrollbacks/apps.py#L35-L43 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrollbacks/apps.py | WagtailRollbacksAppConfig.add_rollback_methods | 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) | python | 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) | [
"def",
"add_rollback_methods",
"(",
")",
":",
"# Modified Page.save_revision method.\r",
"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",
")"
] | Adds rollback methods to applicable model classes. | [
"Adds",
"rollback",
"methods",
"to",
"applicable",
"model",
"classes",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrollbacks/apps.py#L46-L90 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrollbacks/apps.py | WagtailRollbacksAppConfig.ready | def ready(self):
"""
Finalizes application configuration.
"""
self.add_rollback_panels()
self.add_rollback_methods()
super(WagtailRollbacksAppConfig, self).ready() | python | def ready(self):
"""
Finalizes application configuration.
"""
self.add_rollback_panels()
self.add_rollback_methods()
super(WagtailRollbacksAppConfig, self).ready() | [
"def",
"ready",
"(",
"self",
")",
":",
"self",
".",
"add_rollback_panels",
"(",
")",
"self",
".",
"add_rollback_methods",
"(",
")",
"super",
"(",
"WagtailRollbacksAppConfig",
",",
"self",
")",
".",
"ready",
"(",
")"
] | Finalizes application configuration. | [
"Finalizes",
"application",
"configuration",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrollbacks/apps.py#L92-L98 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/templatetags/wagtailrelations_tags.py | get_related | 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 | python | 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",
"(",
"page",
")",
":",
"related",
"=",
"[",
"]",
"entry",
"=",
"Entry",
".",
"get_for_model",
"(",
"page",
")",
"if",
"entry",
":",
"related",
"=",
"entry",
".",
"related",
"return",
"related"
] | Returns list of related Entry instances for specified page.
:param page: the page instance.
:rtype: list. | [
"Returns",
"list",
"of",
"related",
"Entry",
"instances",
"for",
"specified",
"page",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/templatetags/wagtailrelations_tags.py#L17-L30 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/templatetags/wagtailrelations_tags.py | get_related_entry_admin_url | 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 '' | python | 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 '' | [
"def",
"get_related_entry_admin_url",
"(",
"entry",
")",
":",
"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",
"''"
] | Returns admin URL for specified entry instance.
:param entry: the entry instance.
:return: str. | [
"Returns",
"admin",
"URL",
"for",
"specified",
"entry",
"instance",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/templatetags/wagtailrelations_tags.py#L33-L50 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/templatetags/wagtailrelations_tags.py | get_related_with_scores | 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 related | python | 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 related | [
"def",
"get_related_with_scores",
"(",
"page",
")",
":",
"related",
"=",
"[",
"]",
"entry",
"=",
"Entry",
".",
"get_for_model",
"(",
"page",
")",
"if",
"entry",
":",
"related",
"=",
"entry",
".",
"related_with_scores",
"return",
"related"
] | Returns list of related tuples (Entry instance, score) for
specified page.
:param page: the page instance.
:rtype: list. | [
"Returns",
"list",
"of",
"related",
"tuples",
"(",
"Entry",
"instance",
"score",
")",
"for",
"specified",
"page",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/templatetags/wagtailrelations_tags.py#L53-L67 | train |
jaraco/keyrings.alt | keyrings/alt/multi.py | MultipartKeyringWrapper.get_password | 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_password(
service,
'%s{{part_%d}}' % (username, i))
if next_part:
parts.append(next_part)
i += 1
else:
break
return ''.join(parts)
return None | python | 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_password(
service,
'%s{{part_%d}}' % (username, i))
if next_part:
parts.append(next_part)
i += 1
else:
break
return ''.join(parts)
return None | [
"def",
"get_password",
"(",
"self",
",",
"service",
",",
"username",
")",
":",
"init_part",
"=",
"self",
".",
"_keyring",
".",
"get_password",
"(",
"service",
",",
"username",
")",
"if",
"init_part",
":",
"parts",
"=",
"[",
"init_part",
"]",
"i",
"=",
"1",
"while",
"True",
":",
"next_part",
"=",
"self",
".",
"_keyring",
".",
"get_password",
"(",
"service",
",",
"'%s{{part_%d}}'",
"%",
"(",
"username",
",",
"i",
")",
")",
"if",
"next_part",
":",
"parts",
".",
"append",
"(",
"next_part",
")",
"i",
"+=",
"1",
"else",
":",
"break",
"return",
"''",
".",
"join",
"(",
"parts",
")",
"return",
"None"
] | Get password of the username for the service | [
"Get",
"password",
"of",
"the",
"username",
"for",
"the",
"service"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/multi.py#L24-L41 | train |
jaraco/keyrings.alt | keyrings/alt/multi.py | MultipartKeyringWrapper.set_password | 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 enumerate(password_parts):
curr_username = username
if i > 0:
curr_username += '{{part_%d}}' % i
self._keyring.set_password(service, curr_username, password_part) | python | 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 enumerate(password_parts):
curr_username = username
if i > 0:
curr_username += '{{part_%d}}' % i
self._keyring.set_password(service, curr_username, password_part) | [
"def",
"set_password",
"(",
"self",
",",
"service",
",",
"username",
",",
"password",
")",
":",
"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",
"enumerate",
"(",
"password_parts",
")",
":",
"curr_username",
"=",
"username",
"if",
"i",
">",
"0",
":",
"curr_username",
"+=",
"'{{part_%d}}'",
"%",
"i",
"self",
".",
"_keyring",
".",
"set_password",
"(",
"service",
",",
"curr_username",
",",
"password_part",
")"
] | Set password for the username of the service | [
"Set",
"password",
"for",
"the",
"username",
"of",
"the",
"service"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/multi.py#L43-L53 | train |
rfosterslo/wagtailplus | wagtailplus/wagtaillinks/rich_text.py | LinkHandler.expand_db_attributes | 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>' | python | 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>' | [
"def",
"expand_db_attributes",
"(",
"attrs",
",",
"for_editor",
")",
":",
"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>'"
] | 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. | [
"Given",
"a",
"dictionary",
"of",
"attributes",
"find",
"the",
"corresponding",
"link",
"instance",
"and",
"return",
"its",
"HTML",
"representation",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtaillinks/rich_text.py#L28-L52 | train |
jaraco/keyrings.alt | keyrings/alt/keyczar.py | BaseCrypter.crypter | 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 | python | 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 | [
"def",
"crypter",
"(",
"self",
")",
":",
"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"
] | The actual keyczar crypter | [
"The",
"actual",
"keyczar",
"crypter"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/keyczar.py#L39-L52 | train |
mozilla/elasticutils | elasticutils/contrib/django/tasks.py | index_objects | 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) | python | 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) | [
"def",
"index_objects",
"(",
"mapping_type",
",",
"ids",
",",
"chunk_size",
"=",
"100",
",",
"es",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"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",
")"
] | 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()`. | [
"Index",
"documents",
"of",
"a",
"specified",
"mapping",
"type",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/contrib/django/tasks.py#L13-L65 | train |
mozilla/elasticutils | elasticutils/contrib/django/tasks.py | unindex_objects | 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) | python | 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) | [
"def",
"unindex_objects",
"(",
"mapping_type",
",",
"ids",
",",
"es",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"if",
"settings",
".",
"ES_DISABLED",
":",
"return",
"for",
"id_",
"in",
"ids",
":",
"mapping_type",
".",
"unindex",
"(",
"id_",
",",
"es",
"=",
"es",
",",
"index",
"=",
"index",
")"
] | 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()`. | [
"Remove",
"documents",
"of",
"a",
"specified",
"mapping_type",
"from",
"the",
"index",
"."
] | b880cc5d51fb1079b0581255ec664c1ec934656e | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/contrib/django/tasks.py#L69-L93 | train |
rfosterslo/wagtailplus | wagtailplus/wagtaillinks/views/chooser.py | LinkChooser.get_json | 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}
),
}) | python | 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}
),
}) | [
"def",
"get_json",
"(",
"self",
",",
"link",
")",
":",
"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",
"}",
")",
",",
"}",
")"
] | Returns specified link instance as JSON.
:param link: the link instance.
:rtype: JSON. | [
"Returns",
"specified",
"link",
"instance",
"as",
"JSON",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtaillinks/views/chooser.py#L14-L29 | train |
jaraco/keyrings.alt | keyrings/alt/file.py | Encrypted._create_cipher | 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) | python | 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) | [
"def",
"_create_cipher",
"(",
"self",
",",
"password",
",",
"salt",
",",
"IV",
")",
":",
"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",
")"
] | Create the cipher object to encrypt or decrypt a payload. | [
"Create",
"the",
"cipher",
"object",
"to",
"encrypt",
"or",
"decrypt",
"a",
"payload",
"."
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/file.py#L47-L54 | train |
jaraco/keyrings.alt | keyrings/alt/file.py | EncryptedKeyring._init_file | 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) | python | 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) | [
"def",
"_init_file",
"(",
"self",
")",
":",
"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",
")"
] | Initialize a new password file and set the reference password. | [
"Initialize",
"a",
"new",
"password",
"file",
"and",
"set",
"the",
"reference",
"password",
"."
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/file.py#L101-L116 | train |
jaraco/keyrings.alt | keyrings/alt/file.py | EncryptedKeyring._check_file | 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) | python | 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) | [
"def",
"_check_file",
"(",
"self",
")",
":",
"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",
")"
] | Check if the file exists and has the expected password reference. | [
"Check",
"if",
"the",
"file",
"exists",
"and",
"has",
"the",
"expected",
"password",
"reference",
"."
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/file.py#L118-L139 | train |
jaraco/keyrings.alt | keyrings/alt/file.py | EncryptedKeyring._check_version | 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 | python | 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 | [
"def",
"_check_version",
"(",
"self",
",",
"config",
")",
":",
"try",
":",
"self",
".",
"file_version",
"=",
"config",
".",
"get",
"(",
"escape_for_ini",
"(",
"'keyring-setting'",
")",
",",
"escape_for_ini",
"(",
"'version'",
")",
",",
")",
"except",
"(",
"configparser",
".",
"NoSectionError",
",",
"configparser",
".",
"NoOptionError",
")",
":",
"return",
"False",
"return",
"True"
] | check for a valid version
an existing scheme implies an existing version as well
return True, if version is valid, and False otherwise | [
"check",
"for",
"a",
"valid",
"version",
"an",
"existing",
"scheme",
"implies",
"an",
"existing",
"version",
"as",
"well"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/file.py#L164-L178 | train |
jaraco/keyrings.alt | keyrings/alt/file.py | EncryptedKeyring._unlock | 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") | python | 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") | [
"def",
"_unlock",
"(",
"self",
")",
":",
"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\"",
")"
] | Unlock this keyring by getting the password for the keyring from the
user. | [
"Unlock",
"this",
"keyring",
"by",
"getting",
"the",
"password",
"for",
"the",
"keyring",
"from",
"the",
"user",
"."
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/file.py#L180-L192 | train |
jaraco/keyrings.alt | keyrings/alt/escape.py | _escape_char | 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) | python | 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",
"_escape_char",
"(",
"c",
")",
":",
"if",
"isinstance",
"(",
"c",
",",
"int",
")",
":",
"c",
"=",
"_unichr",
"(",
"c",
")",
"return",
"c",
"if",
"c",
"in",
"LEGAL_CHARS",
"else",
"ESCAPE_FMT",
"%",
"ord",
"(",
"c",
")"
] | Single char escape. Return the char, escaped if not already legal | [
"Single",
"char",
"escape",
".",
"Return",
"the",
"char",
"escaped",
"if",
"not",
"already",
"legal"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/escape.py#L25-L29 | train |
jaraco/keyrings.alt | keyrings/alt/escape.py | unescape | 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('ascii')).decode('utf-8') | python | 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('ascii')).decode('utf-8') | [
"def",
"unescape",
"(",
"value",
")",
":",
"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",
"(",
"'ascii'",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")"
] | Inverse of escape. | [
"Inverse",
"of",
"escape",
"."
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/escape.py#L45-L53 | train |
jaraco/keyrings.alt | keyrings/alt/Gnome.py | Keyring._find_passwords | 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')):
attrs = GnomeKeyring.Attribute.list_new()
GnomeKeyring.Attribute.list_append_string(
attrs, attrs_tuple[0], username)
GnomeKeyring.Attribute.list_append_string(
attrs, attrs_tuple[1], service)
result, items = GnomeKeyring.find_items_sync(
GnomeKeyring.ItemType.NETWORK_PASSWORD, attrs)
if result == GnomeKeyring.Result.OK:
passwords += items
elif deleting:
if result == GnomeKeyring.Result.CANCELLED:
raise PasswordDeleteError("Cancelled by user")
elif result != GnomeKeyring.Result.NO_MATCH:
raise PasswordDeleteError(result.value_name)
return passwords | python | 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')):
attrs = GnomeKeyring.Attribute.list_new()
GnomeKeyring.Attribute.list_append_string(
attrs, attrs_tuple[0], username)
GnomeKeyring.Attribute.list_append_string(
attrs, attrs_tuple[1], service)
result, items = GnomeKeyring.find_items_sync(
GnomeKeyring.ItemType.NETWORK_PASSWORD, attrs)
if result == GnomeKeyring.Result.OK:
passwords += items
elif deleting:
if result == GnomeKeyring.Result.CANCELLED:
raise PasswordDeleteError("Cancelled by user")
elif result != GnomeKeyring.Result.NO_MATCH:
raise PasswordDeleteError(result.value_name)
return passwords | [
"def",
"_find_passwords",
"(",
"self",
",",
"service",
",",
"username",
",",
"deleting",
"=",
"False",
")",
":",
"passwords",
"=",
"[",
"]",
"service",
"=",
"self",
".",
"_safe_string",
"(",
"service",
")",
"username",
"=",
"self",
".",
"_safe_string",
"(",
"username",
")",
"for",
"attrs_tuple",
"in",
"(",
"(",
"'username'",
",",
"'service'",
")",
",",
"(",
"'user'",
",",
"'domain'",
")",
")",
":",
"attrs",
"=",
"GnomeKeyring",
".",
"Attribute",
".",
"list_new",
"(",
")",
"GnomeKeyring",
".",
"Attribute",
".",
"list_append_string",
"(",
"attrs",
",",
"attrs_tuple",
"[",
"0",
"]",
",",
"username",
")",
"GnomeKeyring",
".",
"Attribute",
".",
"list_append_string",
"(",
"attrs",
",",
"attrs_tuple",
"[",
"1",
"]",
",",
"service",
")",
"result",
",",
"items",
"=",
"GnomeKeyring",
".",
"find_items_sync",
"(",
"GnomeKeyring",
".",
"ItemType",
".",
"NETWORK_PASSWORD",
",",
"attrs",
")",
"if",
"result",
"==",
"GnomeKeyring",
".",
"Result",
".",
"OK",
":",
"passwords",
"+=",
"items",
"elif",
"deleting",
":",
"if",
"result",
"==",
"GnomeKeyring",
".",
"Result",
".",
"CANCELLED",
":",
"raise",
"PasswordDeleteError",
"(",
"\"Cancelled by user\"",
")",
"elif",
"result",
"!=",
"GnomeKeyring",
".",
"Result",
".",
"NO_MATCH",
":",
"raise",
"PasswordDeleteError",
"(",
"result",
".",
"value_name",
")",
"return",
"passwords"
] | Get password of the username for the service | [
"Get",
"password",
"of",
"the",
"username",
"for",
"the",
"service"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/Gnome.py#L39-L61 | train |
jaraco/keyrings.alt | keyrings/alt/Gnome.py | Keyring.get_password | 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.text_type) else
secret.decode('utf-8')
) | python | 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.text_type) else
secret.decode('utf-8')
) | [
"def",
"get_password",
"(",
"self",
",",
"service",
",",
"username",
")",
":",
"items",
"=",
"self",
".",
"_find_passwords",
"(",
"service",
",",
"username",
")",
"if",
"not",
"items",
":",
"return",
"None",
"secret",
"=",
"items",
"[",
"0",
"]",
".",
"secret",
"return",
"(",
"secret",
"if",
"isinstance",
"(",
"secret",
",",
"six",
".",
"text_type",
")",
"else",
"secret",
".",
"decode",
"(",
"'utf-8'",
")",
")"
] | Get password of the username for the service | [
"Get",
"password",
"of",
"the",
"username",
"for",
"the",
"service"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/Gnome.py#L63-L75 | train |
jaraco/keyrings.alt | keyrings/alt/Gnome.py | Keyring.set_password | 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()
GnomeKeyring.Attribute.list_append_string(attrs, 'username', username)
GnomeKeyring.Attribute.list_append_string(attrs, 'service', service)
GnomeKeyring.Attribute.list_append_string(
attrs, 'application', 'python-keyring')
result = GnomeKeyring.item_create_sync(
self.keyring_name, GnomeKeyring.ItemType.NETWORK_PASSWORD,
"Password for '%s' on '%s'" % (username, service),
attrs, password, True)[0]
if result == GnomeKeyring.Result.CANCELLED:
# The user pressed "Cancel" when prompted to unlock their keyring.
raise PasswordSetError("Cancelled by user")
elif result != GnomeKeyring.Result.OK:
raise PasswordSetError(result.value_name) | python | 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()
GnomeKeyring.Attribute.list_append_string(attrs, 'username', username)
GnomeKeyring.Attribute.list_append_string(attrs, 'service', service)
GnomeKeyring.Attribute.list_append_string(
attrs, 'application', 'python-keyring')
result = GnomeKeyring.item_create_sync(
self.keyring_name, GnomeKeyring.ItemType.NETWORK_PASSWORD,
"Password for '%s' on '%s'" % (username, service),
attrs, password, True)[0]
if result == GnomeKeyring.Result.CANCELLED:
# The user pressed "Cancel" when prompted to unlock their keyring.
raise PasswordSetError("Cancelled by user")
elif result != GnomeKeyring.Result.OK:
raise PasswordSetError(result.value_name) | [
"def",
"set_password",
"(",
"self",
",",
"service",
",",
"username",
",",
"password",
")",
":",
"service",
"=",
"self",
".",
"_safe_string",
"(",
"service",
")",
"username",
"=",
"self",
".",
"_safe_string",
"(",
"username",
")",
"password",
"=",
"self",
".",
"_safe_string",
"(",
"password",
")",
"attrs",
"=",
"GnomeKeyring",
".",
"Attribute",
".",
"list_new",
"(",
")",
"GnomeKeyring",
".",
"Attribute",
".",
"list_append_string",
"(",
"attrs",
",",
"'username'",
",",
"username",
")",
"GnomeKeyring",
".",
"Attribute",
".",
"list_append_string",
"(",
"attrs",
",",
"'service'",
",",
"service",
")",
"GnomeKeyring",
".",
"Attribute",
".",
"list_append_string",
"(",
"attrs",
",",
"'application'",
",",
"'python-keyring'",
")",
"result",
"=",
"GnomeKeyring",
".",
"item_create_sync",
"(",
"self",
".",
"keyring_name",
",",
"GnomeKeyring",
".",
"ItemType",
".",
"NETWORK_PASSWORD",
",",
"\"Password for '%s' on '%s'\"",
"%",
"(",
"username",
",",
"service",
")",
",",
"attrs",
",",
"password",
",",
"True",
")",
"[",
"0",
"]",
"if",
"result",
"==",
"GnomeKeyring",
".",
"Result",
".",
"CANCELLED",
":",
"# The user pressed \"Cancel\" when prompted to unlock their keyring.",
"raise",
"PasswordSetError",
"(",
"\"Cancelled by user\"",
")",
"elif",
"result",
"!=",
"GnomeKeyring",
".",
"Result",
".",
"OK",
":",
"raise",
"PasswordSetError",
"(",
"result",
".",
"value_name",
")"
] | Set password for the username of the service | [
"Set",
"password",
"for",
"the",
"username",
"of",
"the",
"service"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/Gnome.py#L77-L96 | train |
jaraco/keyrings.alt | keyrings/alt/Gnome.py | Keyring.delete_password | 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:
result = GnomeKeyring.item_delete_sync(current.keyring,
current.item_id)
if result == GnomeKeyring.Result.CANCELLED:
raise PasswordDeleteError("Cancelled by user")
elif result != GnomeKeyring.Result.OK:
raise PasswordDeleteError(result.value_name) | python | 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:
result = GnomeKeyring.item_delete_sync(current.keyring,
current.item_id)
if result == GnomeKeyring.Result.CANCELLED:
raise PasswordDeleteError("Cancelled by user")
elif result != GnomeKeyring.Result.OK:
raise PasswordDeleteError(result.value_name) | [
"def",
"delete_password",
"(",
"self",
",",
"service",
",",
"username",
")",
":",
"items",
"=",
"self",
".",
"_find_passwords",
"(",
"service",
",",
"username",
",",
"deleting",
"=",
"True",
")",
"if",
"not",
"items",
":",
"raise",
"PasswordDeleteError",
"(",
"\"Password not found\"",
")",
"for",
"current",
"in",
"items",
":",
"result",
"=",
"GnomeKeyring",
".",
"item_delete_sync",
"(",
"current",
".",
"keyring",
",",
"current",
".",
"item_id",
")",
"if",
"result",
"==",
"GnomeKeyring",
".",
"Result",
".",
"CANCELLED",
":",
"raise",
"PasswordDeleteError",
"(",
"\"Cancelled by user\"",
")",
"elif",
"result",
"!=",
"GnomeKeyring",
".",
"Result",
".",
"OK",
":",
"raise",
"PasswordDeleteError",
"(",
"result",
".",
"value_name",
")"
] | Delete the password for the username of the service. | [
"Delete",
"the",
"password",
"for",
"the",
"username",
"of",
"the",
"service",
"."
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/Gnome.py#L98-L110 | train |
jaraco/keyrings.alt | keyrings/alt/Gnome.py | Keyring._safe_string | 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) | python | 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",
"_safe_string",
"(",
"self",
",",
"source",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"not",
"isinstance",
"(",
"source",
",",
"str",
")",
":",
"return",
"source",
".",
"encode",
"(",
"encoding",
")",
"return",
"str",
"(",
"source",
")"
] | Convert unicode to string as gnomekeyring barfs on unicode | [
"Convert",
"unicode",
"to",
"string",
"as",
"gnomekeyring",
"barfs",
"on",
"unicode"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/Gnome.py#L112-L116 | train |
rfosterslo/wagtailplus | wagtailplus/wagtaillinks/views/links.py | CreateView.get_context_data | 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': Link.LINK_TYPE_EMAIL,
'type_external': Link.LINK_TYPE_EXTERNAL,
})
# If a form has been submitted, update context with
# the submitted form value.
if 'form' in kwargs:
submitted_form = kwargs.pop('form')
if isinstance(submitted_form, EmailLinkForm):
kwargs.update({'email_form': submitted_form})
elif isinstance(submitted_form, ExternalLinkForm):
kwargs.update({'external_form': submitted_form})
return kwargs | python | 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': Link.LINK_TYPE_EMAIL,
'type_external': Link.LINK_TYPE_EXTERNAL,
})
# If a form has been submitted, update context with
# the submitted form value.
if 'form' in kwargs:
submitted_form = kwargs.pop('form')
if isinstance(submitted_form, EmailLinkForm):
kwargs.update({'email_form': submitted_form})
elif isinstance(submitted_form, ExternalLinkForm):
kwargs.update({'external_form': submitted_form})
return kwargs | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'view'",
":",
"self",
",",
"'email_form'",
":",
"EmailLinkForm",
"(",
")",
",",
"'external_form'",
":",
"ExternalLinkForm",
"(",
")",
",",
"'type_email'",
":",
"Link",
".",
"LINK_TYPE_EMAIL",
",",
"'type_external'",
":",
"Link",
".",
"LINK_TYPE_EXTERNAL",
",",
"}",
")",
"# If a form has been submitted, update context with",
"# the submitted form value.",
"if",
"'form'",
"in",
"kwargs",
":",
"submitted_form",
"=",
"kwargs",
".",
"pop",
"(",
"'form'",
")",
"if",
"isinstance",
"(",
"submitted_form",
",",
"EmailLinkForm",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'email_form'",
":",
"submitted_form",
"}",
")",
"elif",
"isinstance",
"(",
"submitted_form",
",",
"ExternalLinkForm",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'external_form'",
":",
"submitted_form",
"}",
")",
"return",
"kwargs"
] | Returns context dictionary for view.
:rtype: dict. | [
"Returns",
"context",
"dictionary",
"for",
"view",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtaillinks/views/links.py#L26-L49 | train |
rfosterslo/wagtailplus | wagtailplus/wagtaillinks/views/links.py | CreateView.post | 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:
form = EmailLinkForm(**self.get_form_kwargs())
elif link_type == Link.LINK_TYPE_EXTERNAL:
form = ExternalLinkForm(**self.get_form_kwargs())
if form:
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
else:
raise Http404() | python | 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:
form = EmailLinkForm(**self.get_form_kwargs())
elif link_type == Link.LINK_TYPE_EXTERNAL:
form = ExternalLinkForm(**self.get_form_kwargs())
if form:
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
else:
raise Http404() | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"form",
"=",
"None",
"link_type",
"=",
"int",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"'link_type'",
",",
"0",
")",
")",
"if",
"link_type",
"==",
"Link",
".",
"LINK_TYPE_EMAIL",
":",
"form",
"=",
"EmailLinkForm",
"(",
"*",
"*",
"self",
".",
"get_form_kwargs",
"(",
")",
")",
"elif",
"link_type",
"==",
"Link",
".",
"LINK_TYPE_EXTERNAL",
":",
"form",
"=",
"ExternalLinkForm",
"(",
"*",
"*",
"self",
".",
"get_form_kwargs",
"(",
")",
")",
"if",
"form",
":",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"return",
"self",
".",
"form_valid",
"(",
"form",
")",
"else",
":",
"return",
"self",
".",
"form_invalid",
"(",
"form",
")",
"else",
":",
"raise",
"Http404",
"(",
")"
] | Returns POST response.
:param request: the request instance.
:rtype: django.http.HttpResponse. | [
"Returns",
"POST",
"response",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtaillinks/views/links.py#L57-L78 | train |
rfosterslo/wagtailplus | wagtailplus/wagtaillinks/views/links.py | UpdateView.get_form_class | 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 ExternalLinkForm
return None | python | 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 ExternalLinkForm
return None | [
"def",
"get_form_class",
"(",
"self",
")",
":",
"if",
"self",
".",
"object",
".",
"link_type",
"==",
"Link",
".",
"LINK_TYPE_EMAIL",
":",
"return",
"EmailLinkForm",
"elif",
"self",
".",
"object",
".",
"link_type",
"==",
"Link",
".",
"LINK_TYPE_EXTERNAL",
":",
"return",
"ExternalLinkForm",
"return",
"None"
] | Returns form class to use in the view.
:rtype: django.forms.ModelForm. | [
"Returns",
"form",
"class",
"to",
"use",
"in",
"the",
"view",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtaillinks/views/links.py#L84-L95 | train |
jaraco/keyrings.alt | keyrings/alt/Windows.py | RegistryKeyring.get_password | 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(hkey, username)[0]
password_base64 = password_saved.encode('ascii')
# decode with base64
password_encrypted = base64.decodestring(password_base64)
# decrypted the password
password = _win_crypto.decrypt(password_encrypted).decode('utf-8')
except EnvironmentError:
password = None
return password | python | 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(hkey, username)[0]
password_base64 = password_saved.encode('ascii')
# decode with base64
password_encrypted = base64.decodestring(password_base64)
# decrypted the password
password = _win_crypto.decrypt(password_encrypted).decode('utf-8')
except EnvironmentError:
password = None
return password | [
"def",
"get_password",
"(",
"self",
",",
"service",
",",
"username",
")",
":",
"try",
":",
"# fetch the password",
"key",
"=",
"self",
".",
"_key_for_service",
"(",
"service",
")",
"hkey",
"=",
"winreg",
".",
"OpenKey",
"(",
"winreg",
".",
"HKEY_CURRENT_USER",
",",
"key",
")",
"password_saved",
"=",
"winreg",
".",
"QueryValueEx",
"(",
"hkey",
",",
"username",
")",
"[",
"0",
"]",
"password_base64",
"=",
"password_saved",
".",
"encode",
"(",
"'ascii'",
")",
"# decode with base64",
"password_encrypted",
"=",
"base64",
".",
"decodestring",
"(",
"password_base64",
")",
"# decrypted the password",
"password",
"=",
"_win_crypto",
".",
"decrypt",
"(",
"password_encrypted",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"EnvironmentError",
":",
"password",
"=",
"None",
"return",
"password"
] | Get password of the username for the service | [
"Get",
"password",
"of",
"the",
"username",
"for",
"the",
"service"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/Windows.py#L86-L101 | train |
jaraco/keyrings.alt | keyrings/alt/Windows.py | RegistryKeyring.set_password | 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)
# encode again to unicode
password_saved = password_base64.decode('ascii')
# store the password
key_name = self._key_for_service(service)
hkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER, key_name)
winreg.SetValueEx(hkey, username, 0, winreg.REG_SZ, password_saved) | python | 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)
# encode again to unicode
password_saved = password_base64.decode('ascii')
# store the password
key_name = self._key_for_service(service)
hkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER, key_name)
winreg.SetValueEx(hkey, username, 0, winreg.REG_SZ, password_saved) | [
"def",
"set_password",
"(",
"self",
",",
"service",
",",
"username",
",",
"password",
")",
":",
"# encrypt the password",
"password_encrypted",
"=",
"_win_crypto",
".",
"encrypt",
"(",
"password",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"# encode with base64",
"password_base64",
"=",
"base64",
".",
"encodestring",
"(",
"password_encrypted",
")",
"# encode again to unicode",
"password_saved",
"=",
"password_base64",
".",
"decode",
"(",
"'ascii'",
")",
"# store the password",
"key_name",
"=",
"self",
".",
"_key_for_service",
"(",
"service",
")",
"hkey",
"=",
"winreg",
".",
"CreateKey",
"(",
"winreg",
".",
"HKEY_CURRENT_USER",
",",
"key_name",
")",
"winreg",
".",
"SetValueEx",
"(",
"hkey",
",",
"username",
",",
"0",
",",
"winreg",
".",
"REG_SZ",
",",
"password_saved",
")"
] | Write the password to the registry | [
"Write",
"the",
"password",
"to",
"the",
"registry"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/Windows.py#L103-L116 | train |
jaraco/keyrings.alt | keyrings/alt/Windows.py | RegistryKeyring.delete_password | 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)
winreg.DeleteValue(hkey, username)
winreg.CloseKey(hkey)
except WindowsError:
e = sys.exc_info()[1]
raise PasswordDeleteError(e)
self._delete_key_if_empty(service) | python | 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)
winreg.DeleteValue(hkey, username)
winreg.CloseKey(hkey)
except WindowsError:
e = sys.exc_info()[1]
raise PasswordDeleteError(e)
self._delete_key_if_empty(service) | [
"def",
"delete_password",
"(",
"self",
",",
"service",
",",
"username",
")",
":",
"try",
":",
"key_name",
"=",
"self",
".",
"_key_for_service",
"(",
"service",
")",
"hkey",
"=",
"winreg",
".",
"OpenKey",
"(",
"winreg",
".",
"HKEY_CURRENT_USER",
",",
"key_name",
",",
"0",
",",
"winreg",
".",
"KEY_ALL_ACCESS",
")",
"winreg",
".",
"DeleteValue",
"(",
"hkey",
",",
"username",
")",
"winreg",
".",
"CloseKey",
"(",
"hkey",
")",
"except",
"WindowsError",
":",
"e",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"raise",
"PasswordDeleteError",
"(",
"e",
")",
"self",
".",
"_delete_key_if_empty",
"(",
"service",
")"
] | Delete the password for the username of the service. | [
"Delete",
"the",
"password",
"for",
"the",
"username",
"of",
"the",
"service",
"."
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/Windows.py#L118-L131 | train |
jaraco/keyrings.alt | keyrings/alt/pyfs.py | BasicKeyring.encrypt | def encrypt(self, password):
"""Encrypt the password.
"""
if not password or not self._crypter:
return password or b''
return self._crypter.encrypt(password) | python | def encrypt(self, password):
"""Encrypt the password.
"""
if not password or not self._crypter:
return password or b''
return self._crypter.encrypt(password) | [
"def",
"encrypt",
"(",
"self",
",",
"password",
")",
":",
"if",
"not",
"password",
"or",
"not",
"self",
".",
"_crypter",
":",
"return",
"password",
"or",
"b''",
"return",
"self",
".",
"_crypter",
".",
"encrypt",
"(",
"password",
")"
] | Encrypt the password. | [
"Encrypt",
"the",
"password",
"."
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/pyfs.py#L71-L76 | train |
jaraco/keyrings.alt | keyrings/alt/pyfs.py | BasicKeyring.decrypt | 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) | python | 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",
"decrypt",
"(",
"self",
",",
"password_encrypted",
")",
":",
"if",
"not",
"password_encrypted",
"or",
"not",
"self",
".",
"_crypter",
":",
"return",
"password_encrypted",
"or",
"b''",
"return",
"self",
".",
"_crypter",
".",
"decrypt",
"(",
"password_encrypted",
")"
] | Decrypt the password. | [
"Decrypt",
"the",
"password",
"."
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/pyfs.py#L78-L83 | train |
jaraco/keyrings.alt | keyrings/alt/pyfs.py | BasicKeyring._open | 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()
# so we add a dummy name and open it separately
if (self.filename.startswith('mem://')
or self.filename.startswith('ram://')):
open_file = fs.opener.fsopendir(self.filename).open('kr.cfg',
mode)
else:
if not hasattr(self, '_pyfs'):
# reuse the pyfilesystem and path
self._pyfs, self._path = fs.opener.opener.parse(
self.filename, writeable=writeable)
# cache if permitted
if self._cache_timeout is not None:
self._pyfs = fs.remote.CacheFS(
self._pyfs, cache_timeout=self._cache_timeout)
open_file = self._pyfs.open(self._path, mode)
except fs.errors.ResourceNotFoundError:
if self._can_create:
segments = fs.opener.opener.split_segments(self.filename)
if segments:
# this seems broken, but pyfilesystem uses it, so we must
fs_name, credentials, url1, url2, path = segments.groups()
assert fs_name, 'Should be a remote filesystem'
host = ''
# allow for domain:port
if ':' in url2:
split_url2 = url2.split('/', 1)
if len(split_url2) > 1:
url2 = split_url2[1]
else:
url2 = ''
host = split_url2[0]
pyfs = fs.opener.opener.opendir(
'%s://%s' % (fs_name, host))
# cache if permitted
if self._cache_timeout is not None:
pyfs = fs.remote.CacheFS(
pyfs, cache_timeout=self._cache_timeout)
# NOTE: fs.path.split does not function in the same
# way os os.path.split... at least under windows
url2_path, url2_filename = os.path.split(url2)
if url2_path and not pyfs.exists(url2_path):
pyfs.makedir(url2_path, recursive=True)
else:
# assume local filesystem
full_url = fs.opener._expand_syspath(self.filename)
# NOTE: fs.path.split does not function in the same
# way os os.path.split... at least under windows
url2_path, url2 = os.path.split(full_url)
pyfs = fs.osfs.OSFS(url2_path)
try:
# reuse the pyfilesystem and path
self._pyfs = pyfs
self._path = url2
return pyfs.open(url2, mode)
except fs.errors.ResourceNotFoundError:
if writeable:
raise
else:
pass
# NOTE: ignore read errors as the underlying caller can fail safely
if writeable:
raise
else:
pass
return open_file | python | 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()
# so we add a dummy name and open it separately
if (self.filename.startswith('mem://')
or self.filename.startswith('ram://')):
open_file = fs.opener.fsopendir(self.filename).open('kr.cfg',
mode)
else:
if not hasattr(self, '_pyfs'):
# reuse the pyfilesystem and path
self._pyfs, self._path = fs.opener.opener.parse(
self.filename, writeable=writeable)
# cache if permitted
if self._cache_timeout is not None:
self._pyfs = fs.remote.CacheFS(
self._pyfs, cache_timeout=self._cache_timeout)
open_file = self._pyfs.open(self._path, mode)
except fs.errors.ResourceNotFoundError:
if self._can_create:
segments = fs.opener.opener.split_segments(self.filename)
if segments:
# this seems broken, but pyfilesystem uses it, so we must
fs_name, credentials, url1, url2, path = segments.groups()
assert fs_name, 'Should be a remote filesystem'
host = ''
# allow for domain:port
if ':' in url2:
split_url2 = url2.split('/', 1)
if len(split_url2) > 1:
url2 = split_url2[1]
else:
url2 = ''
host = split_url2[0]
pyfs = fs.opener.opener.opendir(
'%s://%s' % (fs_name, host))
# cache if permitted
if self._cache_timeout is not None:
pyfs = fs.remote.CacheFS(
pyfs, cache_timeout=self._cache_timeout)
# NOTE: fs.path.split does not function in the same
# way os os.path.split... at least under windows
url2_path, url2_filename = os.path.split(url2)
if url2_path and not pyfs.exists(url2_path):
pyfs.makedir(url2_path, recursive=True)
else:
# assume local filesystem
full_url = fs.opener._expand_syspath(self.filename)
# NOTE: fs.path.split does not function in the same
# way os os.path.split... at least under windows
url2_path, url2 = os.path.split(full_url)
pyfs = fs.osfs.OSFS(url2_path)
try:
# reuse the pyfilesystem and path
self._pyfs = pyfs
self._path = url2
return pyfs.open(url2, mode)
except fs.errors.ResourceNotFoundError:
if writeable:
raise
else:
pass
# NOTE: ignore read errors as the underlying caller can fail safely
if writeable:
raise
else:
pass
return open_file | [
"def",
"_open",
"(",
"self",
",",
"mode",
"=",
"'r'",
")",
":",
"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()",
"# so we add a dummy name and open it separately",
"if",
"(",
"self",
".",
"filename",
".",
"startswith",
"(",
"'mem://'",
")",
"or",
"self",
".",
"filename",
".",
"startswith",
"(",
"'ram://'",
")",
")",
":",
"open_file",
"=",
"fs",
".",
"opener",
".",
"fsopendir",
"(",
"self",
".",
"filename",
")",
".",
"open",
"(",
"'kr.cfg'",
",",
"mode",
")",
"else",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_pyfs'",
")",
":",
"# reuse the pyfilesystem and path",
"self",
".",
"_pyfs",
",",
"self",
".",
"_path",
"=",
"fs",
".",
"opener",
".",
"opener",
".",
"parse",
"(",
"self",
".",
"filename",
",",
"writeable",
"=",
"writeable",
")",
"# cache if permitted",
"if",
"self",
".",
"_cache_timeout",
"is",
"not",
"None",
":",
"self",
".",
"_pyfs",
"=",
"fs",
".",
"remote",
".",
"CacheFS",
"(",
"self",
".",
"_pyfs",
",",
"cache_timeout",
"=",
"self",
".",
"_cache_timeout",
")",
"open_file",
"=",
"self",
".",
"_pyfs",
".",
"open",
"(",
"self",
".",
"_path",
",",
"mode",
")",
"except",
"fs",
".",
"errors",
".",
"ResourceNotFoundError",
":",
"if",
"self",
".",
"_can_create",
":",
"segments",
"=",
"fs",
".",
"opener",
".",
"opener",
".",
"split_segments",
"(",
"self",
".",
"filename",
")",
"if",
"segments",
":",
"# this seems broken, but pyfilesystem uses it, so we must",
"fs_name",
",",
"credentials",
",",
"url1",
",",
"url2",
",",
"path",
"=",
"segments",
".",
"groups",
"(",
")",
"assert",
"fs_name",
",",
"'Should be a remote filesystem'",
"host",
"=",
"''",
"# allow for domain:port",
"if",
"':'",
"in",
"url2",
":",
"split_url2",
"=",
"url2",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"if",
"len",
"(",
"split_url2",
")",
">",
"1",
":",
"url2",
"=",
"split_url2",
"[",
"1",
"]",
"else",
":",
"url2",
"=",
"''",
"host",
"=",
"split_url2",
"[",
"0",
"]",
"pyfs",
"=",
"fs",
".",
"opener",
".",
"opener",
".",
"opendir",
"(",
"'%s://%s'",
"%",
"(",
"fs_name",
",",
"host",
")",
")",
"# cache if permitted",
"if",
"self",
".",
"_cache_timeout",
"is",
"not",
"None",
":",
"pyfs",
"=",
"fs",
".",
"remote",
".",
"CacheFS",
"(",
"pyfs",
",",
"cache_timeout",
"=",
"self",
".",
"_cache_timeout",
")",
"# NOTE: fs.path.split does not function in the same",
"# way os os.path.split... at least under windows",
"url2_path",
",",
"url2_filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"url2",
")",
"if",
"url2_path",
"and",
"not",
"pyfs",
".",
"exists",
"(",
"url2_path",
")",
":",
"pyfs",
".",
"makedir",
"(",
"url2_path",
",",
"recursive",
"=",
"True",
")",
"else",
":",
"# assume local filesystem",
"full_url",
"=",
"fs",
".",
"opener",
".",
"_expand_syspath",
"(",
"self",
".",
"filename",
")",
"# NOTE: fs.path.split does not function in the same",
"# way os os.path.split... at least under windows",
"url2_path",
",",
"url2",
"=",
"os",
".",
"path",
".",
"split",
"(",
"full_url",
")",
"pyfs",
"=",
"fs",
".",
"osfs",
".",
"OSFS",
"(",
"url2_path",
")",
"try",
":",
"# reuse the pyfilesystem and path",
"self",
".",
"_pyfs",
"=",
"pyfs",
"self",
".",
"_path",
"=",
"url2",
"return",
"pyfs",
".",
"open",
"(",
"url2",
",",
"mode",
")",
"except",
"fs",
".",
"errors",
".",
"ResourceNotFoundError",
":",
"if",
"writeable",
":",
"raise",
"else",
":",
"pass",
"# NOTE: ignore read errors as the underlying caller can fail safely",
"if",
"writeable",
":",
"raise",
"else",
":",
"pass",
"return",
"open_file"
] | Open the password file in the specified mode | [
"Open",
"the",
"password",
"file",
"in",
"the",
"specified",
"mode"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/pyfs.py#L85-L158 | train |
jaraco/keyrings.alt | keyrings/alt/pyfs.py | BasicKeyring.config | 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_config
return self._config | python | 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_config
return self._config | [
"def",
"config",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_config'",
")",
":",
"raw_config",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"f",
"=",
"self",
".",
"_open",
"(",
")",
"if",
"f",
":",
"raw_config",
".",
"readfp",
"(",
"f",
")",
"f",
".",
"close",
"(",
")",
"self",
".",
"_config",
"=",
"raw_config",
"return",
"self",
".",
"_config"
] | load the passwords from the config file | [
"load",
"the",
"passwords",
"from",
"the",
"config",
"file"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/pyfs.py#L161-L171 | train |
jaraco/keyrings.alt | keyrings/alt/pyfs.py | BasicKeyring.get_password | 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()
# decode with base64
password_encrypted = base64.decodestring(password_base64)
# decrypted the password
password = self.decrypt(password_encrypted).decode('utf-8')
except (configparser.NoOptionError, configparser.NoSectionError):
password = None
return password | python | 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()
# decode with base64
password_encrypted = base64.decodestring(password_base64)
# decrypted the password
password = self.decrypt(password_encrypted).decode('utf-8')
except (configparser.NoOptionError, configparser.NoSectionError):
password = None
return password | [
"def",
"get_password",
"(",
"self",
",",
"service",
",",
"username",
")",
":",
"service",
"=",
"escape_for_ini",
"(",
"service",
")",
"username",
"=",
"escape_for_ini",
"(",
"username",
")",
"# fetch the password",
"try",
":",
"password_base64",
"=",
"self",
".",
"config",
".",
"get",
"(",
"service",
",",
"username",
")",
".",
"encode",
"(",
")",
"# decode with base64",
"password_encrypted",
"=",
"base64",
".",
"decodestring",
"(",
"password_base64",
")",
"# decrypted the password",
"password",
"=",
"self",
".",
"decrypt",
"(",
"password_encrypted",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"(",
"configparser",
".",
"NoOptionError",
",",
"configparser",
".",
"NoSectionError",
")",
":",
"password",
"=",
"None",
"return",
"password"
] | Read the password from the file. | [
"Read",
"the",
"password",
"from",
"the",
"file",
"."
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/pyfs.py#L173-L188 | train |
jaraco/keyrings.alt | keyrings/alt/pyfs.py | BasicKeyring.set_password | 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('utf-8'))
# encode with base64
password_base64 = base64.encodestring(password_encrypted).decode()
# write the modification
if not self.config.has_section(service):
self.config.add_section(service)
self.config.set(service, username, password_base64)
config_file = UnicodeWriterAdapter(self._open('w'))
self.config.write(config_file)
config_file.close() | python | 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('utf-8'))
# encode with base64
password_base64 = base64.encodestring(password_encrypted).decode()
# write the modification
if not self.config.has_section(service):
self.config.add_section(service)
self.config.set(service, username, password_base64)
config_file = UnicodeWriterAdapter(self._open('w'))
self.config.write(config_file)
config_file.close() | [
"def",
"set_password",
"(",
"self",
",",
"service",
",",
"username",
",",
"password",
")",
":",
"service",
"=",
"escape_for_ini",
"(",
"service",
")",
"username",
"=",
"escape_for_ini",
"(",
"username",
")",
"# encrypt the password",
"password",
"=",
"password",
"or",
"''",
"password_encrypted",
"=",
"self",
".",
"encrypt",
"(",
"password",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"# encode with base64",
"password_base64",
"=",
"base64",
".",
"encodestring",
"(",
"password_encrypted",
")",
".",
"decode",
"(",
")",
"# write the modification",
"if",
"not",
"self",
".",
"config",
".",
"has_section",
"(",
"service",
")",
":",
"self",
".",
"config",
".",
"add_section",
"(",
"service",
")",
"self",
".",
"config",
".",
"set",
"(",
"service",
",",
"username",
",",
"password_base64",
")",
"config_file",
"=",
"UnicodeWriterAdapter",
"(",
"self",
".",
"_open",
"(",
"'w'",
")",
")",
"self",
".",
"config",
".",
"write",
"(",
"config_file",
")",
"config_file",
".",
"close",
"(",
")"
] | Write the password in the file. | [
"Write",
"the",
"password",
"in",
"the",
"file",
"."
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/pyfs.py#L190-L208 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/models.py | LiveEntryCategoryManager.get_queryset | 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
for entry_tag
in EntryTag.objects.filter(entry__live=True)
]) | python | 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
for entry_tag
in EntryTag.objects.filter(entry__live=True)
]) | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"queryset",
"=",
"super",
"(",
"LiveEntryCategoryManager",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
"return",
"queryset",
".",
"filter",
"(",
"tag__in",
"=",
"[",
"entry_tag",
".",
"tag",
"for",
"entry_tag",
"in",
"EntryTag",
".",
"objects",
".",
"filter",
"(",
"entry__live",
"=",
"True",
")",
"]",
")"
] | Returns queryset limited to categories with live Entry instances.
:rtype: django.db.models.query.QuerySet. | [
"Returns",
"queryset",
"limited",
"to",
"categories",
"with",
"live",
"Entry",
"instances",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/models.py#L33-L44 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/models.py | EntryManager.get_for_model | 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),
object_id = model.pk
) | python | 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),
object_id = model.pk
) | [
"def",
"get_for_model",
"(",
"self",
",",
"model",
")",
":",
"return",
"self",
".",
"get_or_create",
"(",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"model",
")",
",",
"object_id",
"=",
"model",
".",
"pk",
")"
] | Returns tuple (Entry instance, created) for specified
model instance.
:rtype: wagtailplus.wagtailrelations.models.Entry. | [
"Returns",
"tuple",
"(",
"Entry",
"instance",
"created",
")",
"for",
"specified",
"model",
"instance",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/models.py#L120-L130 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/models.py | EntryManager.get_for_tag | def get_for_tag(self, tag):
"""
Returns queryset of Entry instances assigned to specified
tag, which can be a PK value, a slug value, or a Tag instance.
:param tag: tag PK, slug, or instance.
:rtype: django.db.models.query.QuerySet.
"""
tag_filter = {'tag': tag}
if isinstance(tag, six.integer_types):
tag_filter = {'tag_id': tag}
elif isinstance(tag, str):
tag_filter = {'tag__slug': tag}
return self.filter(id__in=[
entry_tag.entry_id
for entry_tag
in EntryTag.objects.filter(**tag_filter)
]) | python | def get_for_tag(self, tag):
"""
Returns queryset of Entry instances assigned to specified
tag, which can be a PK value, a slug value, or a Tag instance.
:param tag: tag PK, slug, or instance.
:rtype: django.db.models.query.QuerySet.
"""
tag_filter = {'tag': tag}
if isinstance(tag, six.integer_types):
tag_filter = {'tag_id': tag}
elif isinstance(tag, str):
tag_filter = {'tag__slug': tag}
return self.filter(id__in=[
entry_tag.entry_id
for entry_tag
in EntryTag.objects.filter(**tag_filter)
]) | [
"def",
"get_for_tag",
"(",
"self",
",",
"tag",
")",
":",
"tag_filter",
"=",
"{",
"'tag'",
":",
"tag",
"}",
"if",
"isinstance",
"(",
"tag",
",",
"six",
".",
"integer_types",
")",
":",
"tag_filter",
"=",
"{",
"'tag_id'",
":",
"tag",
"}",
"elif",
"isinstance",
"(",
"tag",
",",
"str",
")",
":",
"tag_filter",
"=",
"{",
"'tag__slug'",
":",
"tag",
"}",
"return",
"self",
".",
"filter",
"(",
"id__in",
"=",
"[",
"entry_tag",
".",
"entry_id",
"for",
"entry_tag",
"in",
"EntryTag",
".",
"objects",
".",
"filter",
"(",
"*",
"*",
"tag_filter",
")",
"]",
")"
] | Returns queryset of Entry instances assigned to specified
tag, which can be a PK value, a slug value, or a Tag instance.
:param tag: tag PK, slug, or instance.
:rtype: django.db.models.query.QuerySet. | [
"Returns",
"queryset",
"of",
"Entry",
"instances",
"assigned",
"to",
"specified",
"tag",
"which",
"can",
"be",
"a",
"PK",
"value",
"a",
"slug",
"value",
"or",
"a",
"Tag",
"instance",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/models.py#L132-L151 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/models.py | EntryTagManager.for_category | def for_category(self, category, live_only=False):
"""
Returns queryset of EntryTag instances for specified category.
:param category: the Category instance.
:param live_only: flag to include only "live" entries.
:rtype: django.db.models.query.QuerySet.
"""
filters = {'tag': category.tag}
if live_only:
filters.update({'entry__live': True})
return self.filter(**filters) | python | def for_category(self, category, live_only=False):
"""
Returns queryset of EntryTag instances for specified category.
:param category: the Category instance.
:param live_only: flag to include only "live" entries.
:rtype: django.db.models.query.QuerySet.
"""
filters = {'tag': category.tag}
if live_only:
filters.update({'entry__live': True})
return self.filter(**filters) | [
"def",
"for_category",
"(",
"self",
",",
"category",
",",
"live_only",
"=",
"False",
")",
":",
"filters",
"=",
"{",
"'tag'",
":",
"category",
".",
"tag",
"}",
"if",
"live_only",
":",
"filters",
".",
"update",
"(",
"{",
"'entry__live'",
":",
"True",
"}",
")",
"return",
"self",
".",
"filter",
"(",
"*",
"*",
"filters",
")"
] | Returns queryset of EntryTag instances for specified category.
:param category: the Category instance.
:param live_only: flag to include only "live" entries.
:rtype: django.db.models.query.QuerySet. | [
"Returns",
"queryset",
"of",
"EntryTag",
"instances",
"for",
"specified",
"category",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/models.py#L343-L356 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/models.py | EntryTagManager.related_to | def related_to(self, entry, live_only=False):
"""
Returns queryset of Entry instances related to specified
Entry instance.
:param entry: the Entry instance.
:param live_only: flag to include only "live" entries.
:rtype: django.db.models.query.QuerySet.
"""
filters = {'tag__in': entry.tags}
if live_only:
filters.update({'entry__live': True})
return self.filter(**filters).exclude(entry=entry) | python | def related_to(self, entry, live_only=False):
"""
Returns queryset of Entry instances related to specified
Entry instance.
:param entry: the Entry instance.
:param live_only: flag to include only "live" entries.
:rtype: django.db.models.query.QuerySet.
"""
filters = {'tag__in': entry.tags}
if live_only:
filters.update({'entry__live': True})
return self.filter(**filters).exclude(entry=entry) | [
"def",
"related_to",
"(",
"self",
",",
"entry",
",",
"live_only",
"=",
"False",
")",
":",
"filters",
"=",
"{",
"'tag__in'",
":",
"entry",
".",
"tags",
"}",
"if",
"live_only",
":",
"filters",
".",
"update",
"(",
"{",
"'entry__live'",
":",
"True",
"}",
")",
"return",
"self",
".",
"filter",
"(",
"*",
"*",
"filters",
")",
".",
"exclude",
"(",
"entry",
"=",
"entry",
")"
] | Returns queryset of Entry instances related to specified
Entry instance.
:param entry: the Entry instance.
:param live_only: flag to include only "live" entries.
:rtype: django.db.models.query.QuerySet. | [
"Returns",
"queryset",
"of",
"Entry",
"instances",
"related",
"to",
"specified",
"Entry",
"instance",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/models.py#L365-L379 | train |
rfosterslo/wagtailplus | wagtailplus/utils/views/chooser.py | chosen_view_factory | def chosen_view_factory(chooser_cls):
"""
Returns a ChosenView class that extends specified chooser class.
:param chooser_cls: the class to extend.
:rtype: class.
"""
class ChosenView(chooser_cls):
#noinspection PyUnusedLocal
def get(self, request, *args, **kwargs):
"""
Returns GET response.
:param request: the request instance.
:rtype: django.http.HttpResponse.
"""
#noinspection PyAttributeOutsideInit
self.object = self.get_object()
return render_modal_workflow(
self.request,
None,
'{0}/chosen.js'.format(self.template_dir),
{'obj': self.get_json(self.object)}
)
def get_object(self, queryset=None):
"""
Returns chosen object instance.
:param queryset: the queryset instance.
:rtype: django.db.models.Model.
"""
if queryset is None:
queryset = self.get_queryset()
pk = self.kwargs.get('pk', None)
try:
return queryset.get(pk=pk)
except self.models.DoesNotExist:
raise Http404()
def post(self, request, *args, **kwargs):
"""
Returns POST response.
:param request: the request instance.
:rtype: django.http.HttpResponse.
"""
return self.get(request, *args, **kwargs)
return ChosenView | python | def chosen_view_factory(chooser_cls):
"""
Returns a ChosenView class that extends specified chooser class.
:param chooser_cls: the class to extend.
:rtype: class.
"""
class ChosenView(chooser_cls):
#noinspection PyUnusedLocal
def get(self, request, *args, **kwargs):
"""
Returns GET response.
:param request: the request instance.
:rtype: django.http.HttpResponse.
"""
#noinspection PyAttributeOutsideInit
self.object = self.get_object()
return render_modal_workflow(
self.request,
None,
'{0}/chosen.js'.format(self.template_dir),
{'obj': self.get_json(self.object)}
)
def get_object(self, queryset=None):
"""
Returns chosen object instance.
:param queryset: the queryset instance.
:rtype: django.db.models.Model.
"""
if queryset is None:
queryset = self.get_queryset()
pk = self.kwargs.get('pk', None)
try:
return queryset.get(pk=pk)
except self.models.DoesNotExist:
raise Http404()
def post(self, request, *args, **kwargs):
"""
Returns POST response.
:param request: the request instance.
:rtype: django.http.HttpResponse.
"""
return self.get(request, *args, **kwargs)
return ChosenView | [
"def",
"chosen_view_factory",
"(",
"chooser_cls",
")",
":",
"class",
"ChosenView",
"(",
"chooser_cls",
")",
":",
"#noinspection PyUnusedLocal",
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Returns GET response.\n\n :param request: the request instance.\n :rtype: django.http.HttpResponse.\n \"\"\"",
"#noinspection PyAttributeOutsideInit",
"self",
".",
"object",
"=",
"self",
".",
"get_object",
"(",
")",
"return",
"render_modal_workflow",
"(",
"self",
".",
"request",
",",
"None",
",",
"'{0}/chosen.js'",
".",
"format",
"(",
"self",
".",
"template_dir",
")",
",",
"{",
"'obj'",
":",
"self",
".",
"get_json",
"(",
"self",
".",
"object",
")",
"}",
")",
"def",
"get_object",
"(",
"self",
",",
"queryset",
"=",
"None",
")",
":",
"\"\"\"\n Returns chosen object instance.\n\n :param queryset: the queryset instance.\n :rtype: django.db.models.Model.\n \"\"\"",
"if",
"queryset",
"is",
"None",
":",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
"pk",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"'pk'",
",",
"None",
")",
"try",
":",
"return",
"queryset",
".",
"get",
"(",
"pk",
"=",
"pk",
")",
"except",
"self",
".",
"models",
".",
"DoesNotExist",
":",
"raise",
"Http404",
"(",
")",
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Returns POST response.\n\n :param request: the request instance.\n :rtype: django.http.HttpResponse.\n \"\"\"",
"return",
"self",
".",
"get",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"ChosenView"
] | Returns a ChosenView class that extends specified chooser class.
:param chooser_cls: the class to extend.
:rtype: class. | [
"Returns",
"a",
"ChosenView",
"class",
"that",
"extends",
"specified",
"chooser",
"class",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/views/chooser.py#L163-L215 | train |
rfosterslo/wagtailplus | wagtailplus/utils/views/chooser.py | ChooserView.form_invalid | def form_invalid(self, form):
"""
Processes an invalid form submittal.
:param form: the form instance.
:rtype: django.http.HttpResponse.
"""
context = self.get_context_data(form=form)
#noinspection PyUnresolvedReferences
return render_modal_workflow(
self.request,
'{0}/chooser.html'.format(self.template_dir),
'{0}/chooser.js'.format(self.template_dir),
context
) | python | def form_invalid(self, form):
"""
Processes an invalid form submittal.
:param form: the form instance.
:rtype: django.http.HttpResponse.
"""
context = self.get_context_data(form=form)
#noinspection PyUnresolvedReferences
return render_modal_workflow(
self.request,
'{0}/chooser.html'.format(self.template_dir),
'{0}/chooser.js'.format(self.template_dir),
context
) | [
"def",
"form_invalid",
"(",
"self",
",",
"form",
")",
":",
"context",
"=",
"self",
".",
"get_context_data",
"(",
"form",
"=",
"form",
")",
"#noinspection PyUnresolvedReferences",
"return",
"render_modal_workflow",
"(",
"self",
".",
"request",
",",
"'{0}/chooser.html'",
".",
"format",
"(",
"self",
".",
"template_dir",
")",
",",
"'{0}/chooser.js'",
".",
"format",
"(",
"self",
".",
"template_dir",
")",
",",
"context",
")"
] | Processes an invalid form submittal.
:param form: the form instance.
:rtype: django.http.HttpResponse. | [
"Processes",
"an",
"invalid",
"form",
"submittal",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/views/chooser.py#L20-L35 | train |
rfosterslo/wagtailplus | wagtailplus/utils/views/chooser.py | ChooserView.form_valid | 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()
# Index the link.
for backend in get_search_backends():
backend.add(self.object)
#noinspection PyUnresolvedReferences
return render_modal_workflow(
self.request,
None,
'{0}/chosen.js'.format(self.template_dir),
{'obj': self.get_json(self.object)}
) | python | 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()
# Index the link.
for backend in get_search_backends():
backend.add(self.object)
#noinspection PyUnresolvedReferences
return render_modal_workflow(
self.request,
None,
'{0}/chosen.js'.format(self.template_dir),
{'obj': self.get_json(self.object)}
) | [
"def",
"form_valid",
"(",
"self",
",",
"form",
")",
":",
"#noinspection PyAttributeOutsideInit",
"self",
".",
"object",
"=",
"form",
".",
"save",
"(",
")",
"# Index the link.",
"for",
"backend",
"in",
"get_search_backends",
"(",
")",
":",
"backend",
".",
"add",
"(",
"self",
".",
"object",
")",
"#noinspection PyUnresolvedReferences",
"return",
"render_modal_workflow",
"(",
"self",
".",
"request",
",",
"None",
",",
"'{0}/chosen.js'",
".",
"format",
"(",
"self",
".",
"template_dir",
")",
",",
"{",
"'obj'",
":",
"self",
".",
"get_json",
"(",
"self",
".",
"object",
")",
"}",
")"
] | Processes a valid form submittal.
:param form: the form instance.
:rtype: django.http.HttpResponse. | [
"Processes",
"a",
"valid",
"form",
"submittal",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/views/chooser.py#L37-L57 | train |
rfosterslo/wagtailplus | wagtailplus/utils/views/chooser.py | ChooserView.get | def get(self, request, *args, **kwargs):
"""
Returns GET response.
:param request: the request instance.
:rtype: django.http.HttpResponse.
"""
#noinspection PyAttributeOutsideInit
self.object_list = self.get_queryset()
context = self.get_context_data(force_search=True)
if self.form_class:
context.update({'form': self.get_form()})
if 'q' in request.GET or 'p' in request.GET:
return render(
request,
'{0}/results.html'.format(self.template_dir),
context
)
else:
return render_modal_workflow(
request,
'{0}/chooser.html'.format(self.template_dir),
'{0}/chooser.js'.format(self.template_dir),
context
) | python | def get(self, request, *args, **kwargs):
"""
Returns GET response.
:param request: the request instance.
:rtype: django.http.HttpResponse.
"""
#noinspection PyAttributeOutsideInit
self.object_list = self.get_queryset()
context = self.get_context_data(force_search=True)
if self.form_class:
context.update({'form': self.get_form()})
if 'q' in request.GET or 'p' in request.GET:
return render(
request,
'{0}/results.html'.format(self.template_dir),
context
)
else:
return render_modal_workflow(
request,
'{0}/chooser.html'.format(self.template_dir),
'{0}/chooser.js'.format(self.template_dir),
context
) | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#noinspection PyAttributeOutsideInit",
"self",
".",
"object_list",
"=",
"self",
".",
"get_queryset",
"(",
")",
"context",
"=",
"self",
".",
"get_context_data",
"(",
"force_search",
"=",
"True",
")",
"if",
"self",
".",
"form_class",
":",
"context",
".",
"update",
"(",
"{",
"'form'",
":",
"self",
".",
"get_form",
"(",
")",
"}",
")",
"if",
"'q'",
"in",
"request",
".",
"GET",
"or",
"'p'",
"in",
"request",
".",
"GET",
":",
"return",
"render",
"(",
"request",
",",
"'{0}/results.html'",
".",
"format",
"(",
"self",
".",
"template_dir",
")",
",",
"context",
")",
"else",
":",
"return",
"render_modal_workflow",
"(",
"request",
",",
"'{0}/chooser.html'",
".",
"format",
"(",
"self",
".",
"template_dir",
")",
",",
"'{0}/chooser.js'",
".",
"format",
"(",
"self",
".",
"template_dir",
")",
",",
"context",
")"
] | Returns GET response.
:param request: the request instance.
:rtype: django.http.HttpResponse. | [
"Returns",
"GET",
"response",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/views/chooser.py#L59-L85 | train |
rfosterslo/wagtailplus | wagtailplus/utils/views/chooser.py | ChooserView.get_form_kwargs | def get_form_kwargs(self):
"""
Returns the keyword arguments for instantiating the form.
:rtype: dict.
"""
kwargs = {
'initial': self.get_initial(),
'prefix': self.get_prefix(),
}
#noinspection PyUnresolvedReferences
if self.request.method in ('POST', 'PUT'):
#noinspection PyUnresolvedReferences
kwargs.update({
'data': self.request.POST,
'files': self.request.FILES,
})
if hasattr(self, 'object'):
kwargs.update({'instance': self.object})
return kwargs | python | def get_form_kwargs(self):
"""
Returns the keyword arguments for instantiating the form.
:rtype: dict.
"""
kwargs = {
'initial': self.get_initial(),
'prefix': self.get_prefix(),
}
#noinspection PyUnresolvedReferences
if self.request.method in ('POST', 'PUT'):
#noinspection PyUnresolvedReferences
kwargs.update({
'data': self.request.POST,
'files': self.request.FILES,
})
if hasattr(self, 'object'):
kwargs.update({'instance': self.object})
return kwargs | [
"def",
"get_form_kwargs",
"(",
"self",
")",
":",
"kwargs",
"=",
"{",
"'initial'",
":",
"self",
".",
"get_initial",
"(",
")",
",",
"'prefix'",
":",
"self",
".",
"get_prefix",
"(",
")",
",",
"}",
"#noinspection PyUnresolvedReferences",
"if",
"self",
".",
"request",
".",
"method",
"in",
"(",
"'POST'",
",",
"'PUT'",
")",
":",
"#noinspection PyUnresolvedReferences",
"kwargs",
".",
"update",
"(",
"{",
"'data'",
":",
"self",
".",
"request",
".",
"POST",
",",
"'files'",
":",
"self",
".",
"request",
".",
"FILES",
",",
"}",
")",
"if",
"hasattr",
"(",
"self",
",",
"'object'",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'instance'",
":",
"self",
".",
"object",
"}",
")",
"return",
"kwargs"
] | Returns the keyword arguments for instantiating the form.
:rtype: dict. | [
"Returns",
"the",
"keyword",
"arguments",
"for",
"instantiating",
"the",
"form",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/utils/views/chooser.py#L106-L128 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/signals/handlers.py | create_entry_tag | def create_entry_tag(sender, instance, created, **kwargs):
"""
Creates EntryTag for Entry corresponding to specified
ItemBase instance.
:param sender: the sending ItemBase class.
:param instance: the ItemBase instance.
"""
from ..models import (
Entry,
EntryTag
)
entry = Entry.objects.get_for_model(instance.content_object)[0]
tag = instance.tag
if not EntryTag.objects.filter(tag=tag, entry=entry).exists():
EntryTag.objects.create(tag=tag, entry=entry) | python | def create_entry_tag(sender, instance, created, **kwargs):
"""
Creates EntryTag for Entry corresponding to specified
ItemBase instance.
:param sender: the sending ItemBase class.
:param instance: the ItemBase instance.
"""
from ..models import (
Entry,
EntryTag
)
entry = Entry.objects.get_for_model(instance.content_object)[0]
tag = instance.tag
if not EntryTag.objects.filter(tag=tag, entry=entry).exists():
EntryTag.objects.create(tag=tag, entry=entry) | [
"def",
"create_entry_tag",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"models",
"import",
"(",
"Entry",
",",
"EntryTag",
")",
"entry",
"=",
"Entry",
".",
"objects",
".",
"get_for_model",
"(",
"instance",
".",
"content_object",
")",
"[",
"0",
"]",
"tag",
"=",
"instance",
".",
"tag",
"if",
"not",
"EntryTag",
".",
"objects",
".",
"filter",
"(",
"tag",
"=",
"tag",
",",
"entry",
"=",
"entry",
")",
".",
"exists",
"(",
")",
":",
"EntryTag",
".",
"objects",
".",
"create",
"(",
"tag",
"=",
"tag",
",",
"entry",
"=",
"entry",
")"
] | Creates EntryTag for Entry corresponding to specified
ItemBase instance.
:param sender: the sending ItemBase class.
:param instance: the ItemBase instance. | [
"Creates",
"EntryTag",
"for",
"Entry",
"corresponding",
"to",
"specified",
"ItemBase",
"instance",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/signals/handlers.py#L11-L28 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/signals/handlers.py | delete_entry_tag | def delete_entry_tag(sender, instance, **kwargs):
"""
Deletes EntryTag for Entry corresponding to specified
TaggedItemBase instance.
:param sender: the sending TaggedItemBase class.
:param instance: the TaggedItemBase instance.
"""
from ..models import (
Entry,
EntryTag
)
entry = Entry.objects.get_for_model(instance.content_object)[0]
tag = instance.tag
EntryTag.objects.filter(tag=tag, entry=entry).delete() | python | def delete_entry_tag(sender, instance, **kwargs):
"""
Deletes EntryTag for Entry corresponding to specified
TaggedItemBase instance.
:param sender: the sending TaggedItemBase class.
:param instance: the TaggedItemBase instance.
"""
from ..models import (
Entry,
EntryTag
)
entry = Entry.objects.get_for_model(instance.content_object)[0]
tag = instance.tag
EntryTag.objects.filter(tag=tag, entry=entry).delete() | [
"def",
"delete_entry_tag",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"models",
"import",
"(",
"Entry",
",",
"EntryTag",
")",
"entry",
"=",
"Entry",
".",
"objects",
".",
"get_for_model",
"(",
"instance",
".",
"content_object",
")",
"[",
"0",
"]",
"tag",
"=",
"instance",
".",
"tag",
"EntryTag",
".",
"objects",
".",
"filter",
"(",
"tag",
"=",
"tag",
",",
"entry",
"=",
"entry",
")",
".",
"delete",
"(",
")"
] | Deletes EntryTag for Entry corresponding to specified
TaggedItemBase instance.
:param sender: the sending TaggedItemBase class.
:param instance: the TaggedItemBase instance. | [
"Deletes",
"EntryTag",
"for",
"Entry",
"corresponding",
"to",
"specified",
"TaggedItemBase",
"instance",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/signals/handlers.py#L31-L47 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/signals/handlers.py | delete_entry | def delete_entry(sender, instance, **kwargs):
"""
Deletes Entry instance corresponding to specified instance.
:param sender: the sending class.
:param instance: the instance being deleted.
"""
from ..models import Entry
Entry.objects.get_for_model(instance)[0].delete() | python | def delete_entry(sender, instance, **kwargs):
"""
Deletes Entry instance corresponding to specified instance.
:param sender: the sending class.
:param instance: the instance being deleted.
"""
from ..models import Entry
Entry.objects.get_for_model(instance)[0].delete() | [
"def",
"delete_entry",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"models",
"import",
"Entry",
"Entry",
".",
"objects",
".",
"get_for_model",
"(",
"instance",
")",
"[",
"0",
"]",
".",
"delete",
"(",
")"
] | Deletes Entry instance corresponding to specified instance.
:param sender: the sending class.
:param instance: the instance being deleted. | [
"Deletes",
"Entry",
"instance",
"corresponding",
"to",
"specified",
"instance",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/signals/handlers.py#L50-L59 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrelations/signals/handlers.py | update_entry_attributes | def update_entry_attributes(sender, instance, **kwargs):
"""
Updates attributes for Entry instance corresponding to
specified instance.
:param sender: the sending class.
:param instance: the instance being saved.
"""
from ..models import Entry
entry = Entry.objects.get_for_model(instance)[0]
default_url = getattr(instance, 'get_absolute_url', '')
entry.title = getattr(instance, 'title', str(instance))
entry.url = getattr(instance, 'url', default_url)
entry.live = bool(getattr(instance, 'live', True))
entry.save() | python | def update_entry_attributes(sender, instance, **kwargs):
"""
Updates attributes for Entry instance corresponding to
specified instance.
:param sender: the sending class.
:param instance: the instance being saved.
"""
from ..models import Entry
entry = Entry.objects.get_for_model(instance)[0]
default_url = getattr(instance, 'get_absolute_url', '')
entry.title = getattr(instance, 'title', str(instance))
entry.url = getattr(instance, 'url', default_url)
entry.live = bool(getattr(instance, 'live', True))
entry.save() | [
"def",
"update_entry_attributes",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"models",
"import",
"Entry",
"entry",
"=",
"Entry",
".",
"objects",
".",
"get_for_model",
"(",
"instance",
")",
"[",
"0",
"]",
"default_url",
"=",
"getattr",
"(",
"instance",
",",
"'get_absolute_url'",
",",
"''",
")",
"entry",
".",
"title",
"=",
"getattr",
"(",
"instance",
",",
"'title'",
",",
"str",
"(",
"instance",
")",
")",
"entry",
".",
"url",
"=",
"getattr",
"(",
"instance",
",",
"'url'",
",",
"default_url",
")",
"entry",
".",
"live",
"=",
"bool",
"(",
"getattr",
"(",
"instance",
",",
"'live'",
",",
"True",
")",
")",
"entry",
".",
"save",
"(",
")"
] | Updates attributes for Entry instance corresponding to
specified instance.
:param sender: the sending class.
:param instance: the instance being saved. | [
"Updates",
"attributes",
"for",
"Entry",
"instance",
"corresponding",
"to",
"specified",
"instance",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/signals/handlers.py#L62-L79 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrollbacks/views.py | get_revisions | def get_revisions(page, page_num=1):
"""
Returns paginated queryset of PageRevision instances for
specified Page instance.
:param page: the page instance.
:param page_num: the pagination page number.
:rtype: django.db.models.query.QuerySet.
"""
revisions = page.revisions.order_by('-created_at')
current = page.get_latest_revision()
if current:
revisions.exclude(id=current.id)
paginator = Paginator(revisions, 5)
try:
revisions = paginator.page(page_num)
except PageNotAnInteger:
revisions = paginator.page(1)
except EmptyPage:
revisions = paginator.page(paginator.num_pages)
return revisions | python | def get_revisions(page, page_num=1):
"""
Returns paginated queryset of PageRevision instances for
specified Page instance.
:param page: the page instance.
:param page_num: the pagination page number.
:rtype: django.db.models.query.QuerySet.
"""
revisions = page.revisions.order_by('-created_at')
current = page.get_latest_revision()
if current:
revisions.exclude(id=current.id)
paginator = Paginator(revisions, 5)
try:
revisions = paginator.page(page_num)
except PageNotAnInteger:
revisions = paginator.page(1)
except EmptyPage:
revisions = paginator.page(paginator.num_pages)
return revisions | [
"def",
"get_revisions",
"(",
"page",
",",
"page_num",
"=",
"1",
")",
":",
"revisions",
"=",
"page",
".",
"revisions",
".",
"order_by",
"(",
"'-created_at'",
")",
"current",
"=",
"page",
".",
"get_latest_revision",
"(",
")",
"if",
"current",
":",
"revisions",
".",
"exclude",
"(",
"id",
"=",
"current",
".",
"id",
")",
"paginator",
"=",
"Paginator",
"(",
"revisions",
",",
"5",
")",
"try",
":",
"revisions",
"=",
"paginator",
".",
"page",
"(",
"page_num",
")",
"except",
"PageNotAnInteger",
":",
"revisions",
"=",
"paginator",
".",
"page",
"(",
"1",
")",
"except",
"EmptyPage",
":",
"revisions",
"=",
"paginator",
".",
"page",
"(",
"paginator",
".",
"num_pages",
")",
"return",
"revisions"
] | Returns paginated queryset of PageRevision instances for
specified Page instance.
:param page: the page instance.
:param page_num: the pagination page number.
:rtype: django.db.models.query.QuerySet. | [
"Returns",
"paginated",
"queryset",
"of",
"PageRevision",
"instances",
"for",
"specified",
"Page",
"instance",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrollbacks/views.py#L27-L51 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrollbacks/views.py | page_revisions | def page_revisions(request, page_id, template_name='wagtailrollbacks/edit_handlers/revisions.html'):
"""
Returns GET response for specified page revisions.
:param request: the request instance.
:param page_id: the page ID.
:param template_name: the template name.
:rtype: django.http.HttpResponse.
"""
page = get_object_or_404(Page, pk=page_id)
page_perms = page.permissions_for_user(request.user)
if not page_perms.can_edit():
raise PermissionDenied
page_num = request.GET.get('p', 1)
revisions = get_revisions(page, page_num)
return render(
request,
template_name,
{
'page': page,
'revisions': revisions,
'p': page_num,
}
) | python | def page_revisions(request, page_id, template_name='wagtailrollbacks/edit_handlers/revisions.html'):
"""
Returns GET response for specified page revisions.
:param request: the request instance.
:param page_id: the page ID.
:param template_name: the template name.
:rtype: django.http.HttpResponse.
"""
page = get_object_or_404(Page, pk=page_id)
page_perms = page.permissions_for_user(request.user)
if not page_perms.can_edit():
raise PermissionDenied
page_num = request.GET.get('p', 1)
revisions = get_revisions(page, page_num)
return render(
request,
template_name,
{
'page': page,
'revisions': revisions,
'p': page_num,
}
) | [
"def",
"page_revisions",
"(",
"request",
",",
"page_id",
",",
"template_name",
"=",
"'wagtailrollbacks/edit_handlers/revisions.html'",
")",
":",
"page",
"=",
"get_object_or_404",
"(",
"Page",
",",
"pk",
"=",
"page_id",
")",
"page_perms",
"=",
"page",
".",
"permissions_for_user",
"(",
"request",
".",
"user",
")",
"if",
"not",
"page_perms",
".",
"can_edit",
"(",
")",
":",
"raise",
"PermissionDenied",
"page_num",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'p'",
",",
"1",
")",
"revisions",
"=",
"get_revisions",
"(",
"page",
",",
"page_num",
")",
"return",
"render",
"(",
"request",
",",
"template_name",
",",
"{",
"'page'",
":",
"page",
",",
"'revisions'",
":",
"revisions",
",",
"'p'",
":",
"page_num",
",",
"}",
")"
] | Returns GET response for specified page revisions.
:param request: the request instance.
:param page_id: the page ID.
:param template_name: the template name.
:rtype: django.http.HttpResponse. | [
"Returns",
"GET",
"response",
"for",
"specified",
"page",
"revisions",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrollbacks/views.py#L53-L79 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrollbacks/views.py | preview_page_version | def preview_page_version(request, revision_id):
"""
Returns GET response for specified page preview.
:param request: the request instance.
:param reversion_pk: the page revision ID.
:rtype: django.http.HttpResponse.
"""
revision = get_object_or_404(PageRevision, pk=revision_id)
if not revision.page.permissions_for_user(request.user).can_publish():
raise PermissionDenied
page = revision.as_page_object()
request.revision_id = revision_id
return page.serve_preview(request, page.default_preview_mode) | python | def preview_page_version(request, revision_id):
"""
Returns GET response for specified page preview.
:param request: the request instance.
:param reversion_pk: the page revision ID.
:rtype: django.http.HttpResponse.
"""
revision = get_object_or_404(PageRevision, pk=revision_id)
if not revision.page.permissions_for_user(request.user).can_publish():
raise PermissionDenied
page = revision.as_page_object()
request.revision_id = revision_id
return page.serve_preview(request, page.default_preview_mode) | [
"def",
"preview_page_version",
"(",
"request",
",",
"revision_id",
")",
":",
"revision",
"=",
"get_object_or_404",
"(",
"PageRevision",
",",
"pk",
"=",
"revision_id",
")",
"if",
"not",
"revision",
".",
"page",
".",
"permissions_for_user",
"(",
"request",
".",
"user",
")",
".",
"can_publish",
"(",
")",
":",
"raise",
"PermissionDenied",
"page",
"=",
"revision",
".",
"as_page_object",
"(",
")",
"request",
".",
"revision_id",
"=",
"revision_id",
"return",
"page",
".",
"serve_preview",
"(",
"request",
",",
"page",
".",
"default_preview_mode",
")"
] | Returns GET response for specified page preview.
:param request: the request instance.
:param reversion_pk: the page revision ID.
:rtype: django.http.HttpResponse. | [
"Returns",
"GET",
"response",
"for",
"specified",
"page",
"preview",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrollbacks/views.py#L81-L97 | train |
rfosterslo/wagtailplus | wagtailplus/wagtailrollbacks/views.py | confirm_page_reversion | def confirm_page_reversion(request, revision_id, template_name='wagtailrollbacks/pages/confirm_reversion.html'):
"""
Handles page reversion process (GET and POST).
:param request: the request instance.
:param revision_id: the page revision ID.
:param template_name: the template name.
:rtype: django.http.HttpResponse.
"""
revision = get_object_or_404(PageRevision, pk=revision_id)
page = revision.page
if page.locked:
messages.error(
request,
_("Page '{0}' is locked.").format(page.title),
buttons = []
)
return redirect(reverse('wagtailadmin_pages:edit', args=(page.id,)))
page_perms = page.permissions_for_user(request.user)
if not page_perms.can_edit():
raise PermissionDenied
if request.POST:
is_publishing = bool(request.POST.get('action-publish')) and page_perms.can_publish()
is_submitting = bool(request.POST.get('action-submit'))
new_revision = page.rollback(
revision_id = revision_id,
user = request.user,
submitted_for_moderation = is_submitting
)
if is_publishing:
new_revision.publish()
messages.success(
request,
_("Page '{0}' published.").format(page.title),
buttons=[
messages.button(page.url, _('View live')),
messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit'))
]
)
elif is_submitting:
messages.success(
request,
_("Page '{0}' submitted for moderation.").format(page.title),
buttons=[
messages.button(reverse('wagtailadmin_pages:view_draft', args=(page.id,)), _('View draft')),
messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit'))
]
)
send_notification(new_revision.id, 'submitted', request.user.id)
else:
messages.success(
request,
_("Page '{0}' updated.").format(page.title),
buttons=[]
)
for fn in hooks.get_hooks('after_edit_page'):
result = fn(request, page)
if hasattr(result, 'status_code'):
return result
return redirect('wagtailadmin_explore', page.get_parent().id)
return render(
request,
template_name,
{
'page': page,
'revision': revision,
'page_perms': page_perms
}
) | python | def confirm_page_reversion(request, revision_id, template_name='wagtailrollbacks/pages/confirm_reversion.html'):
"""
Handles page reversion process (GET and POST).
:param request: the request instance.
:param revision_id: the page revision ID.
:param template_name: the template name.
:rtype: django.http.HttpResponse.
"""
revision = get_object_or_404(PageRevision, pk=revision_id)
page = revision.page
if page.locked:
messages.error(
request,
_("Page '{0}' is locked.").format(page.title),
buttons = []
)
return redirect(reverse('wagtailadmin_pages:edit', args=(page.id,)))
page_perms = page.permissions_for_user(request.user)
if not page_perms.can_edit():
raise PermissionDenied
if request.POST:
is_publishing = bool(request.POST.get('action-publish')) and page_perms.can_publish()
is_submitting = bool(request.POST.get('action-submit'))
new_revision = page.rollback(
revision_id = revision_id,
user = request.user,
submitted_for_moderation = is_submitting
)
if is_publishing:
new_revision.publish()
messages.success(
request,
_("Page '{0}' published.").format(page.title),
buttons=[
messages.button(page.url, _('View live')),
messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit'))
]
)
elif is_submitting:
messages.success(
request,
_("Page '{0}' submitted for moderation.").format(page.title),
buttons=[
messages.button(reverse('wagtailadmin_pages:view_draft', args=(page.id,)), _('View draft')),
messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit'))
]
)
send_notification(new_revision.id, 'submitted', request.user.id)
else:
messages.success(
request,
_("Page '{0}' updated.").format(page.title),
buttons=[]
)
for fn in hooks.get_hooks('after_edit_page'):
result = fn(request, page)
if hasattr(result, 'status_code'):
return result
return redirect('wagtailadmin_explore', page.get_parent().id)
return render(
request,
template_name,
{
'page': page,
'revision': revision,
'page_perms': page_perms
}
) | [
"def",
"confirm_page_reversion",
"(",
"request",
",",
"revision_id",
",",
"template_name",
"=",
"'wagtailrollbacks/pages/confirm_reversion.html'",
")",
":",
"revision",
"=",
"get_object_or_404",
"(",
"PageRevision",
",",
"pk",
"=",
"revision_id",
")",
"page",
"=",
"revision",
".",
"page",
"if",
"page",
".",
"locked",
":",
"messages",
".",
"error",
"(",
"request",
",",
"_",
"(",
"\"Page '{0}' is locked.\"",
")",
".",
"format",
"(",
"page",
".",
"title",
")",
",",
"buttons",
"=",
"[",
"]",
")",
"return",
"redirect",
"(",
"reverse",
"(",
"'wagtailadmin_pages:edit'",
",",
"args",
"=",
"(",
"page",
".",
"id",
",",
")",
")",
")",
"page_perms",
"=",
"page",
".",
"permissions_for_user",
"(",
"request",
".",
"user",
")",
"if",
"not",
"page_perms",
".",
"can_edit",
"(",
")",
":",
"raise",
"PermissionDenied",
"if",
"request",
".",
"POST",
":",
"is_publishing",
"=",
"bool",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"'action-publish'",
")",
")",
"and",
"page_perms",
".",
"can_publish",
"(",
")",
"is_submitting",
"=",
"bool",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"'action-submit'",
")",
")",
"new_revision",
"=",
"page",
".",
"rollback",
"(",
"revision_id",
"=",
"revision_id",
",",
"user",
"=",
"request",
".",
"user",
",",
"submitted_for_moderation",
"=",
"is_submitting",
")",
"if",
"is_publishing",
":",
"new_revision",
".",
"publish",
"(",
")",
"messages",
".",
"success",
"(",
"request",
",",
"_",
"(",
"\"Page '{0}' published.\"",
")",
".",
"format",
"(",
"page",
".",
"title",
")",
",",
"buttons",
"=",
"[",
"messages",
".",
"button",
"(",
"page",
".",
"url",
",",
"_",
"(",
"'View live'",
")",
")",
",",
"messages",
".",
"button",
"(",
"reverse",
"(",
"'wagtailadmin_pages:edit'",
",",
"args",
"=",
"(",
"page",
".",
"id",
",",
")",
")",
",",
"_",
"(",
"'Edit'",
")",
")",
"]",
")",
"elif",
"is_submitting",
":",
"messages",
".",
"success",
"(",
"request",
",",
"_",
"(",
"\"Page '{0}' submitted for moderation.\"",
")",
".",
"format",
"(",
"page",
".",
"title",
")",
",",
"buttons",
"=",
"[",
"messages",
".",
"button",
"(",
"reverse",
"(",
"'wagtailadmin_pages:view_draft'",
",",
"args",
"=",
"(",
"page",
".",
"id",
",",
")",
")",
",",
"_",
"(",
"'View draft'",
")",
")",
",",
"messages",
".",
"button",
"(",
"reverse",
"(",
"'wagtailadmin_pages:edit'",
",",
"args",
"=",
"(",
"page",
".",
"id",
",",
")",
")",
",",
"_",
"(",
"'Edit'",
")",
")",
"]",
")",
"send_notification",
"(",
"new_revision",
".",
"id",
",",
"'submitted'",
",",
"request",
".",
"user",
".",
"id",
")",
"else",
":",
"messages",
".",
"success",
"(",
"request",
",",
"_",
"(",
"\"Page '{0}' updated.\"",
")",
".",
"format",
"(",
"page",
".",
"title",
")",
",",
"buttons",
"=",
"[",
"]",
")",
"for",
"fn",
"in",
"hooks",
".",
"get_hooks",
"(",
"'after_edit_page'",
")",
":",
"result",
"=",
"fn",
"(",
"request",
",",
"page",
")",
"if",
"hasattr",
"(",
"result",
",",
"'status_code'",
")",
":",
"return",
"result",
"return",
"redirect",
"(",
"'wagtailadmin_explore'",
",",
"page",
".",
"get_parent",
"(",
")",
".",
"id",
")",
"return",
"render",
"(",
"request",
",",
"template_name",
",",
"{",
"'page'",
":",
"page",
",",
"'revision'",
":",
"revision",
",",
"'page_perms'",
":",
"page_perms",
"}",
")"
] | Handles page reversion process (GET and POST).
:param request: the request instance.
:param revision_id: the page revision ID.
:param template_name: the template name.
:rtype: django.http.HttpResponse. | [
"Handles",
"page",
"reversion",
"process",
"(",
"GET",
"and",
"POST",
")",
"."
] | 22cac857175d8a6f77e470751831c14a92ccd768 | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrollbacks/views.py#L99-L176 | train |
jaraco/keyrings.alt | keyrings/alt/Google.py | DocsKeyring.get_password | def get_password(self, service, username):
"""Get password of the username for the service
"""
result = self._get_entry(self._keyring, service, username)
if result:
result = self._decrypt(result)
return result | python | def get_password(self, service, username):
"""Get password of the username for the service
"""
result = self._get_entry(self._keyring, service, username)
if result:
result = self._decrypt(result)
return result | [
"def",
"get_password",
"(",
"self",
",",
"service",
",",
"username",
")",
":",
"result",
"=",
"self",
".",
"_get_entry",
"(",
"self",
".",
"_keyring",
",",
"service",
",",
"username",
")",
"if",
"result",
":",
"result",
"=",
"self",
".",
"_decrypt",
"(",
"result",
")",
"return",
"result"
] | Get password of the username for the service | [
"Get",
"password",
"of",
"the",
"username",
"for",
"the",
"service"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/Google.py#L85-L91 | train |
jaraco/keyrings.alt | keyrings/alt/Google.py | DocsKeyring.set_password | def set_password(self, service, username, password):
"""Set password for the username of the service
"""
password = self._encrypt(password or '')
keyring_working_copy = copy.deepcopy(self._keyring)
service_entries = keyring_working_copy.get(service)
if not service_entries:
service_entries = {}
keyring_working_copy[service] = service_entries
service_entries[username] = password
save_result = self._save_keyring(keyring_working_copy)
if save_result == self.OK:
self._keyring_dict = keyring_working_copy
return
elif save_result == self.CONFLICT:
# check if we can avoid updating
self.docs_entry, keyring_dict = self._read()
existing_pwd = self._get_entry(self._keyring, service, username)
conflicting_pwd = self._get_entry(keyring_dict, service, username)
if conflicting_pwd == password:
# if someone else updated it to the same value then we are done
self._keyring_dict = keyring_working_copy
return
elif conflicting_pwd is None or conflicting_pwd == existing_pwd:
# if doesn't already exist or is unchanged then update it
new_service_entries = keyring_dict.get(service, {})
new_service_entries[username] = password
keyring_dict[service] = new_service_entries
save_result = self._save_keyring(keyring_dict)
if save_result == self.OK:
self._keyring_dict = keyring_dict
return
else:
raise errors.PasswordSetError(
'Failed write after conflict detected')
else:
raise errors.PasswordSetError(
'Conflict detected, service:%s and username:%s was '
'set to a different value by someone else' % (
service,
username,
),
)
raise errors.PasswordSetError('Could not save keyring') | python | def set_password(self, service, username, password):
"""Set password for the username of the service
"""
password = self._encrypt(password or '')
keyring_working_copy = copy.deepcopy(self._keyring)
service_entries = keyring_working_copy.get(service)
if not service_entries:
service_entries = {}
keyring_working_copy[service] = service_entries
service_entries[username] = password
save_result = self._save_keyring(keyring_working_copy)
if save_result == self.OK:
self._keyring_dict = keyring_working_copy
return
elif save_result == self.CONFLICT:
# check if we can avoid updating
self.docs_entry, keyring_dict = self._read()
existing_pwd = self._get_entry(self._keyring, service, username)
conflicting_pwd = self._get_entry(keyring_dict, service, username)
if conflicting_pwd == password:
# if someone else updated it to the same value then we are done
self._keyring_dict = keyring_working_copy
return
elif conflicting_pwd is None or conflicting_pwd == existing_pwd:
# if doesn't already exist or is unchanged then update it
new_service_entries = keyring_dict.get(service, {})
new_service_entries[username] = password
keyring_dict[service] = new_service_entries
save_result = self._save_keyring(keyring_dict)
if save_result == self.OK:
self._keyring_dict = keyring_dict
return
else:
raise errors.PasswordSetError(
'Failed write after conflict detected')
else:
raise errors.PasswordSetError(
'Conflict detected, service:%s and username:%s was '
'set to a different value by someone else' % (
service,
username,
),
)
raise errors.PasswordSetError('Could not save keyring') | [
"def",
"set_password",
"(",
"self",
",",
"service",
",",
"username",
",",
"password",
")",
":",
"password",
"=",
"self",
".",
"_encrypt",
"(",
"password",
"or",
"''",
")",
"keyring_working_copy",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_keyring",
")",
"service_entries",
"=",
"keyring_working_copy",
".",
"get",
"(",
"service",
")",
"if",
"not",
"service_entries",
":",
"service_entries",
"=",
"{",
"}",
"keyring_working_copy",
"[",
"service",
"]",
"=",
"service_entries",
"service_entries",
"[",
"username",
"]",
"=",
"password",
"save_result",
"=",
"self",
".",
"_save_keyring",
"(",
"keyring_working_copy",
")",
"if",
"save_result",
"==",
"self",
".",
"OK",
":",
"self",
".",
"_keyring_dict",
"=",
"keyring_working_copy",
"return",
"elif",
"save_result",
"==",
"self",
".",
"CONFLICT",
":",
"# check if we can avoid updating",
"self",
".",
"docs_entry",
",",
"keyring_dict",
"=",
"self",
".",
"_read",
"(",
")",
"existing_pwd",
"=",
"self",
".",
"_get_entry",
"(",
"self",
".",
"_keyring",
",",
"service",
",",
"username",
")",
"conflicting_pwd",
"=",
"self",
".",
"_get_entry",
"(",
"keyring_dict",
",",
"service",
",",
"username",
")",
"if",
"conflicting_pwd",
"==",
"password",
":",
"# if someone else updated it to the same value then we are done",
"self",
".",
"_keyring_dict",
"=",
"keyring_working_copy",
"return",
"elif",
"conflicting_pwd",
"is",
"None",
"or",
"conflicting_pwd",
"==",
"existing_pwd",
":",
"# if doesn't already exist or is unchanged then update it",
"new_service_entries",
"=",
"keyring_dict",
".",
"get",
"(",
"service",
",",
"{",
"}",
")",
"new_service_entries",
"[",
"username",
"]",
"=",
"password",
"keyring_dict",
"[",
"service",
"]",
"=",
"new_service_entries",
"save_result",
"=",
"self",
".",
"_save_keyring",
"(",
"keyring_dict",
")",
"if",
"save_result",
"==",
"self",
".",
"OK",
":",
"self",
".",
"_keyring_dict",
"=",
"keyring_dict",
"return",
"else",
":",
"raise",
"errors",
".",
"PasswordSetError",
"(",
"'Failed write after conflict detected'",
")",
"else",
":",
"raise",
"errors",
".",
"PasswordSetError",
"(",
"'Conflict detected, service:%s and username:%s was '",
"'set to a different value by someone else'",
"%",
"(",
"service",
",",
"username",
",",
")",
",",
")",
"raise",
"errors",
".",
"PasswordSetError",
"(",
"'Could not save keyring'",
")"
] | Set password for the username of the service | [
"Set",
"password",
"for",
"the",
"username",
"of",
"the",
"service"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/Google.py#L93-L137 | train |
jaraco/keyrings.alt | keyrings/alt/Google.py | DocsKeyring._save_keyring | def _save_keyring(self, keyring_dict):
"""Helper to actually write the keyring to Google"""
import gdata
result = self.OK
file_contents = base64.urlsafe_b64encode(pickle.dumps(keyring_dict))
try:
if self.docs_entry:
extra_headers = {'Content-Type': 'text/plain',
'Content-Length': len(file_contents)}
self.docs_entry = self.client.Put(
file_contents,
self.docs_entry.GetEditMediaLink().href,
extra_headers=extra_headers
)
else:
from gdata.docs.service import DocumentQuery
# check for existence of folder, create if required
folder_query = DocumentQuery(categories=['folder'])
folder_query['title'] = self.collection
folder_query['title-exact'] = 'true'
docs = self.client.QueryDocumentListFeed(folder_query.ToUri())
if docs.entry:
folder_entry = docs.entry[0]
else:
folder_entry = self.client.CreateFolder(self.collection)
file_handle = io.BytesIO(file_contents)
media_source = gdata.MediaSource(
file_handle=file_handle,
content_type='text/plain',
content_length=len(file_contents),
file_name='temp')
self.docs_entry = self.client.Upload(
media_source,
self._get_doc_title(),
folder_or_uri=folder_entry
)
except gdata.service.RequestError as ex:
try:
if ex.message['reason'].lower().find('conflict') != -1:
result = self.CONFLICT
else:
# Google docs has a bug when updating a shared document
# using PUT from any account other that the owner.
# It returns an error 400 "Sorry, there was an error saving
# the file. Please try again"
# *despite* actually updating the document!
# Workaround by re-reading to see if it actually updated
msg = 'Sorry, there was an error saving the file'
if ex.message['body'].find(msg) != -1:
new_docs_entry, new_keyring_dict = self._read()
if new_keyring_dict == keyring_dict:
result = self.OK
else:
result = self.FAIL
else:
result = self.FAIL
except Exception:
result = self.FAIL
return result | python | def _save_keyring(self, keyring_dict):
"""Helper to actually write the keyring to Google"""
import gdata
result = self.OK
file_contents = base64.urlsafe_b64encode(pickle.dumps(keyring_dict))
try:
if self.docs_entry:
extra_headers = {'Content-Type': 'text/plain',
'Content-Length': len(file_contents)}
self.docs_entry = self.client.Put(
file_contents,
self.docs_entry.GetEditMediaLink().href,
extra_headers=extra_headers
)
else:
from gdata.docs.service import DocumentQuery
# check for existence of folder, create if required
folder_query = DocumentQuery(categories=['folder'])
folder_query['title'] = self.collection
folder_query['title-exact'] = 'true'
docs = self.client.QueryDocumentListFeed(folder_query.ToUri())
if docs.entry:
folder_entry = docs.entry[0]
else:
folder_entry = self.client.CreateFolder(self.collection)
file_handle = io.BytesIO(file_contents)
media_source = gdata.MediaSource(
file_handle=file_handle,
content_type='text/plain',
content_length=len(file_contents),
file_name='temp')
self.docs_entry = self.client.Upload(
media_source,
self._get_doc_title(),
folder_or_uri=folder_entry
)
except gdata.service.RequestError as ex:
try:
if ex.message['reason'].lower().find('conflict') != -1:
result = self.CONFLICT
else:
# Google docs has a bug when updating a shared document
# using PUT from any account other that the owner.
# It returns an error 400 "Sorry, there was an error saving
# the file. Please try again"
# *despite* actually updating the document!
# Workaround by re-reading to see if it actually updated
msg = 'Sorry, there was an error saving the file'
if ex.message['body'].find(msg) != -1:
new_docs_entry, new_keyring_dict = self._read()
if new_keyring_dict == keyring_dict:
result = self.OK
else:
result = self.FAIL
else:
result = self.FAIL
except Exception:
result = self.FAIL
return result | [
"def",
"_save_keyring",
"(",
"self",
",",
"keyring_dict",
")",
":",
"import",
"gdata",
"result",
"=",
"self",
".",
"OK",
"file_contents",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"pickle",
".",
"dumps",
"(",
"keyring_dict",
")",
")",
"try",
":",
"if",
"self",
".",
"docs_entry",
":",
"extra_headers",
"=",
"{",
"'Content-Type'",
":",
"'text/plain'",
",",
"'Content-Length'",
":",
"len",
"(",
"file_contents",
")",
"}",
"self",
".",
"docs_entry",
"=",
"self",
".",
"client",
".",
"Put",
"(",
"file_contents",
",",
"self",
".",
"docs_entry",
".",
"GetEditMediaLink",
"(",
")",
".",
"href",
",",
"extra_headers",
"=",
"extra_headers",
")",
"else",
":",
"from",
"gdata",
".",
"docs",
".",
"service",
"import",
"DocumentQuery",
"# check for existence of folder, create if required",
"folder_query",
"=",
"DocumentQuery",
"(",
"categories",
"=",
"[",
"'folder'",
"]",
")",
"folder_query",
"[",
"'title'",
"]",
"=",
"self",
".",
"collection",
"folder_query",
"[",
"'title-exact'",
"]",
"=",
"'true'",
"docs",
"=",
"self",
".",
"client",
".",
"QueryDocumentListFeed",
"(",
"folder_query",
".",
"ToUri",
"(",
")",
")",
"if",
"docs",
".",
"entry",
":",
"folder_entry",
"=",
"docs",
".",
"entry",
"[",
"0",
"]",
"else",
":",
"folder_entry",
"=",
"self",
".",
"client",
".",
"CreateFolder",
"(",
"self",
".",
"collection",
")",
"file_handle",
"=",
"io",
".",
"BytesIO",
"(",
"file_contents",
")",
"media_source",
"=",
"gdata",
".",
"MediaSource",
"(",
"file_handle",
"=",
"file_handle",
",",
"content_type",
"=",
"'text/plain'",
",",
"content_length",
"=",
"len",
"(",
"file_contents",
")",
",",
"file_name",
"=",
"'temp'",
")",
"self",
".",
"docs_entry",
"=",
"self",
".",
"client",
".",
"Upload",
"(",
"media_source",
",",
"self",
".",
"_get_doc_title",
"(",
")",
",",
"folder_or_uri",
"=",
"folder_entry",
")",
"except",
"gdata",
".",
"service",
".",
"RequestError",
"as",
"ex",
":",
"try",
":",
"if",
"ex",
".",
"message",
"[",
"'reason'",
"]",
".",
"lower",
"(",
")",
".",
"find",
"(",
"'conflict'",
")",
"!=",
"-",
"1",
":",
"result",
"=",
"self",
".",
"CONFLICT",
"else",
":",
"# Google docs has a bug when updating a shared document",
"# using PUT from any account other that the owner.",
"# It returns an error 400 \"Sorry, there was an error saving",
"# the file. Please try again\"",
"# *despite* actually updating the document!",
"# Workaround by re-reading to see if it actually updated",
"msg",
"=",
"'Sorry, there was an error saving the file'",
"if",
"ex",
".",
"message",
"[",
"'body'",
"]",
".",
"find",
"(",
"msg",
")",
"!=",
"-",
"1",
":",
"new_docs_entry",
",",
"new_keyring_dict",
"=",
"self",
".",
"_read",
"(",
")",
"if",
"new_keyring_dict",
"==",
"keyring_dict",
":",
"result",
"=",
"self",
".",
"OK",
"else",
":",
"result",
"=",
"self",
".",
"FAIL",
"else",
":",
"result",
"=",
"self",
".",
"FAIL",
"except",
"Exception",
":",
"result",
"=",
"self",
".",
"FAIL",
"return",
"result"
] | Helper to actually write the keyring to Google | [
"Helper",
"to",
"actually",
"write",
"the",
"keyring",
"to",
"Google"
] | 5b71223d12bf9ac6abd05b1b395f1efccb5ea660 | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/Google.py#L247-L306 | train |
Boudewijn26/gTTS-token | gtts_token/gtts_token.py | Token.calculate_token | def calculate_token(self, text, seed=None):
""" Calculate the request token (`tk`) of a string
:param text: str The text to calculate a token for
:param seed: str The seed to use. By default this is the number of hours since epoch
"""
if seed is None:
seed = self._get_token_key()
[first_seed, second_seed] = seed.split(".")
try:
d = bytearray(text.encode('UTF-8'))
except UnicodeDecodeError:
# This will probably only occur when d is actually a str containing UTF-8 chars, which means we don't need
# to encode.
d = bytearray(text)
a = int(first_seed)
for value in d:
a += value
a = self._work_token(a, self.SALT_1)
a = self._work_token(a, self.SALT_2)
a ^= int(second_seed)
if 0 > a:
a = (a & 2147483647) + 2147483648
a %= 1E6
a = int(a)
return str(a) + "." + str(a ^ int(first_seed)) | python | def calculate_token(self, text, seed=None):
""" Calculate the request token (`tk`) of a string
:param text: str The text to calculate a token for
:param seed: str The seed to use. By default this is the number of hours since epoch
"""
if seed is None:
seed = self._get_token_key()
[first_seed, second_seed] = seed.split(".")
try:
d = bytearray(text.encode('UTF-8'))
except UnicodeDecodeError:
# This will probably only occur when d is actually a str containing UTF-8 chars, which means we don't need
# to encode.
d = bytearray(text)
a = int(first_seed)
for value in d:
a += value
a = self._work_token(a, self.SALT_1)
a = self._work_token(a, self.SALT_2)
a ^= int(second_seed)
if 0 > a:
a = (a & 2147483647) + 2147483648
a %= 1E6
a = int(a)
return str(a) + "." + str(a ^ int(first_seed)) | [
"def",
"calculate_token",
"(",
"self",
",",
"text",
",",
"seed",
"=",
"None",
")",
":",
"if",
"seed",
"is",
"None",
":",
"seed",
"=",
"self",
".",
"_get_token_key",
"(",
")",
"[",
"first_seed",
",",
"second_seed",
"]",
"=",
"seed",
".",
"split",
"(",
"\".\"",
")",
"try",
":",
"d",
"=",
"bytearray",
"(",
"text",
".",
"encode",
"(",
"'UTF-8'",
")",
")",
"except",
"UnicodeDecodeError",
":",
"# This will probably only occur when d is actually a str containing UTF-8 chars, which means we don't need",
"# to encode.",
"d",
"=",
"bytearray",
"(",
"text",
")",
"a",
"=",
"int",
"(",
"first_seed",
")",
"for",
"value",
"in",
"d",
":",
"a",
"+=",
"value",
"a",
"=",
"self",
".",
"_work_token",
"(",
"a",
",",
"self",
".",
"SALT_1",
")",
"a",
"=",
"self",
".",
"_work_token",
"(",
"a",
",",
"self",
".",
"SALT_2",
")",
"a",
"^=",
"int",
"(",
"second_seed",
")",
"if",
"0",
">",
"a",
":",
"a",
"=",
"(",
"a",
"&",
"2147483647",
")",
"+",
"2147483648",
"a",
"%=",
"1E6",
"a",
"=",
"int",
"(",
"a",
")",
"return",
"str",
"(",
"a",
")",
"+",
"\".\"",
"+",
"str",
"(",
"a",
"^",
"int",
"(",
"first_seed",
")",
")"
] | Calculate the request token (`tk`) of a string
:param text: str The text to calculate a token for
:param seed: str The seed to use. By default this is the number of hours since epoch | [
"Calculate",
"the",
"request",
"token",
"(",
"tk",
")",
"of",
"a",
"string",
":",
"param",
"text",
":",
"str",
"The",
"text",
"to",
"calculate",
"a",
"token",
"for",
":",
"param",
"seed",
":",
"str",
"The",
"seed",
"to",
"use",
".",
"By",
"default",
"this",
"is",
"the",
"number",
"of",
"hours",
"since",
"epoch"
] | 9a1bb569bcce1ec091bfd9586dd54f9c879e7d3c | https://github.com/Boudewijn26/gTTS-token/blob/9a1bb569bcce1ec091bfd9586dd54f9c879e7d3c/gtts_token/gtts_token.py#L21-L49 | train |
paddycarey/dweepy | dweepy/api.py | _request | def _request(method, url, session=None, **kwargs):
"""Make HTTP request, raising an exception if it fails.
"""
url = BASE_URL + url
if session:
request_func = getattr(session, method)
else:
request_func = getattr(requests, method)
response = request_func(url, **kwargs)
# raise an exception if request is not successful
if not response.status_code == requests.codes.ok:
raise DweepyError('HTTP {0} response'.format(response.status_code))
response_json = response.json()
if response_json['this'] == 'failed':
raise DweepyError(response_json['because'])
return response_json['with'] | python | def _request(method, url, session=None, **kwargs):
"""Make HTTP request, raising an exception if it fails.
"""
url = BASE_URL + url
if session:
request_func = getattr(session, method)
else:
request_func = getattr(requests, method)
response = request_func(url, **kwargs)
# raise an exception if request is not successful
if not response.status_code == requests.codes.ok:
raise DweepyError('HTTP {0} response'.format(response.status_code))
response_json = response.json()
if response_json['this'] == 'failed':
raise DweepyError(response_json['because'])
return response_json['with'] | [
"def",
"_request",
"(",
"method",
",",
"url",
",",
"session",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"BASE_URL",
"+",
"url",
"if",
"session",
":",
"request_func",
"=",
"getattr",
"(",
"session",
",",
"method",
")",
"else",
":",
"request_func",
"=",
"getattr",
"(",
"requests",
",",
"method",
")",
"response",
"=",
"request_func",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
"# raise an exception if request is not successful",
"if",
"not",
"response",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"ok",
":",
"raise",
"DweepyError",
"(",
"'HTTP {0} response'",
".",
"format",
"(",
"response",
".",
"status_code",
")",
")",
"response_json",
"=",
"response",
".",
"json",
"(",
")",
"if",
"response_json",
"[",
"'this'",
"]",
"==",
"'failed'",
":",
"raise",
"DweepyError",
"(",
"response_json",
"[",
"'because'",
"]",
")",
"return",
"response_json",
"[",
"'with'",
"]"
] | Make HTTP request, raising an exception if it fails. | [
"Make",
"HTTP",
"request",
"raising",
"an",
"exception",
"if",
"it",
"fails",
"."
] | 1eb69de4a20c929c57be2a21e2aa39ae9a0ae298 | https://github.com/paddycarey/dweepy/blob/1eb69de4a20c929c57be2a21e2aa39ae9a0ae298/dweepy/api.py#L29-L45 | train |
paddycarey/dweepy | dweepy/api.py | _send_dweet | def _send_dweet(payload, url, params=None, session=None):
"""Send a dweet to dweet.io
"""
data = json.dumps(payload)
headers = {'Content-type': 'application/json'}
return _request('post', url, data=data, headers=headers, params=params, session=session) | python | def _send_dweet(payload, url, params=None, session=None):
"""Send a dweet to dweet.io
"""
data = json.dumps(payload)
headers = {'Content-type': 'application/json'}
return _request('post', url, data=data, headers=headers, params=params, session=session) | [
"def",
"_send_dweet",
"(",
"payload",
",",
"url",
",",
"params",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
"headers",
"=",
"{",
"'Content-type'",
":",
"'application/json'",
"}",
"return",
"_request",
"(",
"'post'",
",",
"url",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers",
",",
"params",
"=",
"params",
",",
"session",
"=",
"session",
")"
] | Send a dweet to dweet.io | [
"Send",
"a",
"dweet",
"to",
"dweet",
".",
"io"
] | 1eb69de4a20c929c57be2a21e2aa39ae9a0ae298 | https://github.com/paddycarey/dweepy/blob/1eb69de4a20c929c57be2a21e2aa39ae9a0ae298/dweepy/api.py#L48-L53 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.