sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def _expand_endpoint_name(endpoint_name, flags):
"""
Populate any ``{endpoint_name}`` tags in the flag names for the given
handler, based on the handlers module / file name.
"""
return tuple(flag.format(endpoint_name=endpoint_name) for flag in flags) | Populate any ``{endpoint_name}`` tags in the flag names for the given
handler, based on the handlers module / file name. | entailment |
def _is_endpoint_method(handler):
"""
from the context. Unfortunately, we can't directly detect whether
a handler is an Endpoint method, because at the time of decoration,
the class doesn't actually exist yet so it's impossible to get a
reference to it. So, we use the heuristic of seeing if the ha... | from the context. Unfortunately, we can't directly detect whether
a handler is an Endpoint method, because at the time of decoration,
the class doesn't actually exist yet so it's impossible to get a
reference to it. So, we use the heuristic of seeing if the handler
takes only a single ``self`` param a... | entailment |
def any_hook(*hook_patterns):
"""
Assert that the currently executing hook matches one of the given patterns.
Each pattern will match one or more hooks, and can use the following
special syntax:
* ``db-relation-{joined,changed}`` can be used to match multiple hooks
(in this case, ``db-re... | Assert that the currently executing hook matches one of the given patterns.
Each pattern will match one or more hooks, and can use the following
special syntax:
* ``db-relation-{joined,changed}`` can be used to match multiple hooks
(in this case, ``db-relation-joined`` and ``db-relation-changed`... | entailment |
def any_file_changed(filenames, hash_type='md5'):
"""
Check if any of the given files have changed since the last time this
was called.
:param list filenames: Names of files to check. Accepts callables returning
the filename.
:param str hash_type: Algorithm to use to check the files.
""... | Check if any of the given files have changed since the last time this
was called.
:param list filenames: Names of files to check. Accepts callables returning
the filename.
:param str hash_type: Algorithm to use to check the files. | entailment |
def load_hook_files(pathname):
"""
Loads files either defined as a glob or a single file path
sorted by filenames.
"""
global hooks
if sys.version_info[0] > 2 and sys.version_info[1] > 4:
fsglob = sorted(glob.iglob(pathname, recursive=True))
else:
fsglob = sorted(glob.iglob(... | Loads files either defined as a glob or a single file path
sorted by filenames. | entailment |
def main(relation_name=None):
"""
This is the main entry point for the reactive framework. It calls
:func:`~bus.discover` to find and load all reactive handlers (e.g.,
:func:`@when <decorators.when>` decorated blocks), and then
:func:`~bus.dispatch` to trigger handlers until the queue settles out.
... | This is the main entry point for the reactive framework. It calls
:func:`~bus.discover` to find and load all reactive handlers (e.g.,
:func:`@when <decorators.when>` decorated blocks), and then
:func:`~bus.dispatch` to trigger handlers until the queue settles out.
Finally, :meth:`unitdata.kv().flush <c... | entailment |
def from_flag(cls, flag):
"""
Return an Endpoint subclass instance based on the given flag.
The instance that is returned depends on the endpoint name embedded
in the flag. Flags should be of the form ``endpoint.{name}.extra...``,
though for legacy purposes, the ``endpoint.`` p... | Return an Endpoint subclass instance based on the given flag.
The instance that is returned depends on the endpoint name embedded
in the flag. Flags should be of the form ``endpoint.{name}.extra...``,
though for legacy purposes, the ``endpoint.`` prefix can be omitted.
The ``{name}}`` ... | entailment |
def _startup(cls):
"""
Create Endpoint instances and manage automatic flags.
"""
for endpoint_name in sorted(hookenv.relation_types()):
# populate context based on attached relations
relf = relation_factory(endpoint_name)
if not relf or not issubclass(... | Create Endpoint instances and manage automatic flags. | entailment |
def expand_name(self, flag):
"""
Complete a flag for this endpoint by expanding the endpoint name.
If the flag does not already contain ``{endpoint_name}``, it will be
prefixed with ``endpoint.{endpoint_name}.``. Then, any occurance of
``{endpoint_name}`` will be replaced with `... | Complete a flag for this endpoint by expanding the endpoint name.
If the flag does not already contain ``{endpoint_name}``, it will be
prefixed with ``endpoint.{endpoint_name}.``. Then, any occurance of
``{endpoint_name}`` will be replaced with ``self.endpoint_name``. | entailment |
def _manage_flags(self):
"""
Manage automatic relation flags.
"""
already_joined = is_flag_set(self.expand_name('joined'))
hook_name = hookenv.hook_name()
rel_hook = hook_name.startswith(self.endpoint_name + '-relation-')
departed_hook = rel_hook and hook_name.end... | Manage automatic relation flags. | entailment |
def all_joined_units(self):
"""
A list view of all the units of all relations attached to this
:class:`~charms.reactive.endpoints.Endpoint`.
This is actually a
:class:`~charms.reactive.endpoints.CombinedUnitsView`, so the units
will be in order by relation ID and then un... | A list view of all the units of all relations attached to this
:class:`~charms.reactive.endpoints.Endpoint`.
This is actually a
:class:`~charms.reactive.endpoints.CombinedUnitsView`, so the units
will be in order by relation ID and then unit name, and you can access a
merged vie... | entailment |
def all_departed_units(self):
"""
Collection of all units that were previously part of any relation on
this endpoint but which have since departed.
This collection is persistent and mutable. The departed units will
be kept until they are explicitly removed, to allow for reasona... | Collection of all units that were previously part of any relation on
this endpoint but which have since departed.
This collection is persistent and mutable. The departed units will
be kept until they are explicitly removed, to allow for reasonable
cleanup of units that have left.
... | entailment |
def application_name(self):
"""
The name of the remote application for this relation, or ``None``.
This is equivalent to::
relation.units[0].unit_name.split('/')[0]
"""
if self._application_name is None and self.units:
self._application_name = self.units... | The name of the remote application for this relation, or ``None``.
This is equivalent to::
relation.units[0].unit_name.split('/')[0] | entailment |
def joined_units(self):
"""
A list view of all the units joined on this relation.
This is actually a
:class:`~charms.reactive.endpoints.CombinedUnitsView`, so the units
will be in order by unit name, and you can access a merged view of all
of the units' data with ``self.... | A list view of all the units joined on this relation.
This is actually a
:class:`~charms.reactive.endpoints.CombinedUnitsView`, so the units
will be in order by unit name, and you can access a merged view of all
of the units' data with ``self.units.received`` and
``self.units.re... | entailment |
def to_publish(self):
"""
This is the relation data that the local unit publishes so it is
visible to all related units. Use this to communicate with related
units. It is a writeable
:class:`~charms.reactive.endpoints.JSONUnitDataView`.
All values stored in this collecti... | This is the relation data that the local unit publishes so it is
visible to all related units. Use this to communicate with related
units. It is a writeable
:class:`~charms.reactive.endpoints.JSONUnitDataView`.
All values stored in this collection will be automatically JSON
enco... | entailment |
def _flush_data(self):
"""
If this relation's local unit data has been modified, publish it on the
relation. This should be automatically called.
"""
if self._data and self._data.modified:
hookenv.relation_set(self.relation_id, dict(self.to_publish.data)) | If this relation's local unit data has been modified, publish it on the
relation. This should be automatically called. | entailment |
def received(self):
"""
A :class:`~charms.reactive.endpoints.JSONUnitDataView` of the data
received from this remote unit over the relation, with values being
automatically decoded as JSON.
"""
if self._data is None:
self._data = JSONUnitDataView(hookenv.relat... | A :class:`~charms.reactive.endpoints.JSONUnitDataView` of the data
received from this remote unit over the relation, with values being
automatically decoded as JSON. | entailment |
def load(cls, cache_key, deserializer, key_attr):
"""
Load the persisted cache and return a new instance of this class.
"""
items = unitdata.kv().get(cache_key) or []
return cls(cache_key,
[deserializer(item) for item in items],
key_attr) | Load the persisted cache and return a new instance of this class. | entailment |
def received(self):
"""
Combined :class:`~charms.reactive.endpoints.JSONUnitDataView` of the
data of all units in this list, with automatic JSON decoding.
"""
if not hasattr(self, '_data'):
# NB: units are reversed so that lowest numbered unit takes precedence
... | Combined :class:`~charms.reactive.endpoints.JSONUnitDataView` of the
data of all units in this list, with automatic JSON decoding. | entailment |
def AuthorizingClient(domain, auth, user_agent=None):
"""Creates a Podio client using an auth object."""
http_transport = transport.HttpTransport(domain, build_headers(auth, user_agent))
return client.Client(http_transport) | Creates a Podio client using an auth object. | entailment |
def from_image(cls, image):
"""
Create a PrintableImage from a PIL Image
:param image: a PIL Image
:return:
"""
(w, h) = image.size
# Thermal paper is 512 pixels wide
if w > 512:
ratio = 512. / w
h = int(h * ratio)
imag... | Create a PrintableImage from a PIL Image
:param image: a PIL Image
:return: | entailment |
def append(self, other):
"""
Append a Printable Image at the end of the current instance.
:param other: another PrintableImage
:return: PrintableImage containing data from both self and other
"""
self.data.extend(other.data)
self.height = self.height + other.heigh... | Append a Printable Image at the end of the current instance.
:param other: another PrintableImage
:return: PrintableImage containing data from both self and other | entailment |
def write_this(func):
"""
Decorator that writes the bytes to the wire
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
byte_array = func(self, *args, **kwargs)
self.write_bytes(byte_array)
return wrapper | Decorator that writes the bytes to the wire | entailment |
def print_images(self, *printable_images):
"""
This method allows printing several images in one shot. This is useful if the client code does not want the
printer to make pause during printing
"""
printable_image = reduce(lambda x, y: x.append(y), list(printable_images))
... | This method allows printing several images in one shot. This is useful if the client code does not want the
printer to make pause during printing | entailment |
def encode_and_quote(data):
"""If ``data`` is unicode, return urllib.quote_plus(data.encode("utf-8"))
otherwise return urllib.quote_plus(data)"""
if data is None:
return None
if isinstance(data, unicode):
data = data.encode("utf-8")
return urllib.quote_plus(data) | If ``data`` is unicode, return urllib.quote_plus(data.encode("utf-8"))
otherwise return urllib.quote_plus(data) | entailment |
def _strify(s):
"""If s is a unicode string, encode it to UTF-8 and return the results,
otherwise return str(s), or None if s is None"""
if s is None:
return None
if isinstance(s, unicode):
return s.encode("utf-8")
return str(s) | If s is a unicode string, encode it to UTF-8 and return the results,
otherwise return str(s), or None if s is None | entailment |
def encode_file_header(boundary, paramname, filesize, filename=None,
filetype=None):
"""Returns the leading data for a multipart/form-data field that contains
file data.
``boundary`` is the boundary string used throughout a single request to
separate variables.
``paramname``... | Returns the leading data for a multipart/form-data field that contains
file data.
``boundary`` is the boundary string used throughout a single request to
separate variables.
``paramname`` is the name of the variable in this request.
``filesize`` is the size of the file data.
``filename`` if ... | entailment |
def get_body_size(params, boundary):
"""Returns the number of bytes that the multipart/form-data encoding
of ``params`` will be."""
size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params))
return size + len(boundary) + 6 | Returns the number of bytes that the multipart/form-data encoding
of ``params`` will be. | entailment |
def get_headers(params, boundary):
"""Returns a dictionary with Content-Type and Content-Length headers
for the multipart/form-data encoding of ``params``."""
headers = {}
boundary = urllib.quote_plus(boundary)
headers['Content-Type'] = "multipart/form-data; boundary=%s" % boundary
headers['Cont... | Returns a dictionary with Content-Type and Content-Length headers
for the multipart/form-data encoding of ``params``. | entailment |
def multipart_encode(params, boundary=None, cb=None):
"""Encode ``params`` as multipart/form-data.
``params`` should be a sequence of (name, value) pairs or MultipartParam
objects, or a mapping of names to values.
Values are either strings parameter values, or file-like objects to use as
the parame... | Encode ``params`` as multipart/form-data.
``params`` should be a sequence of (name, value) pairs or MultipartParam
objects, or a mapping of names to values.
Values are either strings parameter values, or file-like objects to use as
the parameter value. The file-like objects must support .read() and ei... | entailment |
def from_file(cls, paramname, filename):
"""Returns a new MultipartParam object constructed from the local
file at ``filename``.
``filesize`` is determined by os.path.getsize(``filename``)
``filetype`` is determined by mimetypes.guess_type(``filename``)[0]
``filename`` is set ... | Returns a new MultipartParam object constructed from the local
file at ``filename``.
``filesize`` is determined by os.path.getsize(``filename``)
``filetype`` is determined by mimetypes.guess_type(``filename``)[0]
``filename`` is set to os.path.basename(``filename``) | entailment |
def from_params(cls, params):
"""Returns a list of MultipartParam objects from a sequence of
name, value pairs, MultipartParam instances,
or from a mapping of names to values
The values may be strings or file objects, or MultipartParam objects.
MultipartParam object names must m... | Returns a list of MultipartParam objects from a sequence of
name, value pairs, MultipartParam instances,
or from a mapping of names to values
The values may be strings or file objects, or MultipartParam objects.
MultipartParam object names must match the given names in the
name,... | entailment |
def encode_hdr(self, boundary):
"""Returns the header of the encoding of this parameter"""
boundary = encode_and_quote(boundary)
headers = ["--%s" % boundary]
if self.filename:
disposition = 'form-data; name="%s"; filename="%s"' % (self.name,
... | Returns the header of the encoding of this parameter | entailment |
def encode(self, boundary):
"""Returns the string encoding of this parameter"""
if self.value is None:
value = self.fileobj.read()
else:
value = self.value
if re.search("^--%s$" % re.escape(boundary), value, re.M):
raise ValueError("boundary found in ... | Returns the string encoding of this parameter | entailment |
def iter_encode(self, boundary, blocksize=4096):
"""Yields the encoding of this parameter
If self.fileobj is set, then blocks of ``blocksize`` bytes are read and
yielded."""
total = self.get_size(boundary)
current = 0
if self.value is not None:
block = self.en... | Yields the encoding of this parameter
If self.fileobj is set, then blocks of ``blocksize`` bytes are read and
yielded. | entailment |
def get_size(self, boundary):
"""Returns the size in bytes that this param will be when encoded
with the given boundary."""
if self.filesize is not None:
valuesize = self.filesize
else:
valuesize = len(self.value)
return len(self.encode_hdr(boundary)) + 2... | Returns the size in bytes that this param will be when encoded
with the given boundary. | entailment |
def next(self):
"""generator function to yield multipart/form-data representation
of parameters"""
if self.param_iter is not None:
try:
block = self.param_iter.next()
self.current += len(block)
if self.cb:
self.cb(se... | generator function to yield multipart/form-data representation
of parameters | entailment |
def get_options(silent=False, hook=True):
"""
Generate a query string with the appropriate options.
:param silent: If set to true, the object will not be bumped up in the stream and
notifications will not be generated.
:type silent: bool
:param hook: True ... | Generate a query string with the appropriate options.
:param silent: If set to true, the object will not be bumped up in the stream and
notifications will not be generated.
:type silent: bool
:param hook: True if hooks should be executed for the change, false otherwise.
... | entailment |
def find(self, item_id, basic=False, **kwargs):
"""
Get item
:param item_id: Item ID
:param basic: ?
:type item_id: int
:return: Item info
:rtype: dict
"""
if basic:
return self.transport.GET(url='/item/%d/basic' % item_id)
... | Get item
:param item_id: Item ID
:param basic: ?
:type item_id: int
:return: Item info
:rtype: dict | entailment |
def update(self, item_id, attributes, silent=False, hook=True):
"""
Updates the item using the supplied attributes. If 'silent' is true, Podio will send
no notifications to subscribed users and not post updates to the stream.
Important: webhooks will still be called.
"""... | Updates the item using the supplied attributes. If 'silent' is true, Podio will send
no notifications to subscribed users and not post updates to the stream.
Important: webhooks will still be called. | entailment |
def create(self, attributes, silent=False, hook=True):
"""
https://developers.podio.com/doc/tasks/create-task-22419
Creates the task using the supplied attributes. If 'silent' is true,
Podio will send no notifications to subscribed users and not post
updates to the stream. If 'ho... | https://developers.podio.com/doc/tasks/create-task-22419
Creates the task using the supplied attributes. If 'silent' is true,
Podio will send no notifications to subscribed users and not post
updates to the stream. If 'hook' is false webhooks will not be called. | entailment |
def create_for(self, ref_type, ref_id, attributes, silent=False, hook=True):
"""
https://developers.podio.com/doc/tasks/create-task-with-reference-22420
If 'silent' is true, Podio will send no notifications and not post
updates to the stream. If 'hook' is false webhooks will not be calle... | https://developers.podio.com/doc/tasks/create-task-with-reference-22420
If 'silent' is true, Podio will send no notifications and not post
updates to the stream. If 'hook' is false webhooks will not be called. | entailment |
def find_by_url(self, space_url, id_only=True):
"""
Returns a space ID given the URL of the space.
:param space_url: URL of the Space
:param id_only: ?
:return: space_id: Space url
:rtype: str
"""
resp = self.transport.GET(url='/space/url?%s' % urlencode(... | Returns a space ID given the URL of the space.
:param space_url: URL of the Space
:param id_only: ?
:return: space_id: Space url
:rtype: str | entailment |
def create(self, attributes):
"""
Create a new space
:param attributes: Refer to API. Pass in argument as dictionary
:type attributes: dict
:return: Details of newly created space
:rtype: dict
"""
if not isinstance(attributes, dict):
r... | Create a new space
:param attributes: Refer to API. Pass in argument as dictionary
:type attributes: dict
:return: Details of newly created space
:rtype: dict | entailment |
def find_by_ref(self, ref_type, ref_id):
"""
Returns an object of type "item", "status" or "task" as a
stream object. This is useful when a new status has been
posted and should be rendered directly in the stream without
reloading the entire stream.
For details, see: htt... | Returns an object of type "item", "status" or "task" as a
stream object. This is useful when a new status has been
posted and should be rendered directly in the stream without
reloading the entire stream.
For details, see: https://developers.podio.com/doc/stream/get-stream-object-80054 | entailment |
def find_raw(self, file_id):
"""Returns raw file as string. Pass to a file object"""
raw_handler = lambda resp, data: data
return self.transport.GET(url='/file/%d/raw' % file_id, handler=raw_handler) | Returns raw file as string. Pass to a file object | entailment |
def create(self, filename, filedata):
"""Create a file from raw data"""
attributes = {'filename': filename,
'source': filedata}
return self.transport.POST(url='/file/v2/', body=attributes, type='multipart/form-data') | Create a file from raw data | entailment |
def get(self, app_id, view_specifier):
"""
Retrieve the definition of a given view, provided the app_id and the view_id
:param app_id: the app id
:param view_specifier:
Can be one of the following:
1. The view ID
2. The view's name
3. "las... | Retrieve the definition of a given view, provided the app_id and the view_id
:param app_id: the app id
:param view_specifier:
Can be one of the following:
1. The view ID
2. The view's name
3. "last" to look up the last view used | entailment |
def get_views(self, app_id, include_standard_views=False):
"""
Get all of the views for the specified app
:param app_id: the app containing the views
:param include_standard_views: defaults to false. Set to true if you wish to include standard views.
"""
include_standard... | Get all of the views for the specified app
:param app_id: the app containing the views
:param include_standard_views: defaults to false. Set to true if you wish to include standard views. | entailment |
def update_last_view(self, app_id, attributes):
"""
Updates the last view for the active user
:param app_id: the app id
:param attributes: the body of the request in dictionary format
"""
if not isinstance(attributes, dict):
raise TypeError('Must be of type d... | Updates the last view for the active user
:param app_id: the app id
:param attributes: the body of the request in dictionary format | entailment |
def update_view(self, view_id, attributes):
"""
Update an existing view using the details supplied via the attributes parameter
:param view_id: the view's id
:param attributes: a dictionary containing the modifications to be made to the view
:return:
"""
if not i... | Update an existing view using the details supplied via the attributes parameter
:param view_id: the view's id
:param attributes: a dictionary containing the modifications to be made to the view
:return: | entailment |
def is_active(self, timeout=2):
"""
:param timeout: int
:return: boolean
"""
try:
result = Result(*self.perform_request('HEAD', '/', params={'request_timeout': timeout}))
except ConnectionError:
return False
except TransportError:
... | :param timeout: int
:return: boolean | entailment |
def query(self, sql, timeout=10):
"""
Submit a query and return results.
:param sql: string
:param timeout: int
:return: pydrill.client.ResultQuery
"""
if not sql:
raise QueryError('No query passed to drill.')
result = ResultQuery(*self.perfo... | Submit a query and return results.
:param sql: string
:param timeout: int
:return: pydrill.client.ResultQuery | entailment |
def plan(self, sql, timeout=10):
"""
:param sql: string
:param timeout: int
:return: pydrill.client.ResultQuery
"""
sql = 'explain plan for ' + sql
return self.query(sql, timeout) | :param sql: string
:param timeout: int
:return: pydrill.client.ResultQuery | entailment |
def storage_detail(self, name, timeout=10):
"""
Get the definition of the named storage plugin.
:param name: The assigned name in the storage plugin definition.
:param timeout: int
:return: pydrill.client.Result
"""
result = Result(*self.perform_request(**{
... | Get the definition of the named storage plugin.
:param name: The assigned name in the storage plugin definition.
:param timeout: int
:return: pydrill.client.Result | entailment |
def storage_enable(self, name, value=True, timeout=10):
"""
Enable or disable the named storage plugin.
:param name: The assigned name in the storage plugin definition.
:param value: Either True (to enable) or False (to disable).
:param timeout: int
:return: pydrill.clie... | Enable or disable the named storage plugin.
:param name: The assigned name in the storage plugin definition.
:param value: Either True (to enable) or False (to disable).
:param timeout: int
:return: pydrill.client.Result | entailment |
def storage_update(self, name, config, timeout=10):
"""
Create or update a storage plugin configuration.
:param name: The name of the storage plugin configuration to create or update.
:param config: Overwrites the existing configuration if there is any, and therefore, must include all
... | Create or update a storage plugin configuration.
:param name: The name of the storage plugin configuration to create or update.
:param config: Overwrites the existing configuration if there is any, and therefore, must include all
required attributes and definitions.
:param timeout: int
... | entailment |
def storage_delete(self, name, timeout=10):
"""
Delete a storage plugin configuration.
:param name: The name of the storage plugin configuration to delete.
:param timeout: int
:return: pydrill.client.Result
"""
result = Result(*self.perform_request(**{
... | Delete a storage plugin configuration.
:param name: The name of the storage plugin configuration to delete.
:param timeout: int
:return: pydrill.client.Result | entailment |
def profile(self, query_id, timeout=10):
"""
Get the profile of the query that has the given queryid.
:param query_id: The UUID of the query in standard UUID format that Drill assigns to each query.
:param timeout: int
:return: pydrill.client.Result
"""
result = ... | Get the profile of the query that has the given queryid.
:param query_id: The UUID of the query in standard UUID format that Drill assigns to each query.
:param timeout: int
:return: pydrill.client.Result | entailment |
def profile_cancel(self, query_id, timeout=10):
"""
Cancel the query that has the given queryid.
:param query_id: The UUID of the query in standard UUID format that Drill assigns to each query.
:param timeout: int
:return: pydrill.client.Result
"""
result = Resul... | Cancel the query that has the given queryid.
:param query_id: The UUID of the query in standard UUID format that Drill assigns to each query.
:param timeout: int
:return: pydrill.client.Result | entailment |
def log_request_success(self, method, full_url, path, body, status_code, response, duration):
""" Log a successful API call. """
if body and not isinstance(body, dict):
body = body.decode('utf-8')
logger.info(
'%s %s [status:%s request:%.3fs]', method, full_url,
... | Log a successful API call. | entailment |
def log_request_fail(self, method, full_url, body, duration, status_code=None, exception=None):
"""
Log an unsuccessful API call.
"""
logger.warning(
'%s %s [status:%s request:%.3fs]', method, full_url,
status_code or 'N/A', duration, exc_info=exception is not Non... | Log an unsuccessful API call. | entailment |
def _raise_error(self, status_code, raw_data):
"""
Locate appropriate exception and raise it.
"""
error_message = raw_data
additional_info = None
try:
additional_info = json.loads(raw_data)
error_message = additional_info.get('error', error_message... | Locate appropriate exception and raise it. | entailment |
def perform_request(self, method, url, params=None, body=None):
"""
Perform the actual request.
Retrieve a connection.
Pass all the information to it's perform_request method and return the data.
:arg method: HTTP method to use
:arg url: absolute url (without host) to ta... | Perform the actual request.
Retrieve a connection.
Pass all the information to it's perform_request method and return the data.
:arg method: HTTP method to use
:arg url: absolute url (without host) to target
:arg params: dictionary of query parameters, will be handed over to the... | entailment |
def release(ctx, type_, repo, prebump=PREBUMP, config_file=None, commit=True, yes=False):
"""Make a new release.
"""
if prebump not in REL_TYPES:
raise ValueError(f"{type_} not in {REL_TYPES}")
prebump = REL_TYPES.index(prebump)
version = _read_version()
version = _bump_release(version,... | Make a new release. | entailment |
def init_menu():
"""Initialize menu before first request."""
# Register breadcrumb root
item = current_menu.submenu('breadcrumbs.settings')
item.register('', _('Account'))
item = current_menu.submenu('breadcrumbs.{0}'.format(
current_app.config['SECURITY_BLUEPRINT_NAME']))
if current_ap... | Initialize menu before first request. | entailment |
def check_security_settings():
"""Warn if session cookie is not secure in production."""
in_production = not (current_app.debug or current_app.testing)
secure = current_app.config.get('SESSION_COOKIE_SECURE')
if in_production and not secure:
current_app.logger.warning(
"SESSION_COOKI... | Warn if session cookie is not secure in production. | entailment |
def jwt_proccessor():
"""Context processor for jwt."""
def jwt():
"""Context processor function to generate jwt."""
token = current_accounts.jwt_creation_factory()
return Markup(
render_template(
current_app.config['ACCOUNTS_JWT_DOM_TOKEN_TEMPLATE'],
... | Context processor for jwt. | entailment |
def _to_binary(val):
"""Convert to binary."""
if isinstance(val, text_type):
return val.encode('utf-8')
assert isinstance(val, binary_type)
return val | Convert to binary. | entailment |
def _to_string(val):
"""Convert to text."""
if isinstance(val, binary_type):
return val.decode('utf-8')
assert isinstance(val, text_type)
return val | Convert to text. | entailment |
def _mysql_aes_key(key):
"""Format key."""
final_key = bytearray(16)
for i, c in enumerate(key):
final_key[i % 16] ^= key[i] if PY3 else ord(key[i])
return bytes(final_key) | Format key. | entailment |
def _mysql_aes_pad(val):
"""Padding."""
val = _to_string(val)
pad_value = 16 - (len(val) % 16)
return _to_binary('{0}{1}'.format(val, chr(pad_value) * pad_value)) | Padding. | entailment |
def _mysql_aes_unpad(val):
"""Reverse padding."""
val = _to_string(val)
pad_value = ord(val[-1])
return val[:-pad_value] | Reverse padding. | entailment |
def mysql_aes_encrypt(val, key):
"""Mysql AES encrypt value with secret key.
:param val: Plain text value.
:param key: The AES key.
:returns: The encrypted AES value.
"""
assert isinstance(val, binary_type) or isinstance(val, text_type)
assert isinstance(key, binary_type) or isinstance(key,... | Mysql AES encrypt value with secret key.
:param val: Plain text value.
:param key: The AES key.
:returns: The encrypted AES value. | entailment |
def mysql_aes_decrypt(encrypted_val, key):
"""Mysql AES decrypt value with secret key.
:param encrypted_val: Encrypted value.
:param key: The AES key.
:returns: The AES value decrypted.
"""
assert isinstance(encrypted_val, binary_type) \
or isinstance(encrypted_val, text_type)
asser... | Mysql AES decrypt value with secret key.
:param encrypted_val: Encrypted value.
:param key: The AES key.
:returns: The AES value decrypted. | entailment |
def from_string(cls, hash, **context):
"""Parse instance from configuration string in Modular Crypt Format."""
salt, checksum = parse_mc2(hash, cls.ident, handler=cls)
return cls(salt=salt, checksum=checksum) | Parse instance from configuration string in Modular Crypt Format. | entailment |
def _calc_checksum(self, secret):
"""Calculate string.
:param secret: The secret key.
:returns: The checksum.
"""
return str_to_uascii(
hashlib.sha256(mysql_aes_encrypt(self.salt, secret)).hexdigest()
) | Calculate string.
:param secret: The secret key.
:returns: The checksum. | entailment |
def _ip2country(ip):
"""Get user country."""
if ip:
match = geolite2.reader().get(ip)
return match.get('country', {}).get('iso_code') if match else None | Get user country. | entailment |
def _extract_info_from_useragent(user_agent):
"""Extract extra informations from user."""
parsed_string = user_agent_parser.Parse(user_agent)
return {
'os': parsed_string.get('os', {}).get('family'),
'browser': parsed_string.get('user_agent', {}).get('family'),
'browser_version': par... | Extract extra informations from user. | entailment |
def add_session(session=None):
r"""Add a session to the SessionActivity table.
:param session: Flask Session object to add. If None, ``session``
is used. The object is expected to have a dictionary entry named
``"user_id"`` and a field ``sid_s``
"""
user_id, sid_s = session['user_id'], ... | r"""Add a session to the SessionActivity table.
:param session: Flask Session object to add. If None, ``session``
is used. The object is expected to have a dictionary entry named
``"user_id"`` and a field ``sid_s`` | entailment |
def login_listener(app, user):
"""Connect to the user_logged_in signal for table population.
:param app: The Flask application.
:param user: The :class:`invenio_accounts.models.User` instance.
"""
@after_this_request
def add_user_session(response):
"""Regenerate current session and add ... | Connect to the user_logged_in signal for table population.
:param app: The Flask application.
:param user: The :class:`invenio_accounts.models.User` instance. | entailment |
def logout_listener(app, user):
"""Connect to the user_logged_out signal.
:param app: The Flask application.
:param user: The :class:`invenio_accounts.models.User` instance.
"""
@after_this_request
def _commit(response=None):
if hasattr(session, 'sid_s'):
delete_session(sess... | Connect to the user_logged_out signal.
:param app: The Flask application.
:param user: The :class:`invenio_accounts.models.User` instance. | entailment |
def delete_session(sid_s):
"""Delete entries in the data- and kvsessionstore with the given sid_s.
On a successful deletion, the flask-kvsession store returns 1 while the
sqlalchemy datastore returns None.
:param sid_s: The session ID.
:returns: ``1`` if deletion was successful.
"""
# Remo... | Delete entries in the data- and kvsessionstore with the given sid_s.
On a successful deletion, the flask-kvsession store returns 1 while the
sqlalchemy datastore returns None.
:param sid_s: The session ID.
:returns: ``1`` if deletion was successful. | entailment |
def delete_user_sessions(user):
"""Delete all active user sessions.
:param user: User instance.
:returns: If ``True`` then the session is successfully deleted.
"""
with db.session.begin_nested():
for s in user.active_sessions:
_sessionstore.delete(s.sid_s)
SessionActivi... | Delete all active user sessions.
:param user: User instance.
:returns: If ``True`` then the session is successfully deleted. | entailment |
def confirm_register_form_factory(Form, app):
"""Return confirmation for extended registration form."""
if app.config.get('RECAPTCHA_PUBLIC_KEY') and \
app.config.get('RECAPTCHA_PRIVATE_KEY'):
class ConfirmRegisterForm(Form):
recaptcha = FormField(RegistrationFormRecaptcha, separ... | Return confirmation for extended registration form. | entailment |
def register_form_factory(Form, app):
"""Return extended registration form."""
if app.config.get('RECAPTCHA_PUBLIC_KEY') and \
app.config.get('RECAPTCHA_PRIVATE_KEY'):
class RegisterForm(Form):
recaptcha = FormField(RegistrationFormRecaptcha, separator='.')
return Regist... | Return extended registration form. | entailment |
def login_form_factory(Form, app):
"""Return extended login form."""
class LoginForm(Form):
def __init__(self, *args, **kwargs):
"""Init the login form.
.. note::
The ``remember me`` option will be completely disabled.
"""
super(LoginFor... | Return extended login form. | entailment |
def on_model_change(self, form, User, is_created):
"""Hash password when saving."""
if form.password.data is not None:
pwd_ctx = current_app.extensions['security'].pwd_context
if pwd_ctx.identify(form.password.data) is None:
User.password = hash_password(form.pass... | Hash password when saving. | entailment |
def after_model_change(self, form, User, is_created):
"""Send password instructions if desired."""
if is_created and form.notification.data is True:
send_reset_password_instructions(User) | Send password instructions if desired. | entailment |
def action_inactivate(self, ids):
"""Inactivate users."""
try:
count = 0
for user_id in ids:
user = _datastore.get_user(user_id)
if user is None:
raise ValueError(_("Cannot find user."))
if _datastore.deactivate_... | Inactivate users. | entailment |
def delete_model(self, model):
"""Delete a specific session."""
if SessionActivity.is_current(sid_s=model.sid_s):
flash('You could not remove your current session', 'error')
return
delete_session(sid_s=model.sid_s)
db.session.commit() | Delete a specific session. | entailment |
def action_delete(self, ids):
"""Delete selected sessions."""
is_current = any(SessionActivity.is_current(sid_s=id_) for id_ in ids)
if is_current:
flash('You could not remove your current session', 'error')
return
for id_ in ids:
delete_session(sid_s=... | Delete selected sessions. | entailment |
def users_create(email, password, active):
"""Create a user."""
kwargs = dict(email=email, password=password, active='y' if active else '')
form = ConfirmRegisterForm(MultiDict(kwargs), csrf_enabled=False)
if form.validate():
kwargs['password'] = hash_password(kwargs['password'])
kwarg... | Create a user. | entailment |
def send_security_email(data):
"""Celery task to send security email.
:param data: Contains the email data.
"""
msg = Message()
msg.__dict__.update(data)
current_app.extensions['mail'].send(msg) | Celery task to send security email.
:param data: Contains the email data. | entailment |
def clean_session_table():
"""Automatically clean session table.
To enable a periodically clean of the session table, you should configure
the task as a celery periodic task.
.. code-block:: python
from datetime import timedelta
CELERYBEAT_SCHEDULE = {
'session_cleaner': {... | Automatically clean session table.
To enable a periodically clean of the session table, you should configure
the task as a celery periodic task.
.. code-block:: python
from datetime import timedelta
CELERYBEAT_SCHEDULE = {
'session_cleaner': {
'task': 'invenio_... | entailment |
def upgrade():
"""Upgrade database."""
op.create_table(
'accounts_role',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=80), nullable=True),
sa.Column('description', sa.String(length=255), nullable=True),
sa.PrimaryKeyConstraint('id'),
... | Upgrade database. | entailment |
def downgrade():
"""Downgrade database."""
ctx = op.get_context()
insp = Inspector.from_engine(ctx.connection.engine)
for fk in insp.get_foreign_keys('transaction'):
if fk['referred_table'] == 'accounts_user':
op.drop_constraint(
op.f(fk['name']), 'transaction', type... | Downgrade database. | entailment |
def jwt_create_token(user_id=None, additional_data=None):
"""Encode the JWT token.
:param int user_id: Addition of user_id.
:param dict additional_data: Additional information for the token.
:returns: The encoded token.
:rtype: str
.. note::
Definition of the JWT claims:
* exp... | Encode the JWT token.
:param int user_id: Addition of user_id.
:param dict additional_data: Additional information for the token.
:returns: The encoded token.
:rtype: str
.. note::
Definition of the JWT claims:
* exp: ((Expiration Time) expiration time of the JWT.
* sub: (... | entailment |
def jwt_decode_token(token):
"""Decode the JWT token.
:param str token: Additional information for the token.
:returns: The token data.
:rtype: dict
"""
try:
return decode(
token,
current_app.config['ACCOUNTS_JWT_SECRET_KEY'],
algorithms=[
... | Decode the JWT token.
:param str token: Additional information for the token.
:returns: The token data.
:rtype: dict | entailment |
def set_session_info(app, response, **extra):
"""Add X-Session-ID and X-User-ID to http response."""
session_id = getattr(session, 'sid_s', None)
if session_id:
response.headers['X-Session-ID'] = session_id
if current_user.is_authenticated:
response.headers['X-User-ID'] = current_user.ge... | Add X-Session-ID and X-User-ID to http response. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.