Search is not available for this dataset
text stringlengths 75 104k |
|---|
def set_node(self, dst, src):
"""
Basically copy one node to another.
usefull to transmit a node from a terminal
rule as result of the current rule.
example::
R = [
In : node #set(_, node)
]
here the node return by the rule In is
... |
def set_node_as_int(self, dst, src):
"""
Set a node to a value captured from another node
example::
R = [
In : node #setcapture(_, node)
]
"""
dst.value = self.value(src)
return True |
def get_subnode(self, dst, ast, expr):
"""
get the value of subnode
example::
R = [
__scope__:big getsomethingbig:>big
#get(_, big, '.val') // copy big.val into _
]
"""
dst.value = eval('ast' + expr)
return True |
def default_serializer(o):
"""Default serializer for json."""
defs = (
((datetime.date, datetime.time),
lambda x: x.isoformat(), ),
((datetime.datetime, ),
lambda x: dt2utc_timestamp(x), ),
)
for types, fun in defs:
if isinstance(o, types):
return fu... |
def _get_depositions(user=None, type=None):
"""Get list of depositions (as iterator).
This is redefined Deposition.get_depositions classmethod without order-by
for better performance.
"""
from invenio.modules.workflows.models import BibWorkflowObject, Workflow
from invenio.modules.deposit.model... |
def get(query, from_date, limit=0, **kwargs):
"""Get deposits."""
dep_generator = _get_depositions()
total_depids = 1 # Count of depositions is hard to determine
# If limit provided, serve only first n=limit items
if limit > 0:
dep_generator = islice(dep_generator, limit)
total_dep... |
def dump(deposition, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the deposition object as dictionary."""
# Serialize the __getstate__ and fall back to default serializer
dep_json = json.dumps(deposition.__getstate__(),
default=default_serializer)
dep_dict =... |
def _get_recids_invenio12(from_date):
"""Get BibDocs for Invenio 1."""
from invenio.dbquery import run_sql
return (id[0] for id in run_sql(
'select id_bibrec from '
'bibrec_bibdoc as r join bibdoc as d on r.id_bibdoc=d.id '
'where d.modification_date >=%s',
(from_date, ), run... |
def _get_recids_invenio2(from_date):
"""Get BibDocs for Invenio 2."""
from invenio.legacy.dbquery import run_sql
return (id[0] for id in run_sql(
'select id_bibrec from '
'bibrec_bibdoc as r join bibdoc as d on r.id_bibdoc=d.id '
'where d.modification_date >=%s',
(from_date, ... |
def _import_bibdoc():
"""Import BibDocFile."""
try:
from invenio.bibdocfile import BibRecDocs, BibDoc
except ImportError:
from invenio.legacy.bibdocfile.api import BibRecDocs, BibDoc
return BibRecDocs, BibDoc |
def dump_bibdoc(recid, from_date, **kwargs):
"""Dump all BibDoc metadata.
:param docid: BibDoc ID
:param from_date: Dump only BibDoc revisions newer than this date.
:returns: List of version of the BibDoc formatted as a dict
"""
BibRecDocs, BibDoc = _import_bibdoc()
bibdocfile_dump = []
... |
def get_check():
"""Get bibdocs to check."""
try:
from invenio.dbquery import run_sql
except ImportError:
from invenio.legacy.dbquery import run_sql
return (
run_sql('select count(id) from bibdoc', run_on_slave=True)[0][0],
[id[0] for id in run_sql('select id from bibdoc... |
def check(id_):
"""Check bibdocs."""
BibRecDocs, BibDoc = _import_bibdoc()
try:
BibDoc(id_).list_all_files()
except Exception:
click.secho("BibDoc {0} failed check.".format(id_), fg='red') |
def dump(obj, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the oauth2server tokens."""
return dict(id=obj.id,
client_id=obj.client_id,
user_id=obj.user_id,
token_type=obj.token_type,
access_token=obj.access_token,
... |
def get(*args, **kwargs):
"""Get UserEXT objects."""
try:
from invenio.modules.accounts.models import UserEXT
except ImportError:
from invenio_accounts.models import UserEXT
q = UserEXT.query
return q.count(), q.all() |
def dump(u, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the UserEXt objects as a list of dictionaries.
:param u: UserEXT to be dumped.
:type u: `invenio_accounts.models.UserEXT [Invenio2.x]`
:returns: User serialized to dictionary.
:rtype: dict
"""
return dict(id=u.id, ... |
def get(*args, **kwargs):
"""Get communities."""
from invenio.modules.communities.models import FeaturedCommunity
q = FeaturedCommunity.query
return q.count(), q.all() |
def dump(fc, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the community object as dictionary.
:param fc: Community featuring to be dumped.
:type fc: `invenio_communities.models.FeaturedCommunity [Invenio2.x]`
:returns: Community serialized to dictionary.
:rtype: dict
"""
... |
def _get_modified_recids_invenio12(from_date):
"""Get record ids for Invenio 1."""
from invenio.search_engine import search_pattern
from invenio.dbquery import run_sql
return set((id[0] for id in run_sql(
'select id from bibrec where modification_date >= %s',
(from_date, ), run_on_slave=... |
def _get_modified_recids_invenio2(from_date):
"""Get record ids for Invenio 2."""
from invenio.legacy.search_engine import search_pattern
from invenio.modules.records.models import Record
date = datetime.datetime.strptime(from_date, '%Y-%m-%d %H:%M:%S')
return set(
(x[0]
for x in R... |
def _get_collection_restrictions(collection):
"""Get all restrictions for a given collection, users and fireroles."""
try:
from invenio.dbquery import run_sql
from invenio.access_control_firerole import compile_role_definition
except ImportError:
from invenio.modules.access.firerole ... |
def get_record_revisions(recid, from_date):
"""Get record revisions."""
try:
from invenio.dbquery import run_sql
except ImportError:
from invenio.legacy.dbquery import run_sql
return run_sql(
'SELECT job_date, marcxml '
'FROM hstRECORD WHERE id_bibrec = %s AND job_date >... |
def get_record_collections(recid):
"""Get all collections the record belong to."""
try:
from invenio.search_engine import (
get_all_collections_of_a_record,
get_restricted_collections_for_recid)
except ImportError:
from invenio.legacy.search_engine import (
... |
def dump_record_json(marcxml):
"""Dump JSON of record."""
try:
from invenio.modules.records.api import Record
d = Record.create(marcxml, 'marc')
return d.dumps(clean=True)
except ImportError:
from invenio.bibfield import create_record
d = create_record(marcxml, master... |
def get(query, from_date, **kwargs):
"""Get recids matching query and with changes."""
recids, search_pattern = get_modified_recids(from_date)
recids = recids.union(get_modified_bibdoc_recids(from_date))
if query:
recids = recids.intersection(
set(search_pattern(p=query.encode('utf-... |
def dump(recid,
from_date,
with_json=False,
latest_only=False,
with_collections=False,
**kwargs):
"""Dump MARCXML and JSON representation of a record.
:param recid: Record identifier
:param from_date: Dump only revisions from this date onwards.
:param with_j... |
def dump(ra, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the remote accounts as a list of dictionaries.
:param ra: Remote account to be dumped.
:type ra: `invenio_oauthclient.models.RemoteAccount [Invenio2.x]`
:returns: Remote accounts serialized to dictionary.
:rtype: dict
... |
def load_common(model_cls, data):
"""Helper function for loading JSON data verbatim into model."""
obj = model_cls(**data)
db.session.add(obj)
db.session.commit() |
def collect_things_entry_points():
"""Collect entry points."""
things = dict()
for entry_point in iter_entry_points(group='invenio_migrator.things'):
things[entry_point.name] = entry_point.load()
return things |
def init_app_context():
"""Initialize app context for Invenio 2.x."""
try:
from invenio.base.factory import create_app
app = create_app()
app.test_request_context('/').push()
app.preprocess_request()
except ImportError:
pass |
def memoize(func):
"""Cache for heavy function calls."""
cache = {}
@wraps(func)
def wrap(*args, **kwargs):
key = '{0}{1}'.format(args, kwargs)
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrap |
def _get_run_sql():
"""Import ``run_sql``."""
try:
from invenio.dbquery import run_sql
except ImportError:
from invenio.legacy.dbquery import run_sql
return run_sql |
def get_connected_roles(action_id):
"""Get roles connected to an action."""
try:
from invenio.access_control_admin import compile_role_definition
except ImportError:
from invenio.modules.access.firerole import compile_role_definition
run_sql = _get_run_sql()
roles = {}
res = ru... |
def get(query, *args, **kwargs):
"""Get action definitions to dump."""
run_sql = _get_run_sql()
actions = [
dict(id=row[0],
name=row[1],
allowedkeywords=row[2],
optional=row[3])
for action in query.split(',') for row in run_sql(
'select id,... |
def get(*args, **kwargs):
"""Get users."""
from invenio.modules.oauthclient.models import RemoteToken
q = RemoteToken.query
return q.count(), q.all() |
def dump(rt, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the remote tokens as a list of dictionaries.
:param ra: Remote toekn to be dumped.
:type ra: `invenio_oauthclient.models.RemoteToken [Invenio2.x]`
:returns: Remote tokens serialized to dictionary.
:rtype: dict
"""
... |
def load_token(data):
"""Load the oauth2server token from data dump."""
from invenio_oauth2server.models import Token
data['expires'] = iso2dt_or_none(data['expires'])
load_common(Token, data) |
def import_record(data, source_type=None, latest_only=False):
"""Migrate a record from a migration dump.
:param data: Dictionary for representing a single record and files.
:param source_type: Determines if the MARCXML or the JSON dump is used.
Default: ``marcxml``.
:param latest_only: Determin... |
def config_imp_or_default(app, config_var_imp, default):
"""Import config var import path or use default value."""
imp = app.config.get(config_var_imp)
return import_string(imp) if imp else default |
def init_app(self, app):
"""Flask application initialization."""
self.init_config(app.config)
state = _InvenioMigratorState(app)
app.extensions['invenio-migrator'] = state
app.cli.add_command(dumps)
return state |
def get(*args, **kwargs):
"""Get users."""
from invenio.modules.oauth2server.models import Client
q = Client.query
return q.count(), q.all() |
def dump(obj, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the oauth2server Client."""
return dict(name=obj.name,
description=obj.description,
website=obj.website,
user_id=obj.user_id,
client_id=obj.client_id,
cl... |
def _get_users_invenio12(*args, **kwargs):
"""Get user accounts Invenio 1."""
from invenio.dbquery import run_sql, deserialize_via_marshal
User = namedtuple('User', [
'id', 'email', 'password', 'password_salt', 'note', 'full_name',
'settings', 'nickname', 'last_login'
])
users = run_... |
def _get_users_invenio2(*args, **kwargs):
"""Get user accounts from Invenio 2."""
from invenio.modules.accounts.models import User
q = User.query
return q.count(), q.all() |
def get(*args, **kwargs):
"""Get users."""
try:
return _get_users_invenio12(*args, **kwargs)
except ImportError:
return _get_users_invenio2(*args, **kwargs) |
def dump(u, *args, **kwargs):
"""Dump the users as a list of dictionaries.
:param u: User to be dumped.
:type u: `invenio.modules.accounts.models.User [Invenio2.x]` or namedtuple.
:returns: User serialized to dictionary.
:rtype: dict
"""
return dict(
id=u.id,
email=u.email,
... |
def load_deposit(data):
"""Load the raw JSON dump of the Deposition.
Uses Record API in order to bypass all Deposit-specific initialization,
which are to be done after the final stage of deposit migration.
:param data: Dictionary containing deposition data.
:type data: dict
"""
from inveni... |
def create_record_and_pid(data):
"""Create the deposit record metadata and persistent identifier.
:param data: Raw JSON dump of the deposit.
:type data: dict
:returns: A deposit object and its pid
:rtype: (`invenio_records.api.Record`,
`invenio_pidstore.models.PersistentIdentifier`)
... |
def create_files_and_sip(deposit, dep_pid):
"""Create deposit Bucket, Files and SIPs."""
from invenio_pidstore.errors import PIDDoesNotExistError
from invenio_pidstore.models import PersistentIdentifier, PIDStatus, \
RecordIdentifier
from invenio_sipstore.errors import SIPUserDoesNotExist
fr... |
def dump(c, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the community object as dictionary.
:param c: Community to be dumped.
:type c: `invenio.modules.communities.models.Community`
:returns: Community serialized to dictionary.
:rtype: dict
"""
return dict(id=c.id,
... |
def _loadrecord(record_dump, source_type, eager=False):
"""Load a single record into the database.
:param record_dump: Record dump.
:type record_dump: dict
:param source_type: 'json' or 'marcxml'
:param eager: If ``True`` execute the task synchronously.
"""
if eager:
import_record.s... |
def loadrecords(sources, source_type, recid):
"""Load records migration dump."""
# Load all record dumps up-front and find the specific JSON
if recid is not None:
for source in sources:
records = json.load(source)
for item in records:
if str(item['recid']) == ... |
def inspectrecords(sources, recid, entity=None):
"""Inspect records in a migration dump."""
for idx, source in enumerate(sources, 1):
click.echo('Loading dump {0} of {1} ({2})'.format(idx, len(sources),
source.name))
data = json.load(sour... |
def loadcommon(sources, load_task, asynchronous=True, predicate=None,
task_args=None, task_kwargs=None):
"""Common helper function for load simple objects.
.. note::
Keyword arguments ``task_args`` and ``task_kwargs`` are passed to the
``load_task`` function as ``*task_args`` and ``... |
def loadcommunities(sources, logos_dir):
"""Load communities."""
from invenio_migrator.tasks.communities import load_community
loadcommon(sources, load_community, task_args=(logos_dir, )) |
def loadusers(sources):
"""Load users."""
from .tasks.users import load_user
# Cannot be executed asynchronously due to duplicate emails and usernames
# which can create a racing condition.
loadcommon(sources, load_user, asynchronous=False) |
def loaddeposit(sources, depid):
"""Load deposit.
Usage:
invenio dumps loaddeposit ~/data/deposit_dump_*.json
invenio dumps loaddeposit -d 12345 ~/data/deposit_dump_*.json
"""
from .tasks.deposit import load_deposit
if depid is not None:
def pred(dep):
return int... |
def get_profiler_statistics(sort="cum_time", count=20, strip_dirs=True):
"""Return profiler statistics.
:param str sort: dictionary key to sort by
:param int|None count: the number of results to return, None returns all results.
:param bool strip_dirs: if True strip the directory, otherwise return the ... |
def main(port=8888):
"""Run as sample test server."""
import tornado.ioloop
routes = [] + TornadoProfiler().get_routes()
app = tornado.web.Application(routes)
app.listen(port)
tornado.ioloop.IOLoop.current().start() |
def get(self):
"""Return current profiler statistics."""
sort = self.get_argument('sort', 'cum_time')
count = self.get_argument('count', 20)
strip_dirs = self.get_argument('strip_dirs', True)
error = ''
sorts = ('num_calls', 'cum_time', 'total_time',
'cu... |
def post(self):
"""Start a new profiler."""
if is_profiler_running():
self.set_status(201)
self.finish()
return
start_profiling()
self.set_status(201)
self.finish() |
def post(self):
"""Dump current profiler statistics into a file."""
filename = self.get_argument('filename', 'dump.prof')
CProfileWrapper.profiler.dump_stats(filename)
self.finish() |
def get(self):
"""Return current profiler statistics."""
CProfileWrapper.profiler.print_stats()
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(CProfileWrapper.profiler, stream=s).sort_stats(sortby)
ps.print_stats()
self.set_status(200)
sel... |
def delete(self):
"""Clear profiler statistics."""
CProfileWrapper.profiler.create_stats()
self.enable()
self.set_status(204)
self.finish() |
def post(self):
"""Start a new profiler."""
CProfileWrapper.profiler = cProfile.Profile()
CProfileWrapper.profiler.enable()
self.running = True
self.set_status(201)
self.finish() |
def delete(self):
"""Stop the profiler."""
CProfileWrapper.profiler.disable()
self.running = False
self.set_status(204)
self.finish() |
def get(self):
"""Check if the profiler is running."""
self.write({"running": self.running})
self.set_status(200)
self.finish() |
def disable_timestamp(method):
"""Disable timestamp update per method."""
@wraps(method)
def wrapper(*args, **kwargs):
result = None
with correct_date():
result = method(*args, **kwargs)
return result
return wrapper |
def load_user(data):
"""Load user from data dump.
NOTE: This task takes into account the possible duplication of emails and
usernames, hence it should be called synchronously.
In such case of collision it will raise UserEmailExistsError or
UserUsernameExistsError, if email or username are already e... |
def calc_translations_parallel(images):
"""Calculate image translations in parallel.
Parameters
----------
images : ImageCollection
Images as instance of ImageCollection.
Returns
-------
2d array, (ty, tx)
ty and tx is translation to previous image in respectively
x... |
def stitch(images):
"""Stitch regular spaced images.
Parameters
----------
images : ImageCollection or list of tuple(path, row, column)
Each image-tuple should contain path, row and column. Row 0,
column 0 is top left image.
Example:
>>> images = [('1.png', 0, 0), ('2.p... |
def _add_ones_dim(arr):
"Adds a dimensions with ones to array."
arr = arr[..., np.newaxis]
return np.concatenate((arr, np.ones_like(arr)), axis=-1) |
def create(cls, dump):
"""Create record based on dump."""
# If 'record' is not present, just create the PID
if not dump.data.get('record'):
try:
PersistentIdentifier.get(pid_type='recid',
pid_value=dump.recid)
excep... |
def create_record(cls, dump):
"""Create a new record from dump."""
# Reserve record identifier, create record and recid pid in one
# operation.
timestamp, data = dump.latest
record = Record.create(data)
record.model.created = dump.created.replace(tzinfo=None)
reco... |
def update_record(cls, revisions, created, record):
"""Update an existing record."""
for timestamp, revision in revisions:
record.model.json = revision
record.model.created = created.replace(tzinfo=None)
record.model.updated = timestamp.replace(tzinfo=None)
... |
def create_pids(cls, record_uuid, pids):
"""Create persistent identifiers."""
for p in pids:
PersistentIdentifier.create(
pid_type=p.pid_type,
pid_value=p.pid_value,
pid_provider=p.provider.pid_provider if p.provider else None,
... |
def delete_record(cls, record):
"""Delete a record and it's persistent identifiers."""
record.delete()
PersistentIdentifier.query.filter_by(
object_type='rec', object_uuid=record.id,
).update({PersistentIdentifier.status: PIDStatus.DELETED})
cls.delete_buckets(record)... |
def create_files(cls, record, files, existing_files):
"""Create files.
This method is currently limited to a single bucket per record.
"""
default_bucket = None
# Look for bucket id in existing files.
for f in existing_files:
if 'bucket' in f:
... |
def create_file(self, bucket, key, file_versions):
"""Create a single file with all versions."""
objs = []
for file_ver in file_versions:
f = FileInstance.create().set_uri(
file_ver['full_path'],
file_ver['size'],
'md5:{0}'.format(file_... |
def delete_buckets(cls, record):
"""Delete the bucket."""
files = record.get('_files', [])
buckets = set()
for f in files:
buckets.add(f.get('bucket'))
for b_id in buckets:
b = Bucket.get(b_id)
b.deleted = True |
def missing_pids(self):
"""Filter persistent identifiers."""
missing = []
for p in self.pids:
try:
PersistentIdentifier.get(p.pid_type, p.pid_value)
except PIDDoesNotExistError:
missing.append(p)
return missing |
def prepare_revisions(self):
"""Prepare data."""
# Prepare revisions
self.revisions = []
it = [self.data['record'][0]] if self.latest_only \
else self.data['record']
for i in it:
self.revisions.append(self._prepare_revision(i)) |
def prepare_files(self):
"""Get files from data dump."""
# Prepare files
files = {}
for f in self.data['files']:
k = f['full_name']
if k not in files:
files[k] = []
files[k].append(f)
# Sort versions
for k in files.keys... |
def prepare_pids(self):
"""Prepare persistent identifiers."""
self.pids = []
for fetcher in self.pid_fetchers:
val = fetcher(None, self.revisions[-1][1])
if val:
self.pids.append(val) |
def is_deleted(self, record=None):
"""Check if record is deleted."""
record = record or self.revisions[-1][1]
return any(
col == 'deleted'
for col in record.get('collections', [])
) |
def load_community(data, logos_dir):
"""Load community from data dump.
:param data: Dictionary containing community data.
:type data: dict
:param logos_dir: Path to a local directory with community logos.
:type logos_dir: str
"""
from invenio_communities.models import Community
from inv... |
def load_featured(data):
"""Load community featuring from data dump.
:param data: Dictionary containing community featuring data.
:type data: dict
"""
from invenio_communities.models import FeaturedCommunity
obj = FeaturedCommunity(id=data['id'],
id_community=data['i... |
def dump(thing, query, from_date, file_prefix, chunk_size, limit, thing_flags):
"""Dump data from Invenio legacy."""
init_app_context()
file_prefix = file_prefix if file_prefix else '{0}_dump'.format(thing)
kwargs = dict((f.strip('-').replace('-', '_'), True) for f in thing_flags)
try:
th... |
def check(thing):
"""Check data in Invenio legacy."""
init_app_context()
try:
thing_func = collect_things_entry_points()[thing]
except KeyError:
click.Abort(
'{0} is not in the list of available things to migrate: '
'{1}'.format(thing, collect_things_entry_points... |
def registerEventHandlers(self):
"""
Registers event handlers used by this widget, e.g. mouse click/motion and window resize.
This will allow the widget to redraw itself upon resizing of the window in case the position needs to be adjusted.
"""
self.peng.registerEventHan... |
def pos(self):
"""
Property that will always be a 2-tuple representing the position of the widget.
Note that this method may call the method given as ``pos`` in the initializer.
The returned object will actually be an instance of a helper class to allow for setting only... |
def size(self):
"""
Similar to :py:attr:`pos` but for the size instead.
"""
if isinstance(self._size,list) or isinstance(self._size,tuple):
s = self._size
elif callable(self._size):
w,h = self.submenu.size[:]
s = self._size(w,h)
else:
... |
def clickable(self):
"""
Property used for determining if the widget should be clickable by the user.
This is only true if the submenu of this widget is active and this widget is enabled.
The widget may be either disabled by setting this property or the :py:attr:`enable... |
def delete(self):
"""
Deletes resources of this widget that require manual cleanup.
Currently removes all actions, event handlers and the background.
The background itself should automatically remove all vertex lists to avoid visual artifacts.
Note that... |
def on_redraw(self):
"""
Draws the background and the widget itself.
Subclasses should use ``super()`` to call this method, or rendering may glitch out.
"""
if self.bg is not None:
if not self.bg.initialized:
self.bg.init_bg()
... |
def calcSphereCoordinates(pos,radius,rot):
"""
Calculates the Cartesian coordinates from spherical coordinates.
``pos`` is a simple offset to offset the result with.
``radius`` is the radius of the input.
``rot`` is a 2-tuple of ``(azimuth,polar)`` angles.
Angles are given in... |
def v_magnitude(v):
"""
Simple vector helper function returning the length of a vector.
``v`` may be any vector, with any number of dimensions
"""
return math.sqrt(sum(v[i]*v[i] for i in range(len(v)))) |
def v_normalize(v):
"""
Normalizes the given vector.
The vector given may have any number of dimensions.
"""
vmag = v_magnitude(v)
return [ v[i]/vmag for i in range(len(v)) ] |
def transformTexCoords(self,data,texcoords,dims=2):
"""
Transforms the given texture coordinates using the internal texture coordinates.
Currently, the dimensionality of the input texture coordinates must always be 2 and the output is 3-dimensional with the last coordinate always being ... |
def ensureBones(self,data):
"""
Helper method ensuring per-entity bone data has been properly initialized.
Should be called at the start of every method accessing per-entity data.
``data`` is the entity to check in dictionary form.
"""
if "_bones" not in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.