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_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
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. """ ...
[ "def", "pass_record", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "inner", "(", "self", ",", "pid_value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "pid", ",", "record", "=", "request", ".", "view_args", "[", ...
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", "." ]
train
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. ...
[ "def", "verify_record_permission", "(", "permission_factory", ",", "record", ")", ":", "# Note, cannot be done in one line due overloading of boolean", "# operations permission object.", "if", "not", "permission_factory", "(", "record", "=", "record", ")", ".", "can", "(", ...
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...
[ "Check", "that", "the", "current", "user", "has", "the", "required", "permissions", "on", "record", "." ]
train
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, ...
[ "def", "need_record_permission", "(", "factory_name", ")", ":", "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.
[ "Decorator", "checking", "that", "the", "user", "has", "the", "required", "permissions", "on", "record", "." ]
train
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( ...
[ "def", "get", "(", "self", ")", ":", "opts", "=", "current_app", ".", "config", "[", "'RECORDS_REST_SORT_OPTIONS'", "]", ".", "get", "(", "self", ".", "search_index", ")", "sort_fields", "=", "[", "]", "if", "opts", ":", "for", "key", ",", "item", "in"...
Get options.
[ "Get", "options", "." ]
train
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...
[ "def", "get", "(", "self", ",", "*", "*", "kwargs", ")", ":", "default_results_size", "=", "current_app", ".", "config", ".", "get", "(", "'RECORDS_REST_DEFAULT_RESULTS_SIZE'", ",", "10", ")", "page", "=", "request", ".", "values", ".", "get", "(", "'page'...
Search records. Permissions: the `list_permission_factory` permissions are checked. :returns: Search result containing hits and aggregations as returned by invenio-search.
[ "Search", "records", "." ]
train
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...
[ "def", "post", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "request", ".", "mimetype", "not", "in", "self", ".", "loaders", ":", "raise", "UnsupportedMediaRESTError", "(", "request", ".", "mimetype", ")", "data", "=", "self", ".", "loaders", ...
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...
[ "Create", "a", "record", "." ]
train
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...
[ "def", "delete", "(", "self", ",", "pid", ",", "record", ",", "*", "*", "kwargs", ")", ":", "self", ".", "check_etag", "(", "str", "(", "record", ".", "model", ".", "version_id", ")", ")", "record", ".", "delete", "(", ")", "# mark all PIDs as DELETED"...
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...
[ "Delete", "a", "record", "." ]
train
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...
[ "def", "get", "(", "self", ",", "pid", ",", "record", ",", "*", "*", "kwargs", ")", ":", "etag", "=", "str", "(", "record", ".", "revision_id", ")", "self", ".", "check_etag", "(", "str", "(", "record", ".", "revision_id", ")", ")", "self", ".", ...
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...
[ "Get", "a", "record", "." ]
train
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...
[ "def", "patch", "(", "self", ",", "pid", ",", "record", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "loaders", "[", "request", ".", "mimetype", "]", "(", ")", "if", "data", "is", "None", ":", "raise", "InvalidDataRESTError", "(", "...
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. ...
[ "Modify", "a", "record", "." ]
train
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...
[ "def", "put", "(", "self", ",", "pid", ",", "record", ",", "*", "*", "kwargs", ")", ":", "if", "request", ".", "mimetype", "not", "in", "self", ".", "loaders", ":", "raise", "UnsupportedMediaRESTError", "(", "request", ".", "mimetype", ")", "data", "="...
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()`, ...
[ "Replace", "a", "record", "." ]
train
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...
[ "def", "get", "(", "self", ",", "*", "*", "kwargs", ")", ":", "completions", "=", "[", "]", "size", "=", "request", ".", "values", ".", "get", "(", "'size'", ",", "type", "=", "int", ")", "for", "k", "in", "self", ".", "suggesters", ".", "keys", ...
Get suggestions.
[ "Get", "suggestions", "." ]
train
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
[ "def", "_serialize", "(", "self", ",", "value", ",", "attr", ",", "obj", ")", ":", "try", ":", "return", "super", "(", "DateString", ",", "self", ")", ".", "_serialize", "(", "arrow", ".", "get", "(", "value", ")", ".", "date", "(", ")", ",", "at...
Serialize an ISO8601-formatted date.
[ "Serialize", "an", "ISO8601", "-", "formatted", "date", "." ]
train
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()
[ "def", "_deserialize", "(", "self", ",", "value", ",", "attr", ",", "data", ")", ":", "return", "super", "(", "DateString", ",", "self", ")", ".", "_deserialize", "(", "value", ",", "attr", ",", "data", ")", ".", "isoformat", "(", ")" ]
Deserialize an ISO8601-formatted date.
[ "Deserialize", "an", "ISO8601", "-", "formatted", "date", "." ]
train
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...
[ "def", "records", "(", ")", ":", "import", "uuid", "from", "invenio_records", ".", "api", "import", "Record", "from", "invenio_pidstore", ".", "models", "import", "PersistentIdentifier", ",", "PIDStatus", "indexer", "=", "RecordIndexer", "(", ")", "index_queue", ...
Load test data fixture.
[ "Load", "test", "data", "fixture", "." ]
train
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...
[ "def", "preprocess_record", "(", "self", ",", "pid", ",", "record", ",", "links_factory", "=", "None", ",", "*", "*", "kwargs", ")", ":", "links_factory", "=", "links_factory", "or", "(", "lambda", "x", ",", "record", "=", "None", ",", "*", "*", "k", ...
Prepare a record and persistent identifier for serialization.
[ "Prepare", "a", "record", "and", "persistent", "identifier", "for", "serialization", "." ]
train
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...
[ "def", "preprocess_search_hit", "(", "pid", ",", "record_hit", ",", "links_factory", "=", "None", ",", "*", "*", "kwargs", ")", ":", "links_factory", "=", "links_factory", "or", "(", "lambda", "x", ",", "*", "*", "k", ":", "dict", "(", ")", ")", "recor...
Prepare a record hit from Elasticsearch for serialization.
[ "Prepare", "a", "record", "hit", "from", "Elasticsearch", "for", "serialization", "." ]
train
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): ...
[ "def", "_flatten_marshmallow_errors", "(", "errors", ")", ":", "res", "=", "[", "]", "for", "field", ",", "error", "in", "errors", ".", "items", "(", ")", ":", "if", "isinstance", "(", "error", ",", "list", ")", ":", "res", ".", "append", "(", "dict"...
Flatten marshmallow errors.
[ "Flatten", "marshmallow", "errors", "." ]
train
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 ...
[ "def", "marshmallow_loader", "(", "schema_class", ")", ":", "def", "json_loader", "(", ")", ":", "request_json", "=", "request", ".", "get_json", "(", ")", "context", "=", "{", "}", "pid_data", "=", "request", ".", "view_args", ".", "get", "(", "'pid_value...
Marshmallow loader for JSON requests.
[ "Marshmallow", "loader", "for", "JSON", "requests", "." ]
train
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)
[ "def", "get_body", "(", "self", ",", "environ", "=", "None", ")", ":", "body", "=", "dict", "(", "status", "=", "self", ".", "code", ",", "message", "=", "self", ".", "get_description", "(", "environ", ")", ",", ")", "if", "self", ".", "errors", ":...
Get the request body.
[ "Get", "the", "request", "body", "." ]
train
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]
[ "def", "reset_permission_factories", "(", "self", ")", ":", "for", "key", "in", "(", "'read'", ",", "'create'", ",", "'update'", ",", "'delete'", ")", ":", "full_key", "=", "'{0}_permission_factory'", ".", "format", "(", "key", ")", "if", "full_key", "in", ...
Remove cached permission factories.
[ "Remove", "cached", "permission", "factories", "." ]
train
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)
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "self", ".", "init_config", "(", "app", ")", "app", ".", "extensions", "[", "'invenio-records-rest'", "]", "=", "_RecordRESTState", "(", "app", ")" ]
Flask application initialization.
[ "Flask", "application", "initialization", "." ]
train
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 = ...
[ "def", "init_config", "(", "self", ",", "app", ")", ":", "# Set up API endpoints for records.", "for", "k", "in", "dir", "(", "config", ")", ":", "if", "k", ".", "startswith", "(", "'RECORDS_REST_'", ")", ":", "app", ".", "config", ".", "setdefault", "(", ...
Initialize configuration.
[ "Initialize", "configuration", "." ]
train
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...
[ "def", "range_filter", "(", "field", ",", "start_date_math", "=", "None", ",", "end_date_math", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "inner", "(", "values", ")", ":", "if", "len", "(", "values", ")", "!=", "1", "or", "values", "[", ...
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.
[ "Create", "a", "range", "filter", "." ]
train
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:...
[ "def", "_create_filter_dsl", "(", "urlkwargs", ",", "definitions", ")", ":", "filters", "=", "[", "]", "for", "name", ",", "filter_factory", "in", "definitions", ".", "items", "(", ")", ":", "values", "=", "request", ".", "values", ".", "getlist", "(", "...
Create a filter DSL expression.
[ "Create", "a", "filter", "DSL", "expression", "." ]
train
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)
[ "def", "_post_filter", "(", "search", ",", "urlkwargs", ",", "definitions", ")", ":", "filters", ",", "urlkwargs", "=", "_create_filter_dsl", "(", "urlkwargs", ",", "definitions", ")", "for", "filter_", "in", "filters", ":", "search", "=", "search", ".", "po...
Ingest post filter in query.
[ "Ingest", "post", "filter", "in", "query", "." ]
train
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)
[ "def", "_query_filter", "(", "search", ",", "urlkwargs", ",", "definitions", ")", ":", "filters", ",", "urlkwargs", "=", "_create_filter_dsl", "(", "urlkwargs", ",", "definitions", ")", "for", "filter_", "in", "filters", ":", "search", "=", "search", ".", "f...
Ingest query filter in query.
[ "Ingest", "query", "filter", "in", "query", "." ]
train
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
[ "def", "_aggregations", "(", "search", ",", "definitions", ")", ":", "if", "definitions", ":", "for", "name", ",", "agg", "in", "definitions", ".", "items", "(", ")", ":", "search", ".", "aggs", "[", "name", "]", "=", "agg", "if", "not", "callable", ...
Add aggregations to query.
[ "Add", "aggregations", "to", "query", "." ]
train
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...
[ "def", "default_facets_factory", "(", "search", ",", "index", ")", ":", "urlkwargs", "=", "MultiDict", "(", ")", "facets", "=", "current_app", ".", "config", "[", "'RECORDS_REST_FACETS'", "]", ".", "get", "(", "index", ")", "if", "facets", "is", "not", "No...
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.
[ "Add", "a", "default", "facets", "to", "query", "." ]
train
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
[ "def", "dump", "(", "self", ",", "obj", ",", "context", "=", "None", ")", ":", "return", "self", ".", "schema_class", "(", "context", "=", "context", ")", ".", "dump", "(", "obj", ")", ".", "data" ]
Serialize object with schema.
[ "Serialize", "object", "with", "schema", "." ]
train
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, ...
[ "def", "transform_record", "(", "self", ",", "pid", ",", "record", ",", "links_factory", "=", "None", ",", "*", "*", "kwargs", ")", ":", "context", "=", "kwargs", ".", "get", "(", "'marshmallow_context'", ",", "{", "}", ")", "context", ".", "setdefault",...
Transform record into an intermediate representation.
[ "Transform", "record", "into", "an", "intermediate", "representation", "." ]
train
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...
[ "def", "transform_search_hit", "(", "self", ",", "pid", ",", "record_hit", ",", "links_factory", "=", "None", ",", "*", "*", "kwargs", ")", ":", "context", "=", "kwargs", ".", "get", "(", "'marshmallow_context'", ",", "{", "}", ")", "context", ".", "setd...
Transform search result hit into an intermediate representation.
[ "Transform", "search", "result", "hit", "into", "an", "intermediate", "representation", "." ]
train
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
[ "def", "pid_from_context", "(", "_", ",", "context", ")", ":", "pid", "=", "(", "context", "or", "{", "}", ")", ".", "get", "(", "'pid'", ")", "return", "pid", ".", "pid_value", "if", "pid", "else", "missing" ]
Get PID from marshmallow context.
[ "Get", "PID", "from", "marshmallow", "context", "." ]
train
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...
[ "def", "record_responsify", "(", "serializer", ",", "mimetype", ")", ":", "def", "view", "(", "pid", ",", "record", ",", "code", "=", "200", ",", "headers", "=", "None", ",", "links_factory", "=", "None", ")", ":", "response", "=", "current_app", ".", ...
Create a Records-REST response serializer. :param serializer: Serializer instance. :param mimetype: MIME type of response. :returns: Function that generates a record HTTP response.
[ "Create", "a", "Records", "-", "REST", "response", "serializer", "." ]
train
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...
[ "def", "search_responsify", "(", "serializer", ",", "mimetype", ")", ":", "def", "view", "(", "pid_fetcher", ",", "search_result", ",", "code", "=", "200", ",", "headers", "=", "None", ",", "links", "=", "None", ",", "item_links_factory", "=", "None", ")",...
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.
[ "Create", "a", "Records", "-", "REST", "search", "result", "response", "serializer", "." ]
train
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...
[ "def", "add_link_header", "(", "response", ",", "links", ")", ":", "if", "links", "is", "not", "None", ":", "response", ".", "headers", ".", "extend", "(", "{", "'Link'", ":", "', '", ".", "join", "(", "[", "'<{0}>; rel=\"{1}\"'", ".", "format", "(", "...
Add a Link HTTP header to a REST response. :param response: REST response instance :param links: Dictionary of links
[ "Add", "a", "Link", "HTTP", "header", "to", "a", "REST", "response", "." ]
train
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...
[ "def", "_get_args", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "csl_args", "=", "{", "'style'", ":", "cls", ".", "_default_style", ",", "'locale'", ":", "cls", ".", "_default_locale", "}", "if", "has_request_context", "(", ")", ":", "parser", "=", ...
Parse style and locale. Argument location precedence: kwargs > view_args > query
[ "Parse", "style", "and", "locale", "." ]
train
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)
[ "def", "_get_source", "(", "self", ",", "data", ")", ":", "if", "self", ".", "record_format", "==", "'csl'", ":", "return", "CiteProcJSON", "(", "[", "json", ".", "loads", "(", "data", ")", "]", ")", "elif", "self", ".", "record_format", "==", "'bibtex...
Get source data object for citeproc-py.
[ "Get", "source", "data", "object", "for", "citeproc", "-", "py", "." ]
train
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
[ "def", "_clean_result", "(", "self", ",", "text", ")", ":", "text", "=", "re", ".", "sub", "(", "'\\s\\s+'", ",", "' '", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "'\\.\\.+'", ",", "'.'", ",", "text", ")", "text", "=", "text", ".", ...
Remove double spaces, punctuation and escapes apostrophes.
[ "Remove", "double", "spaces", "punctuation", "and", "escapes", "apostrophes", "." ]
train
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...
[ "def", "serialize", "(", "self", ",", "pid", ",", "record", ",", "links_factory", "=", "None", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "serializer", ".", "serialize", "(", "pid", ",", "record", ",", "links_factory", ")", "source", ...
Serialize a single record. :param pid: Persistent identifier instance. :param record: Record instance. :param links_factory: Factory function for record links.
[ "Serialize", "a", "single", "record", "." ]
train
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...
[ "def", "is_valid_xml_char", "(", "self", ",", "char", ")", ":", "codepoint", "=", "ord", "(", "char", ")", "return", "(", "0x20", "<=", "codepoint", "<=", "0xD7FF", "or", "codepoint", "in", "(", "0x9", ",", "0xA", ",", "0xD", ")", "or", "0xE000", "<=...
Check if a character is valid based on the XML specification.
[ "Check", "if", "a", "character", "is", "valid", "based", "on", "the", "XML", "specification", "." ]
train
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 ...
[ "def", "_deserialize", "(", "self", ",", "value", ",", "attr", ",", "data", ")", ":", "value", "=", "super", "(", "SanitizedUnicode", ",", "self", ")", ".", "_deserialize", "(", "value", ",", "attr", ",", "data", ")", "value", "=", "fix_text", "(", "...
Deserialize sanitized string value.
[ "Deserialize", "sanitized", "string", "value", "." ]
train
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...
[ "def", "serialize", "(", "self", ",", "pid", ",", "record", ",", "links_factory", "=", "None", ")", ":", "return", "self", ".", "schema", ".", "tostring", "(", "self", ".", "transform_record", "(", "pid", ",", "record", ",", "links_factory", ")", ")" ]
Serialize a single record and persistent identifier. :param pid: Persistent identifier instance. :param record: Record instance. :param links_factory: Factory function for record links.
[ "Serialize", "a", "single", "record", "and", "persistent", "identifier", "." ]
train
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 ...
[ "def", "serialize_search", "(", "self", ",", "pid_fetcher", ",", "search_result", ",", "links", "=", "None", ",", "item_links_factory", "=", "None", ")", ":", "records", "=", "[", "]", "for", "hit", "in", "search_result", "[", "'hits'", "]", "[", "'hits'",...
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.
[ "Serialize", "a", "search", "result", "." ]
train
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)
[ "def", "serialize_oaipmh", "(", "self", ",", "pid", ",", "record", ")", ":", "obj", "=", "self", ".", "transform_record", "(", "pid", ",", "record", "[", "'_source'", "]", ")", "if", "isinstance", "(", "record", "[", "'_source'", "]", ",", "Record", ")...
Serialize a single record for OAI-PMH.
[ "Serialize", "a", "single", "record", "for", "OAI", "-", "PMH", "." ]
train
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', ...
[ "def", "serialize_oaipmh", "(", "self", ",", "pid", ",", "record", ")", ":", "root", "=", "etree", ".", "Element", "(", "'oai_datacite'", ",", "nsmap", "=", "{", "None", ":", "'http://schema.datacite.org/oai/oai-1.0/'", ",", "'xsi'", ":", "'http://www.w3.org/200...
Serialize a single record for OAI-PMH.
[ "Serialize", "a", "single", "record", "for", "OAI", "-", "PMH", "." ]
train
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()
[ "def", "_deserialize", "(", "self", ",", "value", ",", "attr", ",", "data", ")", ":", "value", "=", "super", "(", "TrimmedString", ",", "self", ")", ".", "_deserialize", "(", "value", ",", "attr", ",", "data", ")", "return", "value", ".", "strip", "(...
Deserialize string value.
[ "Deserialize", "string", "value", "." ]
train
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...
[ "def", "default_search_factory", "(", "self", ",", "search", ",", "query_parser", "=", "None", ")", ":", "def", "_default_parser", "(", "qstr", "=", "None", ")", ":", "\"\"\"Default parser that uses the Q() from elasticsearch_dsl.\"\"\"", "if", "qstr", ":", "return", ...
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.
[ "Parse", "query", "using", "elasticsearch", "DSL", "query", "." ]
train
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...
[ "def", "_get_func_args", "(", "func", ")", ":", "if", "isinstance", "(", "func", ",", "functools", ".", "partial", ")", ":", "return", "_get_func_args", "(", "func", ".", "func", ")", "if", "inspect", ".", "isfunction", "(", "func", ")", "or", "inspect",...
Get a list of the arguments a function or method has.
[ "Get", "a", "list", "of", "the", "arguments", "a", "function", "or", "method", "has", "." ]
train
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...
[ "def", "serialize", "(", "self", ",", "pid", ",", "record", ",", "links_factory", "=", "None", ")", ":", "return", "simpledc", ".", "tostring", "(", "self", ".", "transform_record", "(", "pid", ",", "record", ",", "links_factory", ")", ")" ]
Serialize a single record and persistent identifier. :param pid: Persistent identifier instance. :param record: Record instance. :param links_factory: Factory function for record links.
[ "Serialize", "a", "single", "record", "and", "persistent", "identifier", "." ]
train
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...
[ "def", "expanded", "(", "self", ")", ":", "# Ensure we can run outside a application/request context.", "if", "request", ":", "if", "'expanded'", "in", "request", ".", "args", ":", "return", "True", "elif", "'compacted'", "in", "request", ".", "args", ":", "return...
Get JSON-LD expanded state.
[ "Get", "JSON", "-", "LD", "expanded", "state", "." ]
train
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...
[ "def", "transform_jsonld", "(", "self", ",", "obj", ")", ":", "rec", "=", "copy", ".", "deepcopy", "(", "obj", ")", "rec", ".", "update", "(", "self", ".", "context", ")", "compacted", "=", "jsonld", ".", "compact", "(", "rec", ",", "self", ".", "c...
Compact JSON according to context.
[ "Compact", "JSON", "according", "to", "context", "." ]
train
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)
[ "def", "transform_record", "(", "self", ",", "pid", ",", "record", ",", "links_factory", "=", "None", ",", "*", "*", "kwargs", ")", ":", "result", "=", "super", "(", "JSONLDTransformerMixin", ",", "self", ")", ".", "transform_record", "(", "pid", ",", "r...
Transform record into an intermediate representation.
[ "Transform", "record", "into", "an", "intermediate", "representation", "." ]
train
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 ...
[ "def", "transform_search_hit", "(", "self", ",", "pid", ",", "record_hit", ",", "links_factory", "=", "None", ",", "*", "*", "kwargs", ")", ":", "result", "=", "super", "(", "JSONLDTransformerMixin", ",", "self", ")", ".", "transform_search_hit", "(", "pid",...
Transform search result hit into an intermediate representation.
[ "Transform", "search", "result", "hit", "into", "an", "intermediate", "representation", "." ]
train
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...
[ "def", "default_links_factory", "(", "pid", ",", "record", "=", "None", ",", "*", "*", "kwargs", ")", ":", "endpoint", "=", "'.{0}_item'", ".", "format", "(", "current_records_rest", ".", "default_endpoint_prefixes", "[", "pid", ".", "pid_type", "]", ")", "l...
Factory for record links generation. :param pid: A Persistent Identifier instance. :returns: Dictionary containing a list of useful links for the record.
[ "Factory", "for", "record", "links", "generation", "." ]
train
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, **...
[ "def", "default_links_factory_with_additional", "(", "additional_links", ")", ":", "def", "factory", "(", "pid", ",", "*", "*", "kwargs", ")", ":", "links", "=", "default_links_factory", "(", "pid", ")", "for", "link", "in", "additional_links", ":", "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.
[ "Generate", "a", "links", "generation", "factory", "with", "the", "specified", "additional", "links", "." ]
train
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 ...
[ "def", "geolocation_sort", "(", "field_name", ",", "argument", ",", "unit", ",", "mode", "=", "None", ",", "distance_type", "=", "None", ")", ":", "def", "inner", "(", "asc", ")", ":", "locations", "=", "request", ".", "values", ".", "getlist", "(", "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 ...
[ "Sort", "field", "factory", "for", "geo", "-", "location", "based", "sorting", "." ]
train
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: ...
[ "def", "eval_field", "(", "field", ",", "asc", ")", ":", "if", "isinstance", "(", "field", ",", "dict", ")", ":", "if", "asc", ":", "return", "field", "else", ":", "# Field should only have one key and must have an order subkey.", "field", "=", "copy", ".", "d...
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.
[ "Evaluate", "a", "field", "for", "sorting", "purpose", "." ]
train
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...
[ "def", "default_sorter_factory", "(", "search", ",", "index", ")", ":", "sort_arg_name", "=", "'sort'", "urlfield", "=", "request", ".", "values", ".", "get", "(", "sort_arg_name", ",", "''", ",", "type", "=", "str", ")", "# Get default sorting if sort is not sp...
Default sort query factory. :param query: Search query. :param index: Index to search in. :returns: Tuple of (query, URL arguments).
[ "Default", "sort", "query", "factory", "." ]
train
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 [ ...
[ "def", "check_unknown_fields", "(", "self", ",", "data", ",", "original_data", ")", ":", "if", "isinstance", "(", "original_data", ",", "list", ")", ":", "for", "elem", "in", "original_data", ":", "self", ".", "check_unknown_fields", "(", "data", ",", "elem"...
Check for unknown keys.
[ "Check", "for", "unknown", "keys", "." ]
train
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 ...
[ "def", "load_unknown_fields", "(", "self", ",", "data", ",", "original_data", ")", ":", "if", "isinstance", "(", "original_data", ",", "list", ")", ":", "for", "elem", "in", "original_data", ":", "self", ".", "load_unknown_fields", "(", "data", ",", "elem", ...
Check for unknown keys.
[ "Check", "for", "unknown", "keys", "." ]
train
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) ...
[ "def", "inject_pid", "(", "self", ",", "data", ")", ":", "# Remove already deserialized \"pid\" field", "pid_value", "=", "data", ".", "pop", "(", "'pid'", ",", "None", ")", "if", "pid_value", ":", "pid_field", "=", "current_app", ".", "config", "[", "'PIDSTOR...
Inject context PID in the RECID field.
[ "Inject", "context", "PID", "in", "the", "RECID", "field", "." ]
train
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...
[ "def", "as_uni_form", "(", "form", ")", ":", "if", "isinstance", "(", "form", ",", "BaseFormSet", ")", ":", "if", "settings", ".", "DEBUG", ":", "template", "=", "get_template", "(", "'uni_form/uni_formset.html'", ")", "else", ":", "template", "=", "uni_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>
[ "The", "original", "and", "still", "very", "useful", "way", "to", "generate", "a", "uni", "-", "form", "form", "/", "formset", "::", "{", "%", "load", "uni_form_tags", "%", "}" ]
train
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...
[ "def", "as_uni_errors", "(", "form", ")", ":", "if", "isinstance", "(", "form", ",", "BaseFormSet", ")", ":", "template", "=", "get_template", "(", "'uni_form/errors_formset.html'", ")", "c", "=", "Context", "(", "{", "'formset'", ":", "form", "}", ")", "e...
Renders only form errors like django-uni-form:: {% load uni_form_tags %} {{ form|as_uni_errors }}
[ "Renders", "only", "form", "errors", "like", "django", "-", "uni", "-", "form", "::" ]
train
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)
[ "def", "as_uni_field", "(", "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 }}
[ "Renders", "a", "form", "field", "like", "a", "django", "-", "uni", "-", "form", "field", "::" ]
train
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}))
[ "def", "render", "(", "self", ",", "form", ",", "form_style", ",", "context", ")", ":", "return", "render_to_string", "(", "self", ".", "template", ",", "Context", "(", "{", "'input'", ":", "self", "}", ")", ")" ]
Renders an `<input />` if container is used as a Layout object
[ "Renders", "an", "<input", "/", ">", "if", "container", "is", "used", "as", "a", "Layout", "object" ]
train
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 ...
[ "def", "render_field", "(", "field", ",", "form", ",", "form_style", ",", "context", ",", "template", "=", "None", ",", "labelclass", "=", "None", ",", "layout_object", "=", "None", ")", ":", "FAIL_SILENTLY", "=", "getattr", "(", "settings", ",", "'UNIFORM...
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...
[ "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", ...
train
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...
[ "def", "do_uni_form", "(", "parser", ",", "token", ")", ":", "token", "=", "token", ".", "split_contents", "(", ")", "form", "=", "token", ".", "pop", "(", "1", ")", "try", ":", "helper", "=", "token", ".", "pop", "(", "1", ")", "except", "IndexErr...
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 %}
[ "You", "need", "to", "pass", "in", "at", "least", "the", "form", "/", "formset", "object", "and", "can", "also", "pass", "in", "the", "optional", "uni_form", ".", "helpers", ".", "FormHelper", "object", "." ]
train
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 ...
[ "def", "get_render", "(", "self", ",", "context", ")", ":", "actual_form", "=", "self", ".", "form", ".", "resolve", "(", "context", ")", "attrs", "=", "{", "}", "if", "self", ".", "helper", "is", "not", "None", ":", "helper", "=", "self", ".", "he...
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...
[ "Returns", "a", "Context", "object", "with", "all", "the", "necesarry", "stuff", "for", "rendering", "the", "form" ]
train
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...
[ "def", "get_response_dict", "(", "self", ",", "attrs", ",", "context", ",", "is_formset", ")", ":", "form_type", "=", "\"form\"", "if", "is_formset", ":", "form_type", "=", "\"formset\"", "# We take form/formset parameters from attrs if they are set, otherwise we use defaul...
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...
[ "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", "...
train
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...
[ "def", "render_layout", "(", "self", ",", "form", ",", "context", ")", ":", "form", ".", "rendered_fields", "=", "[", "]", "html", "=", "self", ".", "layout", ".", "render", "(", "form", ",", "self", ".", "form_style", ",", "context", ")", "for", "fi...
Returns safe html of the rendering of the layout
[ "Returns", "safe", "html", "of", "the", "rendering", "of", "the", "layout" ]
train
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: ...
[ "def", "get_attributes", "(", "self", ")", ":", "items", "=", "{", "}", "items", "[", "'form_method'", "]", "=", "self", ".", "form_method", ".", "strip", "(", ")", "items", "[", "'form_tag'", "]", "=", "self", ".", "form_tag", "items", "[", "'form_sty...
Used by the uni_form_tags to get helper attributes
[ "Used", "by", "the", "uni_form_tags", "to", "get", "helper", "attributes" ]
train
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())
[ "def", "add_exp", "(", "self", ",", "gr", ",", "exp", ")", ":", "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.
[ "Function", "to", "add", "the", "counts", "for", "each", "sample" ]
train
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...
[ "def", "MakeJoint", "(", "pmf1", ",", "pmf2", ")", ":", "joint", "=", "Joint", "(", ")", "for", "v1", ",", "p1", "in", "pmf1", ".", "Items", "(", ")", ":", "for", "v2", ",", "p2", "in", "pmf2", ".", "Items", "(", ")", ":", "joint", ".", "Set"...
Joint distribution of values from pmf1 and pmf2. Args: pmf1: Pmf object pmf2: Pmf object Returns: Joint pmf of value pairs
[ "Joint", "distribution", "of", "values", "from", "pmf1", "and", "pmf2", "." ]
train
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
[ "def", "MakeHistFromList", "(", "t", ",", "name", "=", "''", ")", ":", "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
[ "Makes", "a", "histogram", "from", "an", "unsorted", "sequence", "of", "values", "." ]
train
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...
[ "def", "MakePmfFromList", "(", "t", ",", "name", "=", "''", ")", ":", "hist", "=", "MakeHistFromList", "(", "t", ")", "d", "=", "hist", ".", "GetDict", "(", ")", "pmf", "=", "Pmf", "(", "d", ",", "name", ")", "pmf", ".", "Normalize", "(", ")", ...
Makes a PMF from an unsorted sequence of values. Args: t: sequence of numbers name: string name for this PMF Returns: Pmf object
[ "Makes", "a", "PMF", "from", "an", "unsorted", "sequence", "of", "values", "." ]
train
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
[ "def", "MakePmfFromDict", "(", "d", ",", "name", "=", "''", ")", ":", "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
[ "Makes", "a", "PMF", "from", "a", "map", "from", "values", "to", "probabilities", "." ]
train
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
[ "def", "MakePmfFromItems", "(", "t", ",", "name", "=", "''", ")", ":", "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
[ "Makes", "a", "PMF", "from", "a", "sequence", "of", "value", "-", "probability", "pairs" ]
train
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,...
[ "def", "MakePmfFromHist", "(", "hist", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "hist", ".", "name", "# make a copy of the dictionary", "d", "=", "dict", "(", "hist", ".", "GetDict", "(", ")", ")", "pmf", "=", ...
Makes a normalized PMF from a Hist object. Args: hist: Hist object name: string name Returns: Pmf object
[ "Makes", "a", "normalized", "PMF", "from", "a", "Hist", "object", "." ]
train
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...
[ "def", "MakePmfFromCdf", "(", "cdf", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "cdf", ".", "name", "pmf", "=", "Pmf", "(", "name", "=", "name", ")", "prev", "=", "0.0", "for", "val", ",", "prob", "in", "c...
Makes a normalized Pmf from a Cdf object. Args: cdf: Cdf object name: string name for the new Pmf Returns: Pmf object
[ "Makes", "a", "normalized", "Pmf", "from", "a", "Cdf", "object", "." ]
train
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....
[ "def", "MakeMixture", "(", "metapmf", ",", "name", "=", "'mix'", ")", ":", "mix", "=", "Pmf", "(", "name", "=", "name", ")", "for", "pmf", ",", "p1", "in", "metapmf", ".", "Items", "(", ")", ":", "for", "x", ",", "p2", "in", "pmf", ".", "Items"...
Make a mixture distribution. Args: metapmf: Pmf that maps from Pmfs to probs. name: string name for the new Pmf. Returns: Pmf object.
[ "Make", "a", "mixture", "distribution", "." ]
train
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
[ "def", "MakeUniformPmf", "(", "low", ",", "high", ",", "n", ")", ":", "pmf", "=", "Pmf", "(", ")", "for", "x", "in", "numpy", ".", "linspace", "(", "low", ",", "high", ",", "n", ")", ":", "pmf", ".", "Set", "(", "x", ",", "1", ")", "pmf", "...
Make a uniform Pmf. low: lowest value (inclusive) high: highest value (inclusize) n: number of values
[ "Make", "a", "uniform", "Pmf", "." ]
train
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 = [] ...
[ "def", "MakeCdfFromItems", "(", "items", ",", "name", "=", "''", ")", ":", "runsum", "=", "0", "xs", "=", "[", "]", "cs", "=", "[", "]", "for", "value", ",", "count", "in", "sorted", "(", "items", ")", ":", "runsum", "+=", "count", "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
[ "Makes", "a", "cdf", "from", "an", "unsorted", "sequence", "of", "(", "value", "frequency", ")", "pairs", "." ]
train
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)
[ "def", "MakeCdfFromPmf", "(", "pmf", ",", "name", "=", "None", ")", ":", "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
[ "Makes", "a", "CDF", "from", "a", "Pmf", "object", "." ]
train
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)
[ "def", "MakeSuiteFromList", "(", "t", ",", "name", "=", "''", ")", ":", "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
[ "Makes", "a", "suite", "from", "an", "unsorted", "sequence", "of", "values", "." ]
train
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...
[ "def", "MakeSuiteFromHist", "(", "hist", ",", "name", "=", "None", ")", ":", "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
[ "Makes", "a", "normalized", "suite", "from", "a", "Hist", "object", "." ]
train
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() ...
[ "def", "MakeSuiteFromDict", "(", "d", ",", "name", "=", "''", ")", ":", "suite", "=", "Suite", "(", "name", "=", "name", ")", "suite", ".", "SetDict", "(", "d", ")", "suite", ".", "Normalize", "(", ")", "return", "suite" ]
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
[ "Makes", "a", "suite", "from", "a", "map", "from", "values", "to", "probabilities", "." ]
train
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 ...
[ "def", "MakeSuiteFromCdf", "(", "cdf", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "cdf", ".", "name", "suite", "=", "Suite", "(", "name", "=", "name", ")", "prev", "=", "0.0", "for", "val", ",", "prob", "in"...
Makes a normalized Suite from a Cdf object. Args: cdf: Cdf object name: string name for the new Suite Returns: Suite object
[ "Makes", "a", "normalized", "Suite", "from", "a", "Cdf", "object", "." ]
train
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
[ "def", "Percentile", "(", "pmf", ",", "percentage", ")", ":", "p", "=", "percentage", "/", "100.0", "total", "=", "0", "for", "val", ",", "prob", "in", "pmf", ".", "Items", "(", ")", ":", "total", "+=", "prob", "if", "total", ">=", "p", ":", "ret...
Computes a percentile of a given Pmf. percentage: float 0-100
[ "Computes", "a", "percentile", "of", "a", "given", "Pmf", "." ]
train
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...
[ "def", "CredibleInterval", "(", "pmf", ",", "percentage", "=", "90", ")", ":", "cdf", "=", "pmf", ".", "MakeCdf", "(", ")", "prob", "=", "(", "1", "-", "percentage", "/", "100.0", ")", "/", "2", "interval", "=", "cdf", ".", "Value", "(", "prob", ...
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
[ "Computes", "a", "credible", "interval", "for", "a", "given", "distribution", "." ]
train
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: ...
[ "def", "PmfProbLess", "(", "pmf1", ",", "pmf2", ")", ":", "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
[ "Probability", "that", "a", "value", "from", "pmf1", "is", "less", "than", "a", "value", "from", "pmf2", "." ]
train
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
[ "def", "SampleSum", "(", "dists", ",", "n", ")", ":", "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
[ "Draws", "a", "sample", "of", "sums", "from", "a", "list", "of", "distributions", "." ]
train
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)
[ "def", "EvalGaussianPdf", "(", "x", ",", "mu", ",", "sigma", ")", ":", "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
[ "Computes", "the", "unnormalized", "PDF", "of", "the", "normal", "distribution", "." ]
train
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(...
[ "def", "MakeGaussianPmf", "(", "mu", ",", "sigma", ",", "num_sigmas", ",", "n", "=", "201", ")", ":", "pmf", "=", "Pmf", "(", ")", "low", "=", "mu", "-", "num_sigmas", "*", "sigma", "high", "=", "mu", "+", "num_sigmas", "*", "sigma", "for", "x", ...
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
[ "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", "...
train
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)
[ "def", "EvalBinomialPmf", "(", "k", ",", "n", ",", "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.
[ "Evaluates", "the", "binomial", "pmf", "." ]
train
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...
[ "def", "EvalPoissonPmf", "(", "k", ",", "lam", ")", ":", "# don't use the scipy function (yet). for lam=0 it returns NaN;", "# should be 0.0", "# return scipy.stats.poisson.pmf(k, lam)", "return", "lam", "**", "k", "*", "math", ".", "exp", "(", "-", "lam", ")", "/", ...
Computes the Poisson PMF. k: number of events lam: parameter lambda in events per unit time returns: float probability
[ "Computes", "the", "Poisson", "PMF", "." ]
train
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) ...
[ "def", "MakePoissonPmf", "(", "lam", ",", "high", ",", "step", "=", "1", ")", ":", "pmf", "=", "Pmf", "(", ")", "for", "k", "in", "xrange", "(", "0", ",", "high", "+", "1", ",", "step", ")", ":", "p", "=", "EvalPoissonPmf", "(", "k", ",", "la...
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
[ "Makes", "a", "PMF", "discrete", "approx", "to", "a", "Poisson", "distribution", "." ]
train
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...
[ "def", "MakeExponentialPmf", "(", "lam", ",", "high", ",", "n", "=", "200", ")", ":", "pmf", "=", "Pmf", "(", ")", "for", "x", "in", "numpy", ".", "linspace", "(", "0", ",", "high", ",", "n", ")", ":", "p", "=", "EvalExponentialPdf", "(", "x", ...
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
[ "Makes", "a", "PMF", "discrete", "approx", "to", "an", "exponential", "distribution", "." ]
train
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...
[ "def", "GaussianCdfInverse", "(", "p", ",", "mu", "=", "0", ",", "sigma", "=", "1", ")", ":", "x", "=", "ROOT2", "*", "erfinv", "(", "2", "*", "p", "-", "1", ")", "return", "mu", "+", "x", "*", "sigma" ]
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
[ "Evaluates", "the", "inverse", "CDF", "of", "the", "gaussian", "distribution", "." ]
train
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...
[ "def", "LogBinomialCoef", "(", "n", ",", "k", ")", ":", "return", "n", "*", "log", "(", "n", ")", "-", "k", "*", "log", "(", "k", ")", "-", "(", "n", "-", "k", ")", "*", "log", "(", "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
[ "Computes", "the", "log", "of", "the", "binomial", "coefficient", "." ]
train
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)
[ "def", "Lookup", "(", "self", ",", "x", ")", ":", "return", "self", ".", "_Bisect", "(", "x", ",", "self", ".", "xs", ",", "self", ".", "ys", ")" ]
Looks up x and returns the corresponding value of y.
[ "Looks", "up", "x", "and", "returns", "the", "corresponding", "value", "of", "y", "." ]
train
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L100-L102