sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def naturalize_person(self, string):
"""
Attempt to make a version of the string that has the surname, if any,
at the start.
'John, Brown' to 'Brown, John'
'Sir John Brown Jr' to 'Brown, Sir John Jr'
'Prince' to 'Prince'
string -- The string to change.
"... | Attempt to make a version of the string that has the surname, if any,
at the start.
'John, Brown' to 'Brown, John'
'Sir John Brown Jr' to 'Brown, Sir John Jr'
'Prince' to 'Prince'
string -- The string to change. | entailment |
def _naturalize_numbers(self, string):
"""
Makes any integers into very zero-padded numbers.
e.g. '1' becomes '00000001'.
"""
def naturalize_int_match(match):
return '%08d' % (int(match.group(0)),)
string = re.sub(r'\d+', naturalize_int_match, string)
... | Makes any integers into very zero-padded numbers.
e.g. '1' becomes '00000001'. | entailment |
def annual_reading_counts(kind='all'):
"""
Returns a list of dicts, one per year of reading. In year order.
Each dict is like this (if kind is 'all'):
{'year': datetime.date(2003, 1, 1),
'book': 12, # only included if kind is 'all' or 'book'
'periodical': 18, ... | Returns a list of dicts, one per year of reading. In year order.
Each dict is like this (if kind is 'all'):
{'year': datetime.date(2003, 1, 1),
'book': 12, # only included if kind is 'all' or 'book'
'periodical': 18, # only included if kind is 'all' or 'periodical'
... | entailment |
def lookups(self, request, model_admin):
"""
Returns a list of tuples like:
[
('AU', 'Australia'),
('GB', 'UK'),
('US', 'USA'),
]
One for each country that has at least one Venue.
Sorted by the label names.
... | Returns a list of tuples like:
[
('AU', 'Australia'),
('GB', 'UK'),
('US', 'USA'),
]
One for each country that has at least one Venue.
Sorted by the label names. | entailment |
def queryset(self, request, queryset):
"""
Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`.
"""
if self.value():
return queryset.filter(country=self.value())
else:
return quer... | Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`. | entailment |
def forward(apps, schema_editor):
"""
Copying data from the old `Event.movie` and `Event.play` ForeignKey fields
into the new `Event.movies` and `Event.plays` ManyToManyFields.
"""
Event = apps.get_model('spectator_events', 'Event')
MovieSelection = apps.get_model('spectator_events', 'MovieSele... | Copying data from the old `Event.movie` and `Event.play` ForeignKey fields
into the new `Event.movies` and `Event.plays` ManyToManyFields. | entailment |
def set_slug(apps, schema_editor):
"""
Create a slug for each Event already in the DB.
"""
Event = apps.get_model('spectator_events', 'Event')
for e in Event.objects.all():
e.slug = generate_slug(e.pk)
e.save(update_fields=['slug']) | Create a slug for each Event already in the DB. | entailment |
def page(self, number, *args, **kwargs):
"""Return a standard ``Page`` instance with custom, digg-specific
page ranges attached.
"""
page = super().page(number, *args, **kwargs)
number = int(number) # we know this will work
# easier access
num_pages, body, tail,... | Return a standard ``Page`` instance with custom, digg-specific
page ranges attached. | entailment |
def version():
"""Get the version number without importing the mrcfile package."""
namespace = {}
with open(os.path.join('mrcfile', 'version.py')) as f:
exec(f.read(), namespace)
return namespace['__version__'] | Get the version number without importing the mrcfile package. | entailment |
def get_event_counts(self):
"""
Returns a dict like:
{'counts': {
'all': 30,
'movie': 12,
'gig': 10,
}}
"""
counts = {'all': Event.objects.count(),}
for k,v in Event.KIND_CHOICES:
# e.g. 'movie_c... | Returns a dict like:
{'counts': {
'all': 30,
'movie': 12,
'gig': 10,
}} | entailment |
def get_event_kind(self):
"""
Unless we're on the front page we'll have a kind_slug like 'movies'.
We need to translate that into an event `kind` like 'movie'.
"""
slug = self.kwargs.get('kind_slug', None)
if slug is None:
return None # Front page; showing al... | Unless we're on the front page we'll have a kind_slug like 'movies'.
We need to translate that into an event `kind` like 'movie'. | entailment |
def get_queryset(self):
"Restrict to a single kind of event, if any, and include Venue data."
qs = super().get_queryset()
kind = self.get_event_kind()
if kind is not None:
qs = qs.filter(kind=kind)
qs = qs.select_related('venue')
return qs | Restrict to a single kind of event, if any, and include Venue data. | entailment |
def get_work_kind(self):
"""
We'll have a kind_slug like 'movies'.
We need to translate that into a work `kind` like 'movie'.
"""
slugs_to_kinds = {v:k for k,v in Work.KIND_SLUGS.items()}
return slugs_to_kinds.get(self.kind_slug, None) | We'll have a kind_slug like 'movies'.
We need to translate that into a work `kind` like 'movie'. | entailment |
def get_countries(self):
"""
Returns a list of dicts, one per country that has at least one Venue
in it.
Each dict has 'code' and 'name' elements.
The list is sorted by the country 'name's.
"""
qs = Venue.objects.values('country') \
... | Returns a list of dicts, one per country that has at least one Venue
in it.
Each dict has 'code' and 'name' elements.
The list is sorted by the country 'name's. | entailment |
def forwards(apps, schema_editor):
"""
Re-save all the Works because something earlier didn't create their slugs.
"""
Work = apps.get_model('spectator_events', 'Work')
for work in Work.objects.all():
if not work.slug:
work.slug = generate_slug(work.pk)
work.save() | Re-save all the Works because something earlier didn't create their slugs. | entailment |
def annual_event_counts(kind='all'):
"""
Returns a QuerySet of dicts, each one with these keys:
* year - a date object representing the year
* total - the number of events of `kind` that year
kind - The Event `kind`, or 'all' for all kinds (default).
"""
qs = Event.objects
if ... | Returns a QuerySet of dicts, each one with these keys:
* year - a date object representing the year
* total - the number of events of `kind` that year
kind - The Event `kind`, or 'all' for all kinds (default). | entailment |
def annual_event_counts_card(kind='all', current_year=None):
"""
Displays years and the number of events per year.
kind is an Event kind (like 'cinema', 'gig', etc.) or 'all' (default).
current_year is an optional date object representing the year we're already
showing information about.
""... | Displays years and the number of events per year.
kind is an Event kind (like 'cinema', 'gig', etc.) or 'all' (default).
current_year is an optional date object representing the year we're already
showing information about. | entailment |
def display_date(d):
"""
Render a date/datetime (d) as a date, using the SPECTATOR_DATE_FORMAT
setting. Wrap the output in a <time> tag.
Time tags: http://www.brucelawson.co.uk/2012/best-of-time/
"""
stamp = d.strftime('%Y-%m-%d')
visible_date = d.strftime(app_settings.DATE_FORMAT)
ret... | Render a date/datetime (d) as a date, using the SPECTATOR_DATE_FORMAT
setting. Wrap the output in a <time> tag.
Time tags: http://www.brucelawson.co.uk/2012/best-of-time/ | entailment |
def event_list_tabs(counts, current_kind, page_number=1):
"""
Displays the tabs to different event_list pages.
`counts` is a dict of number of events for each kind, like:
{'all': 30, 'gig': 12, 'movie': 18,}
`current_kind` is the event kind that's active, if any. e.g. 'gig',
'movie', e... | Displays the tabs to different event_list pages.
`counts` is a dict of number of events for each kind, like:
{'all': 30, 'gig': 12, 'movie': 18,}
`current_kind` is the event kind that's active, if any. e.g. 'gig',
'movie', etc.
`page_number` is the current page of this kind of events we'r... | entailment |
def day_events_card(date):
"""
Displays Events that happened on the supplied date.
`date` is a date object.
"""
d = date.strftime(app_settings.DATE_FORMAT)
card_title = 'Events on {}'.format(d)
return {
'card_title': card_title,
'event_list': day_events(date=date),
... | Displays Events that happened on the supplied date.
`date` is a date object. | entailment |
def most_seen_creators_card(event_kind=None, num=10):
"""
Displays a card showing the Creators that are associated with the most Events.
"""
object_list = most_seen_creators(event_kind=event_kind, num=num)
object_list = chartify(object_list, 'num_events', cutoff=1)
return {
'card_title... | Displays a card showing the Creators that are associated with the most Events. | entailment |
def most_seen_creators_by_works(work_kind=None, role_name=None, num=10):
"""
Returns a QuerySet of the Creators that are associated with the most Works.
"""
return Creator.objects.by_works(kind=work_kind, role_name=role_name)[:num] | Returns a QuerySet of the Creators that are associated with the most Works. | entailment |
def most_seen_creators_by_works_card(work_kind=None, role_name=None, num=10):
"""
Displays a card showing the Creators that are associated with the most Works.
e.g.:
{% most_seen_creators_by_works_card work_kind='movie' role_name='Director' num=5 %}
"""
object_list = most_seen_creators_by_wo... | Displays a card showing the Creators that are associated with the most Works.
e.g.:
{% most_seen_creators_by_works_card work_kind='movie' role_name='Director' num=5 %} | entailment |
def most_seen_works_card(kind=None, num=10):
"""
Displays a card showing the Works that are associated with the most Events.
"""
object_list = most_seen_works(kind=kind, num=num)
object_list = chartify(object_list, 'num_views', cutoff=1)
if kind:
card_title = 'Most seen {}'.format(
... | Displays a card showing the Works that are associated with the most Events. | entailment |
def _generate_slug(self, value):
"""
Generates a slug using a Hashid of `value`.
"""
alphabet = app_settings.SLUG_ALPHABET
salt = app_settings.SLUG_SALT
hashids = Hashids(alphabet=alphabet, salt=salt, min_length=5)
return hashids.encode(value) | Generates a slug using a Hashid of `value`. | entailment |
def create(self, bucket, descriptor, force=False):
"""https://github.com/frictionlessdata/tableschema-pandas-py#storage
"""
# Make lists
buckets = bucket
if isinstance(bucket, six.string_types):
buckets = [bucket]
descriptors = descriptor
if isinstanc... | https://github.com/frictionlessdata/tableschema-pandas-py#storage | entailment |
def delete(self, bucket=None, ignore=False):
"""https://github.com/frictionlessdata/tableschema-pandas-py#storage
"""
# Make lists
buckets = bucket
if isinstance(bucket, six.string_types):
buckets = [bucket]
elif bucket is None:
buckets = reversed... | https://github.com/frictionlessdata/tableschema-pandas-py#storage | entailment |
def describe(self, bucket, descriptor=None):
"""https://github.com/frictionlessdata/tableschema-pandas-py#storage
"""
# Set descriptor
if descriptor is not None:
self.__descriptors[bucket] = descriptor
# Get descriptor
else:
descriptor = self.__d... | https://github.com/frictionlessdata/tableschema-pandas-py#storage | entailment |
def iter(self, bucket):
"""https://github.com/frictionlessdata/tableschema-pandas-py#storage
"""
# Check existense
if bucket not in self.buckets:
message = 'Bucket "%s" doesn\'t exist.' % bucket
raise tableschema.exceptions.StorageError(message)
# Prepar... | https://github.com/frictionlessdata/tableschema-pandas-py#storage | entailment |
def write(self, bucket, rows):
"""https://github.com/frictionlessdata/tableschema-pandas-py#storage
"""
# Prepare
descriptor = self.describe(bucket)
new_data_frame = self.__mapper.convert_descriptor_and_rows(descriptor, rows)
# Just set new DataFrame if current is empty... | https://github.com/frictionlessdata/tableschema-pandas-py#storage | entailment |
def forwards(apps, schema_editor):
"""
Change all Movie objects into Work objects, and their associated
data into WorkRole and WorkSelection models, then delete the Movie.
"""
Movie = apps.get_model('spectator_events', 'Movie')
Work = apps.get_model('spectator_events', 'Work')
WorkRole = app... | Change all Movie objects into Work objects, and their associated
data into WorkRole and WorkSelection models, then delete the Movie. | entailment |
def paginate_queryset(self, queryset, page_size):
"""
Paginate the queryset, if needed.
This is EXACTLY the same as the standard ListView.paginate_queryset()
except for this line:
page = paginator.page(page_number, softlimit=True)
Because we want to use the DiggPagin... | Paginate the queryset, if needed.
This is EXACTLY the same as the standard ListView.paginate_queryset()
except for this line:
page = paginator.page(page_number, softlimit=True)
Because we want to use the DiggPaginator's softlimit option.
So that if you're viewing a page of, ... | entailment |
def annual_reading_counts_card(kind='all', current_year=None):
"""
Displays years and the number of books/periodicals read per year.
kind is one of 'book', 'periodical', 'all' (default).
current_year is an optional date object representing the year we're already
showing information about.
"... | Displays years and the number of books/periodicals read per year.
kind is one of 'book', 'periodical', 'all' (default).
current_year is an optional date object representing the year we're already
showing information about. | entailment |
def day_publications(date):
"""
Returns a QuerySet of Publications that were being read on `date`.
`date` is a date tobject.
"""
readings = Reading.objects \
.filter(start_date__lte=date) \
.filter(
Q(end_date__gte=date)
... | Returns a QuerySet of Publications that were being read on `date`.
`date` is a date tobject. | entailment |
def day_publications_card(date):
"""
Displays Publications that were being read on `date`.
`date` is a date tobject.
"""
d = date.strftime(app_settings.DATE_FORMAT)
card_title = 'Reading on {}'.format(d)
return {
'card_title': card_title,
'publication_list': day_publi... | Displays Publications that were being read on `date`.
`date` is a date tobject. | entailment |
def reading_dates(reading):
"""
Given a Reading, with start and end dates and granularities[1] it returns
an HTML string representing that period. eg:
* '1–6 Feb 2017'
* '1 Feb to 3 Mar 2017'
* 'Feb 2017 to Mar 2018'
* '2017–2018'
etc.
[1] https://www.flickr.com/ser... | Given a Reading, with start and end dates and granularities[1] it returns
an HTML string representing that period. eg:
* '1–6 Feb 2017'
* '1 Feb to 3 Mar 2017'
* 'Feb 2017 to Mar 2018'
* '2017–2018'
etc.
[1] https://www.flickr.com/services/api/misc.dates.html | entailment |
def forwards(apps, schema_editor):
"""
Change Events with kind 'movie' to 'cinema'
and Events with kind 'play' to 'theatre'.
Purely for more consistency.
"""
Event = apps.get_model('spectator_events', 'Event')
for ev in Event.objects.filter(kind='movie'):
ev.kind = 'cinema'
... | Change Events with kind 'movie' to 'cinema'
and Events with kind 'play' to 'theatre'.
Purely for more consistency. | entailment |
def get_env_variable(var_name, default=None):
"""Get the environment variable or return exception."""
try:
return os.environ[var_name]
except KeyError:
if default is None:
error_msg = "Set the %s environment variable" % var_name
raise ImproperlyConfigured(error_msg)
... | Get the environment variable or return exception. | entailment |
def generate_slug(value):
"""
Generates a slug using a Hashid of `value`.
COPIED from spectator.core.models.SluggedModelMixin() because migrations
don't make this happen automatically and perhaps the least bad thing is
to copy the method here, ugh.
"""
alphabet = app_settings.SLUG_ALPHABET
... | Generates a slug using a Hashid of `value`.
COPIED from spectator.core.models.SluggedModelMixin() because migrations
don't make this happen automatically and perhaps the least bad thing is
to copy the method here, ugh. | entailment |
def forwards(apps, schema_editor):
"""
Having added the new 'exhibition' Work type, we're going to assume that
every Event of type 'museum' should actually have one Exhibition attached.
So, we'll add one, with the same title as the Event.
And we'll move all Creators from the Event to the Exhibition... | Having added the new 'exhibition' Work type, we're going to assume that
every Event of type 'museum' should actually have one Exhibition attached.
So, we'll add one, with the same title as the Event.
And we'll move all Creators from the Event to the Exhibition. | entailment |
def by_publications(self):
"""
The Creators who have been most-read, ordered by number of read
publications (ignoring if any of those publicatinos have been read
multiple times.)
Each Creator will have a `num_publications` attribute.
"""
if not spectator_apps.is_... | The Creators who have been most-read, ordered by number of read
publications (ignoring if any of those publicatinos have been read
multiple times.)
Each Creator will have a `num_publications` attribute. | entailment |
def by_readings(self, role_names=['', 'Author']):
"""
The Creators who have been most-read, ordered by number of readings.
By default it will only include Creators whose role was left empty,
or is 'Author'.
Each Creator will have a `num_readings` attribute.
"""
... | The Creators who have been most-read, ordered by number of readings.
By default it will only include Creators whose role was left empty,
or is 'Author'.
Each Creator will have a `num_readings` attribute. | entailment |
def by_events(self, kind=None):
"""
Get the Creators involved in the most Events.
This only counts Creators directly involved in an Event.
i.e. if a Creator is the director of a movie Work, and an Event was
a viewing of that movie, that Event wouldn't count. Unless they were
... | Get the Creators involved in the most Events.
This only counts Creators directly involved in an Event.
i.e. if a Creator is the director of a movie Work, and an Event was
a viewing of that movie, that Event wouldn't count. Unless they were
also directly involved in the Event (e.g. speak... | entailment |
def by_works(self, kind=None, role_name=None):
"""
Get the Creators involved in the most Works.
kind - If supplied, only Works with that `kind` value will be counted.
role_name - If supplied, only Works on which the role is that will be counted.
e.g. To get all 'movie' Works on... | Get the Creators involved in the most Works.
kind - If supplied, only Works with that `kind` value will be counted.
role_name - If supplied, only Works on which the role is that will be counted.
e.g. To get all 'movie' Works on which the Creators had the role 'Director':
Creator.o... | entailment |
def index():
"""Query Elasticsearch using Invenio query syntax."""
page = request.values.get('page', 1, type=int)
size = request.values.get('size', 2, type=int)
search = ExampleSearch()[(page - 1) * size:page * size]
if 'q' in request.values:
search = search.query(QueryString(query=request.v... | Query Elasticsearch using Invenio query syntax. | entailment |
def clean_options(self,
using_keytab=False, principal=None,
keytab_file=None, ccache_file=None,
password=None):
"""Clean argument to related object
:param bool using_keytab: refer to ``krbContext.__init__``.
:param str principal:... | Clean argument to related object
:param bool using_keytab: refer to ``krbContext.__init__``.
:param str principal: refer to ``krbContext.__init__``.
:param str keytab_file: refer to ``krbContext.__init__``.
:param str ccache_file: refer to ``krbContext.__init__``.
:param str pas... | entailment |
def init_with_keytab(self):
"""Initialize credential cache with keytab"""
creds_opts = {
'usage': 'initiate',
'name': self._cleaned_options['principal'],
}
store = {}
if self._cleaned_options['keytab'] != DEFAULT_KEYTAB:
store['client_keytab']... | Initialize credential cache with keytab | entailment |
def init_with_password(self):
"""Initialize credential cache with password
**Causion:** once you enter password from command line, or pass it to
API directly, the given password is not encrypted always. Although
getting credential with password works, from security point of view, it
... | Initialize credential cache with password
**Causion:** once you enter password from command line, or pass it to
API directly, the given password is not encrypted always. Although
getting credential with password works, from security point of view, it
is strongly recommended **NOT** use ... | entailment |
def _prepare_context(self):
"""Prepare context
Initialize credential cache with keytab or password according to
``using_keytab`` parameter. Then, ``KRB5CCNAME`` is set properly so
that Kerberos library called in current context is able to get
credential from correct cache.
... | Prepare context
Initialize credential cache with keytab or password according to
``using_keytab`` parameter. Then, ``KRB5CCNAME`` is set properly so
that Kerberos library called in current context is able to get
credential from correct cache.
Internal use only. | entailment |
def templates(self):
"""Generate a dictionary with template names and file paths."""
templates = {}
result = []
if self.entry_point_group_templates:
result = self.load_entry_point_group_templates(
self.entry_point_group_templates) or []
for template i... | Generate a dictionary with template names and file paths. | entailment |
def register_mappings(self, alias, package_name):
"""Register mappings from a package under given alias.
:param alias: The alias.
:param package_name: The package name.
"""
# For backwards compatibility, we also allow for ES2 mappings to be
# placed at the root level of ... | Register mappings from a package under given alias.
:param alias: The alias.
:param package_name: The package name. | entailment |
def register_templates(self, directory):
"""Register templates from the provided directory.
:param directory: The templates directory.
"""
try:
resource_listdir(directory, 'v{}'.format(ES_VERSION[0]))
directory = '{}/v{}'.format(directory, ES_VERSION[0])
... | Register templates from the provided directory.
:param directory: The templates directory. | entailment |
def load_entry_point_group_mappings(self, entry_point_group_mappings):
"""Load actions from an entry point group."""
for ep in iter_entry_points(group=entry_point_group_mappings):
self.register_mappings(ep.name, ep.module_name) | Load actions from an entry point group. | entailment |
def load_entry_point_group_templates(self, entry_point_group_templates):
"""Load actions from an entry point group."""
result = []
for ep in iter_entry_points(group=entry_point_group_templates):
with self.app.app_context():
for template_dir in ep.load()():
... | Load actions from an entry point group. | entailment |
def _client_builder(self):
"""Build Elasticsearch client."""
client_config = self.app.config.get('SEARCH_CLIENT_CONFIG') or {}
client_config.setdefault(
'hosts', self.app.config.get('SEARCH_ELASTIC_HOSTS'))
client_config.setdefault('connection_class', RequestsHttpConnection)
... | Build Elasticsearch client. | entailment |
def client(self):
"""Return client for current application."""
if self._client is None:
self._client = self._client_builder()
return self._client | Return client for current application. | entailment |
def flush_and_refresh(self, index):
"""Flush and refresh one or more indices.
.. warning::
Do not call this method unless you know what you are doing. This
method is only intended to be called during tests.
"""
self.client.indices.flush(wait_if_ongoing=True, index... | Flush and refresh one or more indices.
.. warning::
Do not call this method unless you know what you are doing. This
method is only intended to be called during tests. | entailment |
def cluster_version(self):
"""Get version of Elasticsearch running on the cluster."""
versionstr = self.client.info()['version']['number']
return [int(x) for x in versionstr.split('.')] | Get version of Elasticsearch running on the cluster. | entailment |
def active_aliases(self):
"""Get a filtered list of aliases based on configuration.
Returns aliases and their mappings that are defined in the
`SEARCH_MAPPINGS` config variable. If the `SEARCH_MAPPINGS` is set to
`None` (the default), all aliases are included.
"""
whitel... | Get a filtered list of aliases based on configuration.
Returns aliases and their mappings that are defined in the
`SEARCH_MAPPINGS` config variable. If the `SEARCH_MAPPINGS` is set to
`None` (the default), all aliases are included. | entailment |
def create(self, ignore=None):
"""Yield tuple with created index name and responses from a client."""
ignore = ignore or []
def _create(tree_or_filename, alias=None):
"""Create indices and aliases by walking DFS."""
# Iterate over aliases:
for name, value in ... | Yield tuple with created index name and responses from a client. | entailment |
def put_templates(self, ignore=None):
"""Yield tuple with registered template and response from client."""
ignore = ignore or []
def _replace_prefix(template_path, body):
"""Replace index prefix in template request body."""
pattern = '__SEARCH_INDEX_PREFIX__'
... | Yield tuple with registered template and response from client. | entailment |
def delete(self, ignore=None):
"""Yield tuple with deleted index name and responses from a client."""
ignore = ignore or []
def _delete(tree_or_filename, alias=None):
"""Delete indexes and aliases by walking DFS."""
if alias:
yield alias, self.client.indi... | Yield tuple with deleted index name and responses from a client. | entailment |
def init_app(self, app,
entry_point_group_mappings='invenio_search.mappings',
entry_point_group_templates='invenio_search.templates',
**kwargs):
"""Flask application initialization.
:param app: An instance of :class:`~flask.app.Flask`.
"""
... | Flask application initialization.
:param app: An instance of :class:`~flask.app.Flask`. | entailment |
def main():
"""Start the poor_consumer."""
try:
opts, args = getopt.getopt(sys.argv[1:], "h:v", ["help", "nack=",
"servers=", "queues="])
except getopt.GetoptError as err:
print str(err)
usage()
sys.exit()
# defaults
nack = 0.0
... | Start the poor_consumer. | entailment |
def connect(self):
"""
Connect to one of the Disque nodes.
You can get current connection with connected_node property
:returns: nothing
"""
self.connected_node = None
for i, node in self.nodes.items():
host, port = i.split(':')
port = i... | Connect to one of the Disque nodes.
You can get current connection with connected_node property
:returns: nothing | entailment |
def execute_command(self, *args, **kwargs):
"""Execute a command on the connected server."""
try:
return self.get_connection().execute_command(*args, **kwargs)
except ConnectionError as e:
logger.warn('trying to reconnect')
self.connect()
logger.wa... | Execute a command on the connected server. | entailment |
def add_job(self, queue_name, job, timeout=200, replicate=None, delay=None,
retry=None, ttl=None, maxlen=None, asynchronous=None):
"""
Add a job to a queue.
ADDJOB queue_name job <ms-timeout> [REPLICATE <count>] [DELAY <sec>]
[RETRY <sec>] [TTL <sec>] [MAXLEN <count>... | Add a job to a queue.
ADDJOB queue_name job <ms-timeout> [REPLICATE <count>] [DELAY <sec>]
[RETRY <sec>] [TTL <sec>] [MAXLEN <count>] [ASYNC]
:param queue_name: is the name of the queue, any string, basically.
:param job: is a string representing the job.
:param timeout: is... | entailment |
def get_job(self, queues, timeout=None, count=None, nohang=False, withcounters=False):
"""
Return some number of jobs from specified queues.
GETJOB [NOHANG] [TIMEOUT <ms-timeout>] [COUNT <count>] [WITHCOUNTERS] FROM
queue1 queue2 ... queueN
:param queues: name of queues
... | Return some number of jobs from specified queues.
GETJOB [NOHANG] [TIMEOUT <ms-timeout>] [COUNT <count>] [WITHCOUNTERS] FROM
queue1 queue2 ... queueN
:param queues: name of queues
:returns: list of tuple(job_id, queue_name, job), tuple(job_id, queue_name, job, nacks, additional_de... | entailment |
def qstat(self, queue_name, return_dict=False):
"""
Return the status of the queue (currently unimplemented).
Future support / testing of QSTAT support in Disque
QSTAT <qname>
Return produced ... consumed ... idle ... sources [...] ctime ...
"""
rtn = self.exec... | Return the status of the queue (currently unimplemented).
Future support / testing of QSTAT support in Disque
QSTAT <qname>
Return produced ... consumed ... idle ... sources [...] ctime ... | entailment |
def show(self, job_id, return_dict=False):
"""
Describe the job.
:param job_id:
"""
rtn = self.execute_command('SHOW', job_id)
if return_dict:
grouped = self._grouper(rtn, 2)
rtn = dict((a, b) for a, b in grouped)
return rtn | Describe the job.
:param job_id: | entailment |
def pause(self, queue_name, kw_in=None, kw_out=None, kw_all=None,
kw_none=None, kw_state=None, kw_bcast=None):
"""
Pause a queue.
Unfortunately, the PAUSE keywords are mostly reserved words in Python,
so I've been a little creative in the function variable names. Open
... | Pause a queue.
Unfortunately, the PAUSE keywords are mostly reserved words in Python,
so I've been a little creative in the function variable names. Open
to suggestions to change it (canardleteer)
:param queue_name: The job queue we are modifying.
:param kw_in: pause the queue ... | entailment |
def qscan(self, cursor=0, count=None, busyloop=None, minlen=None,
maxlen=None, importrate=None):
"""
Iterate all the existing queues in the local node.
:param count: An hint about how much work to do per iteration.
:param busyloop: Block and return all the elements in a bu... | Iterate all the existing queues in the local node.
:param count: An hint about how much work to do per iteration.
:param busyloop: Block and return all the elements in a busy loop.
:param minlen: Don't return elements with less than count jobs queued.
:param maxlen: Don't return element... | entailment |
def jscan(self, cursor=0, count=None, busyloop=None, queue=None,
state=None, reply=None):
"""Iterate all the existing jobs in the local node.
:param count: An hint about how much work to do per iteration.
:param busyloop: Block and return all the elements in a busy loop.
:... | Iterate all the existing jobs in the local node.
:param count: An hint about how much work to do per iteration.
:param busyloop: Block and return all the elements in a busy loop.
:param queue: Return only jobs in the specified queue.
:param state: Must be a list - Return jobs in the spe... | entailment |
def build_index_name(app, *parts):
"""Build an index name from parts.
:param parts: Parts that should be combined to make an index name.
"""
base_index = os.path.splitext(
'-'.join([part for part in parts if part])
)[0]
return prefix_index(app=app, index=base_index) | Build an index name from parts.
:param parts: Parts that should be combined to make an index name. | entailment |
def schema_to_index(schema, index_names=None):
"""Get index/doc_type given a schema URL.
:param schema: The schema name
:param index_names: A list of index name.
:returns: A tuple containing (index, doc_type).
"""
parts = schema.split('/')
doc_type = os.path.splitext(parts[-1])
if doc_... | Get index/doc_type given a schema URL.
:param schema: The schema name
:param index_names: A list of index name.
:returns: A tuple containing (index, doc_type). | entailment |
def es_version_check(f):
"""Decorator to check Elasticsearch version."""
@wraps(f)
def inner(*args, **kwargs):
cluster_ver = current_search.cluster_version[0]
client_ver = ES_VERSION[0]
if cluster_ver != client_ver:
raise click.ClickException(
'Elasticsear... | Decorator to check Elasticsearch version. | entailment |
def init(force):
"""Initialize registered aliases and mappings."""
click.secho('Creating indexes...', fg='green', bold=True, file=sys.stderr)
with click.progressbar(
current_search.create(ignore=[400] if force else None),
length=current_search.number_of_indexes) as bar:
for n... | Initialize registered aliases and mappings. | entailment |
def destroy(force):
"""Destroy all indexes."""
click.secho('Destroying indexes...', fg='red', bold=True, file=sys.stderr)
with click.progressbar(
current_search.delete(ignore=[400, 404] if force else None),
length=current_search.number_of_indexes) as bar:
for name, response i... | Destroy all indexes. | entailment |
def create(index_name, body, force, verbose):
"""Create a new index."""
result = current_search_client.indices.create(
index=index_name,
body=json.load(body),
ignore=[400] if force else None,
)
if verbose:
click.echo(json.dumps(result)) | Create a new index. | entailment |
def list_cmd(only_active, only_aliases, verbose):
"""List indices."""
def _tree_print(d, rec_list=None, verbose=False, indent=2):
# Note that on every recursion rec_list is copied,
# which might not be very effective for very deep dictionaries.
rec_list = rec_list or []
for idx, ... | List indices. | entailment |
def delete(index_name, force, verbose):
"""Delete index by its name."""
result = current_search_client.indices.delete(
index=index_name,
ignore=[400, 404] if force else None,
)
if verbose:
click.echo(json.dumps(result)) | Delete index by its name. | entailment |
def put(index_name, doc_type, identifier, body, force, verbose):
"""Index input data."""
result = current_search_client.index(
index=index_name,
doc_type=doc_type or index_name,
id=identifier,
body=json.load(body),
op_type='index' if force or identifier is None else 'crea... | Index input data. | entailment |
def get_records(self, ids):
"""Return records by their identifiers.
:param ids: A list of record identifier.
:returns: A list of records.
"""
return self.query(Ids(values=[str(id_) for id_ in ids])) | Return records by their identifiers.
:param ids: A list of record identifier.
:returns: A list of records. | entailment |
def faceted_search(cls, query=None, filters=None, search=None):
"""Return faceted search instance with defaults set.
:param query: Elastic DSL query object (``Q``).
:param filters: Dictionary with selected facet values.
:param search: An instance of ``Search`` class. (default: ``cls()``... | Return faceted search instance with defaults set.
:param query: Elastic DSL query object (``Q``).
:param filters: Dictionary with selected facet values.
:param search: An instance of ``Search`` class. (default: ``cls()``). | entailment |
def with_preference_param(self):
"""Add the preference param to the ES request and return a new Search.
The preference param avoids the bouncing effect with multiple
replicas, documented on ES documentation.
See: https://www.elastic.co/guide/en/elasticsearch/guide/current
/_sear... | Add the preference param to the ES request and return a new Search.
The preference param avoids the bouncing effect with multiple
replicas, documented on ES documentation.
See: https://www.elastic.co/guide/en/elasticsearch/guide/current
/_search_options.html#_preference for more informa... | entailment |
def _get_user_agent(self):
"""Retrieve the request's User-Agent, if available.
Taken from Flask Login utils.py.
"""
user_agent = request.headers.get('User-Agent')
if user_agent:
user_agent = user_agent.encode('utf-8')
return user_agent or '' | Retrieve the request's User-Agent, if available.
Taken from Flask Login utils.py. | entailment |
def _get_user_hash(self):
"""Calculate a digest based on request's User-Agent and IP address."""
if request:
user_hash = '{ip}-{ua}'.format(ip=request.remote_addr,
ua=self._get_user_agent())
alg = hashlib.md5()
alg.update(use... | Calculate a digest based on request's User-Agent and IP address. | entailment |
def beautify(filename=None, json_str=None):
"""Beautify JSON string or file.
Keyword arguments:
:param filename: use its contents as json string instead of
json_str param.
:param json_str: json string to be beautified.
"""
if filename is not None:
with open(filename) as json_file:
... | Beautify JSON string or file.
Keyword arguments:
:param filename: use its contents as json string instead of
json_str param.
:param json_str: json string to be beautified. | entailment |
def replace(pretty, old_str, new_str):
""" Replace strings giving some info on where
the replacement was done
"""
out_str = ''
line_number = 1
changes = 0
for line in pretty.splitlines(keepends=True):
new_line = line.replace(old_str, new_str)
if line.find(old_str) != -1:
... | Replace strings giving some info on where
the replacement was done | entailment |
def receive_connection():
"""Wait for and then return a connected socket..
Opens a TCP connection on port 8080, and waits for a single client.
"""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("localhost", 8... | Wait for and then return a connected socket..
Opens a TCP connection on port 8080, and waits for a single client. | entailment |
def send_message(client, message):
"""Send message to client and close the connection."""
print(message)
client.send("HTTP/1.1 200 OK\r\n\r\n{}".format(message).encode("utf-8"))
client.close() | Send message to client and close the connection. | entailment |
def main():
"""Provide the program's entry point when directly executed."""
if len(sys.argv) < 2:
print("Usage: {} SCOPE...".format(sys.argv[0]))
return 1
authenticator = prawcore.TrustedAuthenticator(
prawcore.Requestor("prawcore_refresh_token_example"),
os.environ["PRAWCOR... | Provide the program's entry point when directly executed. | entailment |
def watch(logger_name, level=DEBUG, out=stdout):
""" Quick wrapper for using the Watcher.
:param logger_name: name of logger to watch
:param level: minimum log level to show (default INFO)
:param out: where to send output (default stdout)
:return: Watcher instance
"""
watcher = Watcher(logg... | Quick wrapper for using the Watcher.
:param logger_name: name of logger to watch
:param level: minimum log level to show (default INFO)
:param out: where to send output (default stdout)
:return: Watcher instance | entailment |
def get_user_agent():
""" Obtain the default user agent string sent to the server after
a successful handshake.
"""
from sys import platform, version_info
template = "neobolt/{} Python/{}.{}.{}-{}-{} ({})"
fields = (version,) + tuple(version_info) + (platform,)
return template.format(*fields... | Obtain the default user agent string sent to the server after
a successful handshake. | entailment |
def import_best(c_module, py_module):
""" Import the best available module,
with C preferred to pure Python.
"""
from importlib import import_module
from os import getenv
pure_python = getenv("PURE_PYTHON", "")
if pure_python:
return import_module(py_module)
else:
try:
... | Import the best available module,
with C preferred to pure Python. | entailment |
def hydrate(self, values):
""" Convert PackStream values into native values.
"""
def hydrate_(obj):
if isinstance(obj, Structure):
try:
f = self.hydration_functions[obj.tag]
except KeyError:
# If we don't recogn... | Convert PackStream values into native values. | entailment |
def authorize_url(self, duration, scopes, state, implicit=False):
"""Return the URL used out-of-band to grant access to your application.
:param duration: Either ``permanent`` or ``temporary``. ``temporary``
authorizations generate access tokens that last only 1
hour. ``permanen... | Return the URL used out-of-band to grant access to your application.
:param duration: Either ``permanent`` or ``temporary``. ``temporary``
authorizations generate access tokens that last only 1
hour. ``permanent`` authorizations additionally generate a refresh
token that can... | entailment |
def revoke_token(self, token, token_type=None):
"""Ask Reddit to revoke the provided token.
:param token: The access or refresh token to revoke.
:param token_type: (Optional) When provided, hint to Reddit what the
token type is for a possible efficiency gain. The value can be
... | Ask Reddit to revoke the provided token.
:param token: The access or refresh token to revoke.
:param token_type: (Optional) When provided, hint to Reddit what the
token type is for a possible efficiency gain. The value can be
either ``access_token`` or ``refresh_token``. | entailment |
def revoke(self):
"""Revoke the current Authorization."""
if self.access_token is None:
raise InvalidInvocation("no token available to revoke")
self._authenticator.revoke_token(self.access_token, "access_token")
self._clear_access_token() | Revoke the current Authorization. | entailment |
def authorize(self, code):
"""Obtain and set authorization tokens based on ``code``.
:param code: The code obtained by an out-of-band authorization request
to Reddit.
"""
if self._authenticator.redirect_uri is None:
raise InvalidInvocation("redirect URI not prov... | Obtain and set authorization tokens based on ``code``.
:param code: The code obtained by an out-of-band authorization request
to Reddit. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.