repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_documentation_string stringlengths 1 47.2k | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|
inveniosoftware/invenio-records-rest | invenio_records_rest/views.py | pass_record | def pass_record(f):
"""Decorator to retrieve persistent identifier and record.
This decorator will resolve the ``pid_value`` parameter from the route
pattern and resolve it to a PID and a record, which are then available in
the decorated function as ``pid`` and ``record`` kwargs respectively.
"""
... | python | def pass_record(f):
"""Decorator to retrieve persistent identifier and record.
This decorator will resolve the ``pid_value`` parameter from the route
pattern and resolve it to a PID and a record, which are then available in
the decorated function as ``pid`` and ``record`` kwargs respectively.
"""
... | Decorator to retrieve persistent identifier and record.
This decorator will resolve the ``pid_value`` parameter from the route
pattern and resolve it to a PID and a record, which are then available in
the decorated function as ``pid`` and ``record`` kwargs respectively. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/views.py#L361-L376 |
inveniosoftware/invenio-records-rest | invenio_records_rest/views.py | verify_record_permission | def verify_record_permission(permission_factory, record):
"""Check that the current user has the required permissions on record.
In case the permission check fails, an Flask abort is launched.
If the user was previously logged-in, a HTTP error 403 is returned.
Otherwise, is returned a HTTP error 401.
... | python | def verify_record_permission(permission_factory, record):
"""Check that the current user has the required permissions on record.
In case the permission check fails, an Flask abort is launched.
If the user was previously logged-in, a HTTP error 403 is returned.
Otherwise, is returned a HTTP error 401.
... | Check that the current user has the required permissions on record.
In case the permission check fails, an Flask abort is launched.
If the user was previously logged-in, a HTTP error 403 is returned.
Otherwise, is returned a HTTP error 401.
:param permission_factory: permission factory used to check p... | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/views.py#L379-L395 |
inveniosoftware/invenio-records-rest | invenio_records_rest/views.py | need_record_permission | def need_record_permission(factory_name):
"""Decorator checking that the user has the required permissions on record.
:param factory_name: name of the permission factory.
"""
def need_record_permission_builder(f):
@wraps(f)
def need_record_permission_decorator(self, record=None, *args,
... | python | def need_record_permission(factory_name):
"""Decorator checking that the user has the required permissions on record.
:param factory_name: name of the permission factory.
"""
def need_record_permission_builder(f):
@wraps(f)
def need_record_permission_decorator(self, record=None, *args,
... | Decorator checking that the user has the required permissions on record.
:param factory_name: name of the permission factory. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/views.py#L398-L419 |
inveniosoftware/invenio-records-rest | invenio_records_rest/views.py | RecordsListOptionsResource.get | def get(self):
"""Get options."""
opts = current_app.config['RECORDS_REST_SORT_OPTIONS'].get(
self.search_index)
sort_fields = []
if opts:
for key, item in sorted(opts.items(), key=lambda x: x[1]['order']):
sort_fields.append(
... | python | def get(self):
"""Get options."""
opts = current_app.config['RECORDS_REST_SORT_OPTIONS'].get(
self.search_index)
sort_fields = []
if opts:
for key, item in sorted(opts.items(), key=lambda x: x[1]['order']):
sort_fields.append(
... | Get options. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/views.py#L437-L457 |
inveniosoftware/invenio-records-rest | invenio_records_rest/views.py | RecordsListResource.get | def get(self, **kwargs):
"""Search records.
Permissions: the `list_permission_factory` permissions are
checked.
:returns: Search result containing hits and aggregations as
returned by invenio-search.
"""
default_results_size = current_app.config.ge... | python | def get(self, **kwargs):
"""Search records.
Permissions: the `list_permission_factory` permissions are
checked.
:returns: Search result containing hits and aggregations as
returned by invenio-search.
"""
default_results_size = current_app.config.ge... | Search records.
Permissions: the `list_permission_factory` permissions are
checked.
:returns: Search result containing hits and aggregations as
returned by invenio-search. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/views.py#L506-L553 |
inveniosoftware/invenio-records-rest | invenio_records_rest/views.py | RecordsListResource.post | def post(self, **kwargs):
"""Create a record.
Permissions: ``create_permission_factory``
Procedure description:
#. First of all, the `create_permission_factory` permissions are
checked.
#. Then, the record is deserialized by the proper loader.
#. A second... | python | def post(self, **kwargs):
"""Create a record.
Permissions: ``create_permission_factory``
Procedure description:
#. First of all, the `create_permission_factory` permissions are
checked.
#. Then, the record is deserialized by the proper loader.
#. A second... | Create a record.
Permissions: ``create_permission_factory``
Procedure description:
#. First of all, the `create_permission_factory` permissions are
checked.
#. Then, the record is deserialized by the proper loader.
#. A second call to the `create_permission_facto... | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/views.py#L556-L613 |
inveniosoftware/invenio-records-rest | invenio_records_rest/views.py | RecordResource.delete | def delete(self, pid, record, **kwargs):
"""Delete a record.
Permissions: ``delete_permission_factory``
Procedure description:
#. The record is resolved reading the pid value from the url.
#. The ETag is checked.
#. The record is deleted.
#. All PIDs are mar... | python | def delete(self, pid, record, **kwargs):
"""Delete a record.
Permissions: ``delete_permission_factory``
Procedure description:
#. The record is resolved reading the pid value from the url.
#. The ETag is checked.
#. The record is deleted.
#. All PIDs are mar... | Delete a record.
Permissions: ``delete_permission_factory``
Procedure description:
#. The record is resolved reading the pid value from the url.
#. The ETag is checked.
#. The record is deleted.
#. All PIDs are marked as DELETED.
:param pid: Persistent iden... | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/views.py#L650-L683 |
inveniosoftware/invenio-records-rest | invenio_records_rest/views.py | RecordResource.get | def get(self, pid, record, **kwargs):
"""Get a record.
Permissions: ``read_permission_factory``
Procedure description:
#. The record is resolved reading the pid value from the url.
#. The ETag and If-Modifed-Since is checked.
#. The HTTP response is built with the he... | python | def get(self, pid, record, **kwargs):
"""Get a record.
Permissions: ``read_permission_factory``
Procedure description:
#. The record is resolved reading the pid value from the url.
#. The ETag and If-Modifed-Since is checked.
#. The HTTP response is built with the he... | Get a record.
Permissions: ``read_permission_factory``
Procedure description:
#. The record is resolved reading the pid value from the url.
#. The ETag and If-Modifed-Since is checked.
#. The HTTP response is built with the help of the link factory.
:param pid: Pers... | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/views.py#L687-L710 |
inveniosoftware/invenio-records-rest | invenio_records_rest/views.py | RecordResource.patch | def patch(self, pid, record, **kwargs):
"""Modify a record.
Permissions: ``update_permission_factory``
The data should be a JSON-patch, which will be applied to the record.
Requires header ``Content-Type: application/json-patch+json``.
Procedure description:
#. The re... | python | def patch(self, pid, record, **kwargs):
"""Modify a record.
Permissions: ``update_permission_factory``
The data should be a JSON-patch, which will be applied to the record.
Requires header ``Content-Type: application/json-patch+json``.
Procedure description:
#. The re... | Modify a record.
Permissions: ``update_permission_factory``
The data should be a JSON-patch, which will be applied to the record.
Requires header ``Content-Type: application/json-patch+json``.
Procedure description:
#. The record is deserialized using the proper loader.
... | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/views.py#L715-L753 |
inveniosoftware/invenio-records-rest | invenio_records_rest/views.py | RecordResource.put | def put(self, pid, record, **kwargs):
"""Replace a record.
Permissions: ``update_permission_factory``
The body should be a JSON object, which will fully replace the current
record metadata.
Procedure description:
#. The ETag is checked.
#. The record is updat... | python | def put(self, pid, record, **kwargs):
"""Replace a record.
Permissions: ``update_permission_factory``
The body should be a JSON object, which will fully replace the current
record metadata.
Procedure description:
#. The ETag is checked.
#. The record is updat... | Replace a record.
Permissions: ``update_permission_factory``
The body should be a JSON object, which will fully replace the current
record metadata.
Procedure description:
#. The ETag is checked.
#. The record is updated by calling the record API `clear()`,
... | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/views.py#L757-L794 |
inveniosoftware/invenio-records-rest | invenio_records_rest/views.py | SuggestResource.get | def get(self, **kwargs):
"""Get suggestions."""
completions = []
size = request.values.get('size', type=int)
for k in self.suggesters.keys():
val = request.values.get(k)
if val:
# Get completion suggestions
opts = copy.deepcopy(sel... | python | def get(self, **kwargs):
"""Get suggestions."""
completions = []
size = request.values.get('size', type=int)
for k in self.suggesters.keys():
val = request.values.get(k)
if val:
# Get completion suggestions
opts = copy.deepcopy(sel... | Get suggestions. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/views.py#L807-L860 |
inveniosoftware/invenio-records-rest | invenio_records_rest/schemas/fields/datetime.py | DateString._serialize | def _serialize(self, value, attr, obj):
"""Serialize an ISO8601-formatted date."""
try:
return super(DateString, self)._serialize(
arrow.get(value).date(), attr, obj)
except ParserError:
return missing | python | def _serialize(self, value, attr, obj):
"""Serialize an ISO8601-formatted date."""
try:
return super(DateString, self)._serialize(
arrow.get(value).date(), attr, obj)
except ParserError:
return missing | Serialize an ISO8601-formatted date. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/schemas/fields/datetime.py#L21-L27 |
inveniosoftware/invenio-records-rest | invenio_records_rest/schemas/fields/datetime.py | DateString._deserialize | def _deserialize(self, value, attr, data):
"""Deserialize an ISO8601-formatted date."""
return super(DateString, self)._deserialize(value, attr,
data).isoformat() | python | def _deserialize(self, value, attr, data):
"""Deserialize an ISO8601-formatted date."""
return super(DateString, self)._deserialize(value, attr,
data).isoformat() | Deserialize an ISO8601-formatted date. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/schemas/fields/datetime.py#L29-L32 |
inveniosoftware/invenio-records-rest | examples/app.py | records | def records():
"""Load test data fixture."""
import uuid
from invenio_records.api import Record
from invenio_pidstore.models import PersistentIdentifier, PIDStatus
indexer = RecordIndexer()
index_queue = []
# Record 1 - Live record
with db.session.begin_nested():
rec_uuid = uui... | python | def records():
"""Load test data fixture."""
import uuid
from invenio_records.api import Record
from invenio_pidstore.models import PersistentIdentifier, PIDStatus
indexer = RecordIndexer()
index_queue = []
# Record 1 - Live record
with db.session.begin_nested():
rec_uuid = uui... | Load test data fixture. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/examples/app.py#L209-L282 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/base.py | PreprocessorMixin.preprocess_record | def preprocess_record(self, pid, record, links_factory=None, **kwargs):
"""Prepare a record and persistent identifier for serialization."""
links_factory = links_factory or (lambda x, record=None, **k: dict())
metadata = copy.deepcopy(record.replace_refs()) if self.replace_refs \
els... | python | def preprocess_record(self, pid, record, links_factory=None, **kwargs):
"""Prepare a record and persistent identifier for serialization."""
links_factory = links_factory or (lambda x, record=None, **k: dict())
metadata = copy.deepcopy(record.replace_refs()) if self.replace_refs \
els... | Prepare a record and persistent identifier for serialization. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/base.py#L140-L154 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/base.py | PreprocessorMixin.preprocess_search_hit | def preprocess_search_hit(pid, record_hit, links_factory=None, **kwargs):
"""Prepare a record hit from Elasticsearch for serialization."""
links_factory = links_factory or (lambda x, **k: dict())
record = dict(
pid=pid,
metadata=record_hit['_source'],
links=li... | python | def preprocess_search_hit(pid, record_hit, links_factory=None, **kwargs):
"""Prepare a record hit from Elasticsearch for serialization."""
links_factory = links_factory or (lambda x, **k: dict())
record = dict(
pid=pid,
metadata=record_hit['_source'],
links=li... | Prepare a record hit from Elasticsearch for serialization. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/base.py#L157-L173 |
inveniosoftware/invenio-records-rest | invenio_records_rest/loaders/marshmallow.py | _flatten_marshmallow_errors | def _flatten_marshmallow_errors(errors):
"""Flatten marshmallow errors."""
res = []
for field, error in errors.items():
if isinstance(error, list):
res.append(
dict(field=field, message=' '.join([str(x) for x in error])))
elif isinstance(error, dict):
... | python | def _flatten_marshmallow_errors(errors):
"""Flatten marshmallow errors."""
res = []
for field, error in errors.items():
if isinstance(error, list):
res.append(
dict(field=field, message=' '.join([str(x) for x in error])))
elif isinstance(error, dict):
... | Flatten marshmallow errors. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/loaders/marshmallow.py#L24-L33 |
inveniosoftware/invenio-records-rest | invenio_records_rest/loaders/marshmallow.py | marshmallow_loader | def marshmallow_loader(schema_class):
"""Marshmallow loader for JSON requests."""
def json_loader():
request_json = request.get_json()
context = {}
pid_data = request.view_args.get('pid_value')
if pid_data:
pid, _ = pid_data.data
context['pid'] = pid
... | python | def marshmallow_loader(schema_class):
"""Marshmallow loader for JSON requests."""
def json_loader():
request_json = request.get_json()
context = {}
pid_data = request.view_args.get('pid_value')
if pid_data:
pid, _ = pid_data.data
context['pid'] = pid
... | Marshmallow loader for JSON requests. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/loaders/marshmallow.py#L81-L97 |
inveniosoftware/invenio-records-rest | invenio_records_rest/loaders/marshmallow.py | MarshmallowErrors.get_body | def get_body(self, environ=None):
"""Get the request body."""
body = dict(
status=self.code,
message=self.get_description(environ),
)
if self.errors:
body['errors'] = self.errors
return json.dumps(body) | python | def get_body(self, environ=None):
"""Get the request body."""
body = dict(
status=self.code,
message=self.get_description(environ),
)
if self.errors:
body['errors'] = self.errors
return json.dumps(body) | Get the request body. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/loaders/marshmallow.py#L68-L78 |
inveniosoftware/invenio-records-rest | invenio_records_rest/ext.py | _RecordRESTState.reset_permission_factories | def reset_permission_factories(self):
"""Remove cached permission factories."""
for key in ('read', 'create', 'update', 'delete'):
full_key = '{0}_permission_factory'.format(key)
if full_key in self.__dict__:
del self.__dict__[full_key] | python | def reset_permission_factories(self):
"""Remove cached permission factories."""
for key in ('read', 'create', 'update', 'delete'):
full_key = '{0}_permission_factory'.format(key)
if full_key in self.__dict__:
del self.__dict__[full_key] | Remove cached permission factories. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/ext.py#L77-L82 |
inveniosoftware/invenio-records-rest | invenio_records_rest/ext.py | InvenioRecordsREST.init_app | def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
app.extensions['invenio-records-rest'] = _RecordRESTState(app) | python | def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
app.extensions['invenio-records-rest'] = _RecordRESTState(app) | Flask application initialization. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/ext.py#L93-L96 |
inveniosoftware/invenio-records-rest | invenio_records_rest/ext.py | InvenioRecordsREST.init_config | def init_config(self, app):
"""Initialize configuration."""
# Set up API endpoints for records.
for k in dir(config):
if k.startswith('RECORDS_REST_'):
app.config.setdefault(k, getattr(config, k))
# Resolve the Elasticsearch error handlers
handlers = ... | python | def init_config(self, app):
"""Initialize configuration."""
# Set up API endpoints for records.
for k in dir(config):
if k.startswith('RECORDS_REST_'):
app.config.setdefault(k, getattr(config, k))
# Resolve the Elasticsearch error handlers
handlers = ... | Initialize configuration. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/ext.py#L98-L108 |
inveniosoftware/invenio-records-rest | invenio_records_rest/facets.py | range_filter | def range_filter(field, start_date_math=None, end_date_math=None, **kwargs):
"""Create a range filter.
:param field: Field name.
:param start_date_math: Starting date.
:param end_date_math: Ending date.
:param kwargs: Addition arguments passed to the Range query.
:returns: Function that returns... | python | def range_filter(field, start_date_math=None, end_date_math=None, **kwargs):
"""Create a range filter.
:param field: Field name.
:param start_date_math: Starting date.
:param end_date_math: Ending date.
:param kwargs: Addition arguments passed to the Range query.
:returns: Function that returns... | Create a range filter.
:param field: Field name.
:param start_date_math: Starting date.
:param end_date_math: Ending date.
:param kwargs: Addition arguments passed to the Range query.
:returns: Function that returns the Range query. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/facets.py#L36-L79 |
inveniosoftware/invenio-records-rest | invenio_records_rest/facets.py | _create_filter_dsl | def _create_filter_dsl(urlkwargs, definitions):
"""Create a filter DSL expression."""
filters = []
for name, filter_factory in definitions.items():
values = request.values.getlist(name, type=text_type)
if values:
filters.append(filter_factory(values))
for v in values:... | python | def _create_filter_dsl(urlkwargs, definitions):
"""Create a filter DSL expression."""
filters = []
for name, filter_factory in definitions.items():
values = request.values.getlist(name, type=text_type)
if values:
filters.append(filter_factory(values))
for v in values:... | Create a filter DSL expression. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/facets.py#L82-L92 |
inveniosoftware/invenio-records-rest | invenio_records_rest/facets.py | _post_filter | def _post_filter(search, urlkwargs, definitions):
"""Ingest post filter in query."""
filters, urlkwargs = _create_filter_dsl(urlkwargs, definitions)
for filter_ in filters:
search = search.post_filter(filter_)
return (search, urlkwargs) | python | def _post_filter(search, urlkwargs, definitions):
"""Ingest post filter in query."""
filters, urlkwargs = _create_filter_dsl(urlkwargs, definitions)
for filter_ in filters:
search = search.post_filter(filter_)
return (search, urlkwargs) | Ingest post filter in query. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/facets.py#L95-L102 |
inveniosoftware/invenio-records-rest | invenio_records_rest/facets.py | _query_filter | def _query_filter(search, urlkwargs, definitions):
"""Ingest query filter in query."""
filters, urlkwargs = _create_filter_dsl(urlkwargs, definitions)
for filter_ in filters:
search = search.filter(filter_)
return (search, urlkwargs) | python | def _query_filter(search, urlkwargs, definitions):
"""Ingest query filter in query."""
filters, urlkwargs = _create_filter_dsl(urlkwargs, definitions)
for filter_ in filters:
search = search.filter(filter_)
return (search, urlkwargs) | Ingest query filter in query. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/facets.py#L105-L112 |
inveniosoftware/invenio-records-rest | invenio_records_rest/facets.py | _aggregations | def _aggregations(search, definitions):
"""Add aggregations to query."""
if definitions:
for name, agg in definitions.items():
search.aggs[name] = agg if not callable(agg) else agg()
return search | python | def _aggregations(search, definitions):
"""Add aggregations to query."""
if definitions:
for name, agg in definitions.items():
search.aggs[name] = agg if not callable(agg) else agg()
return search | Add aggregations to query. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/facets.py#L115-L120 |
inveniosoftware/invenio-records-rest | invenio_records_rest/facets.py | default_facets_factory | def default_facets_factory(search, index):
"""Add a default facets to query.
:param search: Basic search object.
:param index: Index name.
:returns: A tuple containing the new search object and a dictionary with
all fields and values used.
"""
urlkwargs = MultiDict()
facets = curre... | python | def default_facets_factory(search, index):
"""Add a default facets to query.
:param search: Basic search object.
:param index: Index name.
:returns: A tuple containing the new search object and a dictionary with
all fields and values used.
"""
urlkwargs = MultiDict()
facets = curre... | Add a default facets to query.
:param search: Basic search object.
:param index: Index name.
:returns: A tuple containing the new search object and a dictionary with
all fields and values used. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/facets.py#L123-L147 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/marshmallow.py | MarshmallowMixin.dump | def dump(self, obj, context=None):
"""Serialize object with schema."""
return self.schema_class(context=context).dump(obj).data | python | def dump(self, obj, context=None):
"""Serialize object with schema."""
return self.schema_class(context=context).dump(obj).data | Serialize object with schema. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/marshmallow.py#L26-L28 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/marshmallow.py | MarshmallowMixin.transform_record | def transform_record(self, pid, record, links_factory=None, **kwargs):
"""Transform record into an intermediate representation."""
context = kwargs.get('marshmallow_context', {})
context.setdefault('pid', pid)
return self.dump(self.preprocess_record(pid, record,
... | python | def transform_record(self, pid, record, links_factory=None, **kwargs):
"""Transform record into an intermediate representation."""
context = kwargs.get('marshmallow_context', {})
context.setdefault('pid', pid)
return self.dump(self.preprocess_record(pid, record,
... | Transform record into an intermediate representation. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/marshmallow.py#L30-L35 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/marshmallow.py | MarshmallowMixin.transform_search_hit | def transform_search_hit(self, pid, record_hit, links_factory=None,
**kwargs):
"""Transform search result hit into an intermediate representation."""
context = kwargs.get('marshmallow_context', {})
context.setdefault('pid', pid)
return self.dump(self.preproce... | python | def transform_search_hit(self, pid, record_hit, links_factory=None,
**kwargs):
"""Transform search result hit into an intermediate representation."""
context = kwargs.get('marshmallow_context', {})
context.setdefault('pid', pid)
return self.dump(self.preproce... | Transform search result hit into an intermediate representation. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/marshmallow.py#L37-L43 |
inveniosoftware/invenio-records-rest | invenio_records_rest/schemas/fields/persistentidentifier.py | pid_from_context | def pid_from_context(_, context):
"""Get PID from marshmallow context."""
pid = (context or {}).get('pid')
return pid.pid_value if pid else missing | python | def pid_from_context(_, context):
"""Get PID from marshmallow context."""
pid = (context or {}).get('pid')
return pid.pid_value if pid else missing | Get PID from marshmallow context. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/schemas/fields/persistentidentifier.py#L16-L19 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/response.py | record_responsify | def record_responsify(serializer, mimetype):
"""Create a Records-REST response serializer.
:param serializer: Serializer instance.
:param mimetype: MIME type of response.
:returns: Function that generates a record HTTP response.
"""
def view(pid, record, code=200, headers=None, links_factory=No... | python | def record_responsify(serializer, mimetype):
"""Create a Records-REST response serializer.
:param serializer: Serializer instance.
:param mimetype: MIME type of response.
:returns: Function that generates a record HTTP response.
"""
def view(pid, record, code=200, headers=None, links_factory=No... | Create a Records-REST response serializer.
:param serializer: Serializer instance.
:param mimetype: MIME type of response.
:returns: Function that generates a record HTTP response. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/response.py#L19-L41 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/response.py | search_responsify | def search_responsify(serializer, mimetype):
"""Create a Records-REST search result response serializer.
:param serializer: Serializer instance.
:param mimetype: MIME type of response.
:returns: Function that generates a record HTTP response.
"""
def view(pid_fetcher, search_result, code=200, h... | python | def search_responsify(serializer, mimetype):
"""Create a Records-REST search result response serializer.
:param serializer: Serializer instance.
:param mimetype: MIME type of response.
:returns: Function that generates a record HTTP response.
"""
def view(pid_fetcher, search_result, code=200, h... | Create a Records-REST search result response serializer.
:param serializer: Serializer instance.
:param mimetype: MIME type of response.
:returns: Function that generates a record HTTP response. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/response.py#L44-L67 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/response.py | add_link_header | def add_link_header(response, links):
"""Add a Link HTTP header to a REST response.
:param response: REST response instance
:param links: Dictionary of links
"""
if links is not None:
response.headers.extend({
'Link': ', '.join([
'<{0}>; rel="{1}"'.format(l, r) f... | python | def add_link_header(response, links):
"""Add a Link HTTP header to a REST response.
:param response: REST response instance
:param links: Dictionary of links
"""
if links is not None:
response.headers.extend({
'Link': ', '.join([
'<{0}>; rel="{1}"'.format(l, r) f... | Add a Link HTTP header to a REST response.
:param response: REST response instance
:param links: Dictionary of links | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/response.py#L70-L80 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/citeproc.py | CiteprocSerializer._get_args | def _get_args(cls, **kwargs):
"""Parse style and locale.
Argument location precedence: kwargs > view_args > query
"""
csl_args = {
'style': cls._default_style,
'locale': cls._default_locale
}
if has_request_context():
parser = FlaskPa... | python | def _get_args(cls, **kwargs):
"""Parse style and locale.
Argument location precedence: kwargs > view_args > query
"""
csl_args = {
'style': cls._default_style,
'locale': cls._default_locale
}
if has_request_context():
parser = FlaskPa... | Parse style and locale.
Argument location precedence: kwargs > view_args > query | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/citeproc.py#L79-L102 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/citeproc.py | CiteprocSerializer._get_source | def _get_source(self, data):
"""Get source data object for citeproc-py."""
if self.record_format == 'csl':
return CiteProcJSON([json.loads(data)])
elif self.record_format == 'bibtex':
return BibTeX(data) | python | def _get_source(self, data):
"""Get source data object for citeproc-py."""
if self.record_format == 'csl':
return CiteProcJSON([json.loads(data)])
elif self.record_format == 'bibtex':
return BibTeX(data) | Get source data object for citeproc-py. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/citeproc.py#L104-L109 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/citeproc.py | CiteprocSerializer._clean_result | def _clean_result(self, text):
"""Remove double spaces, punctuation and escapes apostrophes."""
text = re.sub('\s\s+', ' ', text)
text = re.sub('\.\.+', '.', text)
text = text.replace("'", "\\'")
return text | python | def _clean_result(self, text):
"""Remove double spaces, punctuation and escapes apostrophes."""
text = re.sub('\s\s+', ' ', text)
text = re.sub('\.\.+', '.', text)
text = text.replace("'", "\\'")
return text | Remove double spaces, punctuation and escapes apostrophes. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/citeproc.py#L111-L116 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/citeproc.py | CiteprocSerializer.serialize | def serialize(self, pid, record, links_factory=None, **kwargs):
"""Serialize a single record.
:param pid: Persistent identifier instance.
:param record: Record instance.
:param links_factory: Factory function for record links.
"""
data = self.serializer.serialize(pid, re... | python | def serialize(self, pid, record, links_factory=None, **kwargs):
"""Serialize a single record.
:param pid: Persistent identifier instance.
:param record: Record instance.
:param links_factory: Factory function for record links.
"""
data = self.serializer.serialize(pid, re... | Serialize a single record.
:param pid: Persistent identifier instance.
:param record: Record instance.
:param links_factory: Factory function for record links. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/citeproc.py#L118-L132 |
inveniosoftware/invenio-records-rest | invenio_records_rest/schemas/fields/sanitizedunicode.py | SanitizedUnicode.is_valid_xml_char | def is_valid_xml_char(self, char):
"""Check if a character is valid based on the XML specification."""
codepoint = ord(char)
return (0x20 <= codepoint <= 0xD7FF or
codepoint in (0x9, 0xA, 0xD) or
0xE000 <= codepoint <= 0xFFFD or
0x10000 <= codepoin... | python | def is_valid_xml_char(self, char):
"""Check if a character is valid based on the XML specification."""
codepoint = ord(char)
return (0x20 <= codepoint <= 0xD7FF or
codepoint in (0x9, 0xA, 0xD) or
0xE000 <= codepoint <= 0xFFFD or
0x10000 <= codepoin... | Check if a character is valid based on the XML specification. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/schemas/fields/sanitizedunicode.py#L26-L32 |
inveniosoftware/invenio-records-rest | invenio_records_rest/schemas/fields/sanitizedunicode.py | SanitizedUnicode._deserialize | def _deserialize(self, value, attr, data):
"""Deserialize sanitized string value."""
value = super(SanitizedUnicode, self)._deserialize(value, attr, data)
value = fix_text(value)
# NOTE: This `join` might be ineffiecient... There's a solution with a
# large compiled regex lying ... | python | def _deserialize(self, value, attr, data):
"""Deserialize sanitized string value."""
value = super(SanitizedUnicode, self)._deserialize(value, attr, data)
value = fix_text(value)
# NOTE: This `join` might be ineffiecient... There's a solution with a
# large compiled regex lying ... | Deserialize sanitized string value. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/schemas/fields/sanitizedunicode.py#L34-L44 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/datacite.py | BaseDataCiteSerializer.serialize | def serialize(self, pid, record, links_factory=None):
"""Serialize a single record and persistent identifier.
:param pid: Persistent identifier instance.
:param record: Record instance.
:param links_factory: Factory function for record links.
"""
return self.schema.tostr... | python | def serialize(self, pid, record, links_factory=None):
"""Serialize a single record and persistent identifier.
:param pid: Persistent identifier instance.
:param record: Record instance.
:param links_factory: Factory function for record links.
"""
return self.schema.tostr... | Serialize a single record and persistent identifier.
:param pid: Persistent identifier instance.
:param record: Record instance.
:param links_factory: Factory function for record links. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/datacite.py#L34-L42 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/datacite.py | BaseDataCiteSerializer.serialize_search | def serialize_search(self, pid_fetcher, search_result, links=None,
item_links_factory=None):
"""Serialize a search result.
:param pid_fetcher: Persistent identifier fetcher.
:param search_result: Elasticsearch search result.
:param links: Dictionary of links to ... | python | def serialize_search(self, pid_fetcher, search_result, links=None,
item_links_factory=None):
"""Serialize a search result.
:param pid_fetcher: Persistent identifier fetcher.
:param search_result: Elasticsearch search result.
:param links: Dictionary of links to ... | Serialize a search result.
:param pid_fetcher: Persistent identifier fetcher.
:param search_result: Elasticsearch search result.
:param links: Dictionary of links to add to response. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/datacite.py#L44-L60 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/datacite.py | BaseDataCiteSerializer.serialize_oaipmh | def serialize_oaipmh(self, pid, record):
"""Serialize a single record for OAI-PMH."""
obj = self.transform_record(pid, record['_source']) \
if isinstance(record['_source'], Record) \
else self.transform_search_hit(pid, record)
return self.schema.dump_etree(obj) | python | def serialize_oaipmh(self, pid, record):
"""Serialize a single record for OAI-PMH."""
obj = self.transform_record(pid, record['_source']) \
if isinstance(record['_source'], Record) \
else self.transform_search_hit(pid, record)
return self.schema.dump_etree(obj) | Serialize a single record for OAI-PMH. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/datacite.py#L62-L68 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/datacite.py | OAIDataCiteSerializer.serialize_oaipmh | def serialize_oaipmh(self, pid, record):
"""Serialize a single record for OAI-PMH."""
root = etree.Element(
'oai_datacite',
nsmap={
None: 'http://schema.datacite.org/oai/oai-1.0/',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
... | python | def serialize_oaipmh(self, pid, record):
"""Serialize a single record for OAI-PMH."""
root = etree.Element(
'oai_datacite',
nsmap={
None: 'http://schema.datacite.org/oai/oai-1.0/',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
... | Serialize a single record for OAI-PMH. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/datacite.py#L120-L142 |
inveniosoftware/invenio-records-rest | invenio_records_rest/schemas/fields/trimmedstring.py | TrimmedString._deserialize | def _deserialize(self, value, attr, data):
"""Deserialize string value."""
value = super(TrimmedString, self)._deserialize(value, attr, data)
return value.strip() | python | def _deserialize(self, value, attr, data):
"""Deserialize string value."""
value = super(TrimmedString, self)._deserialize(value, attr, data)
return value.strip() | Deserialize string value. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/schemas/fields/trimmedstring.py#L19-L22 |
inveniosoftware/invenio-records-rest | invenio_records_rest/query.py | default_search_factory | def default_search_factory(self, search, query_parser=None):
"""Parse query using elasticsearch DSL query.
:param self: REST view.
:param search: Elastic search DSL search instance.
:returns: Tuple with search instance and URL arguments.
"""
def _default_parser(qstr=None):
"""Default pa... | python | def default_search_factory(self, search, query_parser=None):
"""Parse query using elasticsearch DSL query.
:param self: REST view.
:param search: Elastic search DSL search instance.
:returns: Tuple with search instance and URL arguments.
"""
def _default_parser(qstr=None):
"""Default pa... | Parse query using elasticsearch DSL query.
:param self: REST view.
:param search: Elastic search DSL search instance.
:returns: Tuple with search instance and URL arguments. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/query.py#L19-L54 |
inveniosoftware/invenio-records-rest | invenio_records_rest/schemas/fields/marshmallow_contrib.py | _get_func_args | def _get_func_args(func):
"""Get a list of the arguments a function or method has."""
if isinstance(func, functools.partial):
return _get_func_args(func.func)
if inspect.isfunction(func) or inspect.ismethod(func):
return list(inspect.getargspec(func).args)
if callable(func):
retu... | python | def _get_func_args(func):
"""Get a list of the arguments a function or method has."""
if isinstance(func, functools.partial):
return _get_func_args(func.func)
if inspect.isfunction(func) or inspect.ismethod(func):
return list(inspect.getargspec(func).args)
if callable(func):
retu... | Get a list of the arguments a function or method has. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/schemas/fields/marshmallow_contrib.py#L19-L26 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/dc.py | DublinCoreSerializer.serialize | def serialize(self, pid, record, links_factory=None):
"""Serialize a single record and persistent identifier.
:param pid: Persistent identifier instance.
:param record: Record instance.
:param links_factory: Factory function for record links.
"""
return simpledc.tostring... | python | def serialize(self, pid, record, links_factory=None):
"""Serialize a single record and persistent identifier.
:param pid: Persistent identifier instance.
:param record: Record instance.
:param links_factory: Factory function for record links.
"""
return simpledc.tostring... | Serialize a single record and persistent identifier.
:param pid: Persistent identifier instance.
:param record: Record instance.
:param links_factory: Factory function for record links. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/dc.py#L28-L36 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/jsonld.py | JSONLDTransformerMixin.expanded | def expanded(self):
"""Get JSON-LD expanded state."""
# Ensure we can run outside a application/request context.
if request:
if 'expanded' in request.args:
return True
elif 'compacted' in request.args:
return False
return self._expa... | python | def expanded(self):
"""Get JSON-LD expanded state."""
# Ensure we can run outside a application/request context.
if request:
if 'expanded' in request.args:
return True
elif 'compacted' in request.args:
return False
return self._expa... | Get JSON-LD expanded state. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/jsonld.py#L43-L51 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/jsonld.py | JSONLDTransformerMixin.transform_jsonld | def transform_jsonld(self, obj):
"""Compact JSON according to context."""
rec = copy.deepcopy(obj)
rec.update(self.context)
compacted = jsonld.compact(rec, self.context)
if not self.expanded:
return compacted
else:
return jsonld.expand(compacted)[0... | python | def transform_jsonld(self, obj):
"""Compact JSON according to context."""
rec = copy.deepcopy(obj)
rec.update(self.context)
compacted = jsonld.compact(rec, self.context)
if not self.expanded:
return compacted
else:
return jsonld.expand(compacted)[0... | Compact JSON according to context. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/jsonld.py#L53-L61 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/jsonld.py | JSONLDTransformerMixin.transform_record | def transform_record(self, pid, record, links_factory=None, **kwargs):
"""Transform record into an intermediate representation."""
result = super(JSONLDTransformerMixin, self).transform_record(
pid, record, links_factory, **kwargs
)
return self.transform_jsonld(result) | python | def transform_record(self, pid, record, links_factory=None, **kwargs):
"""Transform record into an intermediate representation."""
result = super(JSONLDTransformerMixin, self).transform_record(
pid, record, links_factory, **kwargs
)
return self.transform_jsonld(result) | Transform record into an intermediate representation. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/jsonld.py#L63-L68 |
inveniosoftware/invenio-records-rest | invenio_records_rest/serializers/jsonld.py | JSONLDTransformerMixin.transform_search_hit | def transform_search_hit(self, pid, record_hit, links_factory=None,
**kwargs):
"""Transform search result hit into an intermediate representation."""
result = super(JSONLDTransformerMixin, self).transform_search_hit(
pid, record_hit, links_factory, **kwargs
... | python | def transform_search_hit(self, pid, record_hit, links_factory=None,
**kwargs):
"""Transform search result hit into an intermediate representation."""
result = super(JSONLDTransformerMixin, self).transform_search_hit(
pid, record_hit, links_factory, **kwargs
... | Transform search result hit into an intermediate representation. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/jsonld.py#L70-L76 |
inveniosoftware/invenio-records-rest | invenio_records_rest/links.py | default_links_factory | def default_links_factory(pid, record=None, **kwargs):
"""Factory for record links generation.
:param pid: A Persistent Identifier instance.
:returns: Dictionary containing a list of useful links for the record.
"""
endpoint = '.{0}_item'.format(
current_records_rest.default_endpoint_prefix... | python | def default_links_factory(pid, record=None, **kwargs):
"""Factory for record links generation.
:param pid: A Persistent Identifier instance.
:returns: Dictionary containing a list of useful links for the record.
"""
endpoint = '.{0}_item'.format(
current_records_rest.default_endpoint_prefix... | Factory for record links generation.
:param pid: A Persistent Identifier instance.
:returns: Dictionary containing a list of useful links for the record. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/links.py#L20-L30 |
inveniosoftware/invenio-records-rest | invenio_records_rest/links.py | default_links_factory_with_additional | def default_links_factory_with_additional(additional_links):
"""Generate a links generation factory with the specified additional links.
:param additional_links: A dict of link names to links to be added to the
returned object.
:returns: A link generation factory.
"""
def factory(pid, **... | python | def default_links_factory_with_additional(additional_links):
"""Generate a links generation factory with the specified additional links.
:param additional_links: A dict of link names to links to be added to the
returned object.
:returns: A link generation factory.
"""
def factory(pid, **... | Generate a links generation factory with the specified additional links.
:param additional_links: A dict of link names to links to be added to the
returned object.
:returns: A link generation factory. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/links.py#L33-L48 |
inveniosoftware/invenio-records-rest | invenio_records_rest/sorter.py | geolocation_sort | def geolocation_sort(field_name, argument, unit, mode=None,
distance_type=None):
"""Sort field factory for geo-location based sorting.
:param argument: Name of URL query string field to parse pin location from.
Multiple locations can be provided. Each location can be either a
... | python | def geolocation_sort(field_name, argument, unit, mode=None,
distance_type=None):
"""Sort field factory for geo-location based sorting.
:param argument: Name of URL query string field to parse pin location from.
Multiple locations can be provided. Each location can be either a
... | Sort field factory for geo-location based sorting.
:param argument: Name of URL query string field to parse pin location from.
Multiple locations can be provided. Each location can be either a
string "latitude,longitude" or a geohash.
:param unit: Distance unit (e.g. km).
:param mode: Sort ... | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/sorter.py#L29-L55 |
inveniosoftware/invenio-records-rest | invenio_records_rest/sorter.py | eval_field | def eval_field(field, asc):
"""Evaluate a field for sorting purpose.
:param field: Field definition (string, dict or callable).
:param asc: ``True`` if order is ascending, ``False`` if descending.
:returns: Dictionary with the sort field query.
"""
if isinstance(field, dict):
if asc:
... | python | def eval_field(field, asc):
"""Evaluate a field for sorting purpose.
:param field: Field definition (string, dict or callable).
:param asc: ``True`` if order is ascending, ``False`` if descending.
:returns: Dictionary with the sort field query.
"""
if isinstance(field, dict):
if asc:
... | Evaluate a field for sorting purpose.
:param field: Field definition (string, dict or callable).
:param asc: ``True`` if order is ascending, ``False`` if descending.
:returns: Dictionary with the sort field query. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/sorter.py#L82-L104 |
inveniosoftware/invenio-records-rest | invenio_records_rest/sorter.py | default_sorter_factory | def default_sorter_factory(search, index):
"""Default sort query factory.
:param query: Search query.
:param index: Index to search in.
:returns: Tuple of (query, URL arguments).
"""
sort_arg_name = 'sort'
urlfield = request.values.get(sort_arg_name, '', type=str)
# Get default sorting... | python | def default_sorter_factory(search, index):
"""Default sort query factory.
:param query: Search query.
:param index: Index to search in.
:returns: Tuple of (query, URL arguments).
"""
sort_arg_name = 'sort'
urlfield = request.values.get(sort_arg_name, '', type=str)
# Get default sorting... | Default sort query factory.
:param query: Search query.
:param index: Index to search in.
:returns: Tuple of (query, URL arguments). | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/sorter.py#L107-L137 |
inveniosoftware/invenio-records-rest | invenio_records_rest/schemas/json.py | StrictKeysMixin.check_unknown_fields | def check_unknown_fields(self, data, original_data):
"""Check for unknown keys."""
if isinstance(original_data, list):
for elem in original_data:
self.check_unknown_fields(data, elem)
else:
for key in original_data:
if key not in [
... | python | def check_unknown_fields(self, data, original_data):
"""Check for unknown keys."""
if isinstance(original_data, list):
for elem in original_data:
self.check_unknown_fields(data, elem)
else:
for key in original_data:
if key not in [
... | Check for unknown keys. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/schemas/json.py#L24-L36 |
inveniosoftware/invenio-records-rest | invenio_records_rest/schemas/json.py | OriginalKeysMixin.load_unknown_fields | def load_unknown_fields(self, data, original_data):
"""Check for unknown keys."""
if isinstance(original_data, list):
for elem in original_data:
self.load_unknown_fields(data, elem)
else:
for key, value in original_data.items():
if key not ... | python | def load_unknown_fields(self, data, original_data):
"""Check for unknown keys."""
if isinstance(original_data, list):
for elem in original_data:
self.load_unknown_fields(data, elem)
else:
for key, value in original_data.items():
if key not ... | Check for unknown keys. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/schemas/json.py#L65-L74 |
inveniosoftware/invenio-records-rest | invenio_records_rest/schemas/json.py | RecordMetadataSchemaJSONV1.inject_pid | def inject_pid(self, data):
"""Inject context PID in the RECID field."""
# Remove already deserialized "pid" field
pid_value = data.pop('pid', None)
if pid_value:
pid_field = current_app.config['PIDSTORE_RECID_FIELD']
data.setdefault(pid_field, pid_value)
... | python | def inject_pid(self, data):
"""Inject context PID in the RECID field."""
# Remove already deserialized "pid" field
pid_value = data.pop('pid', None)
if pid_value:
pid_field = current_app.config['PIDSTORE_RECID_FIELD']
data.setdefault(pid_field, pid_value)
... | Inject context PID in the RECID field. | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/schemas/json.py#L83-L90 |
pydanny-archive/django-uni-form | uni_form/templatetags/uni_form_filters.py | as_uni_form | def as_uni_form(form):
"""
The original and still very useful way to generate a uni-form form/formset::
{% load uni_form_tags %}
<form class="uniForm" action="post">
{% csrf_token %}
{{ myform|as_uni_form }}
</form>
"""
if isinstance(form, BaseFormS... | python | def as_uni_form(form):
"""
The original and still very useful way to generate a uni-form form/formset::
{% load uni_form_tags %}
<form class="uniForm" action="post">
{% csrf_token %}
{{ myform|as_uni_form }}
</form>
"""
if isinstance(form, BaseFormS... | The original and still very useful way to generate a uni-form form/formset::
{% load uni_form_tags %}
<form class="uniForm" action="post">
{% csrf_token %}
{{ myform|as_uni_form }}
</form> | https://github.com/pydanny-archive/django-uni-form/blob/159f539e2fb98752b7964d75e955fc62881c28fb/uni_form/templatetags/uni_form_filters.py#L16-L39 |
pydanny-archive/django-uni-form | uni_form/templatetags/uni_form_filters.py | as_uni_errors | def as_uni_errors(form):
"""
Renders only form errors like django-uni-form::
{% load uni_form_tags %}
{{ form|as_uni_errors }}
"""
if isinstance(form, BaseFormSet):
template = get_template('uni_form/errors_formset.html')
c = Context({'formset': form})
else:
t... | python | def as_uni_errors(form):
"""
Renders only form errors like django-uni-form::
{% load uni_form_tags %}
{{ form|as_uni_errors }}
"""
if isinstance(form, BaseFormSet):
template = get_template('uni_form/errors_formset.html')
c = Context({'formset': form})
else:
t... | Renders only form errors like django-uni-form::
{% load uni_form_tags %}
{{ form|as_uni_errors }} | https://github.com/pydanny-archive/django-uni-form/blob/159f539e2fb98752b7964d75e955fc62881c28fb/uni_form/templatetags/uni_form_filters.py#L42-L55 |
pydanny-archive/django-uni-form | uni_form/templatetags/uni_form_filters.py | as_uni_field | def as_uni_field(field):
"""
Renders a form field like a django-uni-form field::
{% load uni_form_tags %}
{{ form.field|as_uni_field }}
"""
template = get_template('uni_form/field.html')
c = Context({'field':field})
return template.render(c) | python | def as_uni_field(field):
"""
Renders a form field like a django-uni-form field::
{% load uni_form_tags %}
{{ form.field|as_uni_field }}
"""
template = get_template('uni_form/field.html')
c = Context({'field':field})
return template.render(c) | Renders a form field like a django-uni-form field::
{% load uni_form_tags %}
{{ form.field|as_uni_field }} | https://github.com/pydanny-archive/django-uni-form/blob/159f539e2fb98752b7964d75e955fc62881c28fb/uni_form/templatetags/uni_form_filters.py#L58-L67 |
pydanny-archive/django-uni-form | uni_form/layout.py | BaseInput.render | def render(self, form, form_style, context):
"""
Renders an `<input />` if container is used as a Layout object
"""
return render_to_string(self.template, Context({'input': self})) | python | def render(self, form, form_style, context):
"""
Renders an `<input />` if container is used as a Layout object
"""
return render_to_string(self.template, Context({'input': self})) | Renders an `<input />` if container is used as a Layout object | https://github.com/pydanny-archive/django-uni-form/blob/159f539e2fb98752b7964d75e955fc62881c28fb/uni_form/layout.py#L95-L99 |
pydanny-archive/django-uni-form | uni_form/utils.py | render_field | def render_field(field, form, form_style, context, template=None, labelclass=None, layout_object=None):
"""
Renders a django-uni-form field
:param field: Can be a string or a Layout object like `Row`. If it's a layout
object, we call its render method, otherwise we instantiate a BoundField
... | python | def render_field(field, form, form_style, context, template=None, labelclass=None, layout_object=None):
"""
Renders a django-uni-form field
:param field: Can be a string or a Layout object like `Row`. If it's a layout
object, we call its render method, otherwise we instantiate a BoundField
... | Renders a django-uni-form field
:param field: Can be a string or a Layout object like `Row`. If it's a layout
object, we call its render method, otherwise we instantiate a BoundField
and render it using default template 'uni_form/field.html'
The field is added to a list that the form ho... | https://github.com/pydanny-archive/django-uni-form/blob/159f539e2fb98752b7964d75e955fc62881c28fb/uni_form/utils.py#L14-L84 |
pydanny-archive/django-uni-form | uni_form/templatetags/uni_form_tags.py | do_uni_form | def do_uni_form(parser, token):
"""
You need to pass in at least the form/formset object, and can also pass in the
optional `uni_form.helpers.FormHelper` object.
helper (optional): A `uni_form.helpers.FormHelper` object.
Usage::
{% include uni_form_tags %}
{% uni_form my-for... | python | def do_uni_form(parser, token):
"""
You need to pass in at least the form/formset object, and can also pass in the
optional `uni_form.helpers.FormHelper` object.
helper (optional): A `uni_form.helpers.FormHelper` object.
Usage::
{% include uni_form_tags %}
{% uni_form my-for... | You need to pass in at least the form/formset object, and can also pass in the
optional `uni_form.helpers.FormHelper` object.
helper (optional): A `uni_form.helpers.FormHelper` object.
Usage::
{% include uni_form_tags %}
{% uni_form my-form my_helper %} | https://github.com/pydanny-archive/django-uni-form/blob/159f539e2fb98752b7964d75e955fc62881c28fb/uni_form/templatetags/uni_form_tags.py#L165-L187 |
pydanny-archive/django-uni-form | uni_form/templatetags/uni_form_tags.py | BasicNode.get_render | def get_render(self, context):
"""
Returns a `Context` object with all the necesarry stuff for rendering the form
:param context: `django.template.Context` variable holding the context for the node
`self.form` and `self.helper` are resolved into real Python objects resolving them
... | python | def get_render(self, context):
"""
Returns a `Context` object with all the necesarry stuff for rendering the form
:param context: `django.template.Context` variable holding the context for the node
`self.form` and `self.helper` are resolved into real Python objects resolving them
... | Returns a `Context` object with all the necesarry stuff for rendering the form
:param context: `django.template.Context` variable holding the context for the node
`self.form` and `self.helper` are resolved into real Python objects resolving them
from the `context`. The `actual_form` can be a f... | https://github.com/pydanny-archive/django-uni-form/blob/159f539e2fb98752b7964d75e955fc62881c28fb/uni_form/templatetags/uni_form_tags.py#L66-L108 |
pydanny-archive/django-uni-form | uni_form/templatetags/uni_form_tags.py | BasicNode.get_response_dict | def get_response_dict(self, attrs, context, is_formset):
"""
Returns a dictionary with all the parameters necessary to render the form/formset in a template.
:param attrs: Dictionary with the helper's attributes used for rendering the form/formset
:param context: `django.templat... | python | def get_response_dict(self, attrs, context, is_formset):
"""
Returns a dictionary with all the parameters necessary to render the form/formset in a template.
:param attrs: Dictionary with the helper's attributes used for rendering the form/formset
:param context: `django.templat... | Returns a dictionary with all the parameters necessary to render the form/formset in a template.
:param attrs: Dictionary with the helper's attributes used for rendering the form/formset
:param context: `django.template.Context` for the node
:param is_formset: Boolean value. If set to T... | https://github.com/pydanny-archive/django-uni-form/blob/159f539e2fb98752b7964d75e955fc62881c28fb/uni_form/templatetags/uni_form_tags.py#L110-L139 |
pydanny-archive/django-uni-form | uni_form/helper.py | FormHelper.render_layout | def render_layout(self, form, context):
"""
Returns safe html of the rendering of the layout
"""
form.rendered_fields = []
html = self.layout.render(form, self.form_style, context)
for field in form.fields.keys():
if not field in form.rendered_fields... | python | def render_layout(self, form, context):
"""
Returns safe html of the rendering of the layout
"""
form.rendered_fields = []
html = self.layout.render(form, self.form_style, context)
for field in form.fields.keys():
if not field in form.rendered_fields... | Returns safe html of the rendering of the layout | https://github.com/pydanny-archive/django-uni-form/blob/159f539e2fb98752b7964d75e955fc62881c28fb/uni_form/helper.py#L156-L168 |
pydanny-archive/django-uni-form | uni_form/helper.py | FormHelper.get_attributes | def get_attributes(self):
"""
Used by the uni_form_tags to get helper attributes
"""
items = {}
items['form_method'] = self.form_method.strip()
items['form_tag'] = self.form_tag
items['form_style'] = self.form_style.strip()
if self.form_action:
... | python | def get_attributes(self):
"""
Used by the uni_form_tags to get helper attributes
"""
items = {}
items['form_method'] = self.form_method.strip()
items['form_tag'] = self.form_tag
items['form_style'] = self.form_style.strip()
if self.form_action:
... | Used by the uni_form_tags to get helper attributes | https://github.com/pydanny-archive/django-uni-form/blob/159f539e2fb98752b7964d75e955fc62881c28fb/uni_form/helper.py#L170-L191 |
lpantano/seqcluster | seqcluster/libs/classes.py | sequence_unique.add_exp | def add_exp(self,gr,exp):
"""Function to add the counts for each sample
:param gr: name of the sample
:param exp: counts of sample **gr**
:returns: dict with key,values equally to name,counts.
"""
self.group[gr] = exp
self.total = sum(self.group.values()) | python | def add_exp(self,gr,exp):
"""Function to add the counts for each sample
:param gr: name of the sample
:param exp: counts of sample **gr**
:returns: dict with key,values equally to name,counts.
"""
self.group[gr] = exp
self.total = sum(self.group.values()) | Function to add the counts for each sample
:param gr: name of the sample
:param exp: counts of sample **gr**
:returns: dict with key,values equally to name,counts. | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/classes.py#L21-L30 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakeJoint | def MakeJoint(pmf1, pmf2):
"""Joint distribution of values from pmf1 and pmf2.
Args:
pmf1: Pmf object
pmf2: Pmf object
Returns:
Joint pmf of value pairs
"""
joint = Joint()
for v1, p1 in pmf1.Items():
for v2, p2 in pmf2.Items():
joint.Set((v1, v2), p... | python | def MakeJoint(pmf1, pmf2):
"""Joint distribution of values from pmf1 and pmf2.
Args:
pmf1: Pmf object
pmf2: Pmf object
Returns:
Joint pmf of value pairs
"""
joint = Joint()
for v1, p1 in pmf1.Items():
for v2, p2 in pmf2.Items():
joint.Set((v1, v2), p... | Joint distribution of values from pmf1 and pmf2.
Args:
pmf1: Pmf object
pmf2: Pmf object
Returns:
Joint pmf of value pairs | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L702-L716 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakeHistFromList | def MakeHistFromList(t, name=''):
"""Makes a histogram from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this histogram
Returns:
Hist object
"""
hist = Hist(name=name)
[hist.Incr(x) for x in t]
return hist | python | def MakeHistFromList(t, name=''):
"""Makes a histogram from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this histogram
Returns:
Hist object
"""
hist = Hist(name=name)
[hist.Incr(x) for x in t]
return hist | Makes a histogram from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this histogram
Returns:
Hist object | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L719-L731 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakePmfFromList | def MakePmfFromList(t, name=''):
"""Makes a PMF from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this PMF
Returns:
Pmf object
"""
hist = MakeHistFromList(t)
d = hist.GetDict()
pmf = Pmf(d, name)
pmf.Normalize()
return p... | python | def MakePmfFromList(t, name=''):
"""Makes a PMF from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this PMF
Returns:
Pmf object
"""
hist = MakeHistFromList(t)
d = hist.GetDict()
pmf = Pmf(d, name)
pmf.Normalize()
return p... | Makes a PMF from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this PMF
Returns:
Pmf object | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L747-L761 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakePmfFromDict | def MakePmfFromDict(d, name=''):
"""Makes a PMF from a map from values to probabilities.
Args:
d: dictionary that maps values to probabilities
name: string name for this PMF
Returns:
Pmf object
"""
pmf = Pmf(d, name)
pmf.Normalize()
return pmf | python | def MakePmfFromDict(d, name=''):
"""Makes a PMF from a map from values to probabilities.
Args:
d: dictionary that maps values to probabilities
name: string name for this PMF
Returns:
Pmf object
"""
pmf = Pmf(d, name)
pmf.Normalize()
return pmf | Makes a PMF from a map from values to probabilities.
Args:
d: dictionary that maps values to probabilities
name: string name for this PMF
Returns:
Pmf object | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L764-L776 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakePmfFromItems | def MakePmfFromItems(t, name=''):
"""Makes a PMF from a sequence of value-probability pairs
Args:
t: sequence of value-probability pairs
name: string name for this PMF
Returns:
Pmf object
"""
pmf = Pmf(dict(t), name)
pmf.Normalize()
return pmf | python | def MakePmfFromItems(t, name=''):
"""Makes a PMF from a sequence of value-probability pairs
Args:
t: sequence of value-probability pairs
name: string name for this PMF
Returns:
Pmf object
"""
pmf = Pmf(dict(t), name)
pmf.Normalize()
return pmf | Makes a PMF from a sequence of value-probability pairs
Args:
t: sequence of value-probability pairs
name: string name for this PMF
Returns:
Pmf object | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L779-L791 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakePmfFromHist | def MakePmfFromHist(hist, name=None):
"""Makes a normalized PMF from a Hist object.
Args:
hist: Hist object
name: string name
Returns:
Pmf object
"""
if name is None:
name = hist.name
# make a copy of the dictionary
d = dict(hist.GetDict())
pmf = Pmf(d,... | python | def MakePmfFromHist(hist, name=None):
"""Makes a normalized PMF from a Hist object.
Args:
hist: Hist object
name: string name
Returns:
Pmf object
"""
if name is None:
name = hist.name
# make a copy of the dictionary
d = dict(hist.GetDict())
pmf = Pmf(d,... | Makes a normalized PMF from a Hist object.
Args:
hist: Hist object
name: string name
Returns:
Pmf object | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L794-L811 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakePmfFromCdf | def MakePmfFromCdf(cdf, name=None):
"""Makes a normalized Pmf from a Cdf object.
Args:
cdf: Cdf object
name: string name for the new Pmf
Returns:
Pmf object
"""
if name is None:
name = cdf.name
pmf = Pmf(name=name)
prev = 0.0
for val, prob in cdf.Items... | python | def MakePmfFromCdf(cdf, name=None):
"""Makes a normalized Pmf from a Cdf object.
Args:
cdf: Cdf object
name: string name for the new Pmf
Returns:
Pmf object
"""
if name is None:
name = cdf.name
pmf = Pmf(name=name)
prev = 0.0
for val, prob in cdf.Items... | Makes a normalized Pmf from a Cdf object.
Args:
cdf: Cdf object
name: string name for the new Pmf
Returns:
Pmf object | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L814-L834 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakeMixture | def MakeMixture(metapmf, name='mix'):
"""Make a mixture distribution.
Args:
metapmf: Pmf that maps from Pmfs to probs.
name: string name for the new Pmf.
Returns: Pmf object.
"""
mix = Pmf(name=name)
for pmf, p1 in metapmf.Items():
for x, p2 in pmf.Items():
mix.... | python | def MakeMixture(metapmf, name='mix'):
"""Make a mixture distribution.
Args:
metapmf: Pmf that maps from Pmfs to probs.
name: string name for the new Pmf.
Returns: Pmf object.
"""
mix = Pmf(name=name)
for pmf, p1 in metapmf.Items():
for x, p2 in pmf.Items():
mix.... | Make a mixture distribution.
Args:
metapmf: Pmf that maps from Pmfs to probs.
name: string name for the new Pmf.
Returns: Pmf object. | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L837-L850 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakeUniformPmf | def MakeUniformPmf(low, high, n):
"""Make a uniform Pmf.
low: lowest value (inclusive)
high: highest value (inclusize)
n: number of values
"""
pmf = Pmf()
for x in numpy.linspace(low, high, n):
pmf.Set(x, 1)
pmf.Normalize()
return pmf | python | def MakeUniformPmf(low, high, n):
"""Make a uniform Pmf.
low: lowest value (inclusive)
high: highest value (inclusize)
n: number of values
"""
pmf = Pmf()
for x in numpy.linspace(low, high, n):
pmf.Set(x, 1)
pmf.Normalize()
return pmf | Make a uniform Pmf.
low: lowest value (inclusive)
high: highest value (inclusize)
n: number of values | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L853-L864 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakeCdfFromItems | def MakeCdfFromItems(items, name=''):
"""Makes a cdf from an unsorted sequence of (value, frequency) pairs.
Args:
items: unsorted sequence of (value, frequency) pairs
name: string name for this CDF
Returns:
cdf: list of (value, fraction) pairs
"""
runsum = 0
xs = []
... | python | def MakeCdfFromItems(items, name=''):
"""Makes a cdf from an unsorted sequence of (value, frequency) pairs.
Args:
items: unsorted sequence of (value, frequency) pairs
name: string name for this CDF
Returns:
cdf: list of (value, fraction) pairs
"""
runsum = 0
xs = []
... | Makes a cdf from an unsorted sequence of (value, frequency) pairs.
Args:
items: unsorted sequence of (value, frequency) pairs
name: string name for this CDF
Returns:
cdf: list of (value, fraction) pairs | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1065-L1088 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakeCdfFromPmf | def MakeCdfFromPmf(pmf, name=None):
"""Makes a CDF from a Pmf object.
Args:
pmf: Pmf.Pmf object
name: string name for the data.
Returns:
Cdf object
"""
if name == None:
name = pmf.name
return MakeCdfFromItems(pmf.Items(), name) | python | def MakeCdfFromPmf(pmf, name=None):
"""Makes a CDF from a Pmf object.
Args:
pmf: Pmf.Pmf object
name: string name for the data.
Returns:
Cdf object
"""
if name == None:
name = pmf.name
return MakeCdfFromItems(pmf.Items(), name) | Makes a CDF from a Pmf object.
Args:
pmf: Pmf.Pmf object
name: string name for the data.
Returns:
Cdf object | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1117-L1129 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakeSuiteFromList | def MakeSuiteFromList(t, name=''):
"""Makes a suite from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this suite
Returns:
Suite object
"""
hist = MakeHistFromList(t)
d = hist.GetDict()
return MakeSuiteFromDict(d) | python | def MakeSuiteFromList(t, name=''):
"""Makes a suite from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this suite
Returns:
Suite object
"""
hist = MakeHistFromList(t)
d = hist.GetDict()
return MakeSuiteFromDict(d) | Makes a suite from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this suite
Returns:
Suite object | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1250-L1262 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakeSuiteFromHist | def MakeSuiteFromHist(hist, name=None):
"""Makes a normalized suite from a Hist object.
Args:
hist: Hist object
name: string name
Returns:
Suite object
"""
if name is None:
name = hist.name
# make a copy of the dictionary
d = dict(hist.GetDict())
return... | python | def MakeSuiteFromHist(hist, name=None):
"""Makes a normalized suite from a Hist object.
Args:
hist: Hist object
name: string name
Returns:
Suite object
"""
if name is None:
name = hist.name
# make a copy of the dictionary
d = dict(hist.GetDict())
return... | Makes a normalized suite from a Hist object.
Args:
hist: Hist object
name: string name
Returns:
Suite object | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1265-L1280 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakeSuiteFromDict | def MakeSuiteFromDict(d, name=''):
"""Makes a suite from a map from values to probabilities.
Args:
d: dictionary that maps values to probabilities
name: string name for this suite
Returns:
Suite object
"""
suite = Suite(name=name)
suite.SetDict(d)
suite.Normalize()
... | python | def MakeSuiteFromDict(d, name=''):
"""Makes a suite from a map from values to probabilities.
Args:
d: dictionary that maps values to probabilities
name: string name for this suite
Returns:
Suite object
"""
suite = Suite(name=name)
suite.SetDict(d)
suite.Normalize()
... | Makes a suite from a map from values to probabilities.
Args:
d: dictionary that maps values to probabilities
name: string name for this suite
Returns:
Suite object | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1283-L1296 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakeSuiteFromCdf | def MakeSuiteFromCdf(cdf, name=None):
"""Makes a normalized Suite from a Cdf object.
Args:
cdf: Cdf object
name: string name for the new Suite
Returns:
Suite object
"""
if name is None:
name = cdf.name
suite = Suite(name=name)
prev = 0.0
for val, prob ... | python | def MakeSuiteFromCdf(cdf, name=None):
"""Makes a normalized Suite from a Cdf object.
Args:
cdf: Cdf object
name: string name for the new Suite
Returns:
Suite object
"""
if name is None:
name = cdf.name
suite = Suite(name=name)
prev = 0.0
for val, prob ... | Makes a normalized Suite from a Cdf object.
Args:
cdf: Cdf object
name: string name for the new Suite
Returns:
Suite object | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1299-L1319 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | Percentile | def Percentile(pmf, percentage):
"""Computes a percentile of a given Pmf.
percentage: float 0-100
"""
p = percentage / 100.0
total = 0
for val, prob in pmf.Items():
total += prob
if total >= p:
return val | python | def Percentile(pmf, percentage):
"""Computes a percentile of a given Pmf.
percentage: float 0-100
"""
p = percentage / 100.0
total = 0
for val, prob in pmf.Items():
total += prob
if total >= p:
return val | Computes a percentile of a given Pmf.
percentage: float 0-100 | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1389-L1399 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | CredibleInterval | def CredibleInterval(pmf, percentage=90):
"""Computes a credible interval for a given distribution.
If percentage=90, computes the 90% CI.
Args:
pmf: Pmf object representing a posterior distribution
percentage: float between 0 and 100
Returns:
sequence of two floats, low and h... | python | def CredibleInterval(pmf, percentage=90):
"""Computes a credible interval for a given distribution.
If percentage=90, computes the 90% CI.
Args:
pmf: Pmf object representing a posterior distribution
percentage: float between 0 and 100
Returns:
sequence of two floats, low and h... | Computes a credible interval for a given distribution.
If percentage=90, computes the 90% CI.
Args:
pmf: Pmf object representing a posterior distribution
percentage: float between 0 and 100
Returns:
sequence of two floats, low and high | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1402-L1417 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | PmfProbLess | def PmfProbLess(pmf1, pmf2):
"""Probability that a value from pmf1 is less than a value from pmf2.
Args:
pmf1: Pmf object
pmf2: Pmf object
Returns:
float probability
"""
total = 0.0
for v1, p1 in pmf1.Items():
for v2, p2 in pmf2.Items():
if v1 < v2:
... | python | def PmfProbLess(pmf1, pmf2):
"""Probability that a value from pmf1 is less than a value from pmf2.
Args:
pmf1: Pmf object
pmf2: Pmf object
Returns:
float probability
"""
total = 0.0
for v1, p1 in pmf1.Items():
for v2, p2 in pmf2.Items():
if v1 < v2:
... | Probability that a value from pmf1 is less than a value from pmf2.
Args:
pmf1: Pmf object
pmf2: Pmf object
Returns:
float probability | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1420-L1435 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | SampleSum | def SampleSum(dists, n):
"""Draws a sample of sums from a list of distributions.
dists: sequence of Pmf or Cdf objects
n: sample size
returns: new Pmf of sums
"""
pmf = MakePmfFromList(RandomSum(dists) for i in xrange(n))
return pmf | python | def SampleSum(dists, n):
"""Draws a sample of sums from a list of distributions.
dists: sequence of Pmf or Cdf objects
n: sample size
returns: new Pmf of sums
"""
pmf = MakePmfFromList(RandomSum(dists) for i in xrange(n))
return pmf | Draws a sample of sums from a list of distributions.
dists: sequence of Pmf or Cdf objects
n: sample size
returns: new Pmf of sums | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1485-L1494 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | EvalGaussianPdf | def EvalGaussianPdf(x, mu, sigma):
"""Computes the unnormalized PDF of the normal distribution.
x: value
mu: mean
sigma: standard deviation
returns: float probability density
"""
return scipy.stats.norm.pdf(x, mu, sigma) | python | def EvalGaussianPdf(x, mu, sigma):
"""Computes the unnormalized PDF of the normal distribution.
x: value
mu: mean
sigma: standard deviation
returns: float probability density
"""
return scipy.stats.norm.pdf(x, mu, sigma) | Computes the unnormalized PDF of the normal distribution.
x: value
mu: mean
sigma: standard deviation
returns: float probability density | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1497-L1506 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakeGaussianPmf | def MakeGaussianPmf(mu, sigma, num_sigmas, n=201):
"""Makes a PMF discrete approx to a Gaussian distribution.
mu: float mean
sigma: float standard deviation
num_sigmas: how many sigmas to extend in each direction
n: number of values in the Pmf
returns: normalized Pmf
"""
pmf = Pmf(... | python | def MakeGaussianPmf(mu, sigma, num_sigmas, n=201):
"""Makes a PMF discrete approx to a Gaussian distribution.
mu: float mean
sigma: float standard deviation
num_sigmas: how many sigmas to extend in each direction
n: number of values in the Pmf
returns: normalized Pmf
"""
pmf = Pmf(... | Makes a PMF discrete approx to a Gaussian distribution.
mu: float mean
sigma: float standard deviation
num_sigmas: how many sigmas to extend in each direction
n: number of values in the Pmf
returns: normalized Pmf | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1509-L1527 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | EvalBinomialPmf | def EvalBinomialPmf(k, n, p):
"""Evaluates the binomial pmf.
Returns the probabily of k successes in n trials with probability p.
"""
return scipy.stats.binom.pmf(k, n, p) | python | def EvalBinomialPmf(k, n, p):
"""Evaluates the binomial pmf.
Returns the probabily of k successes in n trials with probability p.
"""
return scipy.stats.binom.pmf(k, n, p) | Evaluates the binomial pmf.
Returns the probabily of k successes in n trials with probability p. | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1530-L1535 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | EvalPoissonPmf | def EvalPoissonPmf(k, lam):
"""Computes the Poisson PMF.
k: number of events
lam: parameter lambda in events per unit time
returns: float probability
"""
# don't use the scipy function (yet). for lam=0 it returns NaN;
# should be 0.0
# return scipy.stats.poisson.pmf(k, lam)
retur... | python | def EvalPoissonPmf(k, lam):
"""Computes the Poisson PMF.
k: number of events
lam: parameter lambda in events per unit time
returns: float probability
"""
# don't use the scipy function (yet). for lam=0 it returns NaN;
# should be 0.0
# return scipy.stats.poisson.pmf(k, lam)
retur... | Computes the Poisson PMF.
k: number of events
lam: parameter lambda in events per unit time
returns: float probability | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1538-L1550 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakePoissonPmf | def MakePoissonPmf(lam, high, step=1):
"""Makes a PMF discrete approx to a Poisson distribution.
lam: parameter lambda in events per unit time
high: upper bound of the Pmf
returns: normalized Pmf
"""
pmf = Pmf()
for k in xrange(0, high + 1, step):
p = EvalPoissonPmf(k, lam)
... | python | def MakePoissonPmf(lam, high, step=1):
"""Makes a PMF discrete approx to a Poisson distribution.
lam: parameter lambda in events per unit time
high: upper bound of the Pmf
returns: normalized Pmf
"""
pmf = Pmf()
for k in xrange(0, high + 1, step):
p = EvalPoissonPmf(k, lam)
... | Makes a PMF discrete approx to a Poisson distribution.
lam: parameter lambda in events per unit time
high: upper bound of the Pmf
returns: normalized Pmf | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1553-L1566 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | MakeExponentialPmf | def MakeExponentialPmf(lam, high, n=200):
"""Makes a PMF discrete approx to an exponential distribution.
lam: parameter lambda in events per unit time
high: upper bound
n: number of values in the Pmf
returns: normalized Pmf
"""
pmf = Pmf()
for x in numpy.linspace(0, high, n):
p... | python | def MakeExponentialPmf(lam, high, n=200):
"""Makes a PMF discrete approx to an exponential distribution.
lam: parameter lambda in events per unit time
high: upper bound
n: number of values in the Pmf
returns: normalized Pmf
"""
pmf = Pmf()
for x in numpy.linspace(0, high, n):
p... | Makes a PMF discrete approx to an exponential distribution.
lam: parameter lambda in events per unit time
high: upper bound
n: number of values in the Pmf
returns: normalized Pmf | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1585-L1599 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | GaussianCdfInverse | def GaussianCdfInverse(p, mu=0, sigma=1):
"""Evaluates the inverse CDF of the gaussian distribution.
See http://en.wikipedia.org/wiki/Normal_distribution#Quantile_function
Args:
p: float
mu: mean parameter
sigma: standard deviation parameter
Returns... | python | def GaussianCdfInverse(p, mu=0, sigma=1):
"""Evaluates the inverse CDF of the gaussian distribution.
See http://en.wikipedia.org/wiki/Normal_distribution#Quantile_function
Args:
p: float
mu: mean parameter
sigma: standard deviation parameter
Returns... | Evaluates the inverse CDF of the gaussian distribution.
See http://en.wikipedia.org/wiki/Normal_distribution#Quantile_function
Args:
p: float
mu: mean parameter
sigma: standard deviation parameter
Returns:
float | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1633-L1649 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | LogBinomialCoef | def LogBinomialCoef(n, k):
"""Computes the log of the binomial coefficient.
http://math.stackexchange.com/questions/64716/
approximating-the-logarithm-of-the-binomial-coefficient
n: number of trials
k: number of successes
Returns: float
"""
return n * log(n) - k * log(k) - (n - k) * l... | python | def LogBinomialCoef(n, k):
"""Computes the log of the binomial coefficient.
http://math.stackexchange.com/questions/64716/
approximating-the-logarithm-of-the-binomial-coefficient
n: number of trials
k: number of successes
Returns: float
"""
return n * log(n) - k * log(k) - (n - k) * l... | Computes the log of the binomial coefficient.
http://math.stackexchange.com/questions/64716/
approximating-the-logarithm-of-the-binomial-coefficient
n: number of trials
k: number of successes
Returns: float | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1827-L1838 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | Interpolator.Lookup | def Lookup(self, x):
"""Looks up x and returns the corresponding value of y."""
return self._Bisect(x, self.xs, self.ys) | python | def Lookup(self, x):
"""Looks up x and returns the corresponding value of y."""
return self._Bisect(x, self.xs, self.ys) | Looks up x and returns the corresponding value of y. | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L100-L102 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.