_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q278300
|
create_record_and_pid
|
test
|
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`)
"""
from invenio_records.api import Record
from invenio_pidstore.models import PersistentIdentifier, PIDStatus, \
RecordIdentifier
deposit = Record.create(data=data)
created = arrow.get(data['_p']['created']).datetime
deposit.model.created = created.replace(tzinfo=None)
|
python
|
{
"resource": ""
}
|
q278301
|
_loadrecord
|
test
|
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(record_dump, source_type=source_type).apply(throw=True)
elif current_migrator.records_post_task:
|
python
|
{
"resource": ""
}
|
q278302
|
loadrecords
|
test
|
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']) == str(recid):
_loadrecord(item, source_type, eager=True)
click.echo("Record '{recid}' loaded.".format(recid=recid))
return
click.echo("Record '{recid}' not found.".format(recid=recid))
else:
for idx,
|
python
|
{
"resource": ""
}
|
q278303
|
inspectrecords
|
test
|
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(source)
# Just print record identifiers if none are selected.
if not recid:
click.secho('Record identifiers', fg='green')
total = 0
for r in (d['recid'] for d in data):
click.echo(r)
total += 1
click.echo('{0} records found in dump.'.format(total))
return
data = list(filter(lambda d: d['recid'] == recid, data))
if not data:
click.secho("Record not found.", fg='yellow')
return
for record in data:
if entity is None:
click.echo(json.dumps(record, indent=2))
if entity == 'files':
click.secho('Files', fg='green')
click.echo(
|
python
|
{
"resource": ""
}
|
q278304
|
loadcommon
|
test
|
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 ``**task_kwargs``.
.. note::
The `predicate` argument is used as a predicate function to load only
a *single* item from across all dumps (this CLI function will return
after loading the item). This is primarily used for debugging of
the *dirty* data within the dump. The `predicate` should be a function
with a signature ``f(dict) -> bool``, i.e. taking a single parameter
(an item from the dump) and return ``True`` if the item
should be loaded. See the ``loaddeposit`` for a concrete example.
:param sources: JSON source files with dumps
:type sources: list of str (filepaths)
:param load_task: Shared task which loads the dump.
:type load_task: function
:param asynchronous: Flag for serial or asynchronous execution of the task.
:type asynchronous: bool
:param predicate: Predicate for selecting only a single item from the dump.
:type predicate: function
:param task_args: positional arguments passed to the task.
:type task_args: tuple
:param task_kwargs: named arguments passed to the task.
:type task_kwargs: dict
"""
# resolve the defaults for task_args and task_kwargs
task_args = tuple() if task_args is None else task_args
task_kwargs = dict() if task_kwargs is None else task_kwargs
click.echo('Loading dumps started.')
for idx, source in enumerate(sources, 1):
|
python
|
{
"resource": ""
}
|
q278305
|
loadcommunities
|
test
|
def loadcommunities(sources, logos_dir):
"""Load communities."""
from invenio_migrator.tasks.communities import load_community
|
python
|
{
"resource": ""
}
|
q278306
|
loadusers
|
test
|
def loadusers(sources):
"""Load users."""
from .tasks.users import load_user
# Cannot be executed asynchronously due to duplicate emails and usernames
|
python
|
{
"resource": ""
}
|
q278307
|
loaddeposit
|
test
|
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):
|
python
|
{
"resource": ""
}
|
q278308
|
get_profiler_statistics
|
test
|
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 full path
"""
json_stats = []
pstats = yappi.convert2pstats(yappi.get_func_stats())
if strip_dirs:
pstats.strip_dirs()
for func, func_stat in pstats.stats.iteritems():
path, line, func_name = func
cc, num_calls, total_time, cum_time, callers = func_stat
json_stats.append({
"path": path,
|
python
|
{
"resource": ""
}
|
q278309
|
main
|
test
|
def main(port=8888):
"""Run as sample test server."""
import tornado.ioloop
routes = [] + TornadoProfiler().get_routes()
app =
|
python
|
{
"resource": ""
}
|
q278310
|
CProfileStatsDumpHandler.post
|
test
|
def post(self):
"""Dump current profiler statistics into a file."""
filename = self.get_argument('filename', 'dump.prof')
|
python
|
{
"resource": ""
}
|
q278311
|
CProfileStatsHandler.delete
|
test
|
def delete(self):
"""Clear profiler statistics."""
CProfileWrapper.profiler.create_stats()
|
python
|
{
"resource": ""
}
|
q278312
|
CProfileHandler.delete
|
test
|
def delete(self):
"""Stop the profiler."""
CProfileWrapper.profiler.disable()
self.running
|
python
|
{
"resource": ""
}
|
q278313
|
CProfileHandler.get
|
test
|
def get(self):
"""Check if the profiler is running."""
self.write({"running": self.running})
|
python
|
{
"resource": ""
}
|
q278314
|
disable_timestamp
|
test
|
def disable_timestamp(method):
"""Disable timestamp update per method."""
@wraps(method)
def wrapper(*args, **kwargs):
result = None
|
python
|
{
"resource": ""
}
|
q278315
|
load_user
|
test
|
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 existing in
the database. Caller of this task should take care to to resolve those
collisions beforehand or after catching an exception.
:param data: Dictionary containing user data.
:type data: dict
"""
from invenio_accounts.models import User
from invenio_userprofiles.api import UserProfile
email = data['email'].strip()
if User.query.filter_by(email=email).count() > 0:
raise UserEmailExistsError(
"User email '{email}' already exists.".format(email=email))
last_login = None
if data['last_login']:
last_login = arrow.get(data['last_login']).datetime
confirmed_at = None
if data['note'] == '1':
confirmed_at = datetime.utcnow()
salt = data['password_salt']
checksum = data['password']
if not checksum:
new_password = None
# Test if password hash is in Modular Crypt Format
elif checksum.startswith('$'):
new_password = checksum
else:
new_password = str.join('$', ['', u'invenio-aes', salt, checksum])
with db.session.begin_nested():
obj = User(
id=data['id'],
password=new_password,
email=email,
confirmed_at=confirmed_at,
last_login_at=last_login,
active=(data['note'] != '0'),
)
|
python
|
{
"resource": ""
}
|
q278316
|
calc_translations_parallel
|
test
|
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 or y direction.
"""
w = Parallel(n_jobs=_CPUS)
|
python
|
{
"resource": ""
}
|
q278317
|
stitch
|
test
|
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.png', 0, 1)]
Returns
-------
tuple (stitched, offset)
Stitched image and registered offset (y, x).
"""
if type(images) != ImageCollection:
images = ImageCollection(images)
calc_translations_parallel(images)
_translation_warn(images)
yoffset, xoffset = images.median_translation()
if xoffset != yoffset:
warn('yoffset != xoffset: %s != %s' % (yoffset, xoffset))
# assume all images have the same shape
y, x = imread(images[0].path).shape
height = y*len(images.rows) + yoffset*(len(images.rows)-1)
width = x*len(images.cols) +
|
python
|
{
"resource": ""
}
|
q278318
|
_add_ones_dim
|
test
|
def _add_ones_dim(arr):
"Adds a dimensions with ones to array."
arr = arr[..., np.newaxis]
|
python
|
{
"resource": ""
}
|
q278319
|
RecordDumpLoader.create
|
test
|
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)
except PIDDoesNotExistError:
PersistentIdentifier.create(
'recid', dump.recid,
status=PIDStatus.RESERVED
)
db.session.commit()
return None
dump.prepare_revisions()
dump.prepare_pids()
dump.prepare_files()
# Create or update?
existing_files = []
if dump.record:
existing_files = dump.record.get('_files', [])
record = cls.update_record(revisions=dump.revisions,
created=dump.created,
|
python
|
{
"resource": ""
}
|
q278320
|
RecordDumpLoader.create_record
|
test
|
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)
record.model.updated = timestamp.replace(tzinfo=None)
|
python
|
{
"resource": ""
}
|
q278321
|
RecordDumpLoader.update_record
|
test
|
def update_record(cls, revisions, created, record):
"""Update an existing record."""
for timestamp, revision in revisions:
record.model.json = revision
|
python
|
{
"resource": ""
}
|
q278322
|
RecordDumpLoader.create_pids
|
test
|
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
|
python
|
{
"resource": ""
}
|
q278323
|
RecordDumpLoader.delete_record
|
test
|
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,
|
python
|
{
"resource": ""
}
|
q278324
|
RecordDumpLoader.create_files
|
test
|
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:
default_bucket = f['bucket']
break
# Create a bucket in default location if none is found.
if default_bucket is None:
b = Bucket.create()
BucketTag.create(b, 'record', str(record.id))
default_bucket = str(b.id)
db.session.commit()
else:
b = Bucket.get(default_bucket)
record['_files'] = []
for key, meta in files.items():
obj = cls.create_file(b, key, meta)
ext = splitext(obj.key)[1].lower()
if ext.startswith('.'):
ext = ext[1:]
|
python
|
{
"resource": ""
}
|
q278325
|
RecordDumpLoader.create_file
|
test
|
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'],
|
python
|
{
"resource": ""
}
|
q278326
|
RecordDumpLoader.delete_buckets
|
test
|
def delete_buckets(cls, record):
"""Delete the bucket."""
files = record.get('_files', [])
buckets =
|
python
|
{
"resource": ""
}
|
q278327
|
RecordDump.missing_pids
|
test
|
def missing_pids(self):
"""Filter persistent identifiers."""
missing = []
for p in self.pids:
try:
PersistentIdentifier.get(p.pid_type, p.pid_value)
|
python
|
{
"resource": ""
}
|
q278328
|
RecordDump.prepare_revisions
|
test
|
def prepare_revisions(self):
"""Prepare data."""
# Prepare revisions
self.revisions = []
it = [self.data['record'][0]] if self.latest_only \
|
python
|
{
"resource": ""
}
|
q278329
|
RecordDump.prepare_files
|
test
|
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] = []
|
python
|
{
"resource": ""
}
|
q278330
|
RecordDump.prepare_pids
|
test
|
def prepare_pids(self):
"""Prepare persistent identifiers."""
self.pids = []
for fetcher in self.pid_fetchers:
|
python
|
{
"resource": ""
}
|
q278331
|
RecordDump.is_deleted
|
test
|
def is_deleted(self, record=None):
"""Check if record is deleted."""
record = record or self.revisions[-1][1]
return any(
|
python
|
{
"resource": ""
}
|
q278332
|
load_community
|
test
|
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 invenio_communities.utils import save_and_validate_logo
logo_ext_washed = logo_ext_wash(data['logo_ext'])
c = Community(
id=data['id'],
id_user=data['id_user'],
title=data['title'],
description=data['description'],
page=data['page'],
curation_policy=data['curation_policy'],
last_record_accepted=iso2dt_or_none(data['last_record_accepted']),
logo_ext=logo_ext_washed,
ranking=data['ranking'],
|
python
|
{
"resource": ""
}
|
q278333
|
load_featured
|
test
|
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'],
|
python
|
{
"resource": ""
}
|
q278334
|
dump
|
test
|
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:
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()))
click.echo("Querying {0}...".format(thing))
count, items = thing_func.get(query, from_date, limit=limit, **kwargs)
progress_i = 0 # Progress bar counter
click.echo("Dumping {0}...".format(thing))
with click.progressbar(length=count) as bar:
for i, chunk_ids in enumerate(grouper(items, chunk_size)):
with open('{0}_{1}.json'.format(file_prefix, i), 'w') as fp:
fp.write("[\n")
for _id in chunk_ids:
try:
json.dump(
|
python
|
{
"resource": ""
}
|
q278335
|
check
|
test
|
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()))
click.echo("Querying {0}...".format(thing))
count, items = thing_func.get_check()
i
|
python
|
{
"resource": ""
}
|
q278336
|
BasicWidget.delete
|
test
|
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 this method is currently experimental, as it seems to have a memory leak.
"""
# TODO: fix memory leak upon widget deletion
del self.bg.widget
del self.bg
#self.clickable=False
del self._pos
del self._size
self.actions = {}
for e_type,e_handlers in self.peng.eventHandlers.items():
if True or e_type in eh:
to_del = []
for e_handler in e_handlers:
# Weird workaround due to implementation details of WeakMethod
if isinstance(e_handler,weakref.ref):
|
python
|
{
"resource": ""
}
|
q278337
|
v_magnitude
|
test
|
def v_magnitude(v):
"""
Simple vector helper function returning the length of a vector.
``v`` may be any vector, with any number of
|
python
|
{
"resource": ""
}
|
q278338
|
v_normalize
|
test
|
def v_normalize(v):
"""
Normalizes the given vector.
The vector given may
|
python
|
{
"resource": ""
}
|
q278339
|
Material.transformTexCoords
|
test
|
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 zero.
The given texture coordinates are fitted to the internal texture coordinates. Note that values higher than 1 or lower than 0 may result in unexpected visual glitches.
The length of the given texture coordinates should be divisible by the dimensionality.
"""
assert dims==2 # TODO
|
python
|
{
"resource": ""
}
|
q278340
|
Bone.ensureBones
|
test
|
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.
|
python
|
{
"resource": ""
}
|
q278341
|
Bone.setLength
|
test
|
def setLength(self,data,blength):
"""
Sets the length of this bone on the given entity.
``data`` is the entity
|
python
|
{
"resource": ""
}
|
q278342
|
Bone.setParent
|
test
|
def setParent(self,parent):
"""
Sets the parent of this bone for all entities.
Note that this method must be called before many other methods
|
python
|
{
"resource": ""
}
|
q278343
|
Bone.getPivotPoint
|
test
|
def getPivotPoint(self,data):
"""
Returns the point this bone pivots around on the given entity.
This method works recursively by calling its parent and then adding its own offset.
The resulting coordinate is relative to the entity, not the world.
|
python
|
{
"resource": ""
}
|
q278344
|
Animation.startAnimation
|
test
|
def startAnimation(self,data,jumptype):
"""
Callback that is called to initialize this animation on a specific actor.
Internally sets the ``_anidata`` key of the given dict ``data``\ .
``jumptype`` is either ``jump`` or ``animate`` to define how to switch to this animation.
|
python
|
{
"resource": ""
}
|
q278345
|
JSONModelGroup.set_state
|
test
|
def set_state(self):
"""
Sets the state required for this actor.
|
python
|
{
"resource": ""
}
|
q278346
|
JSONModelGroup.unset_state
|
test
|
def unset_state(self):
"""
Resets the state required for this actor to the default state.
Currently
|
python
|
{
"resource": ""
}
|
q278347
|
JSONRegionGroup.set_state
|
test
|
def set_state(self):
"""
Sets the state required for this vertex region.
Currently binds and enables the texture of the
|
python
|
{
"resource": ""
}
|
q278348
|
JSONRegionGroup.unset_state
|
test
|
def unset_state(self):
"""
Resets the state required for this actor to the default state.
Currently only disables the target of the texture of the material, it may still be bound.
|
python
|
{
"resource": ""
}
|
q278349
|
Model.ensureModelData
|
test
|
def ensureModelData(self,obj):
"""
Ensures that the given ``obj`` has been initialized to be used with this model.
If the object is found to not be initialized, it will be initialized.
"""
if not hasattr(obj,"_modeldata"):
|
python
|
{
"resource": ""
}
|
q278350
|
Model.redraw
|
test
|
def redraw(self,obj):
"""
Redraws the model of the given object.
Note that currently this method probably won't change any data since all movement and animation is done through pyglet groups.
"""
self.ensureModelData(obj)
data = obj._modeldata
|
python
|
{
"resource": ""
}
|
q278351
|
Model.draw
|
test
|
def draw(self,obj):
"""
Actually draws the model of the given object to the render target.
Note that if the batch used for this object already existed,
|
python
|
{
"resource": ""
}
|
q278352
|
Actor.setModel
|
test
|
def setModel(self,model):
"""
Sets the model this actor should use when drawing.
This method also automatically initializes the new model and removes the old, if any.
|
python
|
{
"resource": ""
}
|
q278353
|
XunitDestination.write_reports
|
test
|
def write_reports(self, relative_path, suite_name, reports,
package_name=None):
"""write the collection of reports to the given path"""
dest_path = self.reserve_file(relative_path)
|
python
|
{
"resource": ""
}
|
q278354
|
toxml
|
test
|
def toxml(test_reports, suite_name,
hostname=gethostname(), package_name="tests"):
"""convert test reports into an xml file"""
testsuites = et.Element("testsuites")
testsuite = et.SubElement(testsuites, "testsuite")
test_count = len(test_reports)
if test_count < 1:
raise ValueError('there must be at least one test report')
assert test_count > 0, 'expecting at least one test'
error_count = len([r for r in test_reports if r.errors])
failure_count = len([r for r in test_reports if r.failures])
ts = test_reports[0].start_ts
start_timestamp = datetime.fromtimestamp(ts).isoformat()
total_duration = test_reports[-1].end_ts - test_reports[0].start_ts
def quote_attribute(value):
return value if value is not None else "(null)"
testsuite.attrib = dict(
id="0",
errors=str(error_count),
failures=str(failure_count),
tests=str(test_count),
hostname=quote_attribute(hostname),
timestamp=quote_attribute(start_timestamp),
time="%f" % total_duration,
name=quote_attribute(suite_name),
package=quote_attribute(package_name),
)
for r in test_reports:
test_name = r.name
test_duration = r.end_ts - r.start_ts
class_name = r.src_location
testcase = et.SubElement(testsuite, "testcase")
testcase.attrib = dict(
|
python
|
{
"resource": ""
}
|
q278355
|
PengWindow.addMenu
|
test
|
def addMenu(self,menu):
"""
Adds a menu to the list of menus.
"""
# If there is no menu selected currently, this menu will automatically
|
python
|
{
"resource": ""
}
|
q278356
|
Label.redraw_label
|
test
|
def redraw_label(self):
"""
Re-draws the text by calculating its position.
Currently, the text will always be centered on the position of the label.
"""
# Convenience variables
sx,sy = self.size
x,y = self.pos
# Label position
self._label.font_name = self.font_name
|
python
|
{
"resource": ""
}
|
q278357
|
TextInput.redraw_label
|
test
|
def redraw_label(self):
"""
Re-draws the label by calculating its position.
Currently, the label will always be centered on the position of the label.
"""
# Convenience variables
sx,sy = self.size
x,y = self.pos
# Label position
x = x+self.bg.border[0]
y = y+sy/2.-self._text.font_size/4.
w = self.size[0]
h = self.size[1]
self._text.x,self._text.y = x,y
self._text.width,self._text.height=w,h
|
python
|
{
"resource": ""
}
|
q278358
|
SubMenu.draw
|
test
|
def draw(self):
"""
Draws the submenu and its background.
Note that this leaves the OpenGL state set to 2d drawing.
"""
# Sets the OpenGL state for 2D-Drawing
self.window.set2d()
# Draws the background
if isinstance(self.bg,Layer):
self.bg._draw()
elif hasattr(self.bg,"draw") and callable(self.bg.draw):
self.bg.draw()
elif isinstance(self.bg,list) or isinstance(self.bg,tuple):
self.bg_vlist.draw(GL_QUADS)
elif callable(self.bg):
self.bg()
elif isinstance(self.bg,Background):
# The background will be drawn via the batch
if not self.bg.initialized:
self.bg.init_bg()
self.bg.redraw_bg()
self.bg.initialized=True
elif self.bg=="blank":
pass
else:
raise TypeError("Unknown background type")
|
python
|
{
"resource": ""
}
|
q278359
|
SubMenu.delWidget
|
test
|
def delWidget(self,widget):
"""
Deletes the widget by the given name.
Note that this feature is currently experimental as there seems to be a memory leak with this method.
"""
# TODO: fix memory leak upon widget deletion
#print("*"*50)
#print("Start delWidget")
if isinstance(widget,BasicWidget):
widget = widget.name
if widget not in self.widgets:
return
w = self.widgets[widget]
#print("refs: %s"%sys.getrefcount(w))
w.delete()
del self.widgets[widget]
del widget
#w_wref = weakref.ref(w)
#print("GC: GARBAGE")
#print(gc.garbage)
#print("Widget Info")
#print(w_wref())
#import objgraph
#print("Objgraph")
|
python
|
{
"resource": ""
}
|
q278360
|
Checkbox.redraw_label
|
test
|
def redraw_label(self):
"""
Re-calculates the position of the Label.
"""
# Convenience variables
sx,sy = self.size
x,y = self.pos
# Label position
|
python
|
{
"resource": ""
}
|
q278361
|
EgoMouseRotationalController.registerEventHandlers
|
test
|
def registerEventHandlers(self):
"""
Registers the motion and drag handlers.
Note that because of the way pyglet treats mouse dragging, there is also an handler registered to the on_mouse_drag event.
|
python
|
{
"resource": ""
}
|
q278362
|
BasicFlightController.registerEventHandlers
|
test
|
def registerEventHandlers(self):
"""
Registers the up and down handlers.
Also registers a scheduled function every 60th of a second, causing pyglet to redraw your window with 60fps.
"""
# Crouch/fly down
self.peng.keybinds.add(self.peng.cfg["controls.controls.crouch"],"peng3d:actor.%s.player.controls.crouch"%self.actor.uuid,self.on_crouch_down,False)
# Jump/fly up
|
python
|
{
"resource": ""
}
|
q278363
|
DialogSubMenu.add_label_main
|
test
|
def add_label_main(self,label_main):
"""
Adds the main label of the dialog.
This widget can be triggered by setting the label ``label_main`` to a string.
This widget will be centered on the screen.
"""
# Main Label
self.wlabel_main = text.Label("label_main",self,self.window,self.peng,
pos=lambda sw,sh, bw,bh: (sw/2-bw/2,sh/2-bh/2),
size=[0,0],
|
python
|
{
"resource": ""
}
|
q278364
|
DialogSubMenu.add_btn_ok
|
test
|
def add_btn_ok(self,label_ok):
"""
Adds an OK button to allow the user to exit the dialog.
This widget can be triggered by setting the label ``label_ok`` to a string.
This widget will be mostly centered on the screen, but below the main label
by the double of its height.
"""
# OK Button
self.wbtn_ok = button.Button("btn_ok",self,self.window,self.peng,
|
python
|
{
"resource": ""
}
|
q278365
|
DialogSubMenu.exitDialog
|
test
|
def exitDialog(self):
"""
Helper method that exits the dialog.
This method will cause the previously active submenu to activate.
"""
if self.prev_submenu is not None:
# change back to the previous submenu
|
python
|
{
"resource": ""
}
|
q278366
|
ConfirmSubMenu.add_btn_confirm
|
test
|
def add_btn_confirm(self,label_confirm):
"""
Adds a confirm button to let the user confirm whatever action they were presented with.
This widget can be triggered by setting the label ``label_confirm`` to a string.
This widget will be positioned slightly below the main label and to the left
of the cancel button.
"""
# Confirm Button
self.wbtn_confirm = button.Button("btn_confirm",self,self.window,self.peng,
|
python
|
{
"resource": ""
}
|
q278367
|
ConfirmSubMenu.add_btn_cancel
|
test
|
def add_btn_cancel(self,label_cancel):
"""
Adds a cancel button to let the user cancel whatever choice they were given.
This widget can be triggered by setting the label ``label_cancel`` to a string.
This widget will be positioned slightly below the main label and to the right
of the confirm button.
"""
# Cancel Button
self.wbtn_cancel = button.Button("btn_cancel",self,self.window,self.peng,
|
python
|
{
"resource": ""
}
|
q278368
|
ProgressSubMenu.update_progressbar
|
test
|
def update_progressbar(self):
"""
Updates the progressbar by re-calculating the label.
It is not required to manually call this method since setting any of the
properties of this class will automatically trigger a re-calculation.
"""
n,nmin,nmax = self.wprogressbar.n,self.wprogressbar.nmin,self.wprogressbar.nmax
if (nmax-nmin)==0:
percent = 0 # prevents ZeroDivisionError
|
python
|
{
"resource": ""
}
|
q278369
|
World.render3d
|
test
|
def render3d(self,view=None):
"""
Renders the world in 3d-mode.
If you want to render custom terrain, you may override this method. Be careful that you still call the original method or else actors may
|
python
|
{
"resource": ""
}
|
q278370
|
StaticWorld.render3d
|
test
|
def render3d(self,view=None):
"""
Renders the world.
|
python
|
{
"resource": ""
}
|
q278371
|
Recorder.step
|
test
|
def step(self, step_name):
"""Start a new step. returns a context manager which allows you to
report an error"""
@contextmanager
def step_context(step_name):
if self.event_receiver.current_case is not None:
raise Exception('cannot open a step within a step')
self.event_receiver.begin_case(step_name, self.now_seconds(), self.name)
try:
yield self.event_receiver
except:
|
python
|
{
"resource": ""
}
|
q278372
|
ResourceManager.resourceExists
|
test
|
def resourceExists(self,name,ext=""):
"""
Returns whether or not the resource with the given name and extension exists.
This
|
python
|
{
"resource": ""
}
|
q278373
|
ResourceManager.addCategory
|
test
|
def addCategory(self,name):
"""
Adds a new texture category with the given name.
If the category already exists, it will be overridden.
"""
self.categories[name]={}
|
python
|
{
"resource": ""
}
|
q278374
|
ResourceManager.getMissingTexture
|
test
|
def getMissingTexture(self):
"""
Returns a texture to be used as a placeholder for missing textures.
A default missing texture file is provided in the assets folder of the source distribution.
It consists of a simple checkerboard pattern of purple and black, this image may be copied to any project using peng3d for similar behavior.
If this texture cannot be found, a pattern is created in-memory, simply a solid square of purple.
This texture will also be cached separately from other textures.
"""
if self.missingTexture is None:
if self.resourceExists(self.missingtexturename,".png"):
|
python
|
{
"resource": ""
}
|
q278375
|
ResourceManager.getModel
|
test
|
def getModel(self,name):
"""
Gets the model object by the given name.
If it was loaded previously, a cached version will be returned.
If it was not loaded, it will be loaded and inserted into the cache.
"""
|
python
|
{
"resource": ""
}
|
q278376
|
ResourceManager.loadModel
|
test
|
def loadModel(self,name):
"""
Loads the model of the given name.
The model will also be inserted into the cache.
"""
|
python
|
{
"resource": ""
}
|
q278377
|
ResourceManager.getModelData
|
test
|
def getModelData(self,name):
"""
Gets the model data associated with the given name.
If it was loaded, a cached copy will be returned.
It it was not loaded, it will be loaded and cached.
"""
|
python
|
{
"resource": ""
}
|
q278378
|
ResourceManager.loadModelData
|
test
|
def loadModelData(self,name):
"""
Loads the model data of the given name.
The model file must always be a .json file.
"""
path = self.resourceNameToPath(name,".json")
try:
data = json.load(open(path,"r"))
except Exception:
# Temporary
print("Exception during model load: ")
import traceback;traceback.print_exc()
return {}# will probably cause other exceptions later on, TODO
out = {}
if data.get("version",1)==1:
# Currently only one version, basic future-proofing
# This version should get incremented with breaking changes to the structure
# Materials
out["materials"]={}
for name,matdata in data.get("materials",{}).items():
m = model.Material(self,name,matdata)
out["materials"][name]=m
out["default_material"]=out["materials"][data.get("default_material",list(out["materials"].keys())[0])]
|
python
|
{
"resource": ""
}
|
q278379
|
Container.addWidget
|
test
|
def addWidget(self,widget):
"""
Adds a widget to this container.
Note that trying to add the Container to itself will be
|
python
|
{
"resource": ""
}
|
q278380
|
Container.draw
|
test
|
def draw(self):
"""
Draws the submenu and its background.
Note that this leaves the OpenGL state set to 2d drawing and may modify the scissor settings.
"""
if not self.visible:
# Simple visibility check, has to be tested to see if it works properly
return
|
python
|
{
"resource": ""
}
|
q278381
|
Container.on_redraw
|
test
|
def on_redraw(self):
"""
Redraws the background and any child widgets.
"""
x,y = self.pos
sx,sy = self.size
self.bg_vlist.vertices = [x,y, x+sx,y, x+sx,y+sy, x,y+sy]
self.stencil_vlist.vertices = [x,y, x+sx,y, x+sx,y+sy, x,y+sy]
|
python
|
{
"resource": ""
}
|
q278382
|
ScrollableContainer.on_redraw
|
test
|
def on_redraw(self):
"""
Redraws the background and contents, including scrollbar.
This method will also check the scrollbar for any movement and will be automatically called on movement of the slider.
"""
n = self._scrollbar.n
self.offset_y = -n # Causes the content to move in the opposite direction of the slider
# Size of scrollbar
sx=24 # Currently constant, TODO: add dynamic sx of scrollbar
sy=self.size[1]
# Pos of scrollbar
x=self.size[0]-sx
y=0 # Currently constant, TODO: add dynamic y-pos of scrollbar
|
python
|
{
"resource": ""
}
|
q278383
|
mouse_aabb
|
test
|
def mouse_aabb(mpos,size,pos):
"""
AABB Collision checker that can be used for most axis-aligned collisions.
Intended for use in widgets to check if the mouse is within the bounds of
|
python
|
{
"resource": ""
}
|
q278384
|
Slider.p
|
test
|
def p(self):
"""
Helper property containing the percentage this slider is "filled".
|
python
|
{
"resource": ""
}
|
q278385
|
Menu.addLayer
|
test
|
def addLayer(self,layer,z=-1):
"""
Adds a new layer to the stack, optionally at the specified z-value.
``layer`` must be an instance of Layer or subclasses.
``z`` can be used to override the index of the layer in the stack. Defaults to ``-1`` for appending.
|
python
|
{
"resource": ""
}
|
q278386
|
_get_region
|
test
|
def _get_region(self, buffer, start, count):
'''Map a buffer region using this attribute as an accessor.
The returned region can be modified as if the buffer was a contiguous
array of this attribute (though it may actually be interleaved or
otherwise non-contiguous).
The returned region consists of a contiguous array of component
data elements. For example, if this attribute uses 3 floats per
vertex, and the `count` parameter is 4, the number of floats mapped
will be ``3 * 4 = 12``.
:Parameters:
`buffer` : `AbstractMappable`
The buffer to map.
`start` : int
Offset of the first vertex to map.
`count` : int
Number of vertices to map
:rtype: `AbstractBufferRegion`
'''
byte_start = self.stride * start
byte_size = self.stride * count
array_count = self.count * count
if self.stride == self.size or not array_count:
# non-interleaved
ptr_type = ctypes.POINTER(self.c_type *
|
python
|
{
"resource": ""
}
|
q278387
|
_draw
|
test
|
def _draw(self, mode, vertex_list=None):
'''Draw vertices in the domain.
If `vertex_list` is not specified, all vertices in the domain are
drawn. This is the most efficient way to render primitives.
If `vertex_list` specifies a `VertexList`, only primitives in that
list will be drawn.
:Parameters:
`mode` : int
OpenGL drawing mode, e.g. ``GL_POINTS``, ``GL_LINES``, etc.
`vertex_list` : `VertexList`
Vertex list to draw, or ``None`` for all lists in this domain.
'''
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
for buffer, attributes in self.buffer_attributes:
buffer.bind()
for attribute in attributes:
attribute.enable()
attribute.set_pointer(attribute.buffer.ptr)
if vertexbuffer._workaround_vbo_finish:
glFinish()
if vertex_list is not None:
glDrawArrays(mode, vertex_list.start, vertex_list.count)
else:
starts, sizes = self.allocator.get_allocated_regions()
primcount = len(starts)
|
python
|
{
"resource": ""
}
|
q278388
|
ActionDispatcher.addAction
|
test
|
def addAction(self,action,func,*args,**kwargs):
"""
Adds a callback to the specified action.
All other positional and keyword arguments will be stored and passed to the function upon activation.
"""
if not hasattr(self,"actions"):
|
python
|
{
"resource": ""
}
|
q278389
|
ActionDispatcher.doAction
|
test
|
def doAction(self,action):
"""
Helper method that calls all callbacks registered for the given action.
"""
if not hasattr(self,"actions"):
return
|
python
|
{
"resource": ""
}
|
q278390
|
SmartRegistry.register
|
test
|
def register(self,name,force_id=None):
"""
Registers a name to the registry.
``name`` is the name of the object and must be a string.
``force_id`` can be optionally set to override the automatic ID generation
and force a specific ID.
Note that using ``force_id`` is discouraged, since it
|
python
|
{
"resource": ""
}
|
q278391
|
LayeredWidget.addLayer
|
test
|
def addLayer(self,layer,z_index=None):
"""
Adds the given layer at the given Z Index.
If ``z_index`` is not given, the Z Index specified by the layer will be used.
|
python
|
{
"resource": ""
}
|
q278392
|
LayeredWidget.draw
|
test
|
def draw(self):
"""
Draws all layers of this LayeredWidget.
This should normally be unneccessary, since it is recommended that layers use Vertex Lists instead of OpenGL Immediate Mode.
|
python
|
{
"resource": ""
}
|
q278393
|
LayeredWidget.delete
|
test
|
def delete(self):
"""
Deletes all layers within this LayeredWidget before deleting itself.
Recommended to call if you are removing the widget, but not yet exiting the interpreter.
"""
for layer,_ in self.layers:
|
python
|
{
"resource": ""
}
|
q278394
|
WidgetLayer.border
|
test
|
def border(self):
"""
Property to be used for setting and getting the border of the layer.
Note that setting this property causes an immediate redraw.
|
python
|
{
"resource": ""
}
|
q278395
|
WidgetLayer.offset
|
test
|
def offset(self):
"""
Property to be used for setting and getting the offset of the layer.
Note that setting this property causes an immediate redraw.
|
python
|
{
"resource": ""
}
|
q278396
|
WidgetLayer.getSize
|
test
|
def getSize(self):
"""
Returns the size of the layer, with the border size already subtracted.
"""
|
python
|
{
"resource": ""
}
|
q278397
|
read_h5
|
test
|
def read_h5(hdfstore, group = ""):
"""
DEPRECATED
Reads a mesh saved in the HDF5 format.
"""
m = Mesh()
m.elements.data = hdf["elements/connectivity"]
m.nodes.data = hdf["nodes/xyz"]
for key in hdf.keys():
if key.startswith("/nodes/sets"):
k = key.replace("/nodes/sets/", "")
m.nodes.sets[k] = set(hdf[key])
if key.startswith("/elements/sets"):
k = key.replace("/elements/sets/", "")
m.elements.sets[k] = set(hdf[key])
if key.startswith("/elements/surfaces"):
k = key.replace("/elements/surfaces/", "")
|
python
|
{
"resource": ""
}
|
q278398
|
_make_conn
|
test
|
def _make_conn(shape):
"""
Connectivity builder using Numba for speed boost.
"""
shape = np.array(shape)
Ne = shape.prod()
if len(shape) == 2:
nx, ny = np.array(shape) +1
conn = np.zeros((Ne, 4), dtype = np.int32)
counter = 0
pattern = np.array([0,1,1+nx,nx])
for j in range(shape[1]):
for i in range(shape[0]):
conn[counter] = pattern + 1 + i + j*nx
counter += 1
if len(shape) == 3:
nx, ny, nz
|
python
|
{
"resource": ""
}
|
q278399
|
Mesh.set_fields
|
test
|
def set_fields(self, fields = None, **kwargs):
"""
Sets the fields.
"""
self.fields = []
if fields
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.