Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|># Copyright 2014 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
def dummy_app(environ, response):
res = webob_response.Response()
return res(environ, response)
<|code_end|>
using the current file's imports:
from unittest import mock
from webob import response as webob_response
from osprofiler import _utils as utils
from osprofiler import profiler
from osprofiler.tests import test
from osprofiler import web
and any relevant context from other files:
# Path: osprofiler/_utils.py
# def split(text, strip=True):
# def binary_encode(text, encoding="utf-8"):
# def binary_decode(data, encoding="utf-8"):
# def generate_hmac(data, hmac_key):
# def signed_pack(data, hmac_key):
# def signed_unpack(data, hmac_data, hmac_keys):
# def itersubclasses(cls, _seen=None):
# def import_modules_from_package(package):
# def shorten_id(span_id):
#
# Path: osprofiler/profiler.py
# def clean():
# def _ensure_no_multiple_traced(traceable_attrs):
# def init(hmac_key, base_id=None, parent_id=None):
# def get():
# def start(name, info=None):
# def stop(info=None):
# def trace(name, info=None, hide_args=False, hide_result=True,
# allow_multiple_trace=True):
# def decorator(f):
# def wrapper(*args, **kwargs):
# def trace_cls(name, info=None, hide_args=False, hide_result=True,
# trace_private=False, allow_multiple_trace=True,
# trace_class_methods=False, trace_static_methods=False):
# def trace_checker(attr_name, to_be_wrapped):
# def decorator(cls):
# def __init__(cls, cls_name, bases, attrs):
# def __init__(self, name, info=None):
# def __enter__(self):
# def __exit__(self, etype, value, traceback):
# def __init__(self, hmac_key, base_id=None, parent_id=None):
# def get_shorten_id(self, uuid_id):
# def get_base_id(self):
# def get_parent_id(self):
# def get_id(self):
# def start(self, name, info=None):
# def stop(self, info=None):
# def _notify(self, name, info):
# class TracedMeta(type):
# class Trace(object):
# class _Profiler(object):
#
# Path: osprofiler/tests/test.py
# class TestCase(testcase.TestCase):
# class FunctionalTestCase(TestCase):
# def setUp(self):
#
# Path: osprofiler/web.py
# _REQUIRED_KEYS = ("base_id", "hmac_key")
# _OPTIONAL_KEYS = ("parent_id",)
# X_TRACE_INFO = "X-Trace-Info"
# X_TRACE_HMAC = "X-Trace-HMAC"
# _ENABLED = None
# _HMAC_KEYS = None
# _ENABLED = False
# _ENABLED = True
# _HMAC_KEYS = utils.split(hmac_keys or "")
# def get_trace_id_headers():
# def disable():
# def enable(hmac_keys=None):
# def __init__(self, application, hmac_keys=None, enabled=False, **kwargs):
# def factory(cls, global_conf, **local_conf):
# def filter_(app):
# def _trace_is_valid(self, trace_info):
# def __call__(self, request):
# class WsgiMiddleware(object):
. Output only the next line. | class WebTestCase(test.TestCase): |
Given the following code snippet before the placeholder: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
def dummy_app(environ, response):
res = webob_response.Response()
return res(environ, response)
class WebTestCase(test.TestCase):
def setUp(self):
super(WebTestCase, self).setUp()
profiler.clean()
self.addCleanup(profiler.clean)
def test_get_trace_id_headers_no_hmac(self):
profiler.init(None, base_id="y", parent_id="z")
<|code_end|>
, predict the next line using imports from the current file:
from unittest import mock
from webob import response as webob_response
from osprofiler import _utils as utils
from osprofiler import profiler
from osprofiler.tests import test
from osprofiler import web
and context including class names, function names, and sometimes code from other files:
# Path: osprofiler/_utils.py
# def split(text, strip=True):
# def binary_encode(text, encoding="utf-8"):
# def binary_decode(data, encoding="utf-8"):
# def generate_hmac(data, hmac_key):
# def signed_pack(data, hmac_key):
# def signed_unpack(data, hmac_data, hmac_keys):
# def itersubclasses(cls, _seen=None):
# def import_modules_from_package(package):
# def shorten_id(span_id):
#
# Path: osprofiler/profiler.py
# def clean():
# def _ensure_no_multiple_traced(traceable_attrs):
# def init(hmac_key, base_id=None, parent_id=None):
# def get():
# def start(name, info=None):
# def stop(info=None):
# def trace(name, info=None, hide_args=False, hide_result=True,
# allow_multiple_trace=True):
# def decorator(f):
# def wrapper(*args, **kwargs):
# def trace_cls(name, info=None, hide_args=False, hide_result=True,
# trace_private=False, allow_multiple_trace=True,
# trace_class_methods=False, trace_static_methods=False):
# def trace_checker(attr_name, to_be_wrapped):
# def decorator(cls):
# def __init__(cls, cls_name, bases, attrs):
# def __init__(self, name, info=None):
# def __enter__(self):
# def __exit__(self, etype, value, traceback):
# def __init__(self, hmac_key, base_id=None, parent_id=None):
# def get_shorten_id(self, uuid_id):
# def get_base_id(self):
# def get_parent_id(self):
# def get_id(self):
# def start(self, name, info=None):
# def stop(self, info=None):
# def _notify(self, name, info):
# class TracedMeta(type):
# class Trace(object):
# class _Profiler(object):
#
# Path: osprofiler/tests/test.py
# class TestCase(testcase.TestCase):
# class FunctionalTestCase(TestCase):
# def setUp(self):
#
# Path: osprofiler/web.py
# _REQUIRED_KEYS = ("base_id", "hmac_key")
# _OPTIONAL_KEYS = ("parent_id",)
# X_TRACE_INFO = "X-Trace-Info"
# X_TRACE_HMAC = "X-Trace-HMAC"
# _ENABLED = None
# _HMAC_KEYS = None
# _ENABLED = False
# _ENABLED = True
# _HMAC_KEYS = utils.split(hmac_keys or "")
# def get_trace_id_headers():
# def disable():
# def enable(hmac_keys=None):
# def __init__(self, application, hmac_keys=None, enabled=False, **kwargs):
# def factory(cls, global_conf, **local_conf):
# def filter_(app):
# def _trace_is_valid(self, trace_info):
# def __call__(self, request):
# class WsgiMiddleware(object):
. Output only the next line. | headers = web.get_trace_id_headers() |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2014 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class SqlalchemyTracingTestCase(test.TestCase):
@mock.patch("osprofiler.sqlalchemy.profiler")
def test_before_execute(self, mock_profiler):
<|code_end|>
, predict the next line using imports from the current file:
import contextlib
from unittest import mock
from osprofiler import sqlalchemy
from osprofiler.tests import test
and context including class names, function names, and sometimes code from other files:
# Path: osprofiler/sqlalchemy.py
# LOG = log.getLogger(__name__)
# _DISABLED = False
# _DISABLED = True
# _DISABLED = False
# def disable():
# def enable():
# def add_tracing(sqlalchemy, engine, name, hide_result=True):
# def wrap_session(sqlalchemy, sess):
# def _before_cursor_execute(name):
# def handler(conn, cursor, statement, params, context, executemany):
# def _after_cursor_execute(hide_result=True):
# def handler(conn, cursor, statement, params, context, executemany):
# def handle_error(exception_context):
#
# Path: osprofiler/tests/test.py
# class TestCase(testcase.TestCase):
# class FunctionalTestCase(TestCase):
# def setUp(self):
. Output only the next line. | handler = sqlalchemy._before_cursor_execute("sql") |
Given snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class ElasticsearchDriver(base.Driver):
def __init__(self, connection_str, index_name="osprofiler-notifications",
project=None, service=None, host=None, conf=cfg.CONF,
**kwargs):
"""Elasticsearch driver for OSProfiler."""
super(ElasticsearchDriver, self).__init__(connection_str,
project=project,
service=service,
host=host,
conf=conf,
**kwargs)
try:
except ImportError:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from urllib import parse as parser
from oslo_config import cfg
from osprofiler.drivers import base
from osprofiler import exc
from elasticsearch import Elasticsearch
and context:
# Path: osprofiler/drivers/base.py
# LOG = logging.getLogger(__name__)
# def get_driver(connection_string, *args, **kwargs):
# def __init__(self, connection_str, project=None, service=None, host=None,
# **kwargs):
# def notify(self, info, **kwargs):
# def get_report(self, base_id):
# def get_name(cls):
# def list_traces(self, fields=None):
# def list_error_traces(self):
# def _build_tree(nodes):
# def _append_results(self, trace_id, parent_id, name, project, service,
# host, timestamp, raw_payload=None):
# def _parse_results(self):
# def msec(dt):
# class Driver(object):
#
# Path: osprofiler/exc.py
# class CommandError(Exception):
# class LogInsightAPIError(Exception):
# class LogInsightLoginTimeout(Exception):
# def __init__(self, message=None):
# def __str__(self):
which might include code, classes, or functions. Output only the next line. | raise exc.CommandError( |
Based on the snippet: <|code_start|># Copyright 2016 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class ConfigTestCase(test.TestCase):
def setUp(self):
super(ConfigTestCase, self).setUp()
self.conf_fixture = self.useFixture(fixture.Config())
def test_options_defaults(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest import mock
from oslo_config import fixture
from osprofiler import opts
from osprofiler.tests import test
and context (classes, functions, sometimes code) from other files:
# Path: osprofiler/opts.py
# _PROFILER_OPTS = [
# _enabled_opt,
# _trace_sqlalchemy_opt,
# _hmac_keys_opt,
# _connection_string_opt,
# _es_doc_type_opt,
# _es_scroll_time_opt,
# _es_scroll_size_opt,
# _socket_timeout_opt,
# _sentinel_service_name_opt,
# _filter_error_trace
# ]
# def set_defaults(conf, enabled=None, trace_sqlalchemy=None, hmac_keys=None,
# connection_string=None, es_doc_type=None,
# es_scroll_time=None, es_scroll_size=None,
# socket_timeout=None, sentinel_service_name=None):
# def is_trace_enabled(conf=None):
# def is_db_trace_enabled(conf=None):
# def enable_web_trace(conf=None):
# def disable_web_trace(conf=None):
# def list_opts():
#
# Path: osprofiler/tests/test.py
# class TestCase(testcase.TestCase):
# class FunctionalTestCase(TestCase):
# def setUp(self):
. Output only the next line. | opts.set_defaults(self.conf_fixture.conf) |
Continue the code snippet: <|code_start|># Copyright 2016 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class MongoDB(base.Driver):
def __init__(self, connection_str, db_name="osprofiler", project=None,
service=None, host=None, **kwargs):
"""MongoDB driver for OSProfiler."""
super(MongoDB, self).__init__(connection_str, project=project,
service=service, host=host, **kwargs)
try:
except ImportError:
<|code_end|>
. Use current file imports:
from osprofiler.drivers import base
from osprofiler import exc
from pymongo import MongoClient
and context (classes, functions, or code) from other files:
# Path: osprofiler/drivers/base.py
# LOG = logging.getLogger(__name__)
# def get_driver(connection_string, *args, **kwargs):
# def __init__(self, connection_str, project=None, service=None, host=None,
# **kwargs):
# def notify(self, info, **kwargs):
# def get_report(self, base_id):
# def get_name(cls):
# def list_traces(self, fields=None):
# def list_error_traces(self):
# def _build_tree(nodes):
# def _append_results(self, trace_id, parent_id, name, project, service,
# host, timestamp, raw_payload=None):
# def _parse_results(self):
# def msec(dt):
# class Driver(object):
#
# Path: osprofiler/exc.py
# class CommandError(Exception):
# class LogInsightAPIError(Exception):
# class LogInsightLoginTimeout(Exception):
# def __init__(self, message=None):
# def __str__(self):
. Output only the next line. | raise exc.CommandError( |
Given the following code snippet before the placeholder: <|code_start|># under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IMUSim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division
RANDOM_SEED=0
def assert_almost_equal(a, b):
for ai, bi in zip(a, b):
testing.assert_almost_equal(ai, bi)
# each element of the list is a tuple of cartesian and polar co-ords
CARTESIAN_POLAR_TEST_VALUES = [
((0,0),(0,0)),
((0,1),(1,np.pi/2)),
((1,0),(1,0)),
((1/sqrt(2), 1/sqrt(2)), (1,np.pi/4)),
((0,10),(10,np.pi/2)),
((5,0),(5,0))
]
def checkPolarToCartesian(cartesian, polar):
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
from numpy import random
from scipy import stats
from numpy import testing
from imusim.maths import transforms
from imusim.maths.vectors import vector
from imusim.maths.quaternions import Quaternion
from imusim.maths.transforms import AffineTransform
from math import sqrt
and context including class names, function names, and sometimes code from other files:
# Path: imusim/maths/transforms.py
# class AffineTransform(object):
# class UnscentedTransform(object):
# def __init__(self, transform=None, rz=0, ry=0, rx=0, scale=1,
# translation=vector(0,0,0)):
# def apply(self,v):
# def reverse(self,v):
# def __init__(self, function):
# def __call__(self, mean, covariance, *args, **kwargs):
# def sigmaPoints(mean, covariance):
# def cartesianToPolar(x,y):
# def polarToCartesian(r,theta):
# def convertCGtoNED(param):
# def convertNEDtoCG(param):
# N = len(mean)
#
# Path: imusim/maths/transforms.py
# class AffineTransform(object):
# """
# Affine transform composed of a linear transform matrix and translation.
# """
# def __init__(self, transform=None, rz=0, ry=0, rx=0, scale=1,
# translation=vector(0,0,0)):
# """
# Construct an affine transform.
#
# A generic transformation matrix can be supplied, or a transform
# composed of rotation and scaling can be built.
#
# Generating rotations using supplied Euler angles is performed from the
# perspective of a fixed camera viewing a rotating object, i.e. points
# rotate within a fixed reference frame. Rotations are applied in
# aerospace (ZYX) order.
#
# @param transform: 3x3 linear transformation matrix.
# @param rx: X rotation angle in radians.
# @param ry: Y rotation angle in radians.
# @param rz: Z rotation angle in radians.
# @param scale: Scaling factor
# @param translation: 3x1 translation vector.
# """
# if transform is not None:
# self._transform = transform
# else:
# self._transform = scale * matrixFromEuler((rz,ry,rx),'zyx',False)
#
# self._inverseTransform = np.linalg.inv(self._transform)
# self._translation = translation
#
# def apply(self,v):
# """
# Apply transform to an array of column vectors.
# """
# return np.tensordot(self._transform, v, axes=([1],[0])) \
# + self._translation
#
# def reverse(self,v):
# """
# Apply the inverse of this transform to an array of column vectors.
# """
# return np.tensordot(self._inverseTransform,
# v-self._translation,axes=([1],[0]))
. Output only the next line. | assert_almost_equal(transforms.polarToCartesian(*polar), cartesian) |
Given the code snippet: <|code_start|>
# each element of the list is a tuple of vectors in NED and CG co-ords
NED_CG_TEST_VALUES = [
(vector(1,0,0), vector(0,0,1)),
(vector(0,1,0), vector(-1,0,0)),
(vector(0,0,1), vector(0,-1,0))
]
def checkNED_to_CG(ned, cg):
assert_almost_equal(transforms.convertNEDtoCG(ned), cg)
def checkCG_to_NED(ned, cg):
assert_almost_equal(transforms.convertCGtoNED(cg), ned)
def testCoordinateChange():
for ned, cg in NED_CG_TEST_VALUES:
yield checkNED_to_CG, ned, cg
yield checkCG_to_NED, ned, cg
def testCG_to_NED_Quat():
testing.assert_equal(
transforms.convertCGtoNED(Quaternion()).components,
Quaternion(0.5, -0.5, 0.5, -0.5).components)
def testNED_to_CG_Quat():
testing.assert_equal(
transforms.convertNEDtoCG(Quaternion()).components,
Quaternion(0.5, 0.5, -0.5, 0.5).components)
AFFINE_TRANSFORM_TESTS = [
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from numpy import random
from scipy import stats
from numpy import testing
from imusim.maths import transforms
from imusim.maths.vectors import vector
from imusim.maths.quaternions import Quaternion
from imusim.maths.transforms import AffineTransform
from math import sqrt
and context (functions, classes, or occasionally code) from other files:
# Path: imusim/maths/transforms.py
# class AffineTransform(object):
# class UnscentedTransform(object):
# def __init__(self, transform=None, rz=0, ry=0, rx=0, scale=1,
# translation=vector(0,0,0)):
# def apply(self,v):
# def reverse(self,v):
# def __init__(self, function):
# def __call__(self, mean, covariance, *args, **kwargs):
# def sigmaPoints(mean, covariance):
# def cartesianToPolar(x,y):
# def polarToCartesian(r,theta):
# def convertCGtoNED(param):
# def convertNEDtoCG(param):
# N = len(mean)
#
# Path: imusim/maths/transforms.py
# class AffineTransform(object):
# """
# Affine transform composed of a linear transform matrix and translation.
# """
# def __init__(self, transform=None, rz=0, ry=0, rx=0, scale=1,
# translation=vector(0,0,0)):
# """
# Construct an affine transform.
#
# A generic transformation matrix can be supplied, or a transform
# composed of rotation and scaling can be built.
#
# Generating rotations using supplied Euler angles is performed from the
# perspective of a fixed camera viewing a rotating object, i.e. points
# rotate within a fixed reference frame. Rotations are applied in
# aerospace (ZYX) order.
#
# @param transform: 3x3 linear transformation matrix.
# @param rx: X rotation angle in radians.
# @param ry: Y rotation angle in radians.
# @param rz: Z rotation angle in radians.
# @param scale: Scaling factor
# @param translation: 3x1 translation vector.
# """
# if transform is not None:
# self._transform = transform
# else:
# self._transform = scale * matrixFromEuler((rz,ry,rx),'zyx',False)
#
# self._inverseTransform = np.linalg.inv(self._transform)
# self._translation = translation
#
# def apply(self,v):
# """
# Apply transform to an array of column vectors.
# """
# return np.tensordot(self._transform, v, axes=([1],[0])) \
# + self._translation
#
# def reverse(self,v):
# """
# Apply the inverse of this transform to an array of column vectors.
# """
# return np.tensordot(self._inverseTransform,
# v-self._translation,axes=([1],[0]))
. Output only the next line. | (AffineTransform(transform=np.eye(3)), vector(1,0,0), vector(1,0,0)), |
Given the following code snippet before the placeholder: <|code_start|>#
# IMUSim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
def testNonLinearMeasurement():
"""
Tests filter estimating constants with a non-linear measurement function
"""
SAMPLES = 1000
stateUpdate = lambda state, control: state
def measurementFunc(state):
state = np.asarray(state)
newState = np.empty_like(state)
newState[0] = state[0]**2
newState[1] = state[1]**3
return newState
initialState = np.matrix('0.1;0.1')
initialCovariance = np.matrix('1,0;0,1')
processCovariance = np.matrix('0.001,0;0,0.001')
measurementCovariance = np.matrix('0.01,0;0,0.01')
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
from imusim.maths.kalman import UnscentedKalmanFilter
and context including class names, function names, and sometimes code from other files:
# Path: imusim/maths/kalman.py
# class UnscentedKalmanFilter(KalmanFilter):
# """
# Implementation of the unscented Kalman filter algorithm for additive noise.
#
# Implementation equations are taken from Wan and Van Der Merwe, "The
# Unscented Kalman Filter", table 7.3.2.
#
# @ivar stateUpdateFunction: Non-linear function to propagate state into the
# next timestep. The function is called with two arguments, the current
# Nx1 state vector and the current Mx1 control input vector. It should
# return a new Nx1 state vector. N and M are the numbers of states and
# control inputs.
# @ivar measurementFunction: Non-linear function relating state variables
# to expected measurements. The function is called with the current Nx1
# state vector as an argument, and should return an Mx1 measurement
# vector. N and M are the numbers of states and measurement outputs.
# @ivar state: Current state estimate.
# @ivar stateCovariance: State covariance matrix.
# @ivar processCovariance: Process noise covariance matrix.
# @ivar measurementCovariance: Measurement noise covariance matrix.
# """
#
# def __init__(self, stateUpdateFunction, measurementFunction, state,
# stateCovariance, processCovariance, measurementCovariance):
# """
# Construct unscented Kalman filter.
#
# @param stateUpdateFunction: Non-linear function to propagate state into
# the next timestep. The function is called with two arguments, the
# current Nx1 state vector and the current Mx1 control input vector.
# It should return a new Nx1 state vector. N and M are the numbers of
# states and control inputs.
# @param measurementFunction: Non-linear function relating state
# variables to expected measurements. The function is called with the
# current Nx1 state vector as an argument, and should return an Mx1
# measurement vector. N and M are the numbers of states and measurement
# outputs.
# @param state: Initial state estimate.
# @param stateCovariance: Initial state covariance matrix.
# @param processCovariance: Process noise covariance matrix.
# @param measurementCovariance: Measurement noise covariance matrix.
# """
#
# self.stateUpdateFunction = stateUpdateFunction
# self.measurementFunction = measurementFunction
#
# self.state = state
# self.stateCovariance = stateCovariance
# self.processCovariance = processCovariance
# self.measurementCovariance = measurementCovariance
#
# @property
# def stateUpdateFunction(self):
# return self._stateUpdateUT._function
#
# @stateUpdateFunction.setter
# def stateUpdateFunction(self, function):
# self._stateUpdateUT = UnscentedTransform(function)
#
# @property
# def measurementFunction(self):
# return self._measurementUT._function
#
# @measurementFunction.setter
# def measurementFunction(self, function):
# self._measurementUT = UnscentedTransform(function)
#
# def predict(self, control=None):
# state, stateCovariance = self._stateUpdateUT(self._x, self._P, *[control])
# self._x = state
# self._P = stateCovariance + self._Q
# assert self._x.shape == (self._states,1)
# assert np.all(np.isfinite(self._x))
# assert self._P.shape == (self._states, self._states)
# assert np.all(np.isfinite(self._P))
#
# def innovation(self, measurement):
# measurement = np.asanyarray(measurement).reshape(-1,1)
# predictedMeasurement, predictionCovariance, \
# stateSigmas, measurementSigmas, weights = \
# self._measurementUT(self._x, self._P, returnSigmas=True)
# x,y = self._x, predictedMeasurement
# sigmaPoints = izip(weights, stateSigmas, measurementSigmas)
# innovation = measurement - predictedMeasurement
# innovationCovariance = self._R + predictionCovariance
# crossCovariance = np.sum((w*(X-x)*(Y-y).T for (w,X,Y) in sigmaPoints), axis=0)
# return innovation, innovationCovariance, crossCovariance
#
# def correct(self, measurement):
# measurement = np.asanyarray(measurement).reshape(-1,1)
# innovation, innovationCovariance, crossCovariance = \
# self.innovation(measurement)
# self._K = np.dot(crossCovariance, inv(innovationCovariance))
# self._x = self._x + self._K * innovation
# assert self._x.shape == (self._states,1)
# assert np.all(np.isfinite(self._x))
# self._P = self._P - self._K * innovationCovariance * self._K.T
# assert self._P.shape == (self._states, self._states)
# assert np.all(np.isfinite(self._P))
. Output only the next line. | ukf = UnscentedKalmanFilter(stateUpdate, measurementFunc, initialState, |
Given the following code snippet before the placeholder: <|code_start|>
from __future__ import division
def loadViconCSVFile(filename):
"""
Load 3DOF marker data from a Vicon CSV file.
@param filename: Name of the CSV file to load.
@return: A L{MarkerCapture} object.
"""
# Open file to read header.
datafile = open(filename, 'r')
# Function to get comma-separated values from a line.
values = lambda line: line.rstrip('\r\n').split(',')
# Get column names.
colnames = values(datafile.readline())
# Get marker names.
markernames = [n.split(':')[-2] for n in colnames[2::3]]
# Get data.
data = np.array([[float(v or np.nan) for v in values(line)]
for line in datafile.readlines()]).T
frameTimes = data[1]
positions = data[2:].reshape((len(markernames),3,-1)) / 1000
<|code_end|>
, predict the next line using imports from the current file:
from imusim.capture.marker import MarkerCapture, Marker3DOF
import numpy as np
and context including class names, function names, and sometimes code from other files:
# Path: imusim/capture/marker.py
# class MarkerCapture(object):
# """
# Marker trajectory data captured synchronously for one or more markers.
#
# @ivar sampleTimes: Sequence of times at which samples were taken.
# """
#
# def __init__(self):
# """
# Initialise capture.
# """
# self._markers = dict()
#
# def _addMarker(self, marker):
# self._markers[marker.id] = marker
#
# @property
# def markers(self):
# """
# List of the markers in this capture.
# """
# return self._markers.values()
#
# def marker(self, id):
# """
# Get a marker by identifier.
#
# @return: The L{Marker} with the given identifier.
# """
# return self._markers[id]
#
# class Marker3DOF(SampledPositionTrajectory, Marker):
# """
# A capture marker with 3DOF position samples.
# """
# def __init__(self, capture, id):
# Marker.__init__(self, capture, id)
# SampledPositionTrajectory.__init__(self)
. Output only the next line. | capture = MarkerCapture() |
Using the snippet: <|code_start|> @param filename: Name of the CSV file to load.
@return: A L{MarkerCapture} object.
"""
# Open file to read header.
datafile = open(filename, 'r')
# Function to get comma-separated values from a line.
values = lambda line: line.rstrip('\r\n').split(',')
# Get column names.
colnames = values(datafile.readline())
# Get marker names.
markernames = [n.split(':')[-2] for n in colnames[2::3]]
# Get data.
data = np.array([[float(v or np.nan) for v in values(line)]
for line in datafile.readlines()]).T
frameTimes = data[1]
positions = data[2:].reshape((len(markernames),3,-1)) / 1000
capture = MarkerCapture()
capture.frameTimes = frameTimes
capture.frameCount = len(frameTimes)
capture.framePeriod = np.min(np.diff(frameTimes))
capture.frameRate = 1 / capture.framePeriod
for i, name in enumerate(markernames):
<|code_end|>
, determine the next line of code. You have imports:
from imusim.capture.marker import MarkerCapture, Marker3DOF
import numpy as np
and context (class names, function names, or code) available:
# Path: imusim/capture/marker.py
# class MarkerCapture(object):
# """
# Marker trajectory data captured synchronously for one or more markers.
#
# @ivar sampleTimes: Sequence of times at which samples were taken.
# """
#
# def __init__(self):
# """
# Initialise capture.
# """
# self._markers = dict()
#
# def _addMarker(self, marker):
# self._markers[marker.id] = marker
#
# @property
# def markers(self):
# """
# List of the markers in this capture.
# """
# return self._markers.values()
#
# def marker(self, id):
# """
# Get a marker by identifier.
#
# @return: The L{Marker} with the given identifier.
# """
# return self._markers[id]
#
# class Marker3DOF(SampledPositionTrajectory, Marker):
# """
# A capture marker with 3DOF position samples.
# """
# def __init__(self, capture, id):
# Marker.__init__(self, capture, id)
# SampledPositionTrajectory.__init__(self)
. Output only the next line. | marker = Marker3DOF(capture, name) |
Based on the snippet: <|code_start|>"""
Tests for vector observation algorithms.
"""
# Copyright (C) 2009-2011 University of Edinburgh
#
# This file is part of IMUSim.
#
# IMUSim is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IMUSim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
angles = [45*p for p in xrange(8)]
def checkVectorObservation(vectorObservationMethod, eulerAngles, inclination):
if issubclass(vectorObservationMethod,
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
import itertools
import math
from imusim.algorithms import vector_observation
from imusim.maths.quaternions import Quaternion
from imusim.testing.quaternions import assertQuaternionAlmostEqual
from imusim.testing.inspection import getImplementations
and context (classes, functions, sometimes code) from other files:
# Path: imusim/algorithms/vector_observation.py
# class VectorObservation(object):
# class TRIAD(VectorObservation):
# class GramSchmidt(VectorObservation):
# class FQA(VectorObservation):
# class LeastSquaresOptimalVectorObservation(VectorObservation):
# class DavenportQ(LeastSquaresOptimalVectorObservation):
# class QUEST(LeastSquaresOptimalVectorObservation):
# def __call__(self, *measurements):
# def _process(self, *measurements):
# def _process(self, g, m):
# def _process(self, g, m):
# def __init__(self):
# def cosHalfAngle(self, cosAngle):
# def sinHalfAngle(self, cosAngle, sinAngle):
# def _process(self, g, m):
# def __init__(self, refs=None, weights=None, inclinationAngle=None):
# def _process(self, *meas):
# def _apply(self, refs, meas):
# def _process(self, *meas):
# B = sum([a * np.dot(b, r.T)
# for a,b,r in zip(self.weights, meas, self.refs)])
# S = B + B.T
# K = np.empty((4,4))
# K[0:3,0:3] = S-sigma*np.identity(3)
# K[0:3,3] = z[:,0]
# K[3,0:3] = z[:,0]
# K[3,3] = sigma
# B = sum([a * np.dot(m, r.T) for a,m,r in zip(self.weights, meas, refs)])
# S = B + B.T
# Z = sum([a * vectors.cross(m, r) for a,m,r in zip(self.weights, meas, refs)])
# X = np.dot(alpha*np.identity(3) + beta*S + np.dot(S,S), Z)
# EPS = 1e-8
. Output only the next line. | vector_observation.LeastSquaresOptimalVectorObservation): |
Predict the next line after this snippet: <|code_start|># IMUSim is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IMUSim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division
def loadQualisysTSVFile(filename):
"""
Load 3DOF or 6DOF marker data from a Qualisys Track Manager TSV file.
@param filename: Name of TSV file to load.
@return: A L{MarkerCapture} instance.
"""
# Open file to read header.
datafile = open(filename, 'r')
# Count of header lines in file.
headerLines = 0
<|code_end|>
using the current file's imports:
from imusim.capture.marker import MarkerCapture, Marker3DOF, Marker6DOF
from imusim.maths.quaternions import Quaternion, QuaternionArray
import numpy as np
and any relevant context from other files:
# Path: imusim/capture/marker.py
# class MarkerCapture(object):
# """
# Marker trajectory data captured synchronously for one or more markers.
#
# @ivar sampleTimes: Sequence of times at which samples were taken.
# """
#
# def __init__(self):
# """
# Initialise capture.
# """
# self._markers = dict()
#
# def _addMarker(self, marker):
# self._markers[marker.id] = marker
#
# @property
# def markers(self):
# """
# List of the markers in this capture.
# """
# return self._markers.values()
#
# def marker(self, id):
# """
# Get a marker by identifier.
#
# @return: The L{Marker} with the given identifier.
# """
# return self._markers[id]
#
# class Marker3DOF(SampledPositionTrajectory, Marker):
# """
# A capture marker with 3DOF position samples.
# """
# def __init__(self, capture, id):
# Marker.__init__(self, capture, id)
# SampledPositionTrajectory.__init__(self)
#
# class Marker6DOF(SampledRotationTrajectory, Marker3DOF):
# """
# A capture marker with 6DOF position & orientation samples.
# """
# def __init__(self, capture, id):
# Marker3DOF.__init__(self, capture, id)
# SampledRotationTrajectory.__init__(self)
. Output only the next line. | capture = MarkerCapture() |
Next line prediction: <|code_start|>
while True:
# Read and count each file header line.
line = datafile.readline().strip('\r\n')
headerLines = headerLines + 1
# Key and values are tab-separated.
items = line.split('\t')
key = items[0]
values = items[1:]
# Handle relevant fields.
if key == 'FREQUENCY':
# Frame rate.
capture.frameRate = int(values[0])
capture.framePeriod = 1/capture.frameRate
elif key == 'DATA_INCLUDED':
# 3D or 6D data.
type = values[0]
if (type == '3D'):
# 3D data fields are implicitly XYZ co-ordinates.
fieldNames = ['X', 'Y', 'Z']
elif key == 'BODY_NAMES' or key == 'MARKER_NAMES':
# List of markers or 6DOF body names.
for i in range(len(values)):
name = values[i]
if type == '6D':
markerClass = Marker6DOF
else:
<|code_end|>
. Use current file imports:
(from imusim.capture.marker import MarkerCapture, Marker3DOF, Marker6DOF
from imusim.maths.quaternions import Quaternion, QuaternionArray
import numpy as np)
and context including class names, function names, or small code snippets from other files:
# Path: imusim/capture/marker.py
# class MarkerCapture(object):
# """
# Marker trajectory data captured synchronously for one or more markers.
#
# @ivar sampleTimes: Sequence of times at which samples were taken.
# """
#
# def __init__(self):
# """
# Initialise capture.
# """
# self._markers = dict()
#
# def _addMarker(self, marker):
# self._markers[marker.id] = marker
#
# @property
# def markers(self):
# """
# List of the markers in this capture.
# """
# return self._markers.values()
#
# def marker(self, id):
# """
# Get a marker by identifier.
#
# @return: The L{Marker} with the given identifier.
# """
# return self._markers[id]
#
# class Marker3DOF(SampledPositionTrajectory, Marker):
# """
# A capture marker with 3DOF position samples.
# """
# def __init__(self, capture, id):
# Marker.__init__(self, capture, id)
# SampledPositionTrajectory.__init__(self)
#
# class Marker6DOF(SampledRotationTrajectory, Marker3DOF):
# """
# A capture marker with 6DOF position & orientation samples.
# """
# def __init__(self, capture, id):
# Marker3DOF.__init__(self, capture, id)
# SampledRotationTrajectory.__init__(self)
. Output only the next line. | markerClass = Marker3DOF |
Predict the next line for this snippet: <|code_start|>
markerIndices = dict()
while True:
# Read and count each file header line.
line = datafile.readline().strip('\r\n')
headerLines = headerLines + 1
# Key and values are tab-separated.
items = line.split('\t')
key = items[0]
values = items[1:]
# Handle relevant fields.
if key == 'FREQUENCY':
# Frame rate.
capture.frameRate = int(values[0])
capture.framePeriod = 1/capture.frameRate
elif key == 'DATA_INCLUDED':
# 3D or 6D data.
type = values[0]
if (type == '3D'):
# 3D data fields are implicitly XYZ co-ordinates.
fieldNames = ['X', 'Y', 'Z']
elif key == 'BODY_NAMES' or key == 'MARKER_NAMES':
# List of markers or 6DOF body names.
for i in range(len(values)):
name = values[i]
if type == '6D':
<|code_end|>
with the help of current file imports:
from imusim.capture.marker import MarkerCapture, Marker3DOF, Marker6DOF
from imusim.maths.quaternions import Quaternion, QuaternionArray
import numpy as np
and context from other files:
# Path: imusim/capture/marker.py
# class MarkerCapture(object):
# """
# Marker trajectory data captured synchronously for one or more markers.
#
# @ivar sampleTimes: Sequence of times at which samples were taken.
# """
#
# def __init__(self):
# """
# Initialise capture.
# """
# self._markers = dict()
#
# def _addMarker(self, marker):
# self._markers[marker.id] = marker
#
# @property
# def markers(self):
# """
# List of the markers in this capture.
# """
# return self._markers.values()
#
# def marker(self, id):
# """
# Get a marker by identifier.
#
# @return: The L{Marker} with the given identifier.
# """
# return self._markers[id]
#
# class Marker3DOF(SampledPositionTrajectory, Marker):
# """
# A capture marker with 3DOF position samples.
# """
# def __init__(self, capture, id):
# Marker.__init__(self, capture, id)
# SampledPositionTrajectory.__init__(self)
#
# class Marker6DOF(SampledRotationTrajectory, Marker3DOF):
# """
# A capture marker with 6DOF position & orientation samples.
# """
# def __init__(self, capture, id):
# Marker3DOF.__init__(self, capture, id)
# SampledRotationTrajectory.__init__(self)
, which may contain function names, class names, or code. Output only the next line. | markerClass = Marker6DOF |
Here is a snippet: <|code_start|>"""
Tests for static trajectories
"""
# Copyright (C) 2009-2011 University of Edinburgh
#
# This file is part of IMUSim.
#
# IMUSim is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IMUSim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
def testStaticTrajectory():
p = randomPosition()
r = randomRotation()
<|code_end|>
. Write the next line using the current file imports:
from imusim.trajectories.base import StaticTrajectory
from imusim.testing.random_data import randomPosition, randomRotation
from numpy.testing import assert_equal
from imusim.maths.vectors import vector
from imusim.maths.quaternions import QuaternionArray
import numpy as np
and context from other files:
# Path: imusim/trajectories/base.py
# class StaticTrajectory(ConstantPositionTrajectory, ConstantRotationTrajectory):
# """
# Represents the trajectory of a static object.
# """
#
# def __init__(self, position=None, rotation=None):
# """
# Construct static trajectory.
#
# @param position: the constant position of the object (3x1 L{np.ndarray})
# @param rotation: the constant rotation of the object (L{Quaternion})
# """
# ConstantPositionTrajectory.__init__(self, position)
# ConstantRotationTrajectory.__init__(self, rotation)
#
# @property
# def startTime(self):
# return 0
#
# @property
# def endTime(self):
# return np.inf
, which may include functions, classes, or code. Output only the next line. | s = StaticTrajectory(p, r) |
Based on the snippet: <|code_start|># under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IMUSim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
def checkVectorSpline(splineClass, x, y, order):
try:
spline = splineClass(x, y, order=order)
ys = spline(x)
splines = spline.splines if isinstance(spline, PartialInputVectorSpline) else [spline]
valid = np.array(
np.sum(((x >= spline.validFrom) & (x <= spline.validTo) for spline in splines)),
dtype=bool)
assert_almost_equal(y[:,valid], ys[:,valid])
except Spline.InsufficientPointsError:
pass
def testVectorSpline():
for order in (1, 3, 5):
for i in range(10):
x = randomTimeSequence()
y = randomPositionSequence(x)
<|code_end|>
, predict the immediate next line with the help of imports:
from imusim.maths.splines import Spline
from imusim.maths.vector_splines import UnivariateVectorSpline
from imusim.maths.vector_splines import PartialInputVectorSpline
from imusim.testing.random_data import randomTimeSequence
from imusim.testing.random_data import randomPositionSequence
from imusim.testing.random_data import randomValidity, invalidate
from numpy.testing import assert_almost_equal
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: imusim/maths/vector_splines.py
# class UnivariateVectorSpline(Spline):
# """
# Model of a vector function of a single variable using spline fitting.
#
# The implementation uses an independent L{UnivariateSpline} for each
# component of the vector function.
# """
# def __init__(self, x, y, **kwargs):
# """
# Construct vector spline.
#
# @param x: Length N, monotonically increasing sequence of input values.
# @param y: MxN L{np.ndarray} of output values.
# @param kwargs: Additional parameters passed to L{UnivariateSpline}.
# """
# self.splines = [UnivariateSpline(x, yi, **kwargs) for yi in y]
#
# def __call__(self,x,n=0):
# """
# Evaluate the n-th derivative of the function at input value(s) x.
# """
# return np.vstack([s(x, n) for s in self.splines])
#
# @property
# def validFrom(self):
# return max([s.validFrom for s in self.splines])
#
# @property
# def validTo(self):
# return min([s.validTo for s in self.splines])
#
# Path: imusim/maths/vector_splines.py
# class PartialInputVectorSpline(PartialInputSpline):
# """
# Piecewise vector spline allowing for undefined regions in output domain.
# """
# _splineClass = UnivariateVectorSpline
#
# def __init__(self, x, y, **kwargs):
# PartialInputSpline.__init__(self, x, y, **kwargs)
# self._dims = np.shape(y)[0]
#
# def _validity(self, y):
# return vectors.validity(y)
#
# def _output(self, x, conditions, results, undefined):
# out = np.empty((self._dims, len(np.atleast_1d(x))))
# for cond, result in izip(conditions, results):
# out[:,cond] = result
# out[:,undefined] = np.nan
# return out
. Output only the next line. | yield checkVectorSpline, UnivariateVectorSpline, x, y, order |
Predict the next line for this snippet: <|code_start|>"""
Tests for vector splines.
"""
# Copyright (C) 2009-2011 University of Edinburgh
#
# This file is part of IMUSim.
#
# IMUSim is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IMUSim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
def checkVectorSpline(splineClass, x, y, order):
try:
spline = splineClass(x, y, order=order)
ys = spline(x)
<|code_end|>
with the help of current file imports:
from imusim.maths.splines import Spline
from imusim.maths.vector_splines import UnivariateVectorSpline
from imusim.maths.vector_splines import PartialInputVectorSpline
from imusim.testing.random_data import randomTimeSequence
from imusim.testing.random_data import randomPositionSequence
from imusim.testing.random_data import randomValidity, invalidate
from numpy.testing import assert_almost_equal
import numpy as np
and context from other files:
# Path: imusim/maths/vector_splines.py
# class UnivariateVectorSpline(Spline):
# """
# Model of a vector function of a single variable using spline fitting.
#
# The implementation uses an independent L{UnivariateSpline} for each
# component of the vector function.
# """
# def __init__(self, x, y, **kwargs):
# """
# Construct vector spline.
#
# @param x: Length N, monotonically increasing sequence of input values.
# @param y: MxN L{np.ndarray} of output values.
# @param kwargs: Additional parameters passed to L{UnivariateSpline}.
# """
# self.splines = [UnivariateSpline(x, yi, **kwargs) for yi in y]
#
# def __call__(self,x,n=0):
# """
# Evaluate the n-th derivative of the function at input value(s) x.
# """
# return np.vstack([s(x, n) for s in self.splines])
#
# @property
# def validFrom(self):
# return max([s.validFrom for s in self.splines])
#
# @property
# def validTo(self):
# return min([s.validTo for s in self.splines])
#
# Path: imusim/maths/vector_splines.py
# class PartialInputVectorSpline(PartialInputSpline):
# """
# Piecewise vector spline allowing for undefined regions in output domain.
# """
# _splineClass = UnivariateVectorSpline
#
# def __init__(self, x, y, **kwargs):
# PartialInputSpline.__init__(self, x, y, **kwargs)
# self._dims = np.shape(y)[0]
#
# def _validity(self, y):
# return vectors.validity(y)
#
# def _output(self, x, conditions, results, undefined):
# out = np.empty((self._dims, len(np.atleast_1d(x))))
# for cond, result in izip(conditions, results):
# out[:,cond] = result
# out[:,undefined] = np.nan
# return out
, which may contain function names, class names, or code. Output only the next line. | splines = spline.splines if isinstance(spline, PartialInputVectorSpline) else [spline] |
Predict the next line for this snippet: <|code_start|>class OffsetTrajectory(PositionTrajectory, RotationTrajectory):
"""
Trajectory at an offset from another trajectory.
@ivar parent: the L{AbstractTrajectory} from which this one inherits
@ivar positionOffset: the offset from the parent trajectory in the parent
local co-ordinate frame
@ivar rotationOffset: the rotation offset from the parent trajectory
"""
def __init__(self, parent, positionOffset=None, rotationOffset=None):
"""
Initialise trajectory.
@param parent: the L{AbstractTrajectory} which this trajectory follows.
@param positionOffset: the offset vector from the parent trajectory in the
co-ordinate frame of the parent. (3x1 L{np.ndarray})
@param rotationOffset: the rotational offset from the parent trajectory
(L{Quaternion})
"""
self.parent = parent
if positionOffset is None:
self.positionOffset = np.zeros((3,1))
else:
self.positionOffset = positionOffset
if rotationOffset is None:
self.rotationOffset = Quaternion()
else:
self.rotationOffset = rotationOffset
<|code_end|>
with the help of current file imports:
import numpy as np
from imusim.maths import vectors
from imusim.trajectories.base import PositionTrajectory, RotationTrajectory
from imusim.maths.quaternions import Quaternion
from imusim.utilities.caching import CacheLastValue
from imusim.utilities.documentation import prepend_method_doc
and context from other files:
# Path: imusim/trajectories/base.py
# class PositionTrajectory(AbstractTrajectory):
# """Represents a continous trajectory of positions"""
#
# @abstractmethod
# def position(self, t):
# """
# Return position in the global frame at time t.
#
# @param t: the time at which to evaluate the position
# @return: the position vector at time t
# """
# pass
#
# @abstractmethod
# def velocity(self, t):
# """
# Return velocity in the global frame at time t.
#
# @param t: the time at which to evaluate the velocity
# @return: the velocity vector at time t
# """
# pass
#
# @abstractmethod
# def acceleration(self, t):
# """
# Return acceleration in the global frame at time t.
#
# @param t: the time at which to evaluate the acceleration
# @return: the acceleration vector at time t
# """
# pass
#
# class RotationTrajectory(AbstractTrajectory):
# """
# Represents a continuous trajectory of rotations
# """
#
# @abstractmethod
# def rotation(self,t):
# """
# Return rotation relative to the global frame at time t.
#
# @param t: the time at which to evaluate the rotation
# @return: the rotation L{Quaternion} at time t
# """
# pass
#
# @abstractmethod
# def rotationalVelocity(self, t):
# """
# Return rotational velocity relative to the global frame at time t.
#
# @param t: the time at which to evaluate the rotational velocity
# @return: the rotational velocity vector at time t
# """
# pass
#
# @abstractmethod
# def rotationalAcceleration(self, t):
# """
# Return rotational acceleration relative to the global frame at time t.
#
# @param t: the time at which to evaluate the rotational acceleration
# @return: the rotational accelration vector at time t
# """
# pass
#
# Path: imusim/utilities/caching.py
# class CacheLastValue(object):
# """
# Provides a decorator for methods of the form f(t)
# to cache the last value
#
# @param tolerance: tolerance to use when checking that two times are equal.
# """
#
# def __init__(self, tolerance=1e-6):
# self._tolerance = tolerance
# self._cache = defaultdict(CacheEntry)
#
# def __call__(self, method):
# tolerance = self._tolerance
# closure_abs = abs
# cache = self._cache
#
# @wraps(method)
# def checkcache(obj, t):
# cacheEntry = cache[obj]
# try:
# if closure_abs(t - cacheEntry.time) < tolerance:
# return cacheEntry.result
# cacheEntry.time = t
# cacheEntry.result = method(obj, t)
# return cacheEntry.result
# except:
# return method(obj, t)
# return checkcache
, which may contain function names, class names, or code. Output only the next line. | @CacheLastValue() |
Predict the next line after this snippet: <|code_start|>
class NoisyTransformedAccelerometer(NoisyTransformedSensor, IdealAccelerometer):
"""
Accelerometer with affine transform transfer function and Gaussian noise.
"""
pass
class MMA7260Q(NoisyTransformedSensor, Accelerometer):
"""
Model of the Freescale MMA7260Q accelerometer.
@ivar sensitivity: Sensitivity setting, '1.5g', '2g', '4g', or '6g'.
"""
NOMINAL_SENSITIVITIES = {'1.5g':800E-3, '2g':600E-3,
'4g':300E-3, '6g':200E-3}
NOMINAL_OFFSET = 1.65
MAX_CROSS_AXIS = 0.05
@prepend_method_doc(Accelerometer)
def __init__(self, platform, sensitivity, noiseStdDev, rng=None, **kwargs):
"""
@param sensitivity: Sensitivity setting, '1.5g', '2g', '4g', or '6g'.
@param noiseStdDev: Standard deviation of measured output voltage noise
in the system in which the accelerometer is integrated.
@param rng: L{np.random.RandomState} from which to draw imperfections.
"""
if rng is None:
rng = np.random.RandomState()
<|code_end|>
using the current file's imports:
import numpy as np
from imusim.platforms.sensors import *
from imusim.environment.gravity import STANDARD_GRAVITY
from imusim.utilities.documentation import prepend_method_doc
and any relevant context from other files:
# Path: imusim/environment/gravity.py
# STANDARD_GRAVITY = 9.81
. Output only the next line. | sensitivity = MMA7260Q.NOMINAL_SENSITIVITIES[sensitivity] / STANDARD_GRAVITY |
Here is a snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
class RadioPacket(dict):
"""
Class to represent a radio packet.
Payload fields should be added as dictionary items.
Metadata relevant to radio simulation should be added as attributes.
"""
__metaclass__ = ABCMeta
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
"""
Construct a radio packet.
"""
pass
@abstractproperty
def bytes(self):
pass
<|code_end|>
. Write the next line using the current file imports:
from abc import ABCMeta, abstractmethod, abstractproperty
from imusim.platforms.base import Component
and context from other files:
# Path: imusim/platforms/base.py
# class Component(object):
# """
# Base class for simulated hardware components.
# """
#
# __metaclass__ = ABCMeta
#
# def __init__(self, platform):
# """
# Initialise simulated component.
#
# @param platform: The L{Platform} this component will be attached to.
# """
# self.platform = platform
#
# def _simulationChange(self):
# """
# Called when the platform is assigned a new simulation.
# """
# pass
#
# def _trajectoryChange(self):
# """
# Called when the platform is assigned a new trajectory.
# """
# pass
, which may include functions, classes, or code. Output only the next line. | class Radio(Component): |
Predict the next line for this snippet: <|code_start|># You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division
x = np.linspace(0,10,100)
dt = x[1]-x[0]
functions = ( lambda x: x,
lambda x: x**2,
lambda x: np.cos(x),
lambda x: np.e**x )
integrals = ( lambda x: 1/2 * x**2,
lambda x: 1/3 * x**3,
lambda x: np.sin(x),
lambda x: np.e**x)
doubleIntegrals = (lambda x: x**3 / 6,
lambda x: x**4 / 12,
lambda x: -np.cos(x),
lambda x: np.e**x)
def checkIntegral(method, function, integral):
estimated_integral = np.empty_like(x)
integrator = method(integral(0))
for i,s in enumerate(x[1:]):
estimated_integral[i+1] = integrator(function(s), dt)
assert_vectors_correlated(estimated_integral[1:], integral(x[1:]))
def checkDoubleIntegral(method, function, integral, doubleIntegral):
estimated_integral = np.empty_like(x)
<|code_end|>
with the help of current file imports:
import numpy as np
from imusim.maths import integrators
from imusim.testing.vectors import assert_vectors_correlated
from imusim.testing.inspection import getImplementations
and context from other files:
# Path: imusim/maths/integrators.py
# class Integrator(object):
# class RectangleRule(Integrator):
# class TrapeziumRule(Integrator):
# class DoubleIntegrator(object):
# def __init__(self, initialValue):
# def __call__(self, sampleValue, dt):
# def __call__(self, sampleValue, dt):
# def __init__(self, initialValue):
# def __call__(self, sampleValue, dt):
# def __init__(self, initialValue, initialDerivative, method=RectangleRule):
# def __call__(self, sampleValue, dt):
, which may contain function names, class names, or code. Output only the next line. | integrator = integrators.DoubleIntegrator(doubleIntegral(0),integral(0), |
Given snippet: <|code_start|>"""
Tests for orientation tracking algorithms.
"""
# Copyright (C) 2009-2011 University of Edinburgh
#
# This file is part of IMUSim.
#
# IMUSim is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IMUSim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
dt = 0.01
GRAVITY = vector(0,0,1)
NORTH = vector(1,0,0)
filterParameters = {
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from imusim.testing.random_data import RandomRotationTrajectory
from imusim.testing.quaternions import assert_quaternions_correlated, assertMaximumErrorAngle
from imusim.testing.inspection import getImplementations
from imusim.algorithms import orientation
from imusim.maths.quaternions import Quaternion, QuaternionArray
from imusim.trajectories.rigid_body import Joint
from imusim.maths.vectors import vector
and context:
# Path: imusim/algorithms/orientation.py
# class OrientationFilter(object):
# class GyroIntegrator(OrientationFilter):
# class BachmannCF(OrientationFilter):
# class OrientCF(OrientationFilter):
# class YunEKF(OrientationFilter):
# class DistLinAccelCF(OrientationFilter):
# def __init__(self, initialTime, initialRotation):
# def __call__(self, accel, mag, gyro, t):
# def _update(self, accel, mag, gyro, dt, t):
# def __init__(self, initialTime, initialRotation, **kwargs):
# def _update(self, accel, mag, gyro, dt, t):
# def __init__(self, initialTime, initialRotation, k, **kwargs):
# def _update(self, accel, mag, gyro, dt, t):
# def __init__(self, initialTime, initialRotation, k, aT, **kwargs):
# def _update(self, accel, mag, gyro, dt, t):
# def __init__(self, initialTime, initialRotation, initialRotationalVelocity,
# initialCovariance, measurementCovariance, D, tau, **kwargs):
# def _update(self, accel, mag, gyro, dt, t):
# def dotx(self, xHat):
# def Phi(self, xHat, dt):
# def __init__(self, initialTime, initialRotation, k, joint, offset,
# **kwargs):
# def handleLinearAcceleration(self, jointAcceleration, dt):
# def childAcceleration(self, o, dt):
# def _update(self, accel, mag, gyro, dt, t):
# K = self.P_minus * np.linalg.inv(self.P_minus + self.R)
# P = (np.eye(7) - K) * self.P_minus
# GRAVITY_VECTOR = vectors.vector(0, 0, STANDARD_GRAVITY)
#
# Path: imusim/trajectories/rigid_body.py
# class Joint(Point):
# """
# A joint in a rigid body model, with its own rotating co-ordinate frame.
#
# @ivar children: List of child points that have this joint as parent.
# """
#
# def __init__(self, parent, name=None, offset=None):
# """
# Construct a joint.
#
# @param parent: Parent L{Joint}, or None for the root joint.
# @param name: Name of this joint.
# @param offset: Offset of this joint in the co-ordinate frame of its
# parent, as a 3x1 L{np.ndarray}. Default is zero offset.
# """
# Point.__init__(self, parent, name, offset)
# self.children = []
#
# @property
# def points(self):
# """
# Iterator for the points of the body model starting at this point.
#
# @see: L{preorderTraversal}
# """
# return self.preorderTraversal()
#
# @property
# def pointNames(self):
# """
# List of point names in the tree rooted at this joint.
# """
# return [p.name for p in self.points]
#
# def getPoint(self, pointName):
# """
# Get a point by name from the point tree rooted at this point.
#
# @param pointName: The name of the point to return (string).
# @return: The corresponding L{Point} object.
# @raises KeyError: If the named point is not present in the subtree.
# """
# for p in self.points:
# if p.name == pointName:
# return p
# raise KeyError
#
# @property
# def childJoints(self):
# """
# List of child joints that have this joint as parent.
# """
# return filter(lambda p: p.isJoint, self.children)
#
# @property
# def hasChildJoints(self):
# """
# Whether this joint has any child joints.
# """
# return len(self.childJoints) != 0
#
# @property
# def joints(self):
# """
# Iterator for the joints of the body model starting at this joint.
# """
# return self.preorderTraversal(condition=lambda p: p.isJoint)
#
# @property
# def jointNames(self):
# """
# List of joint names in the body model tree rooted at this joint.
# """
# return [j.name for j in self.joints]
#
# def getJoint(self, jointName):
# """
# Get a joint by name from the subtree rooted at this joint.
#
# @param jointName: The name of the joint to return (string).
# @return: The corresponding L{Joint} object.
# @raises KeyError: If the named joint is not present in the subtree.
# """
# for p in self.joints:
# if p.name == jointName:
# return p
# raise KeyError
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# """
# Create a deep copy of the body model tree starting from the given joint.
# """
# joint = cls(parent, ref.name, ref.positionOffset)
# for child in ref.children:
# if child.isJoint:
# cls.structureCopy(child, joint)
# else:
# Point(joint, child.name, child.positionOffset)
# return joint
which might include code, classes, or functions. Output only the next line. | orientation.OrientCF : { |
Given the following code snippet before the placeholder: <|code_start|> ]
def checkBaseField(field, nominal):
assert_almost_equal(field.nominalValue, nominal)
assert_almost_equal(field(vector(0,0,0), 0), nominal)
def testEarthField():
for args, nominal in TEST_PARAMS:
yield checkBaseField, EarthMagneticField(*args), nominal
def checkZeroHeadingVariation(field, position):
assert_almost_equal(field.headingVariation(position, 0), 0)
def testUndistortedField():
random.seed(0)
for args, nominal in TEST_PARAMS:
base = EarthMagneticField(*args)
field = DistortedMagneticField(base)
yield checkBaseField, field, nominal
for i in xrange(10):
yield checkZeroHeadingVariation, field, random.uniform(size=(3,1),
low=-10, high=10)
def checkNonZeroHeadingVariation(field, position):
assert abs(field.headingVariation(position, 0)) > 0.01
def testDistortedField():
random.seed(0)
field = DistortedMagneticField(EarthMagneticField())
field.addDistortion(SolenoidMagneticField(200,20,0.05,0.2,
<|code_end|>
, predict the next line using imports from the current file:
from imusim.environment.magnetic_fields import EarthMagneticField
from imusim.environment.magnetic_fields import DistortedMagneticField
from imusim.environment.magnetic_fields import SolenoidMagneticField
from numpy.testing import assert_almost_equal
from imusim.maths.vectors import vector
from imusim.maths.transforms import AffineTransform
from numpy import random
and context including class names, function names, and sometimes code from other files:
# Path: imusim/maths/transforms.py
# class AffineTransform(object):
# """
# Affine transform composed of a linear transform matrix and translation.
# """
# def __init__(self, transform=None, rz=0, ry=0, rx=0, scale=1,
# translation=vector(0,0,0)):
# """
# Construct an affine transform.
#
# A generic transformation matrix can be supplied, or a transform
# composed of rotation and scaling can be built.
#
# Generating rotations using supplied Euler angles is performed from the
# perspective of a fixed camera viewing a rotating object, i.e. points
# rotate within a fixed reference frame. Rotations are applied in
# aerospace (ZYX) order.
#
# @param transform: 3x3 linear transformation matrix.
# @param rx: X rotation angle in radians.
# @param ry: Y rotation angle in radians.
# @param rz: Z rotation angle in radians.
# @param scale: Scaling factor
# @param translation: 3x1 translation vector.
# """
# if transform is not None:
# self._transform = transform
# else:
# self._transform = scale * matrixFromEuler((rz,ry,rx),'zyx',False)
#
# self._inverseTransform = np.linalg.inv(self._transform)
# self._translation = translation
#
# def apply(self,v):
# """
# Apply transform to an array of column vectors.
# """
# return np.tensordot(self._transform, v, axes=([1],[0])) \
# + self._translation
#
# def reverse(self,v):
# """
# Apply the inverse of this transform to an array of column vectors.
# """
# return np.tensordot(self._inverseTransform,
# v-self._translation,axes=([1],[0]))
. Output only the next line. | AffineTransform())) |
Using the snippet: <|code_start|>"""
Tests for position estimation algorithms.
"""
# Copyright (C) 2009-2011 University of Edinburgh
#
# This file is part of IMUSim.
#
# IMUSim is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IMUSim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
referenceModel = SplinedBodyModel(
loadBVHFile(path.join(path.dirname(__file__), 'test.bvh'), 0.01))
dt = 0.01
sampleTimes = np.arange(referenceModel.startTime, referenceModel.endTime, dt)
def checkAlgorithm(algorithm):
<|code_end|>
, determine the next line of code. You have imports:
from os import path
from imusim.io.bvh import loadBVHFile
from imusim.trajectories.rigid_body import SampledBodyModel, SplinedBodyModel
from imusim.algorithms import position
from imusim.testing.inspection import getImplementations
import numpy as np
and context (class names, function names, or code) available:
# Path: imusim/io/bvh.py
# def loadBVHFile(filename, conversionFactor=1):
# """
# Load sampled body model data from a BVH file.
#
# @param filename: Name of file to load.
# @param conversionFactor: Scale factor to apply to position values, e.g.
# to convert meters to centimeters use conversionFactor=100.
#
# @return: A L{SampledBodyModel} object.
# """
# with open(filename,'r') as bvhFile:
# loader = BVHLoader(bvhFile,conversionFactor)
# loader._readHeader()
# loader._readMotionData()
# return loader.model
#
# Path: imusim/trajectories/rigid_body.py
# class SampledBodyModel(SampledPositionTrajectory, SampledJoint):
# """A body model with sampled positions and rotations."""
#
# def __init__(self, name=None):
# """
# Initialise body model.
#
# @param name: The name of the root L{Joint} of the body model
# """
# SampledJoint.__init__(self, None, name)
# SampledPositionTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# model = cls(ref.name)
# for child in ref.children:
# if child.isJoint:
# SampledJoint.structureCopy(child, model)
# else:
# PointTrajectory(model, child.name, child.positionOffset)
# return model
#
# class SplinedBodyModel(SplinedPositionTrajectory, SplinedJoint):
# """A body model with positions and rotations splined from sampled data."""
#
# def __init__(self, sampled, **kwargs):
# """
# Initialise splined body model.
#
# @param sampled: The L{SampledBodyModel} from which to generated
# splined trajectories
# """
# SplinedJoint.__init__(self, None, sampled, **kwargs)
# SplinedPositionTrajectory.__init__(self, sampled, **kwargs)
#
# @property
# def startTime(self):
# return max(self._positionStartTime, self._rotationStartTime)
#
# @property
# def endTime(self):
# return min(self._positionEndTime, self._rotationEndTime)
#
# Path: imusim/algorithms/position.py
# class PositionEstimator(object):
# class ConstantPosition(PositionEstimator):
# class RootAccelerationIntegrator(PositionEstimator):
# class LowestPoint(PositionEstimator):
# class ContactTrackingKalmanFilter(PositionEstimator):
# def __init__(self, model, initialTime=0, initialPosition=np.zeros((3,1))):
# def __call__(self, data, t):
# def _update(self, data, dt, t):
# def getParameter(self, data, jointName, parameter, default=None):
# def __init__(self, model, initialTime=0, initialPosition=np.zeros((3,1)),
# **kwargs):
# def _update(self, data, dt, t):
# def __init__(self, model, initialTime=0, initialPosition=np.zeros((3,1)),
# initialVelocity=np.zeros((3,1)),
# integrationMethod=integrators.TrapeziumRule, **kwargs):
# def _update(self, data, dt, t):
# def __init__(self, model, initialTime=0, initialPosition=np.zeros((3,1)),
# **kwargs):
# def _lowestPoint(self, t):
# def _update(self, data, dt, t):
# def __init__(self, model, initialTime=0,
# initialPosition=np.zeros((3,1)),
# initialVelocity=np.zeros((3,1)),
# accelerationVar=0.2, velocityVar=0.5,
# rejectionProbabilityThreshold=0.4,
# **kwargs):
# def _update(self, data, dt, t):
# def estimateVelocityProbabilities(self, dt, t):
# def transitionMatrix(self, dt):
# def controlMatrix(self, dt):
# def processCovariance(self, dt):
# A = np.matrix([ [1, 0, 0, dt, 0, 0],
# [0, 1, 0, 0, dt, 0],
# [0, 0, 1, 0, 0, dt],
# [0, 0, 0, 1, 0, 0 ],
# [0, 0, 0, 0, 1, 0 ],
# [0, 0, 0, 0, 0, 1 ]])
# B = np.matrix([ [a, 0, 0],
# [0, a, 0],
# [0, 0, a],
# [b, 0, 0],
# [0, b, 0],
# [0, 0, b]])
# Q = np.matrix([ [a, 0, 0, b, 0, 0],
# [0, a, 0, 0, b, 0],
# [0, 0, a, 0, 0, b],
# [b, 0, 0, c, 0, 0],
# [0, b, 0, 0, c, 0],
# [0, 0, b, 0, 0, c]])
. Output only the next line. | sampledModel = SampledBodyModel.structureCopy(referenceModel) |
Given the code snippet: <|code_start|>#
# IMUSim is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IMUSim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
referenceModel = SplinedBodyModel(
loadBVHFile(path.join(path.dirname(__file__), 'test.bvh'), 0.01))
dt = 0.01
sampleTimes = np.arange(referenceModel.startTime, referenceModel.endTime, dt)
def checkAlgorithm(algorithm):
sampledModel = SampledBodyModel.structureCopy(referenceModel)
for t in sampleTimes:
for referenceJoint, sampledJoint in zip(referenceModel.joints,
sampledModel.joints):
sampledJoint.rotationKeyFrames.add(t, referenceJoint.rotation(t))
positionEstimator = algorithm(sampledModel,
initialTime = referenceModel.startTime,
<|code_end|>
, generate the next line using the imports in this file:
from os import path
from imusim.io.bvh import loadBVHFile
from imusim.trajectories.rigid_body import SampledBodyModel, SplinedBodyModel
from imusim.algorithms import position
from imusim.testing.inspection import getImplementations
import numpy as np
and context (functions, classes, or occasionally code) from other files:
# Path: imusim/io/bvh.py
# def loadBVHFile(filename, conversionFactor=1):
# """
# Load sampled body model data from a BVH file.
#
# @param filename: Name of file to load.
# @param conversionFactor: Scale factor to apply to position values, e.g.
# to convert meters to centimeters use conversionFactor=100.
#
# @return: A L{SampledBodyModel} object.
# """
# with open(filename,'r') as bvhFile:
# loader = BVHLoader(bvhFile,conversionFactor)
# loader._readHeader()
# loader._readMotionData()
# return loader.model
#
# Path: imusim/trajectories/rigid_body.py
# class SampledBodyModel(SampledPositionTrajectory, SampledJoint):
# """A body model with sampled positions and rotations."""
#
# def __init__(self, name=None):
# """
# Initialise body model.
#
# @param name: The name of the root L{Joint} of the body model
# """
# SampledJoint.__init__(self, None, name)
# SampledPositionTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# model = cls(ref.name)
# for child in ref.children:
# if child.isJoint:
# SampledJoint.structureCopy(child, model)
# else:
# PointTrajectory(model, child.name, child.positionOffset)
# return model
#
# class SplinedBodyModel(SplinedPositionTrajectory, SplinedJoint):
# """A body model with positions and rotations splined from sampled data."""
#
# def __init__(self, sampled, **kwargs):
# """
# Initialise splined body model.
#
# @param sampled: The L{SampledBodyModel} from which to generated
# splined trajectories
# """
# SplinedJoint.__init__(self, None, sampled, **kwargs)
# SplinedPositionTrajectory.__init__(self, sampled, **kwargs)
#
# @property
# def startTime(self):
# return max(self._positionStartTime, self._rotationStartTime)
#
# @property
# def endTime(self):
# return min(self._positionEndTime, self._rotationEndTime)
#
# Path: imusim/algorithms/position.py
# class PositionEstimator(object):
# class ConstantPosition(PositionEstimator):
# class RootAccelerationIntegrator(PositionEstimator):
# class LowestPoint(PositionEstimator):
# class ContactTrackingKalmanFilter(PositionEstimator):
# def __init__(self, model, initialTime=0, initialPosition=np.zeros((3,1))):
# def __call__(self, data, t):
# def _update(self, data, dt, t):
# def getParameter(self, data, jointName, parameter, default=None):
# def __init__(self, model, initialTime=0, initialPosition=np.zeros((3,1)),
# **kwargs):
# def _update(self, data, dt, t):
# def __init__(self, model, initialTime=0, initialPosition=np.zeros((3,1)),
# initialVelocity=np.zeros((3,1)),
# integrationMethod=integrators.TrapeziumRule, **kwargs):
# def _update(self, data, dt, t):
# def __init__(self, model, initialTime=0, initialPosition=np.zeros((3,1)),
# **kwargs):
# def _lowestPoint(self, t):
# def _update(self, data, dt, t):
# def __init__(self, model, initialTime=0,
# initialPosition=np.zeros((3,1)),
# initialVelocity=np.zeros((3,1)),
# accelerationVar=0.2, velocityVar=0.5,
# rejectionProbabilityThreshold=0.4,
# **kwargs):
# def _update(self, data, dt, t):
# def estimateVelocityProbabilities(self, dt, t):
# def transitionMatrix(self, dt):
# def controlMatrix(self, dt):
# def processCovariance(self, dt):
# A = np.matrix([ [1, 0, 0, dt, 0, 0],
# [0, 1, 0, 0, dt, 0],
# [0, 0, 1, 0, 0, dt],
# [0, 0, 0, 1, 0, 0 ],
# [0, 0, 0, 0, 1, 0 ],
# [0, 0, 0, 0, 0, 1 ]])
# B = np.matrix([ [a, 0, 0],
# [0, a, 0],
# [0, 0, a],
# [b, 0, 0],
# [0, b, 0],
# [0, 0, b]])
# Q = np.matrix([ [a, 0, 0, b, 0, 0],
# [0, a, 0, 0, b, 0],
# [0, 0, a, 0, 0, b],
# [b, 0, 0, c, 0, 0],
# [0, b, 0, 0, c, 0],
# [0, 0, b, 0, 0, c]])
. Output only the next line. | initialPosition = referenceModel.position(referenceModel.startTime), |
Next line prediction: <|code_start|> @param stateUpdateFunction: Non-linear function to propagate state into
the next timestep. The function is called with two arguments, the
current Nx1 state vector and the current Mx1 control input vector.
It should return a new Nx1 state vector. N and M are the numbers of
states and control inputs.
@param measurementFunction: Non-linear function relating state
variables to expected measurements. The function is called with the
current Nx1 state vector as an argument, and should return an Mx1
measurement vector. N and M are the numbers of states and measurement
outputs.
@param state: Initial state estimate.
@param stateCovariance: Initial state covariance matrix.
@param processCovariance: Process noise covariance matrix.
@param measurementCovariance: Measurement noise covariance matrix.
"""
self.stateUpdateFunction = stateUpdateFunction
self.measurementFunction = measurementFunction
self.state = state
self.stateCovariance = stateCovariance
self.processCovariance = processCovariance
self.measurementCovariance = measurementCovariance
@property
def stateUpdateFunction(self):
return self._stateUpdateUT._function
@stateUpdateFunction.setter
def stateUpdateFunction(self, function):
<|code_end|>
. Use current file imports:
(import numpy as np
from imusim.maths.transforms import UnscentedTransform
from numpy.linalg import inv
from itertools import izip)
and context including class names, function names, or small code snippets from other files:
# Path: imusim/maths/transforms.py
# class UnscentedTransform(object):
# """
# Implementation of the Unscented Transform of Julier and Uhlmann.
#
# The unscented transform propagates mean and covariance information
# through a non-linear function. An instance of this class is callable
# to apply the function to a vector of mean values and a covariance
# matrix, returning an output mean vector and covariance matrix.
# """
#
# _sum = functools.partial(np.sum, axis=0)
#
# def __init__(self, function):
# """
# Construct unscented transform.
#
# @param function: The function to apply.
# """
# assert isinstance(function, collections.Callable)
# self._function = function
#
# def __call__(self, mean, covariance, *args, **kwargs):
# """
# Propagate mean and covariance values through the transform function.
#
# Additional arguments are passed through to the function.
#
# @param mean: Nx1 column vector of mean input values.
# @param covariance: NxN covariance of input values.
# @param returnSigmas: If True, return sigma points and weights.
#
# @return: Mx1 column vector of mean output values, MxM covariance
# of output values. If returnSigmas is True, additionally a list of
# input sigma point column vectors, a list of output sigma point
# column vectors, and a list of sigma point weights.
# """
# returnSigmas = kwargs.pop('returnSigmas', False)
# inputSigmaPoints, weights = UnscentedTransform.sigmaPoints(mean, covariance)
# outputSigmaPoints = [self._function(p, *args, **kwargs) for p in inputSigmaPoints]
# weightedOutputPoints = zip(weights, outputSigmaPoints)
# outputMean = self._sum(W*y for W,y in weightedOutputPoints)
# outputCovariance = self._sum(W*(y-outputMean)*(y-outputMean).T for W,y in weightedOutputPoints)
# if returnSigmas:
# return outputMean, outputCovariance, inputSigmaPoints, outputSigmaPoints, weights
# else:
# return outputMean, outputCovariance
#
# @staticmethod
# def sigmaPoints(mean, covariance):
# """
# Generate sigma points around the given mean values based on covariance.
#
# Implements the symmetric sigma point set of Julier and Uhlmann 2004,
# 'Unscented Filtering and Nonlinear Estimation', equation 12. Weighting
# applied to first sigma point is 1/3 based on the assumption of Gaussian
# distributions.
#
# @return: List of sigma point column vectors, list of weights.
# """
# N = len(mean)
# mean = np.reshape(mean, (N,1))
# assert covariance.shape == (N,N)
#
# sigmaPoints = [mean] * (2*N + 1)
# w0 = 1/3 # based on assumption of Gaussian distributions.
#
# cholesky = linalg.cholesky((N/(1-w0)) * covariance)
# # cholesky returns A s.t. A*A.T = P so we use the columns of A
# columns = np.hsplit(cholesky, N)
# for i, column in enumerate(columns):
# sigmaPoints[i+1] = mean + column
# sigmaPoints[i+1+N] = mean - column
# weights = [w0] + [(1-w0)/(2*N)] * (2 * N)
# return sigmaPoints, weights
. Output only the next line. | self._stateUpdateUT = UnscentedTransform(function) |
Given the code snippet: <|code_start|>
@property
def bytes(self):
size = 2
for key in self.keys():
data = self[key]
if isinstance(data, Quaternion):
size += array(data.components).nbytes
elif isinstance(data, numpy.ndarray):
size += data.nbytes
return size
class AuxPacket(DataPacket):
"""
Auxillary packet from slave to slave.
@ivar source: Source device ID.
@ivar dest: Destination device ID.
"""
def __init__(self, source, dest, data):
"""
Initialise auxillary packet.
@param source: Source device ID.
@param dest: Destination device ID.
@param data: Payload data.
"""
DataPacket.__init__(self, source, data)
self.dest = dest
<|code_end|>
, generate the next line using the imports in this file:
from imusim.behaviours.mac import MAC
from imusim.behaviours.timing import VirtualTimer
from imusim.platforms.radios import RadioPacket
from imusim.maths.quaternions import Quaternion
from imusim.utilities.documentation import prepend_method_doc
import numpy as np
and context (functions, classes, or occasionally code) from other files:
# Path: imusim/behaviours/mac.py
# class MAC(object):
# """
# Base class for MAC implementations.
#
# @ivar radio: The L{Radio} used by the MAC.
# @ivar timerMux: L{TimerMultiplexer} used by the MAC.
# """
#
# __metaclass__ = ABCMeta
#
# def __init__(self, radio, timerMux):
# """
# Initialise MAC.
#
# @param radio: The L{Radio} to be used by the MAC.
# @param timerMux: L{TimerMultiplexer} to be used by the MAC.
# """
# self.radio = radio
# self.timerMux = timerMux
#
# self.radio.setReceiveHandler(self.handleIncomingPacket)
#
# @abstractmethod
# def queuePacket(self, packet):
# """
# Queue a packet for transmission
#
# @param packet: The L{RadioPacket} to transmit.
# """
# pass
#
# @abstractmethod
# def handleIncomingPacket(self, packet):
# """
# Handle a received packet from the radio.
#
# @param packet: the received L{RadioPacket}.
# """
# pass
#
# Path: imusim/behaviours/timing.py
# class VirtualTimer(object):
# """
# A virtual timer multiplexed to a hardware timer.
#
# Implements the same interface as L{Timer}.
#
# @ivar callback: Function to be called when timer fires.
# """
# def __init__(self, mux, callback=None):
# """
# Create virtual timer.
#
# @param mux: The L{TimerMultiplexer} implementing this timer.
# """
# self._period = None
# self._mux = mux
# self.callback = callback
# self._mux._vtimers.append(self)
#
# @prepend_method_doc(Timer)
# def start(self, period, repeat=False):
# self._period = period
# self._repeat = repeat
#
# if self._mux._inHandler:
# # In timer event, handler is iterating through virtual timer list.
# self._done = True
# self._remaining = self._period
# else:
# self._done = False
# if self._mux._period is None:
# # Timer off, this will become the only active virtual timer.
# self._remaining = self._period
# self._mux._period = self._period
# self._mux._timer.start(self._period, self._mux._timerHandler)
# elif self._period < self._mux._period:
# # This timer will fire before any others.
# self._remaining = self._period
# elapsed = self._mux._timer.timeElapsed()
# for vtimer in self._mux._vtimers:
# if vtimer is not self and vtimer._period is not None:
# vtimer._remaining -= elapsed
# self._mux._period = self._period
# self._mux._timer.start(self._mux._period,
# self._mux._timerHandler)
# elif self._period == self._mux._period:
# # This timer will fire at the same time as others.
# self._remaining = self._period
# else:
# # Other timers will fire before this one.
# self._remaining = self._period + self._mux._timer.timeElapsed()
#
# @prepend_method_doc(Timer)
# def clear(self):
# self._period = None
#
# @prepend_method_doc(Timer)
# def timeElapsed(self):
# return (self._period - self._remaining) + self.mux._timer.timeElapsed()
#
# Path: imusim/platforms/radios.py
# class RadioPacket(dict):
# """
# Class to represent a radio packet.
#
# Payload fields should be added as dictionary items.
#
# Metadata relevant to radio simulation should be added as attributes.
# """
#
# __metaclass__ = ABCMeta
#
# def __init__(self, *args, **kwargs):
# dict.__init__(self, *args, **kwargs)
# """
# Construct a radio packet.
# """
# pass
#
# @abstractproperty
# def bytes(self):
# pass
. Output only the next line. | class MasterMAC(MAC): |
Predict the next line after this snippet: <|code_start|>
@ivar source: Source device ID.
@ivar dest: Destination device ID.
"""
def __init__(self, source, dest, data):
"""
Initialise auxillary packet.
@param source: Source device ID.
@param dest: Destination device ID.
@param data: Payload data.
"""
DataPacket.__init__(self, source, data)
self.dest = dest
class MasterMAC(MAC):
"""
Master MAC implementation.
"""
@prepend_method_doc(MAC)
def __init__(self, radio, timerMux, schedule, frameHandler=None):
"""
@param schedule: L{Schedule} object giving transmission scheduling.
@param frameHandler: Handler function to call at the end of each frame.
The packets received in that frame will be passed as a list.
"""
MAC.__init__(self, radio, timerMux)
self.schedule = schedule
self.frameHandler = frameHandler
<|code_end|>
using the current file's imports:
from imusim.behaviours.mac import MAC
from imusim.behaviours.timing import VirtualTimer
from imusim.platforms.radios import RadioPacket
from imusim.maths.quaternions import Quaternion
from imusim.utilities.documentation import prepend_method_doc
import numpy as np
and any relevant context from other files:
# Path: imusim/behaviours/mac.py
# class MAC(object):
# """
# Base class for MAC implementations.
#
# @ivar radio: The L{Radio} used by the MAC.
# @ivar timerMux: L{TimerMultiplexer} used by the MAC.
# """
#
# __metaclass__ = ABCMeta
#
# def __init__(self, radio, timerMux):
# """
# Initialise MAC.
#
# @param radio: The L{Radio} to be used by the MAC.
# @param timerMux: L{TimerMultiplexer} to be used by the MAC.
# """
# self.radio = radio
# self.timerMux = timerMux
#
# self.radio.setReceiveHandler(self.handleIncomingPacket)
#
# @abstractmethod
# def queuePacket(self, packet):
# """
# Queue a packet for transmission
#
# @param packet: The L{RadioPacket} to transmit.
# """
# pass
#
# @abstractmethod
# def handleIncomingPacket(self, packet):
# """
# Handle a received packet from the radio.
#
# @param packet: the received L{RadioPacket}.
# """
# pass
#
# Path: imusim/behaviours/timing.py
# class VirtualTimer(object):
# """
# A virtual timer multiplexed to a hardware timer.
#
# Implements the same interface as L{Timer}.
#
# @ivar callback: Function to be called when timer fires.
# """
# def __init__(self, mux, callback=None):
# """
# Create virtual timer.
#
# @param mux: The L{TimerMultiplexer} implementing this timer.
# """
# self._period = None
# self._mux = mux
# self.callback = callback
# self._mux._vtimers.append(self)
#
# @prepend_method_doc(Timer)
# def start(self, period, repeat=False):
# self._period = period
# self._repeat = repeat
#
# if self._mux._inHandler:
# # In timer event, handler is iterating through virtual timer list.
# self._done = True
# self._remaining = self._period
# else:
# self._done = False
# if self._mux._period is None:
# # Timer off, this will become the only active virtual timer.
# self._remaining = self._period
# self._mux._period = self._period
# self._mux._timer.start(self._period, self._mux._timerHandler)
# elif self._period < self._mux._period:
# # This timer will fire before any others.
# self._remaining = self._period
# elapsed = self._mux._timer.timeElapsed()
# for vtimer in self._mux._vtimers:
# if vtimer is not self and vtimer._period is not None:
# vtimer._remaining -= elapsed
# self._mux._period = self._period
# self._mux._timer.start(self._mux._period,
# self._mux._timerHandler)
# elif self._period == self._mux._period:
# # This timer will fire at the same time as others.
# self._remaining = self._period
# else:
# # Other timers will fire before this one.
# self._remaining = self._period + self._mux._timer.timeElapsed()
#
# @prepend_method_doc(Timer)
# def clear(self):
# self._period = None
#
# @prepend_method_doc(Timer)
# def timeElapsed(self):
# return (self._period - self._remaining) + self.mux._timer.timeElapsed()
#
# Path: imusim/platforms/radios.py
# class RadioPacket(dict):
# """
# Class to represent a radio packet.
#
# Payload fields should be added as dictionary items.
#
# Metadata relevant to radio simulation should be added as attributes.
# """
#
# __metaclass__ = ABCMeta
#
# def __init__(self, *args, **kwargs):
# dict.__init__(self, *args, **kwargs)
# """
# Construct a radio packet.
# """
# pass
#
# @abstractproperty
# def bytes(self):
# pass
. Output only the next line. | self.frameTimer = VirtualTimer(timerMux, self._frameTimerHandler) |
Predict the next line for this snippet: <|code_start|># along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division
class Schedule(object):
"""
Transmission schedule.
"""
def __init__(self, dataSlotTime, syncSlotTime, dataSlots):
"""
Initialise schedule.
@param dataSlotTime: Data slot duration (float, s).
@param syncSlotTime: Synchronisation slot duration (float, s).
@param dataSlots: List of device IDs indexed by allocated slot.
"""
self.dataSlotTime = dataSlotTime
self.syncSlotTime = syncSlotTime
self.dataSlots = dataSlots
@property
def framePeriod(self):
""" Duration of one complete frame. """
return len(self.dataSlots) * self.dataSlotTime + self.syncSlotTime
def dataTxSlot(self, id):
""" Transmission slot number for given device ID. """
return self.dataSlots.index(id)
<|code_end|>
with the help of current file imports:
from imusim.behaviours.mac import MAC
from imusim.behaviours.timing import VirtualTimer
from imusim.platforms.radios import RadioPacket
from imusim.maths.quaternions import Quaternion
from imusim.utilities.documentation import prepend_method_doc
import numpy as np
and context from other files:
# Path: imusim/behaviours/mac.py
# class MAC(object):
# """
# Base class for MAC implementations.
#
# @ivar radio: The L{Radio} used by the MAC.
# @ivar timerMux: L{TimerMultiplexer} used by the MAC.
# """
#
# __metaclass__ = ABCMeta
#
# def __init__(self, radio, timerMux):
# """
# Initialise MAC.
#
# @param radio: The L{Radio} to be used by the MAC.
# @param timerMux: L{TimerMultiplexer} to be used by the MAC.
# """
# self.radio = radio
# self.timerMux = timerMux
#
# self.radio.setReceiveHandler(self.handleIncomingPacket)
#
# @abstractmethod
# def queuePacket(self, packet):
# """
# Queue a packet for transmission
#
# @param packet: The L{RadioPacket} to transmit.
# """
# pass
#
# @abstractmethod
# def handleIncomingPacket(self, packet):
# """
# Handle a received packet from the radio.
#
# @param packet: the received L{RadioPacket}.
# """
# pass
#
# Path: imusim/behaviours/timing.py
# class VirtualTimer(object):
# """
# A virtual timer multiplexed to a hardware timer.
#
# Implements the same interface as L{Timer}.
#
# @ivar callback: Function to be called when timer fires.
# """
# def __init__(self, mux, callback=None):
# """
# Create virtual timer.
#
# @param mux: The L{TimerMultiplexer} implementing this timer.
# """
# self._period = None
# self._mux = mux
# self.callback = callback
# self._mux._vtimers.append(self)
#
# @prepend_method_doc(Timer)
# def start(self, period, repeat=False):
# self._period = period
# self._repeat = repeat
#
# if self._mux._inHandler:
# # In timer event, handler is iterating through virtual timer list.
# self._done = True
# self._remaining = self._period
# else:
# self._done = False
# if self._mux._period is None:
# # Timer off, this will become the only active virtual timer.
# self._remaining = self._period
# self._mux._period = self._period
# self._mux._timer.start(self._period, self._mux._timerHandler)
# elif self._period < self._mux._period:
# # This timer will fire before any others.
# self._remaining = self._period
# elapsed = self._mux._timer.timeElapsed()
# for vtimer in self._mux._vtimers:
# if vtimer is not self and vtimer._period is not None:
# vtimer._remaining -= elapsed
# self._mux._period = self._period
# self._mux._timer.start(self._mux._period,
# self._mux._timerHandler)
# elif self._period == self._mux._period:
# # This timer will fire at the same time as others.
# self._remaining = self._period
# else:
# # Other timers will fire before this one.
# self._remaining = self._period + self._mux._timer.timeElapsed()
#
# @prepend_method_doc(Timer)
# def clear(self):
# self._period = None
#
# @prepend_method_doc(Timer)
# def timeElapsed(self):
# return (self._period - self._remaining) + self.mux._timer.timeElapsed()
#
# Path: imusim/platforms/radios.py
# class RadioPacket(dict):
# """
# Class to represent a radio packet.
#
# Payload fields should be added as dictionary items.
#
# Metadata relevant to radio simulation should be added as attributes.
# """
#
# __metaclass__ = ABCMeta
#
# def __init__(self, *args, **kwargs):
# dict.__init__(self, *args, **kwargs)
# """
# Construct a radio packet.
# """
# pass
#
# @abstractproperty
# def bytes(self):
# pass
, which may contain function names, class names, or code. Output only the next line. | class SyncPacket(RadioPacket): |
Predict the next line for this snippet: <|code_start|>"""
Tests for ASF/AMC input
"""
# Copyright (C) 2009-2011 University of Edinburgh
#
# This file is part of IMUSim.
#
# IMUSim is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IMUSim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
def testASFInput():
dir = path.dirname(__file__)
asfFile = path.join(dir, "16.asf")
amcFile = path.join(dir, "16_15.amc")
bvhFile = path.join(dir, "16_15.bvh")
<|code_end|>
with the help of current file imports:
from imusim.io.asf_amc import loadASFFile
from imusim.io.bvh import loadBVHFile
from os import path
from numpy.testing import assert_almost_equal
from imusim.testing.quaternions import assertMaximumRMSErrorAngle
and context from other files:
# Path: imusim/io/asf_amc.py
# def loadASFFile(asfFileName, amcFileName, scaleFactor, framePeriod):
# """
# Load motion capture data from an ASF and AMC file pair.
#
# @param asfFileName: Name of the ASF file containing the description of
# the rigid body model
# @param amcFileName: Name of the AMC file containing the motion data
# @param scaleFactor: Scaling factor to convert lengths to m. For data
# from the CMU motion capture corpus this should be 2.54/100 to
# convert from inches to metres.
#
# @return: A {SampledBodyModel} representing the root of the rigid body
# model structure.
# """
# with open(asfFileName, 'r') as asfFile:
# data = asfParser.parseFile(asfFile)
# scale = (1.0/data.units.get('length',1)) * scaleFactor
#
# bones = dict((bone.name,bone) for bone in data.bones)
# asfModel = ASFRoot(data.root)
#
# for entry in data.hierarchy:
# parent = asfModel.getBone(entry.parent)
# for childName in entry.children:
# ASFBone(parent, bones[childName], scale)
#
# imusimModel = SampledBodyModel('root')
# for subtree in asfModel.children:
# for bone in subtree:
# if not bone.isDummy:
# offset = vector(0,0,0)
# ancestors = bone.ascendTree()
# while True:
# ancestor = ancestors.next().parent
# offset += ancestor.childoffset
# if not ancestor.isDummy:
# break
#
# SampledJoint(parent=imusimModel.getJoint(ancestor.name),
# name=bone.name,
# offset=offset)
# if not bone.hasChildren:
# PointTrajectory(
# parent=imusimModel.getJoint(bone.name),
# name=bone.name+'_end',
# offset=bone.childoffset
# )
#
# with open(amcFileName) as amcFile:
# motion = amcParser.parseFile(amcFile)
# t = 0
# for frame in motion.frames:
# for bone in frame.bones:
# bonedata = asfModel.getBone(bone.name)
# if bone.name == 'root':
# data = dict((chan.lower(), v) for chan,v in
# zip(bonedata.channels,bone.channels))
# position = convertCGtoNED(scale * vector(data['tx'],
# data['ty'],data['tz']))
# imusimModel.positionKeyFrames.add(t, position)
#
# axes, angles = zip(*[(chan[-1], angle) for chan, angle in
# zip(bonedata.channels, bone.channels) if
# chan.lower().startswith('r')])
# rotation = (bonedata.rotationOffset.conjugate *
# Quaternion.fromEuler(angles[::-1], axes[::-1]))
# joint = imusimModel.getJoint(bone.name)
# if joint.hasParent:
# parentRot = joint.parent.rotationKeyFrames.latestValue
# parentRotOffset = bonedata.parent.rotationOffset
# rotation = parentRot * parentRotOffset * rotation
# else:
# rotation = convertCGtoNED(rotation)
# joint.rotationKeyFrames.add(t, rotation)
# t += framePeriod
#
# return imusimModel
#
# Path: imusim/io/bvh.py
# def loadBVHFile(filename, conversionFactor=1):
# """
# Load sampled body model data from a BVH file.
#
# @param filename: Name of file to load.
# @param conversionFactor: Scale factor to apply to position values, e.g.
# to convert meters to centimeters use conversionFactor=100.
#
# @return: A L{SampledBodyModel} object.
# """
# with open(filename,'r') as bvhFile:
# loader = BVHLoader(bvhFile,conversionFactor)
# loader._readHeader()
# loader._readMotionData()
# return loader.model
, which may contain function names, class names, or code. Output only the next line. | asfModel = loadASFFile(asfFile, amcFile, scaleFactor=2.54/100, |
Given the code snippet: <|code_start|>"""
Tests for ASF/AMC input
"""
# Copyright (C) 2009-2011 University of Edinburgh
#
# This file is part of IMUSim.
#
# IMUSim is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IMUSim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
def testASFInput():
dir = path.dirname(__file__)
asfFile = path.join(dir, "16.asf")
amcFile = path.join(dir, "16_15.amc")
bvhFile = path.join(dir, "16_15.bvh")
asfModel = loadASFFile(asfFile, amcFile, scaleFactor=2.54/100,
framePeriod=1.0/120)
<|code_end|>
, generate the next line using the imports in this file:
from imusim.io.asf_amc import loadASFFile
from imusim.io.bvh import loadBVHFile
from os import path
from numpy.testing import assert_almost_equal
from imusim.testing.quaternions import assertMaximumRMSErrorAngle
and context (functions, classes, or occasionally code) from other files:
# Path: imusim/io/asf_amc.py
# def loadASFFile(asfFileName, amcFileName, scaleFactor, framePeriod):
# """
# Load motion capture data from an ASF and AMC file pair.
#
# @param asfFileName: Name of the ASF file containing the description of
# the rigid body model
# @param amcFileName: Name of the AMC file containing the motion data
# @param scaleFactor: Scaling factor to convert lengths to m. For data
# from the CMU motion capture corpus this should be 2.54/100 to
# convert from inches to metres.
#
# @return: A {SampledBodyModel} representing the root of the rigid body
# model structure.
# """
# with open(asfFileName, 'r') as asfFile:
# data = asfParser.parseFile(asfFile)
# scale = (1.0/data.units.get('length',1)) * scaleFactor
#
# bones = dict((bone.name,bone) for bone in data.bones)
# asfModel = ASFRoot(data.root)
#
# for entry in data.hierarchy:
# parent = asfModel.getBone(entry.parent)
# for childName in entry.children:
# ASFBone(parent, bones[childName], scale)
#
# imusimModel = SampledBodyModel('root')
# for subtree in asfModel.children:
# for bone in subtree:
# if not bone.isDummy:
# offset = vector(0,0,0)
# ancestors = bone.ascendTree()
# while True:
# ancestor = ancestors.next().parent
# offset += ancestor.childoffset
# if not ancestor.isDummy:
# break
#
# SampledJoint(parent=imusimModel.getJoint(ancestor.name),
# name=bone.name,
# offset=offset)
# if not bone.hasChildren:
# PointTrajectory(
# parent=imusimModel.getJoint(bone.name),
# name=bone.name+'_end',
# offset=bone.childoffset
# )
#
# with open(amcFileName) as amcFile:
# motion = amcParser.parseFile(amcFile)
# t = 0
# for frame in motion.frames:
# for bone in frame.bones:
# bonedata = asfModel.getBone(bone.name)
# if bone.name == 'root':
# data = dict((chan.lower(), v) for chan,v in
# zip(bonedata.channels,bone.channels))
# position = convertCGtoNED(scale * vector(data['tx'],
# data['ty'],data['tz']))
# imusimModel.positionKeyFrames.add(t, position)
#
# axes, angles = zip(*[(chan[-1], angle) for chan, angle in
# zip(bonedata.channels, bone.channels) if
# chan.lower().startswith('r')])
# rotation = (bonedata.rotationOffset.conjugate *
# Quaternion.fromEuler(angles[::-1], axes[::-1]))
# joint = imusimModel.getJoint(bone.name)
# if joint.hasParent:
# parentRot = joint.parent.rotationKeyFrames.latestValue
# parentRotOffset = bonedata.parent.rotationOffset
# rotation = parentRot * parentRotOffset * rotation
# else:
# rotation = convertCGtoNED(rotation)
# joint.rotationKeyFrames.add(t, rotation)
# t += framePeriod
#
# return imusimModel
#
# Path: imusim/io/bvh.py
# def loadBVHFile(filename, conversionFactor=1):
# """
# Load sampled body model data from a BVH file.
#
# @param filename: Name of file to load.
# @param conversionFactor: Scale factor to apply to position values, e.g.
# to convert meters to centimeters use conversionFactor=100.
#
# @return: A L{SampledBodyModel} object.
# """
# with open(filename,'r') as bvhFile:
# loader = BVHLoader(bvhFile,conversionFactor)
# loader._readHeader()
# loader._readMotionData()
# return loader.model
. Output only the next line. | bvhModel = loadBVHFile(bvhFile, 1.0/100) |
Here is a snippet: <|code_start|> """
with open(filename,'r') as bvhFile:
loader = BVHLoader(bvhFile,conversionFactor)
loader._readHeader()
loader._readMotionData()
return loader.model
class BVHLoader(object):
'''
Loader class for BVH files.
'''
def __init__(self, bvhFile, conversionFactor):
'''
Construct a new BVH loader for the specified BVH file.
'''
self.bvhFile = bvhFile
self.tokens = []
self.line = 0
self.totalChannels = 0
self.startOfMotionData = None
self.conversionFactor = conversionFactor
def _readHeader(self):
'''
Read the header information from the BVH file.
'''
assert self.bvhFile.tell() == 0, \
'Must be at the start of file to read header'
self._checkToken("HIERARCHY")
self._checkToken("ROOT")
<|code_end|>
. Write the next line using the current file imports:
from imusim.trajectories.rigid_body import SampledBodyModel, SampledJoint, \
PointTrajectory
from imusim.maths.quaternions import Quaternion
from imusim.maths.transforms import convertCGtoNED, convertNEDtoCG
import numpy as np
and context from other files:
# Path: imusim/trajectories/rigid_body.py
# class SampledBodyModel(SampledPositionTrajectory, SampledJoint):
# """A body model with sampled positions and rotations."""
#
# def __init__(self, name=None):
# """
# Initialise body model.
#
# @param name: The name of the root L{Joint} of the body model
# """
# SampledJoint.__init__(self, None, name)
# SampledPositionTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# model = cls(ref.name)
# for child in ref.children:
# if child.isJoint:
# SampledJoint.structureCopy(child, model)
# else:
# PointTrajectory(model, child.name, child.positionOffset)
# return model
#
# class SampledJoint(SampledRotationTrajectory, OffsetTrajectory, Joint):
# """
# A joint in a rigid body model with sampled rotations.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Initialise sampled joint.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the joint.
# @param offset: Offset of the joint in the parent joint
# co-ordinate frame.
# """
# Joint.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
# SampledRotationTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# joint = cls(parent, ref.name, ref.positionOffset)
# for child in ref.children:
# if child.isJoint:
# cls.structureCopy(child, joint)
# else:
# PointTrajectory(joint, child.name, child.positionOffset)
# return joint
#
# class PointTrajectory(OffsetTrajectory, Point):
# """
# Trajectory followed by a point in a rigid body model.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Construct point trajectory.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the point.
# @param offset: Offset of the point in the parent joint
# co-ordinate frame.
# """
# Point.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
#
# Path: imusim/maths/transforms.py
# def convertCGtoNED(param):
# """
# Convert parameters specified in Computer Graphics co-ordinates to
# North East Down co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in CG frame.
#
# @return: The corresponding L{Quaternion} or vector in NED frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _CGtoNED.conjugate * param * _CGtoNED
# else:
# return _CGtoNED.rotateFrame(param)
#
# def convertNEDtoCG(param):
# """
# Convert parameters specified in North East Down co-ordinates to
# Computer Graphics co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in NED frame.
#
# @return: The corresponding L{Quaternion} or vector in CG frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _NEDtoCG.conjugate * param * _NEDtoCG
# else:
# return _NEDtoCG.rotateFrame(param)
, which may include functions, classes, or code. Output only the next line. | self.model = SampledBodyModel() |
Using the snippet: <|code_start|> name = self._token()
# name will be 'Site' for End Site joints.
if name == 'Site':
name = currentJoint.parent.name+"_end"
currentJoint.name = name
self._checkToken("{")
while True:
token = self._token()
if token == "OFFSET":
x = self._floatToken()
y = self._floatToken()
z = self._floatToken()
currentJoint.positionOffset = \
convertCGtoNED(np.array([[x,y,z]]).T*self.conversionFactor)
elif token == "CHANNELS":
n = self._intToken()
channels = []
for i in range(n):
token = self._token()
if token not in ["Xposition","Yposition","Zposition",\
"Xrotation","Yrotation","Zrotation"]:
raise SyntaxError, "Syntax error in line %d: Invalid \
channel name '%s'" %(self.line,token)
else:
channels.append(token)
self.totalChannels += n
currentJoint.channels = channels
elif token in ("JOINT", "End"):
if token == "JOINT":
<|code_end|>
, determine the next line of code. You have imports:
from imusim.trajectories.rigid_body import SampledBodyModel, SampledJoint, \
PointTrajectory
from imusim.maths.quaternions import Quaternion
from imusim.maths.transforms import convertCGtoNED, convertNEDtoCG
import numpy as np
and context (class names, function names, or code) available:
# Path: imusim/trajectories/rigid_body.py
# class SampledBodyModel(SampledPositionTrajectory, SampledJoint):
# """A body model with sampled positions and rotations."""
#
# def __init__(self, name=None):
# """
# Initialise body model.
#
# @param name: The name of the root L{Joint} of the body model
# """
# SampledJoint.__init__(self, None, name)
# SampledPositionTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# model = cls(ref.name)
# for child in ref.children:
# if child.isJoint:
# SampledJoint.structureCopy(child, model)
# else:
# PointTrajectory(model, child.name, child.positionOffset)
# return model
#
# class SampledJoint(SampledRotationTrajectory, OffsetTrajectory, Joint):
# """
# A joint in a rigid body model with sampled rotations.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Initialise sampled joint.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the joint.
# @param offset: Offset of the joint in the parent joint
# co-ordinate frame.
# """
# Joint.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
# SampledRotationTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# joint = cls(parent, ref.name, ref.positionOffset)
# for child in ref.children:
# if child.isJoint:
# cls.structureCopy(child, joint)
# else:
# PointTrajectory(joint, child.name, child.positionOffset)
# return joint
#
# class PointTrajectory(OffsetTrajectory, Point):
# """
# Trajectory followed by a point in a rigid body model.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Construct point trajectory.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the point.
# @param offset: Offset of the point in the parent joint
# co-ordinate frame.
# """
# Point.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
#
# Path: imusim/maths/transforms.py
# def convertCGtoNED(param):
# """
# Convert parameters specified in Computer Graphics co-ordinates to
# North East Down co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in CG frame.
#
# @return: The corresponding L{Quaternion} or vector in NED frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _CGtoNED.conjugate * param * _CGtoNED
# else:
# return _CGtoNED.rotateFrame(param)
#
# def convertNEDtoCG(param):
# """
# Convert parameters specified in North East Down co-ordinates to
# Computer Graphics co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in NED frame.
#
# @return: The corresponding L{Quaternion} or vector in CG frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _NEDtoCG.conjugate * param * _NEDtoCG
# else:
# return _NEDtoCG.rotateFrame(param)
. Output only the next line. | joint = SampledJoint(currentJoint) |
Predict the next line for this snippet: <|code_start|> if name == 'Site':
name = currentJoint.parent.name+"_end"
currentJoint.name = name
self._checkToken("{")
while True:
token = self._token()
if token == "OFFSET":
x = self._floatToken()
y = self._floatToken()
z = self._floatToken()
currentJoint.positionOffset = \
convertCGtoNED(np.array([[x,y,z]]).T*self.conversionFactor)
elif token == "CHANNELS":
n = self._intToken()
channels = []
for i in range(n):
token = self._token()
if token not in ["Xposition","Yposition","Zposition",\
"Xrotation","Yrotation","Zrotation"]:
raise SyntaxError, "Syntax error in line %d: Invalid \
channel name '%s'" %(self.line,token)
else:
channels.append(token)
self.totalChannels += n
currentJoint.channels = channels
elif token in ("JOINT", "End"):
if token == "JOINT":
joint = SampledJoint(currentJoint)
else:
<|code_end|>
with the help of current file imports:
from imusim.trajectories.rigid_body import SampledBodyModel, SampledJoint, \
PointTrajectory
from imusim.maths.quaternions import Quaternion
from imusim.maths.transforms import convertCGtoNED, convertNEDtoCG
import numpy as np
and context from other files:
# Path: imusim/trajectories/rigid_body.py
# class SampledBodyModel(SampledPositionTrajectory, SampledJoint):
# """A body model with sampled positions and rotations."""
#
# def __init__(self, name=None):
# """
# Initialise body model.
#
# @param name: The name of the root L{Joint} of the body model
# """
# SampledJoint.__init__(self, None, name)
# SampledPositionTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# model = cls(ref.name)
# for child in ref.children:
# if child.isJoint:
# SampledJoint.structureCopy(child, model)
# else:
# PointTrajectory(model, child.name, child.positionOffset)
# return model
#
# class SampledJoint(SampledRotationTrajectory, OffsetTrajectory, Joint):
# """
# A joint in a rigid body model with sampled rotations.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Initialise sampled joint.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the joint.
# @param offset: Offset of the joint in the parent joint
# co-ordinate frame.
# """
# Joint.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
# SampledRotationTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# joint = cls(parent, ref.name, ref.positionOffset)
# for child in ref.children:
# if child.isJoint:
# cls.structureCopy(child, joint)
# else:
# PointTrajectory(joint, child.name, child.positionOffset)
# return joint
#
# class PointTrajectory(OffsetTrajectory, Point):
# """
# Trajectory followed by a point in a rigid body model.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Construct point trajectory.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the point.
# @param offset: Offset of the point in the parent joint
# co-ordinate frame.
# """
# Point.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
#
# Path: imusim/maths/transforms.py
# def convertCGtoNED(param):
# """
# Convert parameters specified in Computer Graphics co-ordinates to
# North East Down co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in CG frame.
#
# @return: The corresponding L{Quaternion} or vector in NED frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _CGtoNED.conjugate * param * _CGtoNED
# else:
# return _CGtoNED.rotateFrame(param)
#
# def convertNEDtoCG(param):
# """
# Convert parameters specified in North East Down co-ordinates to
# Computer Graphics co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in NED frame.
#
# @return: The corresponding L{Quaternion} or vector in CG frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _NEDtoCG.conjugate * param * _NEDtoCG
# else:
# return _NEDtoCG.rotateFrame(param)
, which may contain function names, class names, or code. Output only the next line. | joint = PointTrajectory(currentJoint) |
Predict the next line after this snippet: <|code_start|> Read the motion data from the BVH file.
'''
# update joint tree with new data.
frame = 0
lastRotation = {}
for frame in range(self.frameCount):
time = frame * self.framePeriod
channelData = self._readFrame()
for joint in self.model.joints:
for chan in joint.channels:
chanData = channelData.pop(0)
if chan == "Xposition":
xPos = chanData
elif chan == "Yposition":
yPos = chanData
elif chan == "Zposition":
zPos = chanData
elif chan == "Xrotation":
xRot = chanData
elif chan == "Yrotation":
yRot = chanData
elif chan == "Zrotation":
zRot = chanData
else:
raise RuntimeError('Unknown channel: '+chan)
if not joint.hasParent:
try:
p = np.array([[xPos,yPos,zPos]]).T * \
self.conversionFactor
<|code_end|>
using the current file's imports:
from imusim.trajectories.rigid_body import SampledBodyModel, SampledJoint, \
PointTrajectory
from imusim.maths.quaternions import Quaternion
from imusim.maths.transforms import convertCGtoNED, convertNEDtoCG
import numpy as np
and any relevant context from other files:
# Path: imusim/trajectories/rigid_body.py
# class SampledBodyModel(SampledPositionTrajectory, SampledJoint):
# """A body model with sampled positions and rotations."""
#
# def __init__(self, name=None):
# """
# Initialise body model.
#
# @param name: The name of the root L{Joint} of the body model
# """
# SampledJoint.__init__(self, None, name)
# SampledPositionTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# model = cls(ref.name)
# for child in ref.children:
# if child.isJoint:
# SampledJoint.structureCopy(child, model)
# else:
# PointTrajectory(model, child.name, child.positionOffset)
# return model
#
# class SampledJoint(SampledRotationTrajectory, OffsetTrajectory, Joint):
# """
# A joint in a rigid body model with sampled rotations.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Initialise sampled joint.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the joint.
# @param offset: Offset of the joint in the parent joint
# co-ordinate frame.
# """
# Joint.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
# SampledRotationTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# joint = cls(parent, ref.name, ref.positionOffset)
# for child in ref.children:
# if child.isJoint:
# cls.structureCopy(child, joint)
# else:
# PointTrajectory(joint, child.name, child.positionOffset)
# return joint
#
# class PointTrajectory(OffsetTrajectory, Point):
# """
# Trajectory followed by a point in a rigid body model.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Construct point trajectory.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the point.
# @param offset: Offset of the point in the parent joint
# co-ordinate frame.
# """
# Point.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
#
# Path: imusim/maths/transforms.py
# def convertCGtoNED(param):
# """
# Convert parameters specified in Computer Graphics co-ordinates to
# North East Down co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in CG frame.
#
# @return: The corresponding L{Quaternion} or vector in NED frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _CGtoNED.conjugate * param * _CGtoNED
# else:
# return _CGtoNED.rotateFrame(param)
#
# def convertNEDtoCG(param):
# """
# Convert parameters specified in North East Down co-ordinates to
# Computer Graphics co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in NED frame.
#
# @return: The corresponding L{Quaternion} or vector in CG frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _NEDtoCG.conjugate * param * _NEDtoCG
# else:
# return _NEDtoCG.rotateFrame(param)
. Output only the next line. | p = convertCGtoNED(p) |
Given the following code snippet before the placeholder: <|code_start|> self.bvhFile = bvhFile
self.model = model
self.samplePeriod = samplePeriod
self.conversionFactor = conversionFactor
@property
def frames(self):
""" The number of frames that will be exported. """
return int((self.model.endTime - self.model.startTime) //
self.samplePeriod)
def writeHeader(self):
"""
Write the header of the BVH file.
"""
self.bvhFile.write('HIERARCHY\n')
pad = " "
def post(j):
self.bvhFile.write("%s}\n" %(pad*j.depth))
for p in self.model.preorderTraversal(postFunc=post):
d = p.depth
if not p.hasParent:
self.bvhFile.write("%sROOT %s\n" %(pad*d, p.name))
elif p.isJoint:
self.bvhFile.write("%sJOINT %s\n" %(pad*d, p.name))
else:
self.bvhFile.write("%sEnd Site\n" %(pad*d))
self.bvhFile.write("%s{\n" %(pad*d))
self.bvhFile.write("%sOFFSET" %(pad*(d+1)))
<|code_end|>
, predict the next line using imports from the current file:
from imusim.trajectories.rigid_body import SampledBodyModel, SampledJoint, \
PointTrajectory
from imusim.maths.quaternions import Quaternion
from imusim.maths.transforms import convertCGtoNED, convertNEDtoCG
import numpy as np
and context including class names, function names, and sometimes code from other files:
# Path: imusim/trajectories/rigid_body.py
# class SampledBodyModel(SampledPositionTrajectory, SampledJoint):
# """A body model with sampled positions and rotations."""
#
# def __init__(self, name=None):
# """
# Initialise body model.
#
# @param name: The name of the root L{Joint} of the body model
# """
# SampledJoint.__init__(self, None, name)
# SampledPositionTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# model = cls(ref.name)
# for child in ref.children:
# if child.isJoint:
# SampledJoint.structureCopy(child, model)
# else:
# PointTrajectory(model, child.name, child.positionOffset)
# return model
#
# class SampledJoint(SampledRotationTrajectory, OffsetTrajectory, Joint):
# """
# A joint in a rigid body model with sampled rotations.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Initialise sampled joint.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the joint.
# @param offset: Offset of the joint in the parent joint
# co-ordinate frame.
# """
# Joint.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
# SampledRotationTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# joint = cls(parent, ref.name, ref.positionOffset)
# for child in ref.children:
# if child.isJoint:
# cls.structureCopy(child, joint)
# else:
# PointTrajectory(joint, child.name, child.positionOffset)
# return joint
#
# class PointTrajectory(OffsetTrajectory, Point):
# """
# Trajectory followed by a point in a rigid body model.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Construct point trajectory.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the point.
# @param offset: Offset of the point in the parent joint
# co-ordinate frame.
# """
# Point.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
#
# Path: imusim/maths/transforms.py
# def convertCGtoNED(param):
# """
# Convert parameters specified in Computer Graphics co-ordinates to
# North East Down co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in CG frame.
#
# @return: The corresponding L{Quaternion} or vector in NED frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _CGtoNED.conjugate * param * _CGtoNED
# else:
# return _CGtoNED.rotateFrame(param)
#
# def convertNEDtoCG(param):
# """
# Convert parameters specified in North East Down co-ordinates to
# Computer Graphics co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in NED frame.
#
# @return: The corresponding L{Quaternion} or vector in CG frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _NEDtoCG.conjugate * param * _NEDtoCG
# else:
# return _NEDtoCG.rotateFrame(param)
. Output only the next line. | for v in convertNEDtoCG(p.positionOffset): |
Continue the code snippet: <|code_start|># This file is part of IMUSim.
#
# IMUSim is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IMUSim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division
class Timer(Component):
"""
Base class for simulated hardware timers.
@ivar callback: Function to be called when timer fires.
"""
__metaclass__ = ABCMeta
def __init__(self, platform):
self._process = None
Component.__init__(self, platform)
<|code_end|>
. Use current file imports:
from abc import ABCMeta, abstractmethod
from imusim.platforms.base import Component
from imusim.simulation.base import Simulation
from imusim.utilities.documentation import prepend_method_doc
import SimPy.Simulation
import numpy as np
and context (classes, functions, or code) from other files:
# Path: imusim/platforms/base.py
# class Component(object):
# """
# Base class for simulated hardware components.
# """
#
# __metaclass__ = ABCMeta
#
# def __init__(self, platform):
# """
# Initialise simulated component.
#
# @param platform: The L{Platform} this component will be attached to.
# """
# self.platform = platform
#
# def _simulationChange(self):
# """
# Called when the platform is assigned a new simulation.
# """
# pass
#
# def _trajectoryChange(self):
# """
# Called when the platform is assigned a new trajectory.
# """
# pass
#
# Path: imusim/simulation/base.py
# class Simulation(object):
# """
# Main IMUSim simulation environment.
#
# @ivar rng: L{np.random.RandomState} instance for random number generation.
# @ivar environment: L{Environment} in use for simulation.
# @ivar engine: L{SimPy.Simulation} instance driving simulation.
# """
#
# def __init__(self, seed=None, environment=None,
# engine=SimPy.Simulation.Simulation):
# """
# Initialise simulation.
#
# @param seed: Seed value for L{np.random.RandomState}.
# @param environment: L{Environment} to simulate in.
# @param engine: L{SimPy.Simulation} subclass to drive simulation.
# """
# self.environment = Environment() if environment is None else environment
# self.engine = engine()
# self.engine.initialize()
# self.rng = np.random.RandomState(seed)
#
# @property
# def time(self):
# """ The current true time within the simulation (float). """
# assert hasattr(self, '_startTime'), 'Simulation time has not been set.'
# return self.engine.now() + self._startTime
#
# @time.setter
# def time(self, time):
# assert not hasattr(self, '_startTime'), 'Simulation time already set.'
# self._startTime = time
#
# class ProgressMonitor(SimPy.Simulation.Process):
# """
# Simple process to print status and remaining simulation time at 5%
# progress intervals.
# """
# def __init__(self, sim, duration):
# SimPy.Simulation.Process.__init__(self, sim=sim)
# self.startTime = sim.now()
# self.duration = duration
# sim.activate(self, self.printProgress())
#
# def printProgress(self):
# for i in range(0,20):
# start = time.time()
# yield SimPy.Simulation.hold, self, self.duration / 20.0
# now = self.sim.now() - self.startTime
# end = time.time()
#
# remaining = (20-i) * (end-start)
# print ("Simulated %.1fs of %.1fs (%3.0f%%). " +
# "Estimated time remaining %.1fs") \
# %(now, self.duration, (i + 1) * 5, remaining)
#
# def run(self, endTime, printProgress=True):
# """
# Advance the simulation up to the given time.
#
# @param endTime: Simulation time at which to stop (float).
# @param printProgress: Whether to print progress information (bool).
# """
#
# if printProgress:
# print "Simulating..."
# startTime = self.time
# duration = endTime - startTime
# progressMonitor = self.ProgressMonitor(self.engine, duration)
#
# startWallTime = time.time()
# self.engine.simulate(endTime - self._startTime)
# endWallTime = time.time()
#
# if printProgress:
# print "Simulation complete."
# print "Simulated %.1f seconds in %.1f seconds." % (
# endTime - startTime, endWallTime - startWallTime)
#
# def subrng(self):
# """
# Obtain a new random number generator seeded from the main RNG.
#
# @return: A L{np.random.RandomState} instance.
# """
# return np.random.RandomState(seed=int(self.rng.uniform(0,2**31)))
. Output only the next line. | class _TimerProcess(SimPy.Simulation.Process): |
Predict the next line after this snippet: <|code_start|> ]
initialStates = [
np.zeros((1,1)),
np.array([[1]]),
np.array([[0],[0]])
]
initialCovariances = [
np.array([[0.1]]),
np.array([[0.5]]),
0.2**2 * np.array([[dt**4/4,dt**3/2],[dt**3/2, dt**2]])
]
processCovariances = [
np.array([[0.01]]),
np.array([[0.05]]),
0.2**2 * np.array([[dt**4/4,dt**3/2],[dt**3/2, dt**2]])
]
measurementCovariances = [
np.array([[0.3]]),
np.array([[0.2]]),
np.array([[10]])
]
def checkKalmanFilter(stateTransition, measurement, control, initialState,
initialCovariance, processCovariance, measurementCovariance,
controlFunction):
states = initialState.shape[0]
measurements = measurement.shape[0]
controls = control.shape[1]
<|code_end|>
using the current file's imports:
import numpy as np
import pylab
from imusim.maths import kalman
from numpy import testing
and any relevant context from other files:
# Path: imusim/maths/kalman.py
# class KalmanFilter(object):
# class UnscentedKalmanFilter(KalmanFilter):
# def __init__(self, stateTransitionMatrix, controlMatrix, measurementMatrix,
# state, stateCovariance, processCovariance, measurementCovariance):
# def state(self):
# def state(self, state):
# def stateTransitionMatrix(self):
# def stateTransitionMatrix(self, stateTransitionMatrix):
# def controlMatrix(self):
# def controlMatrix(self, controlMatrix):
# def measurementMatrix(self):
# def measurementMatrix(self, measurementMatrix):
# def stateCovariance(self):
# def stateCovariance(self, stateCovariance):
# def processCovariance(self):
# def processCovariance(self, processCovariance):
# def measurementCovariance(self):
# def measurementCovariance(self, measurementCovariance):
# def gain(self):
# def predict(self, control=None):
# def innovation(self, measurement):
# def correct(self, measurement):
# def update(self, measurement, control=None):
# def normalisedInnovation(self, measurement):
# def __init__(self, stateUpdateFunction, measurementFunction, state,
# stateCovariance, processCovariance, measurementCovariance):
# def stateUpdateFunction(self):
# def stateUpdateFunction(self, function):
# def measurementFunction(self):
# def measurementFunction(self, function):
# def predict(self, control=None):
# def innovation(self, measurement):
# def correct(self, measurement):
# B = 0
. Output only the next line. | filter = kalman.KalmanFilter(stateTransition, control, |
Next line prediction: <|code_start|> for bone in self:
if bone.name == bonename:
return bone
def loadASFFile(asfFileName, amcFileName, scaleFactor, framePeriod):
"""
Load motion capture data from an ASF and AMC file pair.
@param asfFileName: Name of the ASF file containing the description of
the rigid body model
@param amcFileName: Name of the AMC file containing the motion data
@param scaleFactor: Scaling factor to convert lengths to m. For data
from the CMU motion capture corpus this should be 2.54/100 to
convert from inches to metres.
@return: A {SampledBodyModel} representing the root of the rigid body
model structure.
"""
with open(asfFileName, 'r') as asfFile:
data = asfParser.parseFile(asfFile)
scale = (1.0/data.units.get('length',1)) * scaleFactor
bones = dict((bone.name,bone) for bone in data.bones)
asfModel = ASFRoot(data.root)
for entry in data.hierarchy:
parent = asfModel.getBone(entry.parent)
for childName in entry.children:
ASFBone(parent, bones[childName], scale)
<|code_end|>
. Use current file imports:
(from imusim.trajectories.rigid_body import SampledBodyModel, SampledJoint
from imusim.trajectories.rigid_body import PointTrajectory
from imusim.maths.vectors import vector
from imusim.maths.transforms import convertCGtoNED
from imusim.maths.quaternions import Quaternion
from imusim.utilities.trees import TreeNode
from pyparsing import Word, Literal, Keyword, Group, Dict, Combine
from pyparsing import ZeroOrMore, OneOrMore, Suppress, Optional, LineEnd
from pyparsing import alphanums, nums, alphas, Regex, SkipTo)
and context including class names, function names, or small code snippets from other files:
# Path: imusim/trajectories/rigid_body.py
# class SampledBodyModel(SampledPositionTrajectory, SampledJoint):
# """A body model with sampled positions and rotations."""
#
# def __init__(self, name=None):
# """
# Initialise body model.
#
# @param name: The name of the root L{Joint} of the body model
# """
# SampledJoint.__init__(self, None, name)
# SampledPositionTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# model = cls(ref.name)
# for child in ref.children:
# if child.isJoint:
# SampledJoint.structureCopy(child, model)
# else:
# PointTrajectory(model, child.name, child.positionOffset)
# return model
#
# class SampledJoint(SampledRotationTrajectory, OffsetTrajectory, Joint):
# """
# A joint in a rigid body model with sampled rotations.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Initialise sampled joint.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the joint.
# @param offset: Offset of the joint in the parent joint
# co-ordinate frame.
# """
# Joint.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
# SampledRotationTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# joint = cls(parent, ref.name, ref.positionOffset)
# for child in ref.children:
# if child.isJoint:
# cls.structureCopy(child, joint)
# else:
# PointTrajectory(joint, child.name, child.positionOffset)
# return joint
#
# Path: imusim/trajectories/rigid_body.py
# class PointTrajectory(OffsetTrajectory, Point):
# """
# Trajectory followed by a point in a rigid body model.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Construct point trajectory.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the point.
# @param offset: Offset of the point in the parent joint
# co-ordinate frame.
# """
# Point.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
#
# Path: imusim/maths/transforms.py
# def convertCGtoNED(param):
# """
# Convert parameters specified in Computer Graphics co-ordinates to
# North East Down co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in CG frame.
#
# @return: The corresponding L{Quaternion} or vector in NED frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _CGtoNED.conjugate * param * _CGtoNED
# else:
# return _CGtoNED.rotateFrame(param)
. Output only the next line. | imusimModel = SampledBodyModel('root') |
Continue the code snippet: <|code_start|> from the CMU motion capture corpus this should be 2.54/100 to
convert from inches to metres.
@return: A {SampledBodyModel} representing the root of the rigid body
model structure.
"""
with open(asfFileName, 'r') as asfFile:
data = asfParser.parseFile(asfFile)
scale = (1.0/data.units.get('length',1)) * scaleFactor
bones = dict((bone.name,bone) for bone in data.bones)
asfModel = ASFRoot(data.root)
for entry in data.hierarchy:
parent = asfModel.getBone(entry.parent)
for childName in entry.children:
ASFBone(parent, bones[childName], scale)
imusimModel = SampledBodyModel('root')
for subtree in asfModel.children:
for bone in subtree:
if not bone.isDummy:
offset = vector(0,0,0)
ancestors = bone.ascendTree()
while True:
ancestor = ancestors.next().parent
offset += ancestor.childoffset
if not ancestor.isDummy:
break
<|code_end|>
. Use current file imports:
from imusim.trajectories.rigid_body import SampledBodyModel, SampledJoint
from imusim.trajectories.rigid_body import PointTrajectory
from imusim.maths.vectors import vector
from imusim.maths.transforms import convertCGtoNED
from imusim.maths.quaternions import Quaternion
from imusim.utilities.trees import TreeNode
from pyparsing import Word, Literal, Keyword, Group, Dict, Combine
from pyparsing import ZeroOrMore, OneOrMore, Suppress, Optional, LineEnd
from pyparsing import alphanums, nums, alphas, Regex, SkipTo
and context (classes, functions, or code) from other files:
# Path: imusim/trajectories/rigid_body.py
# class SampledBodyModel(SampledPositionTrajectory, SampledJoint):
# """A body model with sampled positions and rotations."""
#
# def __init__(self, name=None):
# """
# Initialise body model.
#
# @param name: The name of the root L{Joint} of the body model
# """
# SampledJoint.__init__(self, None, name)
# SampledPositionTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# model = cls(ref.name)
# for child in ref.children:
# if child.isJoint:
# SampledJoint.structureCopy(child, model)
# else:
# PointTrajectory(model, child.name, child.positionOffset)
# return model
#
# class SampledJoint(SampledRotationTrajectory, OffsetTrajectory, Joint):
# """
# A joint in a rigid body model with sampled rotations.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Initialise sampled joint.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the joint.
# @param offset: Offset of the joint in the parent joint
# co-ordinate frame.
# """
# Joint.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
# SampledRotationTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# joint = cls(parent, ref.name, ref.positionOffset)
# for child in ref.children:
# if child.isJoint:
# cls.structureCopy(child, joint)
# else:
# PointTrajectory(joint, child.name, child.positionOffset)
# return joint
#
# Path: imusim/trajectories/rigid_body.py
# class PointTrajectory(OffsetTrajectory, Point):
# """
# Trajectory followed by a point in a rigid body model.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Construct point trajectory.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the point.
# @param offset: Offset of the point in the parent joint
# co-ordinate frame.
# """
# Point.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
#
# Path: imusim/maths/transforms.py
# def convertCGtoNED(param):
# """
# Convert parameters specified in Computer Graphics co-ordinates to
# North East Down co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in CG frame.
#
# @return: The corresponding L{Quaternion} or vector in NED frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _CGtoNED.conjugate * param * _CGtoNED
# else:
# return _CGtoNED.rotateFrame(param)
. Output only the next line. | SampledJoint(parent=imusimModel.getJoint(ancestor.name), |
Using the snippet: <|code_start|> model structure.
"""
with open(asfFileName, 'r') as asfFile:
data = asfParser.parseFile(asfFile)
scale = (1.0/data.units.get('length',1)) * scaleFactor
bones = dict((bone.name,bone) for bone in data.bones)
asfModel = ASFRoot(data.root)
for entry in data.hierarchy:
parent = asfModel.getBone(entry.parent)
for childName in entry.children:
ASFBone(parent, bones[childName], scale)
imusimModel = SampledBodyModel('root')
for subtree in asfModel.children:
for bone in subtree:
if not bone.isDummy:
offset = vector(0,0,0)
ancestors = bone.ascendTree()
while True:
ancestor = ancestors.next().parent
offset += ancestor.childoffset
if not ancestor.isDummy:
break
SampledJoint(parent=imusimModel.getJoint(ancestor.name),
name=bone.name,
offset=offset)
if not bone.hasChildren:
<|code_end|>
, determine the next line of code. You have imports:
from imusim.trajectories.rigid_body import SampledBodyModel, SampledJoint
from imusim.trajectories.rigid_body import PointTrajectory
from imusim.maths.vectors import vector
from imusim.maths.transforms import convertCGtoNED
from imusim.maths.quaternions import Quaternion
from imusim.utilities.trees import TreeNode
from pyparsing import Word, Literal, Keyword, Group, Dict, Combine
from pyparsing import ZeroOrMore, OneOrMore, Suppress, Optional, LineEnd
from pyparsing import alphanums, nums, alphas, Regex, SkipTo
and context (class names, function names, or code) available:
# Path: imusim/trajectories/rigid_body.py
# class SampledBodyModel(SampledPositionTrajectory, SampledJoint):
# """A body model with sampled positions and rotations."""
#
# def __init__(self, name=None):
# """
# Initialise body model.
#
# @param name: The name of the root L{Joint} of the body model
# """
# SampledJoint.__init__(self, None, name)
# SampledPositionTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# model = cls(ref.name)
# for child in ref.children:
# if child.isJoint:
# SampledJoint.structureCopy(child, model)
# else:
# PointTrajectory(model, child.name, child.positionOffset)
# return model
#
# class SampledJoint(SampledRotationTrajectory, OffsetTrajectory, Joint):
# """
# A joint in a rigid body model with sampled rotations.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Initialise sampled joint.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the joint.
# @param offset: Offset of the joint in the parent joint
# co-ordinate frame.
# """
# Joint.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
# SampledRotationTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# joint = cls(parent, ref.name, ref.positionOffset)
# for child in ref.children:
# if child.isJoint:
# cls.structureCopy(child, joint)
# else:
# PointTrajectory(joint, child.name, child.positionOffset)
# return joint
#
# Path: imusim/trajectories/rigid_body.py
# class PointTrajectory(OffsetTrajectory, Point):
# """
# Trajectory followed by a point in a rigid body model.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Construct point trajectory.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the point.
# @param offset: Offset of the point in the parent joint
# co-ordinate frame.
# """
# Point.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
#
# Path: imusim/maths/transforms.py
# def convertCGtoNED(param):
# """
# Convert parameters specified in Computer Graphics co-ordinates to
# North East Down co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in CG frame.
#
# @return: The corresponding L{Quaternion} or vector in NED frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _CGtoNED.conjugate * param * _CGtoNED
# else:
# return _CGtoNED.rotateFrame(param)
. Output only the next line. | PointTrajectory( |
Given the code snippet: <|code_start|> for subtree in asfModel.children:
for bone in subtree:
if not bone.isDummy:
offset = vector(0,0,0)
ancestors = bone.ascendTree()
while True:
ancestor = ancestors.next().parent
offset += ancestor.childoffset
if not ancestor.isDummy:
break
SampledJoint(parent=imusimModel.getJoint(ancestor.name),
name=bone.name,
offset=offset)
if not bone.hasChildren:
PointTrajectory(
parent=imusimModel.getJoint(bone.name),
name=bone.name+'_end',
offset=bone.childoffset
)
with open(amcFileName) as amcFile:
motion = amcParser.parseFile(amcFile)
t = 0
for frame in motion.frames:
for bone in frame.bones:
bonedata = asfModel.getBone(bone.name)
if bone.name == 'root':
data = dict((chan.lower(), v) for chan,v in
zip(bonedata.channels,bone.channels))
<|code_end|>
, generate the next line using the imports in this file:
from imusim.trajectories.rigid_body import SampledBodyModel, SampledJoint
from imusim.trajectories.rigid_body import PointTrajectory
from imusim.maths.vectors import vector
from imusim.maths.transforms import convertCGtoNED
from imusim.maths.quaternions import Quaternion
from imusim.utilities.trees import TreeNode
from pyparsing import Word, Literal, Keyword, Group, Dict, Combine
from pyparsing import ZeroOrMore, OneOrMore, Suppress, Optional, LineEnd
from pyparsing import alphanums, nums, alphas, Regex, SkipTo
and context (functions, classes, or occasionally code) from other files:
# Path: imusim/trajectories/rigid_body.py
# class SampledBodyModel(SampledPositionTrajectory, SampledJoint):
# """A body model with sampled positions and rotations."""
#
# def __init__(self, name=None):
# """
# Initialise body model.
#
# @param name: The name of the root L{Joint} of the body model
# """
# SampledJoint.__init__(self, None, name)
# SampledPositionTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# model = cls(ref.name)
# for child in ref.children:
# if child.isJoint:
# SampledJoint.structureCopy(child, model)
# else:
# PointTrajectory(model, child.name, child.positionOffset)
# return model
#
# class SampledJoint(SampledRotationTrajectory, OffsetTrajectory, Joint):
# """
# A joint in a rigid body model with sampled rotations.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Initialise sampled joint.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the joint.
# @param offset: Offset of the joint in the parent joint
# co-ordinate frame.
# """
# Joint.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
# SampledRotationTrajectory.__init__(self)
#
# @classmethod
# def structureCopy(cls, ref, parent=None):
# joint = cls(parent, ref.name, ref.positionOffset)
# for child in ref.children:
# if child.isJoint:
# cls.structureCopy(child, joint)
# else:
# PointTrajectory(joint, child.name, child.positionOffset)
# return joint
#
# Path: imusim/trajectories/rigid_body.py
# class PointTrajectory(OffsetTrajectory, Point):
# """
# Trajectory followed by a point in a rigid body model.
# """
# def __init__(self, parent, name=None, offset=None):
# """
# Construct point trajectory.
#
# @param parent: Parent L{Joint} in the body model hierarchy.
# @param name: Name of the point.
# @param offset: Offset of the point in the parent joint
# co-ordinate frame.
# """
# Point.__init__(self, parent, name, offset)
# OffsetTrajectory.__init__(self, parent, offset)
#
# Path: imusim/maths/transforms.py
# def convertCGtoNED(param):
# """
# Convert parameters specified in Computer Graphics co-ordinates to
# North East Down co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in CG frame.
#
# @return: The corresponding L{Quaternion} or vector in NED frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _CGtoNED.conjugate * param * _CGtoNED
# else:
# return _CGtoNED.rotateFrame(param)
. Output only the next line. | position = convertCGtoNED(scale * vector(data['tx'], |
Predict the next line for this snippet: <|code_start|>#
# You should have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
def testBVHInput():
data = r"""HIERARCHY
ROOT root
{
OFFSET 0.0 0.0 0.0
CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation
JOINT j1
{
OFFSET 10.0 0.0 0.0
CHANNELS 3 Zrotation Xrotation Yrotation
End Site
{
OFFSET 0.0 10.0 0.0
}
}
}
MOTION
Frames: 1
Frame Time: 0.1
0.0 0.0 0.0 0.0 0.0 0.0 90.0 0.0 0.0
"""
testFile = tempfile.NamedTemporaryFile()
with testFile:
testFile.write(data)
testFile.flush()
<|code_end|>
with the help of current file imports:
from imusim.io import loadBVHFile, saveBVHFile
from imusim.maths.vectors import vector
from imusim.maths.quaternions import Quaternion
from numpy.testing import assert_almost_equal
from imusim.testing.quaternions import assertQuaternionAlmostEqual
from imusim.maths.transforms import convertCGtoNED
from nose.tools import raises
import tempfile
and context from other files:
# Path: imusim/io/bvh.py
# def loadBVHFile(filename, conversionFactor=1):
# """
# Load sampled body model data from a BVH file.
#
# @param filename: Name of file to load.
# @param conversionFactor: Scale factor to apply to position values, e.g.
# to convert meters to centimeters use conversionFactor=100.
#
# @return: A L{SampledBodyModel} object.
# """
# with open(filename,'r') as bvhFile:
# loader = BVHLoader(bvhFile,conversionFactor)
# loader._readHeader()
# loader._readMotionData()
# return loader.model
#
# def saveBVHFile(model, filename, samplePeriod, conversionFactor = 1):
# """
# Save a body model data to a BVH file.
#
# @param model: Body model to save.
# @param filename: Name of file to write to.
# @param samplePeriod: The time between frames in the BVH output.
# @param conversionFactor: Scale factor to apply to position values, e.g.
# to convert meters to centimeters use conversionFactor=100.
# """
# with open(filename,'w') as bvhFile:
# exporter = BVHExporter(model,bvhFile, samplePeriod, conversionFactor)
# exporter.writeHeader()
# for frame in xrange(exporter.frames):
# exporter.writeFrame(model.startTime + frame * samplePeriod)
#
# Path: imusim/maths/transforms.py
# def convertCGtoNED(param):
# """
# Convert parameters specified in Computer Graphics co-ordinates to
# North East Down co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in CG frame.
#
# @return: The corresponding L{Quaternion} or vector in NED frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _CGtoNED.conjugate * param * _CGtoNED
# else:
# return _CGtoNED.rotateFrame(param)
, which may contain function names, class names, or code. Output only the next line. | model = loadBVHFile(testFile.name) |
Given the code snippet: <|code_start|> data = r"""HIERARCHY
ROOT root
{
OFFSET 0.0 0.0 0.0
CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation
JOINT j1
{
OFFSET 10.0 0.0 0.0
CHANNELS 3 Zrotation Xrotation Yrotation
End Site
{
OFFSET 0.0 10.0 0.0
}
}
}
MOTION
Frames: 5
Frame Time: 0.1
0.0 0.0 0.0 0.0 0.0 0.0 90.0 0.0 0.0
0.0 1.0 0.0 0.0 0.0 0.0 80.0 0.0 5.0
0.0 2.0 0.0 0.0 0.0 0.0 70.0 0.0 10.0
0.0 3.0 0.0 0.0 0.0 0.0 60.0 0.0 15.0
0.0 4.0 0.0 0.0 0.0 0.0 50.0 0.0 20.0
"""
testFile = tempfile.NamedTemporaryFile()
exportFile = tempfile.NamedTemporaryFile()
with testFile:
testFile.write(data)
testFile.flush()
model = loadBVHFile(testFile.name)
<|code_end|>
, generate the next line using the imports in this file:
from imusim.io import loadBVHFile, saveBVHFile
from imusim.maths.vectors import vector
from imusim.maths.quaternions import Quaternion
from numpy.testing import assert_almost_equal
from imusim.testing.quaternions import assertQuaternionAlmostEqual
from imusim.maths.transforms import convertCGtoNED
from nose.tools import raises
import tempfile
and context (functions, classes, or occasionally code) from other files:
# Path: imusim/io/bvh.py
# def loadBVHFile(filename, conversionFactor=1):
# """
# Load sampled body model data from a BVH file.
#
# @param filename: Name of file to load.
# @param conversionFactor: Scale factor to apply to position values, e.g.
# to convert meters to centimeters use conversionFactor=100.
#
# @return: A L{SampledBodyModel} object.
# """
# with open(filename,'r') as bvhFile:
# loader = BVHLoader(bvhFile,conversionFactor)
# loader._readHeader()
# loader._readMotionData()
# return loader.model
#
# def saveBVHFile(model, filename, samplePeriod, conversionFactor = 1):
# """
# Save a body model data to a BVH file.
#
# @param model: Body model to save.
# @param filename: Name of file to write to.
# @param samplePeriod: The time between frames in the BVH output.
# @param conversionFactor: Scale factor to apply to position values, e.g.
# to convert meters to centimeters use conversionFactor=100.
# """
# with open(filename,'w') as bvhFile:
# exporter = BVHExporter(model,bvhFile, samplePeriod, conversionFactor)
# exporter.writeHeader()
# for frame in xrange(exporter.frames):
# exporter.writeFrame(model.startTime + frame * samplePeriod)
#
# Path: imusim/maths/transforms.py
# def convertCGtoNED(param):
# """
# Convert parameters specified in Computer Graphics co-ordinates to
# North East Down co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in CG frame.
#
# @return: The corresponding L{Quaternion} or vector in NED frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _CGtoNED.conjugate * param * _CGtoNED
# else:
# return _CGtoNED.rotateFrame(param)
. Output only the next line. | saveBVHFile(model, exportFile.name, 0.1) |
Predict the next line after this snippet: <|code_start|> OFFSET 0.0 0.0 0.0
CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation
JOINT j1
{
OFFSET 10.0 0.0 0.0
CHANNELS 3 Zrotation Xrotation Yrotation
End Site
{
OFFSET 0.0 10.0 0.0
}
}
}
MOTION
Frames: 1
Frame Time: 0.1
0.0 0.0 0.0 0.0 0.0 0.0 90.0 0.0 0.0
"""
testFile = tempfile.NamedTemporaryFile()
with testFile:
testFile.write(data)
testFile.flush()
model = loadBVHFile(testFile.name)
assert len(list(model.points)) == 3
assert model.name == 'root'
assert len(model.channels) == 6
assert len(model.children) == 1
assert_almost_equal(model.position(0),vector(0,0,0))
assertQuaternionAlmostEqual(model.rotation(0),
<|code_end|>
using the current file's imports:
from imusim.io import loadBVHFile, saveBVHFile
from imusim.maths.vectors import vector
from imusim.maths.quaternions import Quaternion
from numpy.testing import assert_almost_equal
from imusim.testing.quaternions import assertQuaternionAlmostEqual
from imusim.maths.transforms import convertCGtoNED
from nose.tools import raises
import tempfile
and any relevant context from other files:
# Path: imusim/io/bvh.py
# def loadBVHFile(filename, conversionFactor=1):
# """
# Load sampled body model data from a BVH file.
#
# @param filename: Name of file to load.
# @param conversionFactor: Scale factor to apply to position values, e.g.
# to convert meters to centimeters use conversionFactor=100.
#
# @return: A L{SampledBodyModel} object.
# """
# with open(filename,'r') as bvhFile:
# loader = BVHLoader(bvhFile,conversionFactor)
# loader._readHeader()
# loader._readMotionData()
# return loader.model
#
# def saveBVHFile(model, filename, samplePeriod, conversionFactor = 1):
# """
# Save a body model data to a BVH file.
#
# @param model: Body model to save.
# @param filename: Name of file to write to.
# @param samplePeriod: The time between frames in the BVH output.
# @param conversionFactor: Scale factor to apply to position values, e.g.
# to convert meters to centimeters use conversionFactor=100.
# """
# with open(filename,'w') as bvhFile:
# exporter = BVHExporter(model,bvhFile, samplePeriod, conversionFactor)
# exporter.writeHeader()
# for frame in xrange(exporter.frames):
# exporter.writeFrame(model.startTime + frame * samplePeriod)
#
# Path: imusim/maths/transforms.py
# def convertCGtoNED(param):
# """
# Convert parameters specified in Computer Graphics co-ordinates to
# North East Down co-ordinates.
#
# @param param: A L{Quaternion} or 3x1 vector in CG frame.
#
# @return: The corresponding L{Quaternion} or vector in NED frame
# """
# if isinstance(param, (Quaternion,QuaternionArray)):
# return _CGtoNED.conjugate * param * _CGtoNED
# else:
# return _CGtoNED.rotateFrame(param)
. Output only the next line. | convertCGtoNED(Quaternion(1,0,0,0))) |
Given snippet: <|code_start|>
class HomeView(DetailView):
def get_object(self, queryset=None):
if self.request.user.is_authenticated:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import hashlib
import rules
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm, SetPasswordForm
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.urls import reverse, reverse_lazy
from django.http.response import Http404
from django.shortcuts import redirect
from django.utils.http import urlquote
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView
from django.views.generic.base import View
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
from rules.contrib.views import PermissionRequiredMixin
from social_django.models import UserSocialAuth
from .models import UserProfile
and context:
# Path: letsmeet/users/models.py
# class UserProfile(TimeStampedModel):
# user = models.OneToOneField('auth.User', unique=True, on_delete=models.CASCADE)
# avatar = StdImageField(
# upload_to='avatars',
# variations={
# 'thumbnail': (400, 400, True),
# 'mini': (200, 200, True),
# 'tiny': (100, 100, True),
# 'micro': (40, 40, True),
# },
# help_text='Image should be square. Otherwise it will be cropped.'
# )
# notify_on_new_event = models.BooleanField(default=True)
# notify_on_new_subscription = models.BooleanField(default=True)
# notify_on_new_rsvp_for_organizer = models.BooleanField(default=True)
# notify_on_new_rsvp_for_attending = models.BooleanField(default=True)
# notify_on_new_comment = models.BooleanField(default=True)
# pending_email_address = models.EmailField(default='')
# personal_ical_uuid = models.UUIDField(default=uuid.uuid4, unique=True)
#
# def get_next_event(self):
# return self.get_upcoming_events().order_by('begin').first()
#
# def get_upcoming_events(self):
# return Event.objects.upcoming().filter(community__in=self.user.communities.all().values_list('id', flat=True))
#
# def get_next_yes_event(self):
# return self.get_upcoming_yes_events().order_by('begin').first()
#
# def get_upcoming_yes_events(self):
# return Event.objects.upcoming().filter(
# pk__in=EventRSVP.objects.filter(user=self.user, coming=True).values_list('event__pk', flat=True))
#
# def get_communitysubscriptions(self):
# return CommunitySubscription.objects.exclude(community__is_deleted=True).filter(user=self.user)
#
# @staticmethod
# def get_absolute_url():
# return reverse('profile')
#
# def __str__(self):
# return 'Profile of {}'.format(self.user.username)
which might include code, classes, or functions. Output only the next line. | up, created = UserProfile.objects.get_or_create(user=self.request.user) |
Predict the next line for this snippet: <|code_start|>
class CommunitySubscriptionInline(admin.TabularInline):
model = CommunitySubscription
extra = 1
<|code_end|>
with the help of current file imports:
from django.contrib import admin
from django.db.models import Count
from .models import (
Community, CommunitySubscription,
)
and context from other files:
# Path: letsmeet/communities/models.py
# class Community(TimeStampedModel):
# name = models.CharField(max_length=64, unique=True)
# slug = models.SlugField(max_length=64, unique=True)
# description = models.TextField(null=True, blank=True, help_text='You can write markown here!')
# subscribers = models.ManyToManyField('auth.User', through='CommunitySubscription', related_name='communities')
# cname = models.CharField(
# max_length=255, null=True, blank=True, verbose_name="CNAME",
# validators=[RegexValidator(r'[a-zA-Z0-9-\.\ ]+')],
# help_text="use your own domain to redirect to this community."
# )
#
# twitter = models.CharField(max_length=128, blank=True, null=True,
# help_text="Twitter username (without leading @)",
# validators=[RegexValidator(r'[a-zA-Z0-9_]+')],)
# github = models.CharField(max_length=128, blank=True, null=True,
# help_text="GitHub username or organisation name")
# homepage = models.URLField(max_length=128, blank=True, null=True,
# help_text="URL of homepage (including http://)")
# irc_channel = models.CharField(
# max_length=128, blank=True, null=True, verbose_name="IRC channel",
# help_text='IRC channel name',
# )
# irc_network = models.CharField(
# max_length=128, blank=True, null=True,
# help_text='Network the IRC channel is located on (e.g. "Freenode")',
# verbose_name='IRC network',
# )
# slack = models.CharField(max_length=128, blank=True, null=True,
# help_text="Slack organisation name")
#
# is_deleted = models.BooleanField(default=False)
#
# objects = CommunityManager()
# default = models.Manager() # the default manager
#
# def __str__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.slug = slugify(self.name)
#
# super().save(*args, **kwargs)
#
# def subscribe_user(self, user):
# subscription, created = CommunitySubscription.objects.get_or_create(
# user=user, community=self,
# )
# if created:
# recipients = User.objects.filter(pk__in=self.community_subscriptions.filter(
# role__in=[CommunitySubscription.ROLE_ADMIN, CommunitySubscription.ROLE_OWNER],
# user__userprofile__notify_on_new_subscription=True,
# ).values_list('user__pk', flat=True))
# # send notification mail to all subscribers
# if recipients:
# from main.utils import send_notification
# send_notification(
# recipients=recipients,
# subject='New subscription to community {}'.format(self.name),
# template='communities/mails/new_subscription.txt',
# context={'subscription': subscription},
# )
#
# return subscription
#
# def get_user_subscription(self, user):
# """returns the CommunitySubscription object of the user. None if user is not subscribed"""
# return self.community_subscriptions.filter(user=user).first()
#
# def get_next_event(self):
# if not hasattr(self, '_next_event'):
# self._next_event = self.events.filter(begin__gte=timezone.now()).order_by('begin').first()
#
# return self._next_event
#
# def get_ical_url(self):
# return reverse('community_events_ical_feed', kwargs={'community_slug': self.slug})
#
# def get_json_feed_url(self):
# return reverse('community_events_json_feed', kwargs={'community_slug': self.slug})
#
# def get_absolute_url(self):
# return reverse('community_detail', kwargs={'slug': self.slug})
#
# def get_update_url(self):
# return reverse('community_update', kwargs={'slug': self.slug})
#
# def get_subscribe_url(self):
# return reverse('community_subscribe', kwargs={'slug': self.slug})
#
# def get_unsubscribe_url(self):
# return reverse('community_unsubscribe', kwargs={'slug': self.slug})
#
# def get_event_create_url(self):
# return reverse('community_event_create', kwargs={'slug': self.slug})
#
# class Meta:
# ordering = ['slug']
# verbose_name_plural = 'Communities'
#
# class CommunitySubscription(TimeStampedModel):
# ROLE_OWNER = 'owner'
# ROLE_ADMIN = 'admin'
# ROLE_SUBSCRIBER = 'subscriber'
# ROLE_CHOICES = (
# (ROLE_OWNER, 'Owner'),
# (ROLE_ADMIN, 'Administrator'),
# (ROLE_SUBSCRIBER, 'Subscriber'),
# )
#
# community = models.ForeignKey(Community, on_delete=models.CASCADE,
# related_name='community_subscriptions')
# user = models.ForeignKey('auth.User', on_delete=models.CASCADE,
# related_name='community_subscriptions')
# role = models.CharField(max_length=64, choices=ROLE_CHOICES, default=ROLE_SUBSCRIBER)
#
# class Meta:
# ordering = ['role', 'user']
# unique_together = (
# ('community', 'user'),
# )
, which may contain function names, class names, or code. Output only the next line. | @admin.register(Community) |
Predict the next line for this snippet: <|code_start|>
class JSONFeed(SyndicationFeed):
mime_type = "application/json"
def write(self, outfile, encoding):
data = {}
data.update(self.feed)
data['items'] = self.items
json.dump(data, outfile, cls=DjangoJSONEncoder)
# outfile is a HttpResponse
if isinstance(outfile, HttpResponse):
outfile['Access-Control-Allow-Origin'] = '*'
class LatestEventsFeed(Feed):
description = "letsmeet.click events feed"
def get_object(self, request, community_slug):
return Community.objects.get(slug=community_slug)
def title(self, obj):
return "Events of {}".format(obj.name)
def link(self, obj):
return obj.get_absolute_url()
def items(self, obj):
<|code_end|>
with the help of current file imports:
import json
from django.contrib.auth import get_user_model
from django.contrib.syndication.views import Feed
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.utils.feedgenerator import SyndicationFeed
from django_ical.views import ICalFeed
from .models import Event
from communities.models import Community
from communities.models import Community
and context from other files:
# Path: letsmeet/events/models.py
# class Event(TimeStampedModel):
# community = models.ForeignKey('communities.Community', on_delete=models.CASCADE, related_name='events')
# name = models.CharField(max_length=64)
# description = models.TextField(null=True, blank=True, help_text="You can write markdown here!")
# slug = models.SlugField(max_length=64, help_text="Note: changing the slug will change the URL of the event")
# begin = models.DateTimeField()
# end = models.DateTimeField()
# twitter_hashtag = models.CharField(
# max_length=140, null=True, blank=True, help_text='Twitter hashtag of this event (without leading #)')
# max_attendees = models.PositiveIntegerField(
# blank=True, null=True,
# help_text='Optional maximum number of attendees for this event. Leave blank for no limit.')
# location = models.ForeignKey('locations.Location', on_delete=models.SET_NULL, related_name='events', null=True, blank=True)
# publish = models.BooleanField(default=True, help_text='Should this event be published elsewhere?') # for shackspace blog posts
#
# objects = EventManager()
#
# def __str__(self):
# return self.name
#
# def is_upcoming(self):
# return self.end >= timezone.now()
#
# def is_past(self):
# return self.end < timezone.now()
#
# def is_full(self):
# if not self.max_attendees:
# return False
#
# return self.rsvp_yes().count() >= self.max_attendees
#
# def rsvp_yes(self):
# return self.rsvps.filter(coming=True)
#
# def rsvp_no(self):
# return self.rsvps.filter(coming=False)
#
# def save(self, *args, **kwargs):
# create = False
# if not self.id:
# create = True
# # slugify the name
# slug = "{}-{}".format(slugify(self.name), str(self.begin.date()))
# if Event.objects.filter(slug=slug, community=self.community):
# # use datetime, because date was not unique
# slug = "{}-{}".format(slugify(self.name), slugify(self.begin))
# self.slug = slug
#
# super().save(*args, **kwargs)
#
# if create:
# recipients = self.community.subscribers.filter(
# userprofile__notify_on_new_event=True,
# )
# # send notification mail to all subscribers
# if recipients:
# from main.utils import send_notification
# send_notification(
# recipients=recipients,
# subject='New event in community {}'.format(self.name),
# template='events/mails/new_event.txt',
# context={'event': self},
# )
#
# def get_absolute_url(self):
# return reverse('event_detail', kwargs={'slug': self.slug,
# 'community_slug': self.community.slug})
#
# def get_update_url(self):
# return reverse('event_update', kwargs={'slug': self.slug,
# 'community_slug': self.community.slug})
#
# def get_comment_create_url(self):
# return reverse('eventcomment_create', kwargs={
# 'slug': self.slug, 'community_slug': self.community.slug})
#
# def get_rsvp_yes_url(self):
# return reverse('event_rsvp', kwargs={'slug': self.slug,
# 'community_slug': self.community.slug,
# 'answer': 'yes'})
#
# def get_rsvp_no_url(self):
# return reverse('event_rsvp', kwargs={'slug': self.slug,
# 'community_slug': self.community.slug,
# 'answer': 'no'})
#
# def get_rsvp_reset_url(self):
# return reverse('event_rsvp', kwargs={'slug': self.slug,
# 'community_slug': self.community.slug,
# 'answer': 'reset'})
#
# class Meta:
# ordering = ['begin', 'name']
# unique_together = ('community', 'slug')
, which may contain function names, class names, or code. Output only the next line. | return Event.objects.filter(community=obj).order_by('-created') |
Based on the snippet: <|code_start|># coding: utf-8
class LogHistoryChangeDecoratorTest(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def tearDown(self):
testing.tearDown()
def test_invoke_without_params_must_crash(self):
with self.assertRaises(TypeError):
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from pyramid import testing
from articlemeta.decorators import LogHistoryChange
and context (classes, functions, sometimes code) from other files:
# Path: articlemeta/decorators.py
# class LogHistoryChange(object):
# """
# This decorator operate after decorated functions been invoked,
# logging information about the event made in the decorated view.
#
# The decorator must receive 2 params:
# @param document_type: indicate if the operation applies to a Article or Journal object.
# @param event: indicate if the operation is an: addition (add), change (update), or deletion (delete).
# The only accepted values for this param is: 'add', 'update', or 'delete'. Other values will be ignored.
# The decorated view must return a dict as a result that contains a 'collection' and 'pid' as keys.
# """
#
# def __init__(self, document_type, event_type):
# self.document_type = document_type
# self.event_type = event_type
#
# def __call__(self, fn):
# @wraps(fn)
# def decorated(*args, **kwargs):
# # decorated function call
# result = fn(*args, **kwargs)
#
# # decorated function post-processing
# if self.event_type in ['update', 'delete', 'add'] and result:
# if self.event_type == 'delete' and result.get('deleted_count', None) == 0:
# return result
#
# code = result.get('code', None)
# collection = result.get('collection', None)
# log_data = {
# 'document_type': self.document_type,
# 'event': self.event_type,
# 'code': code,
# 'collection': collection,
# }
# db_broker = args[0]
# db_broker._log_changes(**log_data)
#
# # return view func response
# return result
# return decorated
. Output only the next line. | @LogHistoryChange() |
Based on the snippet: <|code_start|> return data, xml
class RefIdPipe(plumber.Pipe):
def transform(self, data):
raw, xml = data
ref = xml.find('.')
ref.set('id', 'B{0}'.format(str(raw.index_number)))
return data
class MixedCitationPipe(plumber.Pipe):
def precond(data):
raw, xml = data
if not raw.mixed_citation:
raise plumber.UnmetPrecondition()
@plumber.precondition(precond)
def transform(self, data):
raw, xml = data
parser = ET.HTMLParser()
mc = ET.parse(StringIO(raw.mixed_citation), parser)
mixed_citation = mc.find('body/p/.') if mc.find('body/p/.') is not None else mc.find('body/.')
mixed_citation.tag = 'mixed-citation'
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import plumber
from lxml import etree as ET
from io import StringIO
from xylose.scielodocument import UnavailableMetadataException
from articlemeta import utils
and context (classes, functions, sometimes code) from other files:
# Path: articlemeta/utils.py
# def convert_ahref_to_extlink(xml_etree):
# def convert_html_tags_to_jats(xml_etree):
# def convert_all_html_tags_to_jats(xml_etree):
# def __call__(cls, *args, **kwargs):
# def __init__(self, fp, parser_dep=ConfigParser):
# def from_env(cls):
# def from_file(cls, filepath):
# def __getattr__(self, attr):
# def items(self):
# class SingletonMixin(object):
# class Configuration(SingletonMixin):
. Output only the next line. | xml.append(utils.convert_all_html_tags_to_jats(mixed_citation)) |
Given the code snippet: <|code_start|>
class FunctionDatesToStringTests(unittest.TestCase):
def test_converts_datatime_in_processing_date_value(self):
data = {'processing_date': datetime(2017, 9, 14)}
expected_result = {'processing_date': '2017-09-14'}
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from datetime import datetime
from articlemeta import controller
and context (functions, classes, or occasionally code) from other files:
# Path: articlemeta/controller.py
# LIMIT = 1000
# def dates_to_string(data):
# def get_date_range_filter(from_date=None, until_date=None):
# def get_dbconn(db_dsn):
# def _create_indexes(db):
# def __init__(self, db, journalmeta):
# def check(self, metadata):
# def identifiers(self, collection=None, issn=None,
# from_date='1500-01-01', until_date=None, limit=None, offset=0,
# extra_filter=None):
# def get(self, code, collection=None, replace_journal_metadata=False):
# def get_issues_full(self, collection=None, issn=None, from_date='1500-01-01',
# until_date=None, limit=LIMIT, offset=0, extra_filter=None):
# def exists(self, code, collection=None):
# def delete(self, code, collection=None):
# def add(self, metadata):
# def update(self, metadata):
# def get_code_from_label(self, label, journal_code, collection):
# def _get_code_from_label_list(self, label, journal_code, collection):
# def _get_code_from_label_str(self, label, journal_code, collection):
# def __init__(self, db):
# def check(self, metadata):
# def get(self, collection=None, issn=None):
# def delete(self, code, collection):
# def add(self, metadata):
# def update(self, metadata):
# def identifiers(self, collection=None, issn=None, limit=None,
# offset=0, extra_filter=None):
# def exists(self, code, collection=None):
# def __init__(self, db, journalmeta, issuemeta):
# def check(self, metadata):
# def identifiers(self, collection=None, issn=None, from_date='1500-01-01',
# until_date=None, limit=LIMIT, offset=0, extra_filter=None):
# def get(self, code, collection=None, replace_journal_metadata=False, body=False):
# def get_articles_full(self, collection=None, issn=None,
# from_date='1500-01-01', until_date=None, limit=100, offset=0,
# extra_filter=None, replace_journal_metadata=False, body=False):
# def exists(self, code, collection=None):
# def delete(self, code, collection=None):
# def add(self, metadata):
# def update(self, metadata):
# def identifiers_press_release(self, collection=None, issn=None,
# from_date='1500-01-01', until_date=None, limit=LIMIT, offset=0):
# def set_doaj_id(self, code, collection, doaj_id):
# def set_aid(self, code, collection, aid):
# def __init__(self, pubstatus, filepath=COLLECTIONS_PATH):
# def _data(self):
# def _add_counts(self, data, docs_count):
# def identifiers(self):
# def get(self, collection):
# def __init__(self, host='http://publication.scielo.org'):
# def documents_count(self):
# def journals_count(self, collection):
# def __init__(self, db_client):
# def _log_changes(self, document_type, code, event, collection=None, date=None):
# def historychanges(self, document_type, collection=None, event=None,
# code=None, from_date='1997-01-01',
# until_date=None, limit=LIMIT, offset=0):
# def get_journal(self, collection=None, issn=None):
# def delete_journal(self, code, collection=None):
# def add_journal(self, metadata):
# def update_journal(self, metadata):
# def identifiers_collection(self):
# def get_collection(self, collection):
# def collection(self, collection=None):
# def identifiers_journal(self, collection=None, issn=None, limit=LIMIT,
# offset=0, extra_filter=None):
# def identifiers_issue(self, collection=None, issn=None,
# from_date='1500-01-01', until_date=None, limit=LIMIT, offset=0,
# extra_filter=None):
# def get_issue(self, code, collection=None, replace_journal_metadata=False):
# def get_issues_full(self, collection=None, issn=None, from_date='1500-01-01',
# until_date=None, limit=LIMIT, offset=0, extra_filter=None):
# def get_issues(self, code, collection=None, replace_journal_metadata=False):
# def exists_journal(self, code, collection=None):
# def exists_issue(self, code, collection=None):
# def delete_issue(self, code, collection=None):
# def add_issue(self, metadata):
# def update_issue(self, metadata):
# def identifiers_article(self,
# collection=None,
# issn=None,
# from_date='1500-01-01',
# until_date=None,
# limit=LIMIT,
# offset=0,
# extra_filter=None):
# def identifiers_press_release(self,
# collection=None,
# issn=None,
# from_date='1500-01-01',
# until_date=None,
# limit=LIMIT,
# offset=0):
# def get_article(self, code, collection=None, replace_journal_metadata=False,
# body=False):
# def get_articles_full(self, collection=None, issn=None,
# from_date='1500-01-01', until_date=None, limit=100, offset=0,
# extra_filter=None, replace_journal_metadata=False, body=False):
# def get_articles(self, code, collection=None, replace_journal_metadata=False):
# def exists_article(self, code, collection=None):
# def delete_article(self, code, collection=None):
# def add_article(self, metadata):
# def update_article(self, metadata):
# def set_doaj_id(self, code, collection, doaj_id):
# def set_aid(self, code, collection, aid):
# def get_issue_code_from_label(self, label, journal_code, collection):
# class IssueMeta:
# class JournalMeta:
# class ArticleMeta:
# class CollectionMeta:
# class PublicationStatus:
# class DataBroker(object):
. Output only the next line. | self.assertEqual(controller.dates_to_string(data), expected_result) |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
class LoadLicensesTest(unittest.TestCase):
def test_scrapt_body(self):
data = u"""<html><header></header><body><div class="content"><div class="index,en"><div class="title">Crazy <i>Title</i></div><p>Crazy Body</p><p>Really Crazy Body</p></div></div></body></html>"""
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import os
import codecs
import re
import re
import re
from processing import load_body
and context including class names, function names, and sometimes code from other files:
# Path: processing/load_body.py
# SENTRY_DSN = os.environ.get('SENTRY_DSN', None)
# LOGGING_LEVEL = os.environ.get('LOGGING_LEVEL', 'DEBUG')
# MONGODB_HOST = os.environ.get('MONGODB_HOST', None)
# LOGGING = {
# 'version': 1,
# 'disable_existing_loggers': True,
#
# 'formatters': {
# 'console': {
# 'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
# 'datefmt': '%H:%M:%S',
# },
# },
# 'handlers': {
# 'console': {
# 'level': LOGGING_LEVEL,
# 'class': 'logging.StreamHandler',
# 'formatter': 'console'
# }
# },
# 'loggers': {
# '': {
# 'handlers': ['console'],
# 'level': LOGGING_LEVEL,
# 'propagate': False,
# },
# 'processing.load_body': {
# 'level': LOGGING_LEVEL,
# 'propagate': True,
# },
# }
# }
# FROM = datetime.now() - timedelta(days=15)
# FROM = FROM.isoformat()[:10]
# BODY_REGEX = re.compile(r'<div .*class="index,(?P<language>.*?)">(?P<body>.*)</div>')
# REMOVE_LINKS_REGEX = re.compile(r'\[.<a href="javascript\:void\(0\);".*?>Links</a>.\]', re.IGNORECASE)
# def collections_acronym(articlemeta_db):
# def collection_info(articlemeta_db, collection):
# def load_documents_pids(articlemeta_db, pids, collection):
# def load_documents_collection(articlemeta_db, collection, all_records=False):
# def do_request(url, json=True):
# def scrap_body(data, language):
# def add_bodies(articlemeta_db, documents, collection):
# def run(articlemeta_db, collections, pids=None, all_records=False):
# def main():
. Output only the next line. | result = load_body.scrap_body(data.encode('utf-8'), 'en') |
Using the snippet: <|code_start|># coding: utf-8
class ExportTests(unittest.TestCase):
def setUp(self):
self._raw_json = json.loads(open(os.path.dirname(__file__)+'/fixtures/article_meta.json').read())
self._article_meta = Article(self._raw_json)
def test_xmlclose_pipe(self):
pxml = ET.Element('ArticleSet')
pxml.append(ET.Element('Article'))
data = [None, pxml]
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import json
import os
from lxml import etree as ET
from xylose.scielodocument import Article
from articlemeta import export_pubmed
from articlemeta import export
and context (class names, function names, or code) available:
# Path: articlemeta/export_pubmed.py
# SUPPLBEG_REGEX = re.compile(r'^0 ')
# SUPPLEND_REGEX = re.compile(r' 0$')
# class SetupArticleSetPipe(plumber.Pipe):
# class XMLArticlePipe(plumber.Pipe):
# class XMLJournalPipe(plumber.Pipe):
# class XMLPublisherNamePipe(plumber.Pipe):
# class XMLJournalTitlePipe(plumber.Pipe):
# class XMLISSNPipe(plumber.Pipe):
# class XMLVolumePipe(plumber.Pipe):
# class XMLIssuePipe(plumber.Pipe):
# class XMLPubDatePipe(plumber.Pipe):
# class XMLReplacesPipe(plumber.Pipe):
# class XMLArticleTitlePipe(plumber.Pipe):
# class XMLFirstPagePipe(plumber.Pipe):
# class XMLLastPagePipe(plumber.Pipe):
# class XMLElocationIDPipe(plumber.Pipe):
# class XMLLanguagePipe(plumber.Pipe):
# class XMLAuthorListPipe(plumber.Pipe):
# class XMLPublicationTypePipe(plumber.Pipe):
# class XMLArticleIDListPipe(plumber.Pipe):
# class XMLHistoryPipe(plumber.Pipe):
# class XMLAbstractPipe(plumber.Pipe):
# class XMLClosePipe(plumber.Pipe):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
#
# Path: articlemeta/export.py
# class CustomArticle(Article):
# class JournalExport:
# class Export(object):
# def issue_publication_date(self):
# def __init__(self, journal):
# def pipeline_scieloorg(self):
# def _safegetter(func):
# def __init__(self, article):
# def pipeline_sci(self):
# def pipeline_rsps(self):
# def pipeline_doaj(self):
# def pipeline_pubmed(self):
# def pipeline_crossref(self):
# def pipeline_opac(self):
. Output only the next line. | xmlarticle = export_pubmed.XMLClosePipe() |
Given the following code snippet before the placeholder: <|code_start|> self.assertEqual('<ArticleSet><Article><ArticleIdList><ArticleId IdType="pii">S0034-89102010000400007</ArticleId><ArticleId IdType="doi">10.1590/S0034-89102010000400007</ArticleId></ArticleIdList></Article></ArticleSet>'.encode('utf-8'), ET.tostring(xml))
def test_xmlhistory_pipe(self):
pxml = ET.Element('ArticleSet')
pxml.append(ET.Element('Article'))
data = [self._article_meta, pxml]
xmlarticle = export_pubmed.XMLHistoryPipe()
raw, xml = xmlarticle.transform(data)
self.assertEqual('<ArticleSet><Article><History><PubDate PubStatus="received"><Year>2009</Year><Month>08</Month><Day>14</Day></PubDate><PubDate PubStatus="accepted"><Year>2010</Year><Month>02</Month><Day>05</Day></PubDate></History></Article></ArticleSet>'.encode('utf-8'), ET.tostring(xml))
def test_xmlabstract_pipe(self):
pxml = ET.Element('ArticleSet')
pxml.append(ET.Element('Article'))
data = [self._article_meta, pxml]
xmlarticle = export_pubmed.XMLAbstractPipe()
raw, xml = xmlarticle.transform(data)
abstract = xml.find('./Article/Abstract').text[0:30]
self.assertEqual(u'OBJETIVO: Descrever o perfil e', abstract)
def test_validating_against_dtd(self):
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import json
import os
from lxml import etree as ET
from xylose.scielodocument import Article
from articlemeta import export_pubmed
from articlemeta import export
and context including class names, function names, and sometimes code from other files:
# Path: articlemeta/export_pubmed.py
# SUPPLBEG_REGEX = re.compile(r'^0 ')
# SUPPLEND_REGEX = re.compile(r' 0$')
# class SetupArticleSetPipe(plumber.Pipe):
# class XMLArticlePipe(plumber.Pipe):
# class XMLJournalPipe(plumber.Pipe):
# class XMLPublisherNamePipe(plumber.Pipe):
# class XMLJournalTitlePipe(plumber.Pipe):
# class XMLISSNPipe(plumber.Pipe):
# class XMLVolumePipe(plumber.Pipe):
# class XMLIssuePipe(plumber.Pipe):
# class XMLPubDatePipe(plumber.Pipe):
# class XMLReplacesPipe(plumber.Pipe):
# class XMLArticleTitlePipe(plumber.Pipe):
# class XMLFirstPagePipe(plumber.Pipe):
# class XMLLastPagePipe(plumber.Pipe):
# class XMLElocationIDPipe(plumber.Pipe):
# class XMLLanguagePipe(plumber.Pipe):
# class XMLAuthorListPipe(plumber.Pipe):
# class XMLPublicationTypePipe(plumber.Pipe):
# class XMLArticleIDListPipe(plumber.Pipe):
# class XMLHistoryPipe(plumber.Pipe):
# class XMLAbstractPipe(plumber.Pipe):
# class XMLClosePipe(plumber.Pipe):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
#
# Path: articlemeta/export.py
# class CustomArticle(Article):
# class JournalExport:
# class Export(object):
# def issue_publication_date(self):
# def __init__(self, journal):
# def pipeline_scieloorg(self):
# def _safegetter(func):
# def __init__(self, article):
# def pipeline_sci(self):
# def pipeline_rsps(self):
# def pipeline_doaj(self):
# def pipeline_pubmed(self):
# def pipeline_crossref(self):
# def pipeline_opac(self):
. Output only the next line. | xml = ET.XML(export.Export(self._raw_json).pipeline_pubmed()) |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
class XMLCitationTests(unittest.TestCase):
def setUp(self):
self._raw_json = json.loads(open(os.path.dirname(__file__)+'/fixtures/article_meta.json').read())
self._citation_meta = Article(self._raw_json).citations[0]
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import json
import os
from lxml import etree as ET
from lxml import etree
from xylose.scielodocument import Article
from articlemeta import export_sci
from articlemeta import export
and context including class names, function names, and sometimes code from other files:
# Path: articlemeta/export_sci.py
# SUPPLBEG_REGEX = re.compile(r'^0 ')
# SUPPLEND_REGEX = re.compile(r' 0$')
# ALLOWED_LANGUAGES = ['af', 'de', 'en', 'es', 'fr', 'it', 'la', 'pt', 'po']
# def create_children(root_node, tags, values):
# def splited_yyyy_mm_dd(date_iso):
# def create_date_elem(element_date_name, splited_yyyy_mm_dd, date_type=None):
# def __init__(self):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def _create_author(self, author):
# def transform(self, data):
# def _transform_authors_groups(self, data):
# def _transform_authors(self, data):
# def deploy(self, raw):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def transform(self, data):
# def join_publisher_names(self, data, separator='; '):
# def get_first_publisher_name(self, data):
# def transform(self, data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def transform(self, data):
# class XMLCitation(object):
# class SetupCitationPipe(plumber.Pipe):
# class RefIdPipe(plumber.Pipe):
# class ElementCitationPipe(plumber.Pipe):
# class ArticleTitlePipe(plumber.Pipe):
# class SourcePipe(plumber.Pipe):
# class ThesisTitlePipe(plumber.Pipe):
# class ConferencePipe(plumber.Pipe):
# class LinkTitlePipe(plumber.Pipe):
# class URIPipe(plumber.Pipe):
# class DatePipe(plumber.Pipe):
# class StartPagePipe(plumber.Pipe):
# class EndPagePipe(plumber.Pipe):
# class IssuePipe(plumber.Pipe):
# class VolumePipe(plumber.Pipe):
# class PersonGroupPipe(plumber.Pipe):
# class SetupArticlePipe(plumber.Pipe):
# class XMLArticlePipe(plumber.Pipe):
# class XMLFrontPipe(plumber.Pipe):
# class XMLJournalMetaJournalIdPipe(plumber.Pipe):
# class XMLJournalMetaJournalTitleGroupPipe(plumber.Pipe):
# class XMLJournalMetaISSNPipe(plumber.Pipe):
# class XMLJournalMetaCollectionPipe(plumber.Pipe):
# class XMLJournalMetaPublisherPipe(plumber.Pipe):
# class XMLArticleMetaUniqueArticleIdPipe(plumber.Pipe):
# class XMLArticleMetaArticleIdPublisherPipe(plumber.Pipe):
# class XMLArticleMetaArticleIdDOIPipe(plumber.Pipe):
# class XMLArticleMetaArticleCategoriesPipe(plumber.Pipe):
# class XMLArticleMetaTitleGroupPipe(plumber.Pipe):
# class XMLArticleMetaTranslatedTitleGroupPipe(plumber.Pipe):
# class XMLArticleMetaContribGroupPipe(plumber.Pipe):
# class XMLArticleMetaAffiliationPipe(plumber.Pipe):
# class XMLArticleMetaDatesInfoPipe(plumber.Pipe):
# class XMLArticleMetaPagesInfoPipe(plumber.Pipe):
# class XMLArticleMetaElocationInfoPipe(plumber.Pipe):
# class XMLArticleMetaIssueInfoPipe(plumber.Pipe):
# class XMLArticleMetaURLsPipe(plumber.Pipe):
# class XMLArticleMetaAbstractsPipe(plumber.Pipe):
# class XMLArticleMetaKeywordsPipe(plumber.Pipe):
# class XMLArticleMetaPermissionPipe(plumber.Pipe):
# class XMLArticleMetaCitationsPipe(plumber.Pipe):
# class XMLClosePipe(plumber.Pipe):
#
# Path: articlemeta/export.py
# class CustomArticle(Article):
# class JournalExport:
# class Export(object):
# def issue_publication_date(self):
# def __init__(self, journal):
# def pipeline_scieloorg(self):
# def _safegetter(func):
# def __init__(self, article):
# def pipeline_sci(self):
# def pipeline_rsps(self):
# def pipeline_doaj(self):
# def pipeline_pubmed(self):
# def pipeline_crossref(self):
# def pipeline_opac(self):
. Output only the next line. | self._xmlcitation = export_sci.XMLCitation() |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
"""
This processing import affiliation metadata for the Article Meta database.
input: CSV file formated as below
Collection|PID|Publication Year|Journal Title|number label|Affiliation ID [aff1, aff2]|Affiliaton as it was markedup|Affiliation Country as it was markedup|Normalized Affiliation|Normalized Affiliation Country|iso-3661 country|Normalized Affiliation State|iso-3661 state
input example:
scl|S0001-37652013000100001|2013|An. Acad. Bras. Ciênc.|v85n1|aff1|Museu Nacional/UFRJ|Brasil|Universidade Federal do Rio de Janeiro|Brazil|iso-3661|São Paulo|SP
CSV Total parameters size: 13
"""
logger = logging.getLogger(__name__)
<|code_end|>
, predict the next line using imports from the current file:
import logging
import codecs
import re
import argparse
import csv
from pymongo import MongoClient
from articlemeta import utils
from xylose.scielodocument import Article
and context including class names, function names, and sometimes code from other files:
# Path: articlemeta/utils.py
# def convert_ahref_to_extlink(xml_etree):
# def convert_html_tags_to_jats(xml_etree):
# def convert_all_html_tags_to_jats(xml_etree):
# def __call__(cls, *args, **kwargs):
# def __init__(self, fp, parser_dep=ConfigParser):
# def from_env(cls):
# def from_file(cls, filepath):
# def __getattr__(self, attr):
# def items(self):
# class SingletonMixin(object):
# class Configuration(SingletonMixin):
. Output only the next line. | config = utils.Configuration.from_env() |
Here is a snippet: <|code_start|> class MockJournal(object):
@property
def title(self):
return 'Title'
class MockArticle(object):
def __init__(self):
self.publisher_id = u'S0001-37652013000100001'
self.affiliations = [
{
'index': u'aff1',
'addr_line': u'Rio de Janeiro',
'institution': u'Museu Nacional/UFRJ',
'country': u'Brasil'
}
]
@property
def journal(self):
j = MockJournal()
return j
self.mockarticle = MockArticle()
def test_parse_csv_line_ok_isis_mfn(self):
line = u'27136|scl|S0001-37652013000100001|2013|An. Acad. Bras. Ciênc.|v85n1|aff1|Museu Nacional/UFRJ|Brasil|Universidade Federal do Rio de Janeiro|Brazil|BR|São Paulo|SP'
<|code_end|>
. Write the next line using the current file imports:
import unittest
from processing import importaffiliation
and context from other files:
# Path: processing/importaffiliation.py
# REGEX_ARTICLE = re.compile("^S[0-9]{4}-[0-9]{3}[0-9xX][0-2][0-9]{3}[0-9]{4}[0-9]{5}$")
# def _config_logging(logging_level='INFO', logging_file=None):
# def is_valid_pid(pid):
# def parse_csv_line(data):
# def is_clean_checked(parsed_line, original_article):
# def get_original_article(pid, collection):
# def isis_like_json(data):
# def import_doc_affiliations(data, normalized_affiliations):
# def check_affiliations(file_name='processing/normalized_affiliations.csv', import_data=False, encoding='utf-8'):
# def main():
, which may include functions, classes, or code. Output only the next line. | result = importaffiliation.parse_csv_line(line.split('|')) |
Continue the code snippet: <|code_start|># coding: utf-8
class ViewsTest(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def tearDown(self):
testing.tearDown()
def test_get_request_limit_param_by_default(self):
"""
test default behavior of the helper function: _get_request_limit_param
- only positive limits are allowed
- if request.limit is greater than default_limit, will return the default limit (1000)
"""
# set a list of tuples (limit requested, limit expected in response)
limits = [(1,1), (10, 10), (1000, 1000), (2000, 1000), (12000, 1000)]
for req_limit, resp_limit in limits:
request = testing.DummyRequest(params={'limit': req_limit})
<|code_end|>
. Use current file imports:
import unittest
import pyramid.httpexceptions as exc
from pyramid import testing
from articlemeta import articlemeta
and context (classes, functions, or code) from other files:
# Path: articlemeta/articlemeta.py
# DEFAULT_FROM_DATE = '1900-01-01'
# def _get_request_limit_param(request, default_limit=1000,
# only_positive_limit=True, force_max_limit_to_default=True):
# def notfound(request):
# def index(request):
# def get_collection(request):
# def identifier_collection(request):
# def get_journal(request):
# def identifiers_journal(request):
# def identifiers_issue(request):
# def exists_journal(request):
# def exists_issue(request):
# def get_issue(request):
# def get_issues(request):
# def identifiers_article(request):
# def identifiers_press_release(request):
# def exists_article(request):
# def get_article(request):
# def get_articles(request):
# def list_historychanges(request):
. Output only the next line. | result_limit = articlemeta._get_request_limit_param(request) |
Given snippet: <|code_start|># coding: utf-8
class ExportTests(unittest.TestCase):
def setUp(self):
self._raw_json = json.loads(open(os.path.dirname(__file__)+'/fixtures/article_meta.json').read())
self._article_meta = Article(self._raw_json)
def test_xmlclose_pipe(self):
pxml = ET.Element('records')
pxml.append(ET.Element('record'))
data = [None, pxml]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import json
import os
from lxml import etree as ET
from lxml import etree
from xylose.scielodocument import Article
from articlemeta import export_doaj
from articlemeta import export
and context:
# Path: articlemeta/export_doaj.py
# SUPPLBEG_REGEX = re.compile(r'^0 ')
# SUPPLEND_REGEX = re.compile(r' 0$')
# ISO6392T_TO_ISO6392B = {
# u'sqi': u'alb',
# u'hye': u'arm',
# u'eus': u'baq',
# u'mya': u'bur',
# u'zho': u'chi',
# u'ces': u'cze',
# u'nld': u'dut',
# u'fra': u'fre',
# u'kat': u'geo',
# u'deu': u'ger',
# u'ell': u'gre',
# u'isl': u'ice',
# u'mkd': u'mac',
# u'msa': u'may',
# u'mri': u'mao',
# u'fas': u'per',
# u'ron': u'rum',
# u'slk': u'slo',
# u'bod': u'tib',
# u'cym': u'wel'
# }
# class SetupArticlePipe(plumber.Pipe):
# class XMLArticlePipe(plumber.Pipe):
# class XMLJournalMetaJournalTitlePipe(plumber.Pipe):
# class XMLJournalMetaISSNPipe(plumber.Pipe):
# class XMLJournalMetaPublisherPipe(plumber.Pipe):
# class XMLArticleMetaIdPipe(plumber.Pipe):
# class XMLArticleMetaArticleIdDOIPipe(plumber.Pipe):
# class XMLArticleMetaTitlePipe(plumber.Pipe):
# class XMLArticleMetaAuthorsPipe(plumber.Pipe):
# class XMLArticleMetaAffiliationPipe(plumber.Pipe):
# class XMLArticleMetaPublicationDatePipe(plumber.Pipe):
# class XMLArticleMetaStartPagePipe(plumber.Pipe):
# class XMLArticleMetaEndPagePipe(plumber.Pipe):
# class XMLArticleMetaVolumePipe(plumber.Pipe):
# class XMLArticleMetaIssuePipe(plumber.Pipe):
# class XMLArticleMetaDocumentTypePipe(plumber.Pipe):
# class XMLArticleMetaFullTextUrlPipe(plumber.Pipe):
# class XMLArticleMetaAbstractsPipe(plumber.Pipe):
# class XMLArticleMetaKeywordsPipe(plumber.Pipe):
# class XMLClosePipe(plumber.Pipe):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def transform(self, data):
#
# Path: articlemeta/export.py
# class CustomArticle(Article):
# class JournalExport:
# class Export(object):
# def issue_publication_date(self):
# def __init__(self, journal):
# def pipeline_scieloorg(self):
# def _safegetter(func):
# def __init__(self, article):
# def pipeline_sci(self):
# def pipeline_rsps(self):
# def pipeline_doaj(self):
# def pipeline_pubmed(self):
# def pipeline_crossref(self):
# def pipeline_opac(self):
which might include code, classes, or functions. Output only the next line. | xmlarticle = export_doaj.XMLClosePipe() |
Given the following code snippet before the placeholder: <|code_start|> 'Terapia de Reemplazo Renal',
'Sistemas de Información en Hospital',
'Registros de Mortalidad',
'Insuficiência Renal Crônica',
'Terapia de Substituição Renal',
'Sistemas de Informação Hospitalar',
'Registros de Mortalidade']]), keywords)
def test_xmlarticle_meta_keywords_without_data_pipe(self):
fakexylosearticle = Article({'article': {'v40': [{'_': 'pt'}]}, 'title': {}})
pxml = ET.Element('records')
pxml.append(ET.Element('record'))
data = [fakexylosearticle, pxml]
xmlarticle = export_doaj.XMLArticleMetaKeywordsPipe()
raw, xml = xmlarticle.transform(data)
try:
xml.find('./record/keywords').text
except AttributeError:
self.assertTrue(True)
else:
self.assertTrue(False)
@unittest.skip("demonstrating skipping")
def test_validating_against_schema(self):
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import json
import os
from lxml import etree as ET
from lxml import etree
from xylose.scielodocument import Article
from articlemeta import export_doaj
from articlemeta import export
and context including class names, function names, and sometimes code from other files:
# Path: articlemeta/export_doaj.py
# SUPPLBEG_REGEX = re.compile(r'^0 ')
# SUPPLEND_REGEX = re.compile(r' 0$')
# ISO6392T_TO_ISO6392B = {
# u'sqi': u'alb',
# u'hye': u'arm',
# u'eus': u'baq',
# u'mya': u'bur',
# u'zho': u'chi',
# u'ces': u'cze',
# u'nld': u'dut',
# u'fra': u'fre',
# u'kat': u'geo',
# u'deu': u'ger',
# u'ell': u'gre',
# u'isl': u'ice',
# u'mkd': u'mac',
# u'msa': u'may',
# u'mri': u'mao',
# u'fas': u'per',
# u'ron': u'rum',
# u'slk': u'slo',
# u'bod': u'tib',
# u'cym': u'wel'
# }
# class SetupArticlePipe(plumber.Pipe):
# class XMLArticlePipe(plumber.Pipe):
# class XMLJournalMetaJournalTitlePipe(plumber.Pipe):
# class XMLJournalMetaISSNPipe(plumber.Pipe):
# class XMLJournalMetaPublisherPipe(plumber.Pipe):
# class XMLArticleMetaIdPipe(plumber.Pipe):
# class XMLArticleMetaArticleIdDOIPipe(plumber.Pipe):
# class XMLArticleMetaTitlePipe(plumber.Pipe):
# class XMLArticleMetaAuthorsPipe(plumber.Pipe):
# class XMLArticleMetaAffiliationPipe(plumber.Pipe):
# class XMLArticleMetaPublicationDatePipe(plumber.Pipe):
# class XMLArticleMetaStartPagePipe(plumber.Pipe):
# class XMLArticleMetaEndPagePipe(plumber.Pipe):
# class XMLArticleMetaVolumePipe(plumber.Pipe):
# class XMLArticleMetaIssuePipe(plumber.Pipe):
# class XMLArticleMetaDocumentTypePipe(plumber.Pipe):
# class XMLArticleMetaFullTextUrlPipe(plumber.Pipe):
# class XMLArticleMetaAbstractsPipe(plumber.Pipe):
# class XMLArticleMetaKeywordsPipe(plumber.Pipe):
# class XMLClosePipe(plumber.Pipe):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def precond(data):
# def transform(self, data):
# def transform(self, data):
#
# Path: articlemeta/export.py
# class CustomArticle(Article):
# class JournalExport:
# class Export(object):
# def issue_publication_date(self):
# def __init__(self, journal):
# def pipeline_scieloorg(self):
# def _safegetter(func):
# def __init__(self, article):
# def pipeline_sci(self):
# def pipeline_rsps(self):
# def pipeline_doaj(self):
# def pipeline_pubmed(self):
# def pipeline_crossref(self):
# def pipeline_opac(self):
. Output only the next line. | xml = export.Export(self._raw_json).pipeline_doaj() |
Predict the next line for this snippet: <|code_start|>
class TagHandler(BaseHandler):
def read(self, request, tag_id):
try:
tag = Tag.objects.get(id=tag_id)
except:
resp = rc.NOT_HERE
resp.write(": Tag does not exist.")
return resp
<|code_end|>
with the help of current file imports:
from django.contrib.auth.models import User
from piston.handler import AnonymousBaseHandler, BaseHandler
from piston.utils import rc
from snippet.models import Snippet
from tagging.models import Tag, TaggedItem
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
and context from other files:
# Path: snippet/models.py
# class Snippet(models.Model):
# code = models.TextField()
# description = models.TextField()
# slug = models.SlugField()
# lexer = models.TextField()
# key = models.TextField()
# created = models.DateTimeField(auto_now_add=True)
# user = models.ForeignKey(User)
# public = models.BooleanField()
# tags = TagField()
#
# def __unicode__(self):
# return u'%s' %(self.description)
#
# def get_tags(self):
# return Tag.objects.get_for_object(self)
#
# def get_absolute_url(self):
# return "/%s/%s/" % (self.user.username, self.slug)
#
# def is_favorite(self, user):
# from snipt.favsnipt.models import FavSnipt
# try:
# FavSnipt.objects.get(snipt=self, user=user)
# return 'favorited'
# except:
# return ''
, which may contain function names, class names, or code. Output only the next line. | snipts = TaggedItem.objects.get_by_model(Snippet.objects.filter(public='1'), tag) |
Given snippet: <|code_start|>
DEBUG = False
DATABASE_ENGINE = ''
DATABASE_NAME = ''
DATABASE_USER = ''
DATABASE_PASSWORD = ''
TIME_ZONE = ''
SECRET_KEY = ''
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from settings import INSTALLED_APPS
and context:
# Path: settings.py
# INSTALLED_APPS = (
# 'django.contrib.admin',
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.comments',
# 'django.contrib.sites',
# 'django_authopenid',
# 'django_extensions',
# 'piston',
# 'snippet',
# 'pagination',
# 'compress',
# 'snipt.ad',
# 'snipt.api',
# 'tagging',
# 'favsnipt',
# 'south',
# )
which might include code, classes, or functions. Output only the next line. | INSTALLED_APPS += ('gunicorn',) |
Predict the next line for this snippet: <|code_start|> # If the user is at the homepage (no tag specified).
else:
# Retrieve latest 20 snipts for user.
if mine:
snipts = Snippet.objects.filter(user=context_user.id).order_by('-created')
favsnipts = FavSnipt.objects.filter(user=context_user.id)
favrd = []
for fs in favsnipts:
fs.snipt.favrd = True
fs.snipt.created = fs.created
favrd.append(fs.snipt)
snipts = sorted(
chain(snipts, favrd),
key=attrgetter('created'), reverse=True)
elif not public:
snipts = Snippet.objects.filter(user=context_user.id, public='1').order_by('-created')
else:
snipts = Snippet.objects.filter(public='1').order_by('-created')[:100]
# Compile the list of tags that this user has used.
if mine:
user_tags_list = Tag.objects.usage_for_queryset(Snippet.objects.filter(user=context_user.id).order_by('-created'), counts=True)
elif not public:
user_tags_list = Tag.objects.usage_for_queryset(Snippet.objects.filter(user=context_user.id, public='1').order_by('-created'), counts=True)
else:
user_tags_list = Tag.objects.usage_for_queryset(Snippet.objects.filter(public='1'), counts=True)
<|code_end|>
with the help of current file imports:
from django.contrib.auth import authenticate, login as auth_login
from django.contrib.auth.models import User
from django.contrib.comments.signals import comment_was_posted
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from tagging.models import Tag, TaggedItem
from django.template import RequestContext
from snipt.snippet.models import Snippet, Referer
from django.utils.html import escape
from django.utils import simplejson
from tagging.utils import get_tag
from snipt.snippet.utils import *
from django.http import Http404
from settings import DEBUG
from snipt.forms import *
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from random import choice
from django.core.mail import send_mail
from django.contrib.comments.signals import comment_was_posted
from django.core.mail import EmailMultiAlternatives
from snipt.favsnipt.models import FavSnipt
from operator import attrgetter
from itertools import chain
from snipt.favsnipt.models import FavSnipt
from operator import attrgetter
from itertools import chain
import md5
and context from other files:
# Path: settings.py
# DEBUG = False
, which may contain function names, class names, or code. Output only the next line. | if not DEBUG: |
Given snippet: <|code_start|>
class MemphisCouncilCalNotifier(BaseNotifier):
def get_site(self):
return Document.Site.MEMPHIS_COUNCIL_CALENDAR
def get_listings_pre_text(self, items_length):
return ("We have found {} new documents ".format(items_length) +
"since we last sent you an update:")
def make_item_body(self, doc):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .base_notifier import BaseNotifier
from .notifier_utils import make_doc_item_body
from document import Document
and context:
# Path: bidwire/notifiers/base_notifier.py
# class BaseNotifier:
# def __init__(self):
# self.site_name = self.get_site().value
#
# # TODO(anaulin): Remove this method, and replace it with setting the
# # site_name in each constructor.
# def get_site(self):
# """Identifies the site type of the notifier
#
# Returns:
# site -- object of type Bid.Site
# """
# raise NotImplementedError
#
# def get_listings_pre_text(self, items_length):
# """Heading text before listings are displayed
#
# Arguments:
# bids_length -- number of new bids in the email
#
# Returns:
# text -- string of text preceding the listings
# """
# raise NotImplementedError
#
# def make_item_body(self, item):
# """Returns the HTML-formatted item for the new item list, as string."""
# raise NotImplementedError
#
# def send_new_items_notification(self, bids, recipients):
# log.info("Sending notifications to {} about bids {}"
# .format(recipients, bids))
# subject = "Changes detected on {}".format(self.site_name)
# send_email(subject, self.make_email_body(bids), recipients)
#
# def make_email_body(self, items):
# return make_html_body(
# items,
# self.make_item_body,
# pre_list_text=self.get_listings_pre_text(len(items))
# )
#
# Path: bidwire/notifiers/notifier_utils.py
# def make_doc_item_body(document):
# """Returns the HTML for one Document item"""
# doc, tag, text = Doc().tagtext()
# with tag('strong'):
# with tag('a', href=document.url):
# text(document.title)
# return doc.getvalue()
which might include code, classes, or functions. Output only the next line. | return make_doc_item_body(doc) |
Given the following code snippet before the placeholder: <|code_start|>
log = logging.getLogger(__name__)
URL_PREFIX = 'http://www.mass.gov/eopss/funding-and-training/'
class MassGovEOPSSScraper(BaseScraper):
def __init__(self):
<|code_end|>
, predict the next line using imports from the current file:
from document import Document, get_new_urls
from .base_scraper import BaseScraper
from .massgov import url_scraper_dict
from .massgov import results_page_scraper
import logging
import scrapelib
and context including class names, function names, and sometimes code from other files:
# Path: bidwire/scrapers/base_scraper.py
# class BaseScraper(metaclass=abc.ABCMeta):
# """The interface that must be implemented by all scrapers."""
#
# @abc.abstractmethod
# def scrape(self, session):
# """
# This method performs all scraping for this scraper. Must be implemented
# by subclasses.
#
# Arguments:
# session -- database session to use for persisting items
# """
# pass
#
# Path: bidwire/scrapers/massgov/url_scraper_dict.py
# UL_CATEGORY_LI = '//ul[@class="category"]/li'
# H2_A_TITLELINK = './h2/a[@class="titlelink"]'
# SPAN_A_TITLELINK = './span/a[@class="titlelink"]'
# DIV_BODYFIELD_P = '//div[contains(@class,"bodyfield")]/p'
# CATEGORY_H2_XPATH = [ UL_CATEGORY_LI, H2_A_TITLELINK ]
# BODYFIELD_SPAN_XPATH = [ DIV_BODYFIELD_P, SPAN_A_TITLELINK ]
# MASSGOV_DICT = {
# 'homeland-sec/grants/docs/':
# [
# UL_CATEGORY_LI,
# './h2/span/a[@class="titlelink"]'
# ],
# 'homeland-sec/grants/hs-grant-guidance-and-policies.html':
# BODYFIELD_SPAN_XPATH,
# 'homeland-sec/grants/standard-documents.html':
# [
# '//div[contains(@class,"bodyfield")]/ul/li',
# SPAN_A_TITLELINK
# ],
# 'law-enforce/grants/': CATEGORY_H2_XPATH,
# 'law-enforce/grants/2017-muni-public-safety-staffing-grant.html':
# BODYFIELD_SPAN_XPATH,
# 'law-enforce/grants/le-grants-public-records.html':
# BODYFIELD_SPAN_XPATH,
# 'justice-and-prev/grants/': CATEGORY_H2_XPATH,
# 'justice-and-prev/grants/bgp/': CATEGORY_H2_XPATH,
# 'hwy-safety/grants/': CATEGORY_H2_XPATH,
# 'hwy-safety/grants/ffy-2017-traffic-enforcement-grant-program.html':
# BODYFIELD_SPAN_XPATH,
# 'hwy-safety/grants/ffy2017-hsd-grant-opportunities.html':
# BODYFIELD_SPAN_XPATH,
# 'hwy-safety/grants/ffy-2017-step.html': BODYFIELD_SPAN_XPATH,
# 'hwy-safety/grants/highway-safety-grants-public-records.html':
# BODYFIELD_SPAN_XPATH
# }
#
# Path: bidwire/scrapers/massgov/results_page_scraper.py
# SITE_ROOT = 'https://www.mass.gov'
# def scrape_results_page(page_str, xpath_list):
. Output only the next line. | self.url_dict = url_scraper_dict.MASSGOV_DICT |
Next line prediction: <|code_start|>
log = logging.getLogger(__name__)
URL_PREFIX = 'http://www.mass.gov/eopss/funding-and-training/'
class MassGovEOPSSScraper(BaseScraper):
def __init__(self):
self.url_dict = url_scraper_dict.MASSGOV_DICT
def get_site(self):
return Document.Site.MASSGOV_EOPSS
def scrape(self, session):
"""Iterates through all the sites in url_dict to extract new documents.
This is implemented as follows:
1. Download each of the pages.
2. Extract the URLs from the pages.
3. Check which of those URLs are not yet in our database.
4. For each of the URLs that are not yet in our database,
add them as a new Bid object to the database.
"""
scraper = scrapelib.Scraper()
for url, xpaths in self.url_dict.items():
page = scraper.get(URL_PREFIX + url)
# doc_ids is dictionary: relative URL => title of doc
doc_ids = \
<|code_end|>
. Use current file imports:
(from document import Document, get_new_urls
from .base_scraper import BaseScraper
from .massgov import url_scraper_dict
from .massgov import results_page_scraper
import logging
import scrapelib)
and context including class names, function names, or small code snippets from other files:
# Path: bidwire/scrapers/base_scraper.py
# class BaseScraper(metaclass=abc.ABCMeta):
# """The interface that must be implemented by all scrapers."""
#
# @abc.abstractmethod
# def scrape(self, session):
# """
# This method performs all scraping for this scraper. Must be implemented
# by subclasses.
#
# Arguments:
# session -- database session to use for persisting items
# """
# pass
#
# Path: bidwire/scrapers/massgov/url_scraper_dict.py
# UL_CATEGORY_LI = '//ul[@class="category"]/li'
# H2_A_TITLELINK = './h2/a[@class="titlelink"]'
# SPAN_A_TITLELINK = './span/a[@class="titlelink"]'
# DIV_BODYFIELD_P = '//div[contains(@class,"bodyfield")]/p'
# CATEGORY_H2_XPATH = [ UL_CATEGORY_LI, H2_A_TITLELINK ]
# BODYFIELD_SPAN_XPATH = [ DIV_BODYFIELD_P, SPAN_A_TITLELINK ]
# MASSGOV_DICT = {
# 'homeland-sec/grants/docs/':
# [
# UL_CATEGORY_LI,
# './h2/span/a[@class="titlelink"]'
# ],
# 'homeland-sec/grants/hs-grant-guidance-and-policies.html':
# BODYFIELD_SPAN_XPATH,
# 'homeland-sec/grants/standard-documents.html':
# [
# '//div[contains(@class,"bodyfield")]/ul/li',
# SPAN_A_TITLELINK
# ],
# 'law-enforce/grants/': CATEGORY_H2_XPATH,
# 'law-enforce/grants/2017-muni-public-safety-staffing-grant.html':
# BODYFIELD_SPAN_XPATH,
# 'law-enforce/grants/le-grants-public-records.html':
# BODYFIELD_SPAN_XPATH,
# 'justice-and-prev/grants/': CATEGORY_H2_XPATH,
# 'justice-and-prev/grants/bgp/': CATEGORY_H2_XPATH,
# 'hwy-safety/grants/': CATEGORY_H2_XPATH,
# 'hwy-safety/grants/ffy-2017-traffic-enforcement-grant-program.html':
# BODYFIELD_SPAN_XPATH,
# 'hwy-safety/grants/ffy2017-hsd-grant-opportunities.html':
# BODYFIELD_SPAN_XPATH,
# 'hwy-safety/grants/ffy-2017-step.html': BODYFIELD_SPAN_XPATH,
# 'hwy-safety/grants/highway-safety-grants-public-records.html':
# BODYFIELD_SPAN_XPATH
# }
#
# Path: bidwire/scrapers/massgov/results_page_scraper.py
# SITE_ROOT = 'https://www.mass.gov'
# def scrape_results_page(page_str, xpath_list):
. Output only the next line. | results_page_scraper.scrape_results_page(page.content, xpaths) |
Predict the next line after this snippet: <|code_start|>
class MassGovNotifier(BaseNotifier):
def get_site(self):
return Document.Site.MASSGOV_EOPSS
def get_listings_pre_text(self, items_length):
formatted_text = "{} new Funding and Training documents" \
.format(items_length)
return "We have found " + formatted_text + " since we last sent " + \
" you an update: "
def make_item_body(self, doc):
<|code_end|>
using the current file's imports:
from .base_notifier import BaseNotifier
from .notifier_utils import make_doc_item_body
from document import Document
and any relevant context from other files:
# Path: bidwire/notifiers/base_notifier.py
# class BaseNotifier:
# def __init__(self):
# self.site_name = self.get_site().value
#
# # TODO(anaulin): Remove this method, and replace it with setting the
# # site_name in each constructor.
# def get_site(self):
# """Identifies the site type of the notifier
#
# Returns:
# site -- object of type Bid.Site
# """
# raise NotImplementedError
#
# def get_listings_pre_text(self, items_length):
# """Heading text before listings are displayed
#
# Arguments:
# bids_length -- number of new bids in the email
#
# Returns:
# text -- string of text preceding the listings
# """
# raise NotImplementedError
#
# def make_item_body(self, item):
# """Returns the HTML-formatted item for the new item list, as string."""
# raise NotImplementedError
#
# def send_new_items_notification(self, bids, recipients):
# log.info("Sending notifications to {} about bids {}"
# .format(recipients, bids))
# subject = "Changes detected on {}".format(self.site_name)
# send_email(subject, self.make_email_body(bids), recipients)
#
# def make_email_body(self, items):
# return make_html_body(
# items,
# self.make_item_body,
# pre_list_text=self.get_listings_pre_text(len(items))
# )
#
# Path: bidwire/notifiers/notifier_utils.py
# def make_doc_item_body(document):
# """Returns the HTML for one Document item"""
# doc, tag, text = Doc().tagtext()
# with tag('strong'):
# with tag('a', href=document.url):
# text(document.title)
# return doc.getvalue()
. Output only the next line. | return make_doc_item_body(doc) |
Predict the next line after this snippet: <|code_start|>
class KnoxCoTNAgendaNotifier(BaseNotifier):
def get_site(self):
return Document.Site.KNOX_CO_TN_AGENDAS
def get_listings_pre_text(self, items_length):
return ("We have found {} new documents ".format(items_length) +
"since we last sent you an update:")
def make_item_body(self, doc):
<|code_end|>
using the current file's imports:
from .base_notifier import BaseNotifier
from .notifier_utils import make_doc_item_body
from document import Document
and any relevant context from other files:
# Path: bidwire/notifiers/base_notifier.py
# class BaseNotifier:
# def __init__(self):
# self.site_name = self.get_site().value
#
# # TODO(anaulin): Remove this method, and replace it with setting the
# # site_name in each constructor.
# def get_site(self):
# """Identifies the site type of the notifier
#
# Returns:
# site -- object of type Bid.Site
# """
# raise NotImplementedError
#
# def get_listings_pre_text(self, items_length):
# """Heading text before listings are displayed
#
# Arguments:
# bids_length -- number of new bids in the email
#
# Returns:
# text -- string of text preceding the listings
# """
# raise NotImplementedError
#
# def make_item_body(self, item):
# """Returns the HTML-formatted item for the new item list, as string."""
# raise NotImplementedError
#
# def send_new_items_notification(self, bids, recipients):
# log.info("Sending notifications to {} about bids {}"
# .format(recipients, bids))
# subject = "Changes detected on {}".format(self.site_name)
# send_email(subject, self.make_email_body(bids), recipients)
#
# def make_email_body(self, items):
# return make_html_body(
# items,
# self.make_item_body,
# pre_list_text=self.get_listings_pre_text(len(items))
# )
#
# Path: bidwire/notifiers/notifier_utils.py
# def make_doc_item_body(document):
# """Returns the HTML for one Document item"""
# doc, tag, text = Doc().tagtext()
# with tag('strong'):
# with tag('a', href=document.url):
# text(document.title)
# return doc.getvalue()
. Output only the next line. | return make_doc_item_body(doc) |
Using the snippet: <|code_start|>
# TODO(anaulin): Remove this method, and replace it with setting the
# site_name in each constructor.
def get_site(self):
"""Identifies the site type of the notifier
Returns:
site -- object of type Bid.Site
"""
raise NotImplementedError
def get_listings_pre_text(self, items_length):
"""Heading text before listings are displayed
Arguments:
bids_length -- number of new bids in the email
Returns:
text -- string of text preceding the listings
"""
raise NotImplementedError
def make_item_body(self, item):
"""Returns the HTML-formatted item for the new item list, as string."""
raise NotImplementedError
def send_new_items_notification(self, bids, recipients):
log.info("Sending notifications to {} about bids {}"
.format(recipients, bids))
subject = "Changes detected on {}".format(self.site_name)
<|code_end|>
, determine the next line of code. You have imports:
import logging
import os
import sendgrid
import bidwire_settings
from sendgrid.helpers.mail import *
from yattag import Doc
from .notifier_utils import send_email, make_html_body
and context (class names, function names, or code) available:
# Path: bidwire/notifiers/notifier_utils.py
# def send_email(subject, mail_body, recipients):
# log.info("Sending email to recipients {}".format(recipients))
# sg = sendgrid.SendGridAPIClient(apikey=bidwire_settings.SENDGRID_API_KEY)
# from_email = Email(bidwire_settings.ADMIN_EMAIL)
# content = Content("text/html", mail_body)
# for recipient in recipients:
# to_email = Email(recipient)
# mail = Mail(from_email, subject, to_email, content)
# response = sg.client.mail.send.post(request_body=mail.get())
# log.info("Sendgrid response status: {}".format(response.status_code))
#
# def make_html_body(items, func_format_item, pre_list_text=None):
# """Returns an HTML email body listing all new items.
#
# The produced HTML looks like:
# <pre_list_text>
# <list of new items, generated calling func_format_item>
# <post_list_text>
#
# Arguments:
# items -- a list of new items to put in the email (can be any type)
# func_format_item -- a function that takes one item and returns an
# HTML-formatted version of this item
# pre_list_text -- any text to put before the item list
# post_list_text -- any text to put after the item list
#
# Returns:
# the resulting HTML, as a string
# """
# doc, tag, text = Doc().tagtext()
# if pre_list_text:
# with tag('p'):
# text(pre_list_text)
# with tag('ul'):
# for item in items:
# with tag('li'):
# # Append the HTML for the item to the doc as-is (don't escape)
# doc.asis(func_format_item(item))
# return doc.getvalue()
. Output only the next line. | send_email(subject, self.make_email_body(bids), recipients) |
Based on the snippet: <|code_start|> def get_site(self):
"""Identifies the site type of the notifier
Returns:
site -- object of type Bid.Site
"""
raise NotImplementedError
def get_listings_pre_text(self, items_length):
"""Heading text before listings are displayed
Arguments:
bids_length -- number of new bids in the email
Returns:
text -- string of text preceding the listings
"""
raise NotImplementedError
def make_item_body(self, item):
"""Returns the HTML-formatted item for the new item list, as string."""
raise NotImplementedError
def send_new_items_notification(self, bids, recipients):
log.info("Sending notifications to {} about bids {}"
.format(recipients, bids))
subject = "Changes detected on {}".format(self.site_name)
send_email(subject, self.make_email_body(bids), recipients)
def make_email_body(self, items):
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import os
import sendgrid
import bidwire_settings
from sendgrid.helpers.mail import *
from yattag import Doc
from .notifier_utils import send_email, make_html_body
and context (classes, functions, sometimes code) from other files:
# Path: bidwire/notifiers/notifier_utils.py
# def send_email(subject, mail_body, recipients):
# log.info("Sending email to recipients {}".format(recipients))
# sg = sendgrid.SendGridAPIClient(apikey=bidwire_settings.SENDGRID_API_KEY)
# from_email = Email(bidwire_settings.ADMIN_EMAIL)
# content = Content("text/html", mail_body)
# for recipient in recipients:
# to_email = Email(recipient)
# mail = Mail(from_email, subject, to_email, content)
# response = sg.client.mail.send.post(request_body=mail.get())
# log.info("Sendgrid response status: {}".format(response.status_code))
#
# def make_html_body(items, func_format_item, pre_list_text=None):
# """Returns an HTML email body listing all new items.
#
# The produced HTML looks like:
# <pre_list_text>
# <list of new items, generated calling func_format_item>
# <post_list_text>
#
# Arguments:
# items -- a list of new items to put in the email (can be any type)
# func_format_item -- a function that takes one item and returns an
# HTML-formatted version of this item
# pre_list_text -- any text to put before the item list
# post_list_text -- any text to put after the item list
#
# Returns:
# the resulting HTML, as a string
# """
# doc, tag, text = Doc().tagtext()
# if pre_list_text:
# with tag('p'):
# text(pre_list_text)
# with tag('ul'):
# for item in items:
# with tag('li'):
# # Append the HTML for the item to the doc as-is (don't escape)
# doc.asis(func_format_item(item))
# return doc.getvalue()
. Output only the next line. | return make_html_body( |
Given the code snippet: <|code_start|>
class KnoxvilleTNMeetingsNotifier(BaseNotifier):
def get_site(self):
return Document.Site.KNOXVILLE_TN_MEETINGS
def get_listings_pre_text(self, items_length):
return ("We have found {} new documents ".format(items_length) +
"since we last sent you an update:")
def make_item_body(self, doc):
<|code_end|>
, generate the next line using the imports in this file:
from .base_notifier import BaseNotifier
from .notifier_utils import make_doc_item_body
from document import Document
and context (functions, classes, or occasionally code) from other files:
# Path: bidwire/notifiers/base_notifier.py
# class BaseNotifier:
# def __init__(self):
# self.site_name = self.get_site().value
#
# # TODO(anaulin): Remove this method, and replace it with setting the
# # site_name in each constructor.
# def get_site(self):
# """Identifies the site type of the notifier
#
# Returns:
# site -- object of type Bid.Site
# """
# raise NotImplementedError
#
# def get_listings_pre_text(self, items_length):
# """Heading text before listings are displayed
#
# Arguments:
# bids_length -- number of new bids in the email
#
# Returns:
# text -- string of text preceding the listings
# """
# raise NotImplementedError
#
# def make_item_body(self, item):
# """Returns the HTML-formatted item for the new item list, as string."""
# raise NotImplementedError
#
# def send_new_items_notification(self, bids, recipients):
# log.info("Sending notifications to {} about bids {}"
# .format(recipients, bids))
# subject = "Changes detected on {}".format(self.site_name)
# send_email(subject, self.make_email_body(bids), recipients)
#
# def make_email_body(self, items):
# return make_html_body(
# items,
# self.make_item_body,
# pre_list_text=self.get_listings_pre_text(len(items))
# )
#
# Path: bidwire/notifiers/notifier_utils.py
# def make_doc_item_body(document):
# """Returns the HTML for one Document item"""
# doc, tag, text = Doc().tagtext()
# with tag('strong'):
# with tag('a', href=document.url):
# text(document.title)
# return doc.getvalue()
. Output only the next line. | return make_doc_item_body(doc) |
Predict the next line for this snippet: <|code_start|># Commenting out in since CISv1 is no longer up and running
# todo: this will need to get modified to reach out to person api v2
# import urllib
class API(object):
"""Retrieve data from person api as needed. Will eventually replace Mozillians API"""
def __init__(self):
"""
:param session: the flask session to update with userinfo
"""
<|code_end|>
with the help of current file imports:
import http.client
import json
from dashboard import config
and context from other files:
# Path: dashboard/config.py
# CONFIG = get_config()
# DEBUG = bool(CONFIG("debug", namespace="sso-dashboard", default="True"))
# TESTING = bool(CONFIG("testing", namespace="sso-dashboard", default="False"))
# CSRF_ENABLED = bool(CONFIG("csrf_enabled", default="True"))
# PERMANENT_SESSION = bool(
# CONFIG("permanent_session", namespace="sso-dashboard", default="True")
# )
# PERMANENT_SESSION_LIFETIME = int(
# CONFIG("permanent_session_lifetime", namespace="sso-dashboard", default="86400")
# )
# SESSION_COOKIE_HTTPONLY = bool(
# CONFIG("session_cookie_httponly", namespace="sso-dashboard", default="True")
# )
# LOGGER_NAME = CONFIG(
# "logger_name", namespace="sso-dashboard", default="sso-dashboard"
# )
# SECRET_KEY = CONFIG("secret_key", namespace="sso-dashboard")
# SERVER_NAME = CONFIG(
# "server_name", namespace="sso-dashboard", default="localhost:8000"
# )
# S3_BUCKET = CONFIG("s3_bucket", namespace="sso-dashboard")
# CDN = CONFIG(
# "cdn",
# namespace="sso-dashboard",
# default="https://cdn.{SERVER_NAME}".format(SERVER_NAME=SERVER_NAME),
# )
# FORBIDDEN_PAGE_PUBLIC_KEY = base64.b64decode(
# CONFIG("forbidden_page_public_key", namespace="sso-dashboard")
# )
# PREFERRED_URL_SCHEME = CONFIG(
# "preferred_url_scheme", namespace="sso-dashboard", default="https"
# )
# CONFIG = get_config()
# class Config(object):
# class DefaultConfig(object):
# class OIDCConfig(object):
# def __init__(self, app):
# def _init_env(self):
# def __init__(self):
# def client_id(self):
# def client_secret(self):
# def auth_endpoint(self):
# def token_endpoint(self):
# def userinfo_endpoint(self):
, which may contain function names, class names, or code. Output only the next line. | self.config = config.OIDCConfig() |
Given snippet: <|code_start|>"""Test to cover signed error message system."""
class ErrorTest(object):
public_key_file = os.path.join(
os.path.abspath(
os.path.dirname(__file__)
),
'data/public-signing-key.pem'
)
public_key = open(public_key_file).read()
sample_jwt_file = os.path.join(
os.path.abspath(
os.path.dirname(__file__)
),
'data/mfa-required-jwt'
)
sample_json_web_token = open(sample_jwt_file).read()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dashboard import oidc_auth
import os
and context:
# Path: dashboard/oidc_auth.py
# class OpenIDConnect(object):
# class tokenVerification(object):
# def __init__(self, configuration):
# def client_info(self):
# def get_oidc(self, app):
# def __init__(self, jws, public_key):
# def verify(self):
# def data(self):
# def error_code(self):
# def preferred_connection_name(self):
# def redirect_uri(self):
# def _get_connection_name(self, connection):
# def _signed(self, jwk):
# def _verified(self):
# def error_message(self):
# CONNECTION_NAMES = {
# "google-oauth2": "Google",
# "github": "GitHub",
# "firefoxaccounts": "Firefox Accounts",
# "Mozilla-LDAP-Dev": "LDAP",
# "Mozilla-LDAP": "LDAP",
# "email": "passwordless email",
# }
which might include code, classes, or functions. Output only the next line. | tv = oidc_auth.tokenVerification( |
Predict the next line for this snippet: <|code_start|>
logger = logging.getLogger(__name__)
class AuthorizeAPI(object):
def __init__(self, app, oidc_config):
self.app = app
self.algorithms = "RS256"
self.auth0_domain = oidc_config.OIDC_DOMAIN # auth.mozilla.auth0.com
self.audience = self._get_audience(self.app.config)
def _get_audience(self, app_config):
if app_config["SERVER_NAME"] == "localhost:5000":
return "https://sso.allizom.org"
else:
return "https://" + self.app.config.get(
"SERVER_NAME", "sso.mozilla.com"
) # sso.mozilla.com
# Format error response and append status code
def get_token_auth_header(self):
"""Obtains the Access Token from the Authorization Header
"""
auth = request.headers.get("Authorization", None)
if not auth:
<|code_end|>
with the help of current file imports:
import json
import logging
from functools import wraps
from flask import request
from flask import _request_ctx_stack
from six.moves.urllib.request import urlopen
from jose import jwt
from dashboard.api.exceptions import AuthError
and context from other files:
# Path: dashboard/api/exceptions.py
# class AuthError(Exception):
# def __init__(self, error, status_code):
# self.error = error
# self.status_code = status_code
, which may contain function names, class names, or code. Output only the next line. | raise AuthError( |
Given snippet: <|code_start|> else:
# This could mean a user is authing with non-ldap
return []
@property
def first_name(self):
"""Return user first_name."""
try:
return self.idvault_info.get("firstName", "")
except KeyError:
return ""
except AttributeError:
return ""
@property
def last_name(self):
"""Return user last_name."""
try:
return self.idvault_info.get("lastName", "")
except KeyError:
return ""
except AttributeError:
return ""
def user_identifiers(self):
"""Construct a list of potential user identifiers to match on."""
return [self.email(), self.userinfo["sub"]]
@property
def alerts(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import time
from faker import Faker
from dashboard.models import alert
and context:
# Path: dashboard/models/alert.py
# class Feedback(object):
# class Alert(object):
# class Rules(object):
# class FakeAlert(object):
# def __init__(self, alert_dict, alert_action):
# def connect_sns(self):
# def connect_ssm(self):
# def get_sns_arn(self):
# def _construct_alert(self):
# def send(self):
# def __init__(self):
# def has_actions(self, alert_dict):
# def has_escalation(self, alert_dict):
# def connect_dynamodb(self):
# def find_or_create_by(self, alert_dict, user_id):
# def create(self, alert_dict):
# def destroy(self, alert_id, user_id):
# def update(self, alert_id, alert_dict):
# def find(self, user_id):
# def _alert_is_expired(self, alert):
# def to_summary(self, alert_dict):
# def find_by_id(self, alert_id):
# def _create_alert_id(self):
# def __init__(self, userinfo, request):
# def run(self):
# def alert_firefox_out_of_date(self):
# def _firefox_info(self):
# def _user_firefox_version(self):
# def _version_to_dictionary(self, version_number):
# def _firefox_out_of_date(self):
# def __init__(self, user_id):
# def create_fake_alerts(self):
# def _create_fake_browser_alert(self):
# def _create_fake_geolocation_alert(self):
which might include code, classes, or functions. Output only the next line. | alerts = alert.Alert().find(user_id=self.userinfo["sub"]) |
Continue the code snippet: <|code_start|>
class Router(object):
def __init__(self, app, app_list):
self.app = app
<|code_end|>
. Use current file imports:
from flask import make_response
from flask import redirect
from flask import request
from dashboard.op import yaml_loader
and context (classes, functions, or code) from other files:
# Path: dashboard/op/yaml_loader.py
# class Application(object):
# def __init__(self, app_dict):
# def _load_authorized(self, session):
# def _load_data(self):
# def _render_data(self):
# def _alphabetize(self):
# def _find(self, name, path):
# def _has_vanity(self, app):
# def vanity_urls(self):
. Output only the next line. | self.url_list = yaml_loader.Application(app_list.apps_yml).vanity_urls() |
Based on the snippet: <|code_start|>"""Install siptools."""
def scripts_list():
"""Return list of command line tools from package pas.scripts."""
scripts = []
for modulename in os.listdir('siptools/scripts'):
if modulename == '__init__.py':
continue
if not modulename.endswith('.py'):
continue
modulename = modulename.replace('.py', '')
scriptname = modulename.replace('_', '-')
scripts.append(
'%s = siptools.scripts.%s:main' % (scriptname, modulename)
)
print(scripts)
return scripts
def main():
"""Install siptools."""
setup(
name='siptools',
packages=find_packages(exclude=['tests', 'tests.*']),
include_package_data=True,
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from setuptools import setup, find_packages
from version import get_version
and context (classes, functions, sometimes code) from other files:
# Path: version.py
# def get_version():
# d = os.path.dirname(__file__)
#
# if os.path.isdir(os.path.join(d, '../../.git')):
# # Get the version using "git describe".
# version_git = call_git_describe()
#
# # PEP 386 compatibility
# if version_git:
# version = "%s-%s" % (
# '.post'.join(version_git.split('-')[:2]),
# '-'.join(version_git.split('-')[2:])
# )
#
# print("Version number from GIT repository: {}".format(version))
# else:
# write_pkg_info()
# # Extract the version from the PKG-INFO file.
# with open(os.path.join(d, 'PKG-INFO')) as f:
# version = version_re.search(f.read()).group(1)
# print("Version number from PKG-INFO: {}".format(version))
#
# return version
. Output only the next line. | version=get_version(), |
Here is a snippet: <|code_start|> # If temporary file was written, it'll replace the existing reference
# file as a whole.
if os.path.exists('%s.tmp' % reference_file):
os.rename('%s.tmp' % reference_file, reference_file)
# pylint: disable=too-many-arguments
# pylint: disable=too-many-locals
def write_md(self, metadata, mdtype, mdtypeversion, othermdtype=None,
section=None, stdout=False):
"""
Wraps XML metadata into MD element and writes it to a lxml.etree XML
file in the workspace. The output filename is
<mdtype>-<hash>-othermd.xml,
where <mdtype> is the type of metadata given as parameter and <hash>
is a string generated from the metadata.
Serializing and hashing the root xml element can be rather time
consuming and as such this method should not be called for each file
unless more efficient way of separating files by the metadata can't
be easily implemented. This implementation should be done by the
subclasses of metadata_creator.
:metadata (Element): metadata XML element
:mdtype (string): Value of mdWrap MDTYPE attribute
:mdtypeversion (string): Value of mdWrap MDTYPEVERSION attribute
:othermdtype (string): Value of mdWrap OTHERMDTYPE attribute
:section (string): Type of mets metadata section
:stdout (boolean): Print also to stdout
:returns: md_id, filename - Metadata id and filename
"""
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import json
import six
import mets
import xml_helpers
from siptools.utils import generate_digest, encode_path
and context from other files:
# Path: siptools/utils.py
# def generate_digest(etree):
# """Generate MD5 digest from etree.
#
# Identical metadata must
# generate same digest even if attributes of any given element are
# ordered differently. Also some metadata sections contain unique
# identifiers that have to be removed if digest comparison is to work.
#
# This function creates a copy of the etree. All the attributes of the
# copy are removed and collected to a separete list with path
# information to the XML element the attributes belong to. This list
# is sorted and appended to the end of the serialized XML string
# without the attributes. Thus creating a string with all the original
# information except the information about attribute ordering inside
# any given XML element. This string is hashed and the digest
# returned. For some PREMIS metadata identifiers are also removed.
#
# :etree: XML element for which the MD5 hash is generated
# :returns: MD5 hash
# """
# # Creating copy of the original etree to avoid editing it
# root = copy_etree(etree)
# elem_tree = lxml.etree.ElementTree(root)
# attrib_list = []
#
# # Remove premis identifiers and linking elements before metadata
# # comparison
# elem_tree = _remove_elements(elem_tree, 'eventIdentifierValue')
# elem_tree = _remove_elements(elem_tree, 'agentIdentifierValue')
# elem_tree = _remove_elements(elem_tree, 'linkingAgentIdentifier')
#
# # pop all attributes
# for element in root.iter():
# attributes = element.attrib
# path = elem_tree.getpath(element)
# _pop_attributes(attributes, attrib_list, path)
#
# attrib_list.sort()
# xml_data = xml_helpers.utils.serialize(root)
#
# # Add the sorted attributes at the end of the serialized XML
# attr_data = b"".join([attr.encode("utf-8") for attr in attrib_list])
# xml_data = b"".join([xml_data, attr_data])
# return hashlib.md5(xml_data).hexdigest()
#
# def encode_path(path, suffix='', prefix='', safe=""):
# """
# Encode given path to URL encoding with given perfix and suffix.
#
# :path: Path to encode
# :suffix: Suffix to add
# :prefix: Prefix to add
# :safe: Characters safe from URL quoting
# :returns: Encoded string with given prefix and suffix
# """
# if isinstance(path, six.text_type):
# path = path.encode("utf-8")
#
# if isinstance(safe, six.text_type):
# safe = safe.encode("utf-8")
#
# quoted = quote_plus(path, safe=safe)
# return "{}{}{}".format(prefix, quoted, suffix)
, which may include functions, classes, or code. Output only the next line. | digest = generate_digest(metadata) |
Given the code snippet: <|code_start|> if os.path.exists('%s.tmp' % reference_file):
os.rename('%s.tmp' % reference_file, reference_file)
# pylint: disable=too-many-arguments
# pylint: disable=too-many-locals
def write_md(self, metadata, mdtype, mdtypeversion, othermdtype=None,
section=None, stdout=False):
"""
Wraps XML metadata into MD element and writes it to a lxml.etree XML
file in the workspace. The output filename is
<mdtype>-<hash>-othermd.xml,
where <mdtype> is the type of metadata given as parameter and <hash>
is a string generated from the metadata.
Serializing and hashing the root xml element can be rather time
consuming and as such this method should not be called for each file
unless more efficient way of separating files by the metadata can't
be easily implemented. This implementation should be done by the
subclasses of metadata_creator.
:metadata (Element): metadata XML element
:mdtype (string): Value of mdWrap MDTYPE attribute
:mdtypeversion (string): Value of mdWrap MDTYPEVERSION attribute
:othermdtype (string): Value of mdWrap OTHERMDTYPE attribute
:section (string): Type of mets metadata section
:stdout (boolean): Print also to stdout
:returns: md_id, filename - Metadata id and filename
"""
digest = generate_digest(metadata)
suffix = othermdtype if othermdtype else mdtype
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
import json
import six
import mets
import xml_helpers
from siptools.utils import generate_digest, encode_path
and context (functions, classes, or occasionally code) from other files:
# Path: siptools/utils.py
# def generate_digest(etree):
# """Generate MD5 digest from etree.
#
# Identical metadata must
# generate same digest even if attributes of any given element are
# ordered differently. Also some metadata sections contain unique
# identifiers that have to be removed if digest comparison is to work.
#
# This function creates a copy of the etree. All the attributes of the
# copy are removed and collected to a separete list with path
# information to the XML element the attributes belong to. This list
# is sorted and appended to the end of the serialized XML string
# without the attributes. Thus creating a string with all the original
# information except the information about attribute ordering inside
# any given XML element. This string is hashed and the digest
# returned. For some PREMIS metadata identifiers are also removed.
#
# :etree: XML element for which the MD5 hash is generated
# :returns: MD5 hash
# """
# # Creating copy of the original etree to avoid editing it
# root = copy_etree(etree)
# elem_tree = lxml.etree.ElementTree(root)
# attrib_list = []
#
# # Remove premis identifiers and linking elements before metadata
# # comparison
# elem_tree = _remove_elements(elem_tree, 'eventIdentifierValue')
# elem_tree = _remove_elements(elem_tree, 'agentIdentifierValue')
# elem_tree = _remove_elements(elem_tree, 'linkingAgentIdentifier')
#
# # pop all attributes
# for element in root.iter():
# attributes = element.attrib
# path = elem_tree.getpath(element)
# _pop_attributes(attributes, attrib_list, path)
#
# attrib_list.sort()
# xml_data = xml_helpers.utils.serialize(root)
#
# # Add the sorted attributes at the end of the serialized XML
# attr_data = b"".join([attr.encode("utf-8") for attr in attrib_list])
# xml_data = b"".join([xml_data, attr_data])
# return hashlib.md5(xml_data).hexdigest()
#
# def encode_path(path, suffix='', prefix='', safe=""):
# """
# Encode given path to URL encoding with given perfix and suffix.
#
# :path: Path to encode
# :suffix: Suffix to add
# :prefix: Prefix to add
# :safe: Characters safe from URL quoting
# :returns: Encoded string with given prefix and suffix
# """
# if isinstance(path, six.text_type):
# path = path.encode("utf-8")
#
# if isinstance(safe, six.text_type):
# safe = safe.encode("utf-8")
#
# quoted = quote_plus(path, safe=safe)
# return "{}{}{}".format(prefix, quoted, suffix)
. Output only the next line. | filename = encode_path("%s-%s-amd.xml" % (digest, suffix)) |
Given snippet: <|code_start|> creator.add_videomd_md("tests/data/video/valid_1.m1v")
creator.write()
# Check that mdreference and one VideoMD-amd files are created
assert os.path.isfile(os.path.join(testpath,
'create-videomd-md-references.jsonl'))
filepath = os.path.join(
testpath, '36260c626dac2f82359d7c22ef378392-VideoMD-amd.xml'
)
assert os.path.isfile(filepath)
def test_main_utf8_files(testpath, run_cli):
"""Test for ``main`` function with filenames that contain non-ascii
characters.
"""
# Create sample data directory with file that has non-ascii characters in
# filename
os.makedirs(os.path.join(testpath, 'data'))
relative_path = os.path.join('data', 'äöå.m1v')
full_path = os.path.join(testpath, relative_path)
shutil.copy('tests/data/video/valid_1.m1v', full_path)
# Call main function with encoded filename as parameter
run_cli(
create_videomd.main, [
'--workspace', testpath, '--base_path', testpath,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os.path
import json
import shutil
import pytest
import lxml.etree as ET
import siptools.scripts.create_videomd as create_videomd
from siptools.utils import fsencode_path, read_md_references
and context:
# Path: siptools/utils.py
# def fsencode_path(filename):
# """
# Encode Unicode filenames using the file system encoding.
#
# :filename: File path to encode
# :returns: Encoded path
# :raises: TypeError if wrong type given
# """
# if isinstance(filename, six.text_type):
# return filename.encode(encoding=sys.getfilesystemencoding())
# if isinstance(filename, six.binary_type):
# return filename
#
# raise TypeError("Value is not a (byte) string")
#
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
which might include code, classes, or functions. Output only the next line. | fsencode_path(relative_path) |
Predict the next line for this snippet: <|code_start|> assert os.path.isfile(os.path.join(testpath,
'create-videomd-md-references.jsonl'))
filepath = os.path.join(
testpath, '36260c626dac2f82359d7c22ef378392-VideoMD-amd.xml'
)
assert os.path.isfile(filepath)
def test_main_utf8_files(testpath, run_cli):
"""Test for ``main`` function with filenames that contain non-ascii
characters.
"""
# Create sample data directory with file that has non-ascii characters in
# filename
os.makedirs(os.path.join(testpath, 'data'))
relative_path = os.path.join('data', 'äöå.m1v')
full_path = os.path.join(testpath, relative_path)
shutil.copy('tests/data/video/valid_1.m1v', full_path)
# Call main function with encoded filename as parameter
run_cli(
create_videomd.main, [
'--workspace', testpath, '--base_path', testpath,
fsencode_path(relative_path)
]
)
# Check that filename is found in md-reference file.
<|code_end|>
with the help of current file imports:
import os.path
import json
import shutil
import pytest
import lxml.etree as ET
import siptools.scripts.create_videomd as create_videomd
from siptools.utils import fsencode_path, read_md_references
and context from other files:
# Path: siptools/utils.py
# def fsencode_path(filename):
# """
# Encode Unicode filenames using the file system encoding.
#
# :filename: File path to encode
# :returns: Encoded path
# :raises: TypeError if wrong type given
# """
# if isinstance(filename, six.text_type):
# return filename.encode(encoding=sys.getfilesystemencoding())
# if isinstance(filename, six.binary_type):
# return filename
#
# raise TypeError("Value is not a (byte) string")
#
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
, which may contain function names, class names, or code. Output only the next line. | refs = read_md_references(testpath, 'create-videomd-md-references.jsonl') |
Given the following code snippet before the placeholder: <|code_start|>
filepath = os.path.join(
testpath, 'eae4d239422e21f3a8cfa57bb2afcb9e-AudioMD-amd.xml'
# testpath, '704fbd57169eac3af9388e03c89dd919-AudioMD-amd.xml'
# testpath, '4dab7d9d5bab960188ea0f25e478cb17-AudioMD-amd.xml'
)
assert os.path.isfile(filepath)
def test_main_utf8_files(testpath, run_cli):
"""Test for ``main`` function with filenames that contain non-ascii
characters.
"""
# Create sample data directory with file that has non-ascii characters in
# filename
os.makedirs(os.path.join(testpath, 'data'))
relative_path = os.path.join('data', 'äöå.wav')
full_path = os.path.join(testpath, relative_path)
shutil.copy('tests/data/audio/valid__wav.wav', full_path)
# Call main function with encoded filename as parameter
run_cli(
create_audiomd.main, [
'--workspace', testpath, '--base_path', testpath,
relative_path.encode(sys.getfilesystemencoding())
]
)
# Check that filename is found in amd-reference file.
<|code_end|>
, predict the next line using imports from the current file:
import io
import os.path
import json
import shutil
import sys
import lxml.etree as ET
import pytest
import siptools.scripts.create_audiomd as create_audiomd
from siptools.utils import read_md_references
and context including class names, function names, and sometimes code from other files:
# Path: siptools/utils.py
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
. Output only the next line. | refs = read_md_references(testpath, 'create-audiomd-md-references.jsonl') |
Next line prediction: <|code_start|>
def get_amd_file(path):
"""Get id"""
refs = read_md_references(path, 'define-xml-schemas-md-references.jsonl')
reference = refs['.']
amdrefs = reference['md_ids']
output = []
for amdref in amdrefs:
output_file = os.path.join(
path, amdref[1:] + '-PREMIS%3AOBJECT-amd.xml')
if os.path.exists(output_file):
output.append(output_file)
return output
def test_define_xml_schemas_ok(testpath, run_cli):
"""Test define_xml_schemas.main funtion with valid test data. The
test assert that a PREMIS XML file has been created and linked to
from the references json file and that the XML metadata is as
expected.
"""
input_file = 'tests/data/mets_valid_minimal.xml'
arguments = ['--workspace', testpath,
'--uri_pairs', 'http://localhost/my-uri', input_file,
'--uri_pairs', 'my-path', input_file]
<|code_end|>
. Use current file imports:
(import os
import lxml.etree as ET
from siptools.scripts import define_xml_schemas
from siptools.utils import read_md_references
from siptools.xml.mets import NAMESPACES)
and context including class names, function names, or small code snippets from other files:
# Path: siptools/scripts/define_xml_schemas.py
# def main(**kwargs):
# def define_schemas(uri_pairs,
# base_path='.',
# workspace='./workspace/',
# stdout=False):
# def add_premis_md(self, schemas):
# def write(self, mdtype="PREMIS:OBJECT", mdtypeversion="2.3",
# othermdtype=None, section=None, stdout=False,
# file_metadata_dict=None,
# ref_file="define-xml-schemas-md-references.jsonl"):
# def create_premis_representation(schemas):
# def _check_filepaths(schemas=None, base='.'):
# class PremisCreator(MetsSectionCreator):
# RETVAL = main() # pylint: disable=no-value-for-parameter
#
# Path: siptools/utils.py
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
#
# Path: siptools/xml/mets.py
# NAMESPACES = {
# 'mets': 'http://www.loc.gov/METS/',
# 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
# 'premis': 'info:lc/xmlns/premis-v2',
# 'fi': 'http://digitalpreservation.fi/schemas/mets/fi-extensions',
# 'xlink': 'http://www.w3.org/1999/xlink',
# 'mix': 'http://www.loc.gov/mix/v20',
# 'ead3': 'http://ead3.archivists.org/schema/',
# 'addml': 'http://www.arkivverket.no/standarder/addml',
# 'audiomd': 'http://www.loc.gov/audioMD/',
# 'videomd': 'http://www.loc.gov/videoMD/'
# }
. Output only the next line. | run_cli(define_xml_schemas.main, arguments) |
Continue the code snippet: <|code_start|>
amdrefs = reference['md_ids']
output = []
for amdref in amdrefs:
output_file = os.path.join(
path, amdref[1:] + '-PREMIS%3AOBJECT-amd.xml')
if os.path.exists(output_file):
output.append(output_file)
return output
def test_define_xml_schemas_ok(testpath, run_cli):
"""Test define_xml_schemas.main funtion with valid test data. The
test assert that a PREMIS XML file has been created and linked to
from the references json file and that the XML metadata is as
expected.
"""
input_file = 'tests/data/mets_valid_minimal.xml'
arguments = ['--workspace', testpath,
'--uri_pairs', 'http://localhost/my-uri', input_file,
'--uri_pairs', 'my-path', input_file]
run_cli(define_xml_schemas.main, arguments)
output = get_amd_file(testpath)
tree = ET.parse(output[0])
root = tree.getroot()
assert len(root.xpath('/mets:mets/mets:amdSec/mets:techMD',
<|code_end|>
. Use current file imports:
import os
import lxml.etree as ET
from siptools.scripts import define_xml_schemas
from siptools.utils import read_md_references
from siptools.xml.mets import NAMESPACES
and context (classes, functions, or code) from other files:
# Path: siptools/scripts/define_xml_schemas.py
# def main(**kwargs):
# def define_schemas(uri_pairs,
# base_path='.',
# workspace='./workspace/',
# stdout=False):
# def add_premis_md(self, schemas):
# def write(self, mdtype="PREMIS:OBJECT", mdtypeversion="2.3",
# othermdtype=None, section=None, stdout=False,
# file_metadata_dict=None,
# ref_file="define-xml-schemas-md-references.jsonl"):
# def create_premis_representation(schemas):
# def _check_filepaths(schemas=None, base='.'):
# class PremisCreator(MetsSectionCreator):
# RETVAL = main() # pylint: disable=no-value-for-parameter
#
# Path: siptools/utils.py
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
#
# Path: siptools/xml/mets.py
# NAMESPACES = {
# 'mets': 'http://www.loc.gov/METS/',
# 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
# 'premis': 'info:lc/xmlns/premis-v2',
# 'fi': 'http://digitalpreservation.fi/schemas/mets/fi-extensions',
# 'xlink': 'http://www.w3.org/1999/xlink',
# 'mix': 'http://www.loc.gov/mix/v20',
# 'ead3': 'http://ead3.archivists.org/schema/',
# 'addml': 'http://www.arkivverket.no/standarder/addml',
# 'audiomd': 'http://www.loc.gov/audioMD/',
# 'videomd': 'http://www.loc.gov/videoMD/'
# }
. Output only the next line. | namespaces=NAMESPACES)) == 1 |
Here is a snippet: <|code_start|># encoding: utf-8
"""Unit tests for ``siptools.scripts.import_object`` module."""
from __future__ import unicode_literals
def get_amd_file(path,
input_file,
stream=None,
ref_file='import-object-md-references.jsonl',
suffix='-PREMIS%3AOBJECT-amd.xml'):
"""Get id."""
<|code_end|>
. Write the next line using the current file imports:
import datetime
import io
import os.path
import pytest
import six
import lxml.etree as ET
from siptools.scripts import import_object
from siptools.utils import fsdecode_path, load_scraper_json, read_md_references
from siptools.xml.mets import NAMESPACES
and context from other files:
# Path: siptools/scripts/import_object.py
# def import_object(**kwargs):
# """Import files to generate digital objects.
#
# If attributes charset, file_format, identifier, checksum or
# date_created are not given, then these are created automatically.
#
# :attributes: Given arguments
# filepaths: Files or a directory to import
# workspace: Workspace path
# base_path: Base path of digital objects
# skip_wellformed_check: True skips well-formedness
# checking
# charset: Character encoding of a file
# file_format: File format and version (tuple) of a file
# format_registry: Format registry name and value (tuple)
# identifier: File identifier type and value (tuple)
# checksum: Checksum algorithm and value (tuple)
# date_created: Creation date of a file
# order: Order number of a file
# event_datetime: Timestamp of the event
# event_target: The target of the event
# stdout: True prints output to stdout
# supplementary: Object type for supplementary files
# """
# attributes = _attribute_values(kwargs)
# # Loop files and create premis objects
# files = collect_filepaths(dirs=attributes["filepaths"],
# base=attributes["base_path"])
# creator = PremisCreator(attributes["workspace"])
# agents = []
# for filepath in files:
#
# # If the given path is an absolute path and base_path is current
# # path (i.e. not given), relpath will return ../../.. sequences,
# # if current path is not part of the absolute path. In such case
# # we will use the absolute path for filerel and omit base_path
# # relation.
# if attributes["base_path"] not in ['.']:
# filerel = os.path.relpath(filepath, attributes["base_path"])
# else:
# filerel = filepath
#
# properties = {}
# if attributes["order"] is not None:
# properties['order'] = six.text_type(attributes["order"])
# properties["supplementary"] = attributes["supplementary"]
#
# (streams, scraper_info) = creator.add_premis_md(
# filepath, attributes, filerel=filerel, properties=properties)
# for index in scraper_info:
# agents.append(_parse_scraper_tools(scraper_info[index]))
#
# grade = streams[0]['properties']['grade']
#
# is_native = grade in (
# file_scraper.defaults.BIT_LEVEL,
# file_scraper.defaults.BIT_LEVEL_WITH_RECOMMENDED
# )
#
# is_validated = (
# not bool(attributes["skip_wellformed_check"])
# and not is_native
# )
#
# creator.write(stdout=attributes["stdout"])
#
# # Create events documenting the technical metadata creation
# _create_events(
# workspace=attributes["workspace"],
# base_path=attributes["base_path"],
# filepaths=attributes["filepaths"],
# event_datetime=attributes["event_datetime"],
# event_target=attributes["event_target"],
# identification_event=not bool(attributes["file_format"]),
# validation_event=is_validated,
# checksum_event=not bool(attributes["checksum"]),
# agents=agents
# )
#
# Path: siptools/utils.py
# def fsdecode_path(filename):
# """
# Decode byte filenames using the file system encoding.
#
# :filename: File path to decode
# :returns: Decoded path
# :raises: TypeError if wrong type given
# """
# if isinstance(filename, six.binary_type):
# return filename.decode(encoding=sys.getfilesystemencoding())
# if isinstance(filename, six.text_type):
# return filename
#
# raise TypeError("Value is not a (byte) string")
#
# def load_scraper_json(json_name):
# """
# Load scraper stream from JSON file.
#
# :json_name: JSON file name
# :returns: Stream metadata from JSON file.
# """
# with open(json_name, 'rt') as json_file:
# streams = json.load(json_file)
# new_streams = {}
# for index in streams:
# new_streams[int(index)] = streams[index]
# new_streams[int(index)]["index"] = \
# int(new_streams[int(index)]["index"])
# return new_streams
#
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
#
# Path: siptools/xml/mets.py
# NAMESPACES = {
# 'mets': 'http://www.loc.gov/METS/',
# 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
# 'premis': 'info:lc/xmlns/premis-v2',
# 'fi': 'http://digitalpreservation.fi/schemas/mets/fi-extensions',
# 'xlink': 'http://www.w3.org/1999/xlink',
# 'mix': 'http://www.loc.gov/mix/v20',
# 'ead3': 'http://ead3.archivists.org/schema/',
# 'addml': 'http://www.arkivverket.no/standarder/addml',
# 'audiomd': 'http://www.loc.gov/audioMD/',
# 'videomd': 'http://www.loc.gov/videoMD/'
# }
, which may include functions, classes, or code. Output only the next line. | refs = read_md_references(path, ref_file) |
Given the following code snippet before the placeholder: <|code_start|>def test_create_mix_techmdfile(testpath):
"""Test for ``create_mix_techmdfile`` function. Creates MIX techMD for
three different image files. Two of the image files share the same MIX
metadata, so only two MIX techMD files should be created in workspace.
References to MIX techMD should be written into md-references.jsonl
file.
"""
creator = create_mix.MixCreator(testpath)
os.makedirs(os.path.join(testpath, 'data'))
for image in ['tiff1.tif', 'tiff2.tif', 'tiff1_compressed.tif']:
# copy sample image into data directory in temporary workspace
image_path = os.path.join(testpath, 'data/%s' % image)
shutil.copy('tests/data/images/%s' % image, image_path)
# Add metadata
creator.add_mix_md(image_path)
# Write metadata
creator.write()
# Count the MIX techMD files, i.e. the files with "NISOIMG-" prefix. There
# should two of them since tiff1.tif and tiff2.tif share the same MIX
# metadata.
files = os.listdir(testpath)
assert len([x for x in files if x.endswith('NISOIMG-amd.xml')]) == 2
# Count the references written to md-reference file. There should be
# one reference per image file.
<|code_end|>
, predict the next line using imports from the current file:
import os
import json
import shutil
import sys
import pytest
import siptools.scripts.create_mix as create_mix
from siptools.utils import read_md_references
and context including class names, function names, and sometimes code from other files:
# Path: siptools/utils.py
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
. Output only the next line. | refs = read_md_references(testpath, 'create-mix-md-references.jsonl') |
Next line prediction: <|code_start|>"""Command line tool for collecting agent metadata"""
from __future__ import unicode_literals, print_function
click.disable_unicode_literals_warning = True
@click.command()
@click.argument('agent_name', required=True, type=str)
@click.option('--workspace',
type=click.Path(exists=True),
default='./workspace',
metavar='<WORKSPACE PATH>',
help=("Directory where files are created. Defaults "
"to ./workspace/"))
@click.option('--agent_type', required=True,
type=click.Choice(PREMIS_AGENT_TYPES),
help=('The type of the agent. Possible values are: ' +
<|code_end|>
. Use current file imports:
(import os
import sys
import json
import hashlib
import click
from siptools.utils import list2str
from siptools.xml.premis import PREMIS_AGENT_TYPES)
and context including class names, function names, or small code snippets from other files:
# Path: siptools/utils.py
# def list2str(lst):
# """Create a human readable list of words from list of strings.
#
# :param lst: list of strings
# :returns: list formatted as single string
# """
# first_words = ['"{}"'.format(string) for string in lst[:-1]]
# last_word = '"{}"'.format(lst[-1])
# return ', '.join(first_words) + ', and ' + last_word
#
# Path: siptools/xml/premis.py
# PREMIS_AGENT_TYPES = ['software', 'hardware', 'person', 'organization']
. Output only the next line. | list2str(PREMIS_AGENT_TYPES))) |
Predict the next line after this snippet: <|code_start|>"""Command line tool for collecting agent metadata"""
from __future__ import unicode_literals, print_function
click.disable_unicode_literals_warning = True
@click.command()
@click.argument('agent_name', required=True, type=str)
@click.option('--workspace',
type=click.Path(exists=True),
default='./workspace',
metavar='<WORKSPACE PATH>',
help=("Directory where files are created. Defaults "
"to ./workspace/"))
@click.option('--agent_type', required=True,
<|code_end|>
using the current file's imports:
import os
import sys
import json
import hashlib
import click
from siptools.utils import list2str
from siptools.xml.premis import PREMIS_AGENT_TYPES
and any relevant context from other files:
# Path: siptools/utils.py
# def list2str(lst):
# """Create a human readable list of words from list of strings.
#
# :param lst: list of strings
# :returns: list formatted as single string
# """
# first_words = ['"{}"'.format(string) for string in lst[:-1]]
# last_word = '"{}"'.format(lst[-1])
# return ', '.join(first_words) + ', and ' + last_word
#
# Path: siptools/xml/premis.py
# PREMIS_AGENT_TYPES = ['software', 'hardware', 'person', 'organization']
. Output only the next line. | type=click.Choice(PREMIS_AGENT_TYPES), |
Next line prediction: <|code_start|>"""Command line tool for creating tar file from SIP directory"""
from __future__ import unicode_literals, print_function
click.disable_unicode_literals_warning = True
@click.command()
@click.argument('dir_to_tar', type=click.Path(exists=True))
@click.option(
'--tar_filename', type=str, default='sip.tar',
metavar='<TAR FILE>',
help="Filename for tar. Default is sip.tar")
def main(dir_to_tar, tar_filename):
"""Create tar file from SIP directory.
DIR_TO_TAR: Directory to be added in the TAR file.
"""
return compress(dir_to_tar, tar_filename)
def compress(dir_to_tar, tar_filename):
"""
Create tar file from SIP directory.
:dir_to_tar: Directory to pack in tar package
:tar_filename: File name of the tar file
"""
<|code_end|>
. Use current file imports:
(import sys
import subprocess
import click
from siptools.utils import fsencode_path)
and context including class names, function names, or small code snippets from other files:
# Path: siptools/utils.py
# def fsencode_path(filename):
# """
# Encode Unicode filenames using the file system encoding.
#
# :filename: File path to encode
# :returns: Encoded path
# :raises: TypeError if wrong type given
# """
# if isinstance(filename, six.text_type):
# return filename.encode(encoding=sys.getfilesystemencoding())
# if isinstance(filename, six.binary_type):
# return filename
#
# raise TypeError("Value is not a (byte) string")
. Output only the next line. | command = ['tar', '-cvvf', fsencode_path(tar_filename), '.'] |
Given snippet: <|code_start|> ],
ids=("Agent with minimum data",
"Agent with event role",
"Agent with given identifier that should be written to the output",
"Agent_version that shouldn't be written due to the agent_type",
"Agent with agent_version that should be written",
"Multiple agents, all should be written to the same output"))
# pylint: disable=too-many-arguments
def test_create_agent_ok(
testpath, run_cli, given_identifier, role, version, ag_type, ag_count):
"""Test that main function produces a json file with
correct data for different input.
"""
for i in range(ag_count):
agent_name = 'test-agent%i' % i
cli_args = [
agent_name,
'--workspace', testpath,
'--agent_type', ag_type,
'--agent_version', version,
'--agent_note', 'Notes',
'--create_agent_file', 'test-file',
]
if given_identifier:
cli_args.append('--agent_identifier')
cli_args.append('test')
cli_args.append('foo')
if role:
cli_args.append('--agent_role')
cli_args.append(role)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import io
import json
import pytest
from siptools.scripts import create_agent
and context:
# Path: siptools/scripts/create_agent.py
# def create_agent(**kwargs):
# """
# The script collects provenance metadata for the package. The metadata
# consists of information about the agent and linking information to
# the event that the agent relates to. The result of this function is
# a JSON file containing metadata about the agent and its role in
# relation to the event.
# If the given JSON file exists, the new agent metadata is appended
# to the existing data, allowing for multiple agents to be related to
# the same event.
#
# :kwargs: Given arguments
# agent_name: agent name
# workspace: Workspace path
# agent_type: agent type
# agent_version: Agent version if agent type is "software"
# agent_role: agent role in relation to the event
# agent_note: Agent note as a string
# agent_identifier: Agent identifier type and value (tuple)
# create_agent_file: The name of the JSON file that collects
# agent information in relation to the
# event
#
# :returns: The agent identifier value as a string
# """
# attributes = _attribute_values(kwargs)
#
# agent_dict = {
# "identifier_type": attributes["agent_identifier"][0],
# "identifier_value": attributes["agent_identifier"][1],
# "agent_name": attributes["agent_name"],
# "agent_type": attributes["agent_type"],
# }
# if attributes["agent_version"]:
# agent_dict["agent_version"] = attributes["agent_version"]
# if attributes["agent_role"]:
# agent_dict["agent_role"] = attributes["agent_role"]
# if attributes["agent_note"]:
# agent_dict["agent_note"] = attributes["agent_note"]
#
# output_path = os.path.join(
# attributes["workspace"],
# attributes["create_agent_file"] + '-AGENTS-amd.json')
#
# agents_list = []
# if os.path.exists(output_path):
# with open(output_path) as in_file:
# agents_list = json.load(in_file)
#
# agents_list.append(agent_dict)
#
# with open(output_path, 'wt') as outfile:
# json.dump(agents_list, outfile, indent=4)
#
# print(
# "Collected agent metadata with identifier %s" %
# attributes["agent_identifier"][1])
#
# return attributes["agent_identifier"][1]
which might include code, classes, or functions. Output only the next line. | run_cli(create_agent.main, cli_args) |
Based on the snippet: <|code_start|>
# Check individual elements
tags = ["fieldSeparatingChar", "charset", "recordSeparator", "quotingChar"]
vals = [";", "UTF-8", "CR+LF", '"']
for i, tag in enumerate(tags):
val = addml_etree.find(ADDML_NS + tag).text
assert val == vals[i]
# Check that flatFile element is not added
assert addml_etree.find(ADDML_NS + "flatFile") is None
# Check that correct amount of headers is created
assert len(addml_etree.find(ADDML_NS + "fieldDefinitions")) == 3
@pytest.mark.parametrize('is_header', [False, True])
def test_create_addml_with_flatfile(is_header):
"""Tests that ``create_addml`` adds flatFile element if optional
parameter flatfile_name is provided.
"""
addml_etree = create_addml.create_addml_metadata(
csv_file=CSV_FILE, delimiter=DELIMITER, isheader=is_header,
charset=CHARSET, record_separator=RECORDSEPARATOR,
quoting_char=QUOTINGCHAR, flatfile_name="path/to/test"
)
# Check that URL encoded path is written to flatFile element
flatfile = addml_etree.find(ADDML_NS + "flatFile")
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import pytest
import lxml.etree as ET
import siptools.scripts.create_addml as create_addml
from siptools.utils import decode_path, read_md_references
and context (classes, functions, sometimes code) from other files:
# Path: siptools/utils.py
# def decode_path(path, suffix=''):
# """
# Decode given path from URL encoding and remove given suffix.
#
# :path: Path to decode
# :suffix: Suffix to remove
# :returns: Decoded string without given suffix
# """
# if six.PY2:
# path = unquote_plus(path.encode("utf-8")).decode("utf-8")
# else:
# path = unquote_plus(path)
#
# if path.endswith(suffix):
# path = path.replace(suffix, '', 1)
# return path
#
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
. Output only the next line. | assert decode_path(flatfile.get("name")) == "path/to/test" |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.mark.parametrize("file_, base_path", [
('tests/data/csvfile.csv', ''),
('./tests/data/csvfile.csv', ''),
('csvfile.csv', 'tests/data'),
('./csvfile.csv', './tests/data'),
('data/csvfile.csv', 'absolute')
])
def test_paths(testpath, file_, base_path, run_cli):
""" Test the following path arguments:
(1) Path without base_path
(2) Path without base bath, but with './'
(3) Path with base path
(4) Path with base path and with './'
(5) Absolute base path
"""
if 'absolute' in base_path:
base_path = os.path.join(os.getcwd(), 'tests')
if base_path != '':
run_cli(create_addml.main, [
'--delim', DELIMITER, '--charset', CHARSET,
'--sep', RECORDSEPARATOR, '--quot', QUOTINGCHAR,
'--workspace', testpath, '--base_path', base_path, file_])
else:
run_cli(create_addml.main, [
'--delim', DELIMITER, '--charset', CHARSET,
'--sep', RECORDSEPARATOR, '--quot', QUOTINGCHAR,
'--workspace', testpath, file_])
<|code_end|>
, predict the next line using imports from the current file:
import os
import pytest
import lxml.etree as ET
import siptools.scripts.create_addml as create_addml
from siptools.utils import decode_path, read_md_references
and context including class names, function names, and sometimes code from other files:
# Path: siptools/utils.py
# def decode_path(path, suffix=''):
# """
# Decode given path from URL encoding and remove given suffix.
#
# :path: Path to decode
# :suffix: Suffix to remove
# :returns: Decoded string without given suffix
# """
# if six.PY2:
# path = unquote_plus(path.encode("utf-8")).decode("utf-8")
# else:
# path = unquote_plus(path)
#
# if path.endswith(suffix):
# path = path.replace(suffix, '', 1)
# return path
#
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
. Output only the next line. | references = read_md_references(testpath, |
Based on the snippet: <|code_start|> mets_element.append(metshdr)
for element in elements:
mets_element.append(element)
lxml.etree.cleanup_namespaces(mets_element)
return lxml.etree.ElementTree(mets_element)
def clean_metsparts(path):
"""
Clean mets parts from workspace.
:path: Workspace path
"""
for root, _, files in os.walk(path, topdown=False):
for name in files:
if (name.endswith(('-amd.xml', 'dmdsec.xml', 'structmap.xml',
'filesec.xml', 'rightsmd.xml',
'md-references.jsonl',
'-scraper.json', '-amd.json'))):
os.remove(os.path.join(root, name))
def copy_objects(workspace, data_dir):
"""
Copy digital objects to workspace.
:workspace: Workspace path
:data_dir: Path to digital objects
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
import os
import sys
import uuid
import six
import click
import lxml.etree
import mets
import xml_helpers.utils as xml_utils
from shutil import copyfile
from siptools.utils import get_objectlist, read_md_references
from siptools.xml.mets import (METS_CATALOG, METS_PROFILE, METS_SPECIFICATION,
NAMESPACES, RECORD_STATUS_TYPES, mets_extend)
from scandir import scandir # Python 2
from os import scandir # Python 3+
and context (classes, functions, sometimes code) from other files:
# Path: siptools/utils.py
# def get_objectlist(refs_dict, file_path=None):
# """Get unique and sorted list of files or streams.
#
# Files or streasm are read from md-references.jsonl
#
# :refs_dict: Dictionary of objects
# :file_path: If given, finds streams of the given file.
# If None, finds a sorted list all file paths.
# :returns: Sorted list of files, or streams of a given file
# """
# objectset = set()
# if file_path is not None:
# for stream in refs_dict[file_path]['streams']:
# objectset.add(stream)
# elif refs_dict:
# for key, value in six.iteritems(refs_dict):
# if value['path_type'] == 'file':
# objectset.add(key)
#
# return sorted(objectset)
#
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
#
# Path: siptools/xml/mets.py
# METS_CATALOG = "1.7.3"
#
# METS_PROFILE = {
# 'ch': 'http://digitalpreservation.fi/mets-profiles/cultural-heritage',
# 'tpas': 'http://digitalpreservation.fi/mets-profiles/research-data',
# }
#
# METS_SPECIFICATION = "1.7.3"
#
# NAMESPACES = {
# 'mets': 'http://www.loc.gov/METS/',
# 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
# 'premis': 'info:lc/xmlns/premis-v2',
# 'fi': 'http://digitalpreservation.fi/schemas/mets/fi-extensions',
# 'xlink': 'http://www.w3.org/1999/xlink',
# 'mix': 'http://www.loc.gov/mix/v20',
# 'ead3': 'http://ead3.archivists.org/schema/',
# 'addml': 'http://www.arkivverket.no/standarder/addml',
# 'audiomd': 'http://www.loc.gov/audioMD/',
# 'videomd': 'http://www.loc.gov/videoMD/'
# }
#
# RECORD_STATUS_TYPES = [
# 'submission',
# 'update',
# 'dissemination'
# ]
#
# def mets_extend(mets_root, catalog=METS_CATALOG,
# specification=METS_SPECIFICATION, contentid=None,
# contractid=None):
# """Create METS ElementTree"""
#
# del mets_root.attrib['{%s}schemaLocation' % XSI_NS]
# mets_root.set('{%s}schemaLocation' % XSI_NS,
# NAMESPACES['mets'] + ' ' + METS_SCHEMA)
# mets_root.set('{%s}CATALOG' % FI_NS, catalog)
# mets_root.set('{%s}SPECIFICATION' % FI_NS, specification)
# if contentid:
# mets_root.set('{%s}CONTENTID' % FI_NS, contentid)
# if contractid:
# contractstr = six.text_type(contractid)
# mets_root.set('{%s}CONTRACTID' % FI_NS, contractstr)
#
# return mets_root
. Output only the next line. | files = get_objectlist(read_md_references( |
Next line prediction: <|code_start|> mets_element.append(metshdr)
for element in elements:
mets_element.append(element)
lxml.etree.cleanup_namespaces(mets_element)
return lxml.etree.ElementTree(mets_element)
def clean_metsparts(path):
"""
Clean mets parts from workspace.
:path: Workspace path
"""
for root, _, files in os.walk(path, topdown=False):
for name in files:
if (name.endswith(('-amd.xml', 'dmdsec.xml', 'structmap.xml',
'filesec.xml', 'rightsmd.xml',
'md-references.jsonl',
'-scraper.json', '-amd.json'))):
os.remove(os.path.join(root, name))
def copy_objects(workspace, data_dir):
"""
Copy digital objects to workspace.
:workspace: Workspace path
:data_dir: Path to digital objects
"""
<|code_end|>
. Use current file imports:
(import datetime
import os
import sys
import uuid
import six
import click
import lxml.etree
import mets
import xml_helpers.utils as xml_utils
from shutil import copyfile
from siptools.utils import get_objectlist, read_md_references
from siptools.xml.mets import (METS_CATALOG, METS_PROFILE, METS_SPECIFICATION,
NAMESPACES, RECORD_STATUS_TYPES, mets_extend)
from scandir import scandir # Python 2
from os import scandir # Python 3+)
and context including class names, function names, or small code snippets from other files:
# Path: siptools/utils.py
# def get_objectlist(refs_dict, file_path=None):
# """Get unique and sorted list of files or streams.
#
# Files or streasm are read from md-references.jsonl
#
# :refs_dict: Dictionary of objects
# :file_path: If given, finds streams of the given file.
# If None, finds a sorted list all file paths.
# :returns: Sorted list of files, or streams of a given file
# """
# objectset = set()
# if file_path is not None:
# for stream in refs_dict[file_path]['streams']:
# objectset.add(stream)
# elif refs_dict:
# for key, value in six.iteritems(refs_dict):
# if value['path_type'] == 'file':
# objectset.add(key)
#
# return sorted(objectset)
#
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
#
# Path: siptools/xml/mets.py
# METS_CATALOG = "1.7.3"
#
# METS_PROFILE = {
# 'ch': 'http://digitalpreservation.fi/mets-profiles/cultural-heritage',
# 'tpas': 'http://digitalpreservation.fi/mets-profiles/research-data',
# }
#
# METS_SPECIFICATION = "1.7.3"
#
# NAMESPACES = {
# 'mets': 'http://www.loc.gov/METS/',
# 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
# 'premis': 'info:lc/xmlns/premis-v2',
# 'fi': 'http://digitalpreservation.fi/schemas/mets/fi-extensions',
# 'xlink': 'http://www.w3.org/1999/xlink',
# 'mix': 'http://www.loc.gov/mix/v20',
# 'ead3': 'http://ead3.archivists.org/schema/',
# 'addml': 'http://www.arkivverket.no/standarder/addml',
# 'audiomd': 'http://www.loc.gov/audioMD/',
# 'videomd': 'http://www.loc.gov/videoMD/'
# }
#
# RECORD_STATUS_TYPES = [
# 'submission',
# 'update',
# 'dissemination'
# ]
#
# def mets_extend(mets_root, catalog=METS_CATALOG,
# specification=METS_SPECIFICATION, contentid=None,
# contractid=None):
# """Create METS ElementTree"""
#
# del mets_root.attrib['{%s}schemaLocation' % XSI_NS]
# mets_root.set('{%s}schemaLocation' % XSI_NS,
# NAMESPACES['mets'] + ' ' + METS_SCHEMA)
# mets_root.set('{%s}CATALOG' % FI_NS, catalog)
# mets_root.set('{%s}SPECIFICATION' % FI_NS, specification)
# if contentid:
# mets_root.set('{%s}CONTENTID' % FI_NS, contentid)
# if contractid:
# contractstr = six.text_type(contractid)
# mets_root.set('{%s}CONTRACTID' % FI_NS, contractstr)
#
# return mets_root
. Output only the next line. | files = get_objectlist(read_md_references( |
Predict the next line after this snippet: <|code_start|> agent_role='CREATOR',
othertype='SOFTWARE'))
else:
agents = [mets.agent(attributes["organization_name"],
agent_role='CREATOR')]
# Create mets header
metshdr = mets.metshdr(attributes["create_date"],
attributes["last_moddate"],
attributes["record_status"],
agents)
# Collect elements from workspace XML files
elements = []
for entry in scandir(attributes["workspace"]):
if entry.name.endswith(('-amd.xml', 'dmdsec.xml',
'structmap.xml', 'filesec.xml',
'rightsmd.xml')) and entry.is_file():
element = lxml.etree.parse(entry.path).getroot()[0]
elements.append(element)
elements = mets.merge_elements('{%s}amdSec' % NAMESPACES['mets'], elements)
elements.sort(key=mets.order)
# Create METS element
mets_element = mets.mets(METS_PROFILE[attributes["mets_profile"]],
objid=attributes["objid"],
label=attributes["label"],
namespaces=NAMESPACES)
mets_element = mets_extend(mets_element,
<|code_end|>
using the current file's imports:
import datetime
import os
import sys
import uuid
import six
import click
import lxml.etree
import mets
import xml_helpers.utils as xml_utils
from shutil import copyfile
from siptools.utils import get_objectlist, read_md_references
from siptools.xml.mets import (METS_CATALOG, METS_PROFILE, METS_SPECIFICATION,
NAMESPACES, RECORD_STATUS_TYPES, mets_extend)
from scandir import scandir # Python 2
from os import scandir # Python 3+
and any relevant context from other files:
# Path: siptools/utils.py
# def get_objectlist(refs_dict, file_path=None):
# """Get unique and sorted list of files or streams.
#
# Files or streasm are read from md-references.jsonl
#
# :refs_dict: Dictionary of objects
# :file_path: If given, finds streams of the given file.
# If None, finds a sorted list all file paths.
# :returns: Sorted list of files, or streams of a given file
# """
# objectset = set()
# if file_path is not None:
# for stream in refs_dict[file_path]['streams']:
# objectset.add(stream)
# elif refs_dict:
# for key, value in six.iteritems(refs_dict):
# if value['path_type'] == 'file':
# objectset.add(key)
#
# return sorted(objectset)
#
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
#
# Path: siptools/xml/mets.py
# METS_CATALOG = "1.7.3"
#
# METS_PROFILE = {
# 'ch': 'http://digitalpreservation.fi/mets-profiles/cultural-heritage',
# 'tpas': 'http://digitalpreservation.fi/mets-profiles/research-data',
# }
#
# METS_SPECIFICATION = "1.7.3"
#
# NAMESPACES = {
# 'mets': 'http://www.loc.gov/METS/',
# 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
# 'premis': 'info:lc/xmlns/premis-v2',
# 'fi': 'http://digitalpreservation.fi/schemas/mets/fi-extensions',
# 'xlink': 'http://www.w3.org/1999/xlink',
# 'mix': 'http://www.loc.gov/mix/v20',
# 'ead3': 'http://ead3.archivists.org/schema/',
# 'addml': 'http://www.arkivverket.no/standarder/addml',
# 'audiomd': 'http://www.loc.gov/audioMD/',
# 'videomd': 'http://www.loc.gov/videoMD/'
# }
#
# RECORD_STATUS_TYPES = [
# 'submission',
# 'update',
# 'dissemination'
# ]
#
# def mets_extend(mets_root, catalog=METS_CATALOG,
# specification=METS_SPECIFICATION, contentid=None,
# contractid=None):
# """Create METS ElementTree"""
#
# del mets_root.attrib['{%s}schemaLocation' % XSI_NS]
# mets_root.set('{%s}schemaLocation' % XSI_NS,
# NAMESPACES['mets'] + ' ' + METS_SCHEMA)
# mets_root.set('{%s}CATALOG' % FI_NS, catalog)
# mets_root.set('{%s}SPECIFICATION' % FI_NS, specification)
# if contentid:
# mets_root.set('{%s}CONTENTID' % FI_NS, contentid)
# if contractid:
# contractstr = six.text_type(contractid)
# mets_root.set('{%s}CONTRACTID' % FI_NS, contractstr)
#
# return mets_root
. Output only the next line. | METS_CATALOG, |
Using the snippet: <|code_start|>"""Command line tool for creating METS document and copying files to workspace
directory.
"""
from __future__ import print_function, unicode_literals
try:
except ImportError:
click.disable_unicode_literals_warning = True
@click.command()
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import os
import sys
import uuid
import six
import click
import lxml.etree
import mets
import xml_helpers.utils as xml_utils
from shutil import copyfile
from siptools.utils import get_objectlist, read_md_references
from siptools.xml.mets import (METS_CATALOG, METS_PROFILE, METS_SPECIFICATION,
NAMESPACES, RECORD_STATUS_TYPES, mets_extend)
from scandir import scandir # Python 2
from os import scandir # Python 3+
and context (class names, function names, or code) available:
# Path: siptools/utils.py
# def get_objectlist(refs_dict, file_path=None):
# """Get unique and sorted list of files or streams.
#
# Files or streasm are read from md-references.jsonl
#
# :refs_dict: Dictionary of objects
# :file_path: If given, finds streams of the given file.
# If None, finds a sorted list all file paths.
# :returns: Sorted list of files, or streams of a given file
# """
# objectset = set()
# if file_path is not None:
# for stream in refs_dict[file_path]['streams']:
# objectset.add(stream)
# elif refs_dict:
# for key, value in six.iteritems(refs_dict):
# if value['path_type'] == 'file':
# objectset.add(key)
#
# return sorted(objectset)
#
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
#
# Path: siptools/xml/mets.py
# METS_CATALOG = "1.7.3"
#
# METS_PROFILE = {
# 'ch': 'http://digitalpreservation.fi/mets-profiles/cultural-heritage',
# 'tpas': 'http://digitalpreservation.fi/mets-profiles/research-data',
# }
#
# METS_SPECIFICATION = "1.7.3"
#
# NAMESPACES = {
# 'mets': 'http://www.loc.gov/METS/',
# 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
# 'premis': 'info:lc/xmlns/premis-v2',
# 'fi': 'http://digitalpreservation.fi/schemas/mets/fi-extensions',
# 'xlink': 'http://www.w3.org/1999/xlink',
# 'mix': 'http://www.loc.gov/mix/v20',
# 'ead3': 'http://ead3.archivists.org/schema/',
# 'addml': 'http://www.arkivverket.no/standarder/addml',
# 'audiomd': 'http://www.loc.gov/audioMD/',
# 'videomd': 'http://www.loc.gov/videoMD/'
# }
#
# RECORD_STATUS_TYPES = [
# 'submission',
# 'update',
# 'dissemination'
# ]
#
# def mets_extend(mets_root, catalog=METS_CATALOG,
# specification=METS_SPECIFICATION, contentid=None,
# contractid=None):
# """Create METS ElementTree"""
#
# del mets_root.attrib['{%s}schemaLocation' % XSI_NS]
# mets_root.set('{%s}schemaLocation' % XSI_NS,
# NAMESPACES['mets'] + ' ' + METS_SCHEMA)
# mets_root.set('{%s}CATALOG' % FI_NS, catalog)
# mets_root.set('{%s}SPECIFICATION' % FI_NS, specification)
# if contentid:
# mets_root.set('{%s}CONTENTID' % FI_NS, contentid)
# if contractid:
# contractstr = six.text_type(contractid)
# mets_root.set('{%s}CONTRACTID' % FI_NS, contractstr)
#
# return mets_root
. Output only the next line. | @click.argument('mets_profile', type=click.Choice(METS_PROFILE)) |
Continue the code snippet: <|code_start|> othertype='SOFTWARE'))
else:
agents = [mets.agent(attributes["organization_name"],
agent_role='CREATOR')]
# Create mets header
metshdr = mets.metshdr(attributes["create_date"],
attributes["last_moddate"],
attributes["record_status"],
agents)
# Collect elements from workspace XML files
elements = []
for entry in scandir(attributes["workspace"]):
if entry.name.endswith(('-amd.xml', 'dmdsec.xml',
'structmap.xml', 'filesec.xml',
'rightsmd.xml')) and entry.is_file():
element = lxml.etree.parse(entry.path).getroot()[0]
elements.append(element)
elements = mets.merge_elements('{%s}amdSec' % NAMESPACES['mets'], elements)
elements.sort(key=mets.order)
# Create METS element
mets_element = mets.mets(METS_PROFILE[attributes["mets_profile"]],
objid=attributes["objid"],
label=attributes["label"],
namespaces=NAMESPACES)
mets_element = mets_extend(mets_element,
METS_CATALOG,
<|code_end|>
. Use current file imports:
import datetime
import os
import sys
import uuid
import six
import click
import lxml.etree
import mets
import xml_helpers.utils as xml_utils
from shutil import copyfile
from siptools.utils import get_objectlist, read_md_references
from siptools.xml.mets import (METS_CATALOG, METS_PROFILE, METS_SPECIFICATION,
NAMESPACES, RECORD_STATUS_TYPES, mets_extend)
from scandir import scandir # Python 2
from os import scandir # Python 3+
and context (classes, functions, or code) from other files:
# Path: siptools/utils.py
# def get_objectlist(refs_dict, file_path=None):
# """Get unique and sorted list of files or streams.
#
# Files or streasm are read from md-references.jsonl
#
# :refs_dict: Dictionary of objects
# :file_path: If given, finds streams of the given file.
# If None, finds a sorted list all file paths.
# :returns: Sorted list of files, or streams of a given file
# """
# objectset = set()
# if file_path is not None:
# for stream in refs_dict[file_path]['streams']:
# objectset.add(stream)
# elif refs_dict:
# for key, value in six.iteritems(refs_dict):
# if value['path_type'] == 'file':
# objectset.add(key)
#
# return sorted(objectset)
#
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
#
# Path: siptools/xml/mets.py
# METS_CATALOG = "1.7.3"
#
# METS_PROFILE = {
# 'ch': 'http://digitalpreservation.fi/mets-profiles/cultural-heritage',
# 'tpas': 'http://digitalpreservation.fi/mets-profiles/research-data',
# }
#
# METS_SPECIFICATION = "1.7.3"
#
# NAMESPACES = {
# 'mets': 'http://www.loc.gov/METS/',
# 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
# 'premis': 'info:lc/xmlns/premis-v2',
# 'fi': 'http://digitalpreservation.fi/schemas/mets/fi-extensions',
# 'xlink': 'http://www.w3.org/1999/xlink',
# 'mix': 'http://www.loc.gov/mix/v20',
# 'ead3': 'http://ead3.archivists.org/schema/',
# 'addml': 'http://www.arkivverket.no/standarder/addml',
# 'audiomd': 'http://www.loc.gov/audioMD/',
# 'videomd': 'http://www.loc.gov/videoMD/'
# }
#
# RECORD_STATUS_TYPES = [
# 'submission',
# 'update',
# 'dissemination'
# ]
#
# def mets_extend(mets_root, catalog=METS_CATALOG,
# specification=METS_SPECIFICATION, contentid=None,
# contractid=None):
# """Create METS ElementTree"""
#
# del mets_root.attrib['{%s}schemaLocation' % XSI_NS]
# mets_root.set('{%s}schemaLocation' % XSI_NS,
# NAMESPACES['mets'] + ' ' + METS_SCHEMA)
# mets_root.set('{%s}CATALOG' % FI_NS, catalog)
# mets_root.set('{%s}SPECIFICATION' % FI_NS, specification)
# if contentid:
# mets_root.set('{%s}CONTENTID' % FI_NS, contentid)
# if contractid:
# contractstr = six.text_type(contractid)
# mets_root.set('{%s}CONTRACTID' % FI_NS, contractstr)
#
# return mets_root
. Output only the next line. | METS_SPECIFICATION, |
Using the snippet: <|code_start|> :returns: METS document ElementTree object
"""
attributes = _attribute_values(attributes, fill_contentid)
# Create list of agent elements
if attributes["packagingservice"]:
agents = [mets.agent(attributes["organization_name"],
agent_role='ARCHIVIST')]
agents.append(mets.agent(attributes["packagingservice"],
agent_type='OTHER',
agent_role='CREATOR',
othertype='SOFTWARE'))
else:
agents = [mets.agent(attributes["organization_name"],
agent_role='CREATOR')]
# Create mets header
metshdr = mets.metshdr(attributes["create_date"],
attributes["last_moddate"],
attributes["record_status"],
agents)
# Collect elements from workspace XML files
elements = []
for entry in scandir(attributes["workspace"]):
if entry.name.endswith(('-amd.xml', 'dmdsec.xml',
'structmap.xml', 'filesec.xml',
'rightsmd.xml')) and entry.is_file():
element = lxml.etree.parse(entry.path).getroot()[0]
elements.append(element)
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import os
import sys
import uuid
import six
import click
import lxml.etree
import mets
import xml_helpers.utils as xml_utils
from shutil import copyfile
from siptools.utils import get_objectlist, read_md_references
from siptools.xml.mets import (METS_CATALOG, METS_PROFILE, METS_SPECIFICATION,
NAMESPACES, RECORD_STATUS_TYPES, mets_extend)
from scandir import scandir # Python 2
from os import scandir # Python 3+
and context (class names, function names, or code) available:
# Path: siptools/utils.py
# def get_objectlist(refs_dict, file_path=None):
# """Get unique and sorted list of files or streams.
#
# Files or streasm are read from md-references.jsonl
#
# :refs_dict: Dictionary of objects
# :file_path: If given, finds streams of the given file.
# If None, finds a sorted list all file paths.
# :returns: Sorted list of files, or streams of a given file
# """
# objectset = set()
# if file_path is not None:
# for stream in refs_dict[file_path]['streams']:
# objectset.add(stream)
# elif refs_dict:
# for key, value in six.iteritems(refs_dict):
# if value['path_type'] == 'file':
# objectset.add(key)
#
# return sorted(objectset)
#
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
#
# Path: siptools/xml/mets.py
# METS_CATALOG = "1.7.3"
#
# METS_PROFILE = {
# 'ch': 'http://digitalpreservation.fi/mets-profiles/cultural-heritage',
# 'tpas': 'http://digitalpreservation.fi/mets-profiles/research-data',
# }
#
# METS_SPECIFICATION = "1.7.3"
#
# NAMESPACES = {
# 'mets': 'http://www.loc.gov/METS/',
# 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
# 'premis': 'info:lc/xmlns/premis-v2',
# 'fi': 'http://digitalpreservation.fi/schemas/mets/fi-extensions',
# 'xlink': 'http://www.w3.org/1999/xlink',
# 'mix': 'http://www.loc.gov/mix/v20',
# 'ead3': 'http://ead3.archivists.org/schema/',
# 'addml': 'http://www.arkivverket.no/standarder/addml',
# 'audiomd': 'http://www.loc.gov/audioMD/',
# 'videomd': 'http://www.loc.gov/videoMD/'
# }
#
# RECORD_STATUS_TYPES = [
# 'submission',
# 'update',
# 'dissemination'
# ]
#
# def mets_extend(mets_root, catalog=METS_CATALOG,
# specification=METS_SPECIFICATION, contentid=None,
# contractid=None):
# """Create METS ElementTree"""
#
# del mets_root.attrib['{%s}schemaLocation' % XSI_NS]
# mets_root.set('{%s}schemaLocation' % XSI_NS,
# NAMESPACES['mets'] + ' ' + METS_SCHEMA)
# mets_root.set('{%s}CATALOG' % FI_NS, catalog)
# mets_root.set('{%s}SPECIFICATION' % FI_NS, specification)
# if contentid:
# mets_root.set('{%s}CONTENTID' % FI_NS, contentid)
# if contractid:
# contractstr = six.text_type(contractid)
# mets_root.set('{%s}CONTRACTID' % FI_NS, contractstr)
#
# return mets_root
. Output only the next line. | elements = mets.merge_elements('{%s}amdSec' % NAMESPACES['mets'], elements) |
Predict the next line after this snippet: <|code_start|> help='Workspace directory. Defaults to "./workspace".')
@click.option('--base_path',
metavar='<BASE PATH>',
type=click.Path(exists=True),
default='.',
help='Base path of the digital objects.')
@click.option('--objid', type=str,
default=six.text_type(uuid.uuid4()),
metavar='<OBJID>',
help='Unique identifier for the package')
@click.option('--label',
type=str,
metavar='<LABEL>',
help='Short description of the information package')
@click.option('--contentid',
type=str,
metavar='<CONTENTID>',
help='Identifier for content. Defaults to <OBJID>.')
@click.option('--create_date',
type=str,
default=datetime.datetime.utcnow().isoformat(),
metavar='<CREATION DATE>',
help='SIP create datetime formatted as '
'yyyy-mm-ddThh:mm:ss. Defaults to current time.')
@click.option('--last_moddate',
type=str,
metavar='<LAST MODIFICATION DATE>',
help='Last modification datetime formatted as '
'yyyy-mm-ddThh:mm:ss')
@click.option('--record_status',
<|code_end|>
using the current file's imports:
import datetime
import os
import sys
import uuid
import six
import click
import lxml.etree
import mets
import xml_helpers.utils as xml_utils
from shutil import copyfile
from siptools.utils import get_objectlist, read_md_references
from siptools.xml.mets import (METS_CATALOG, METS_PROFILE, METS_SPECIFICATION,
NAMESPACES, RECORD_STATUS_TYPES, mets_extend)
from scandir import scandir # Python 2
from os import scandir # Python 3+
and any relevant context from other files:
# Path: siptools/utils.py
# def get_objectlist(refs_dict, file_path=None):
# """Get unique and sorted list of files or streams.
#
# Files or streasm are read from md-references.jsonl
#
# :refs_dict: Dictionary of objects
# :file_path: If given, finds streams of the given file.
# If None, finds a sorted list all file paths.
# :returns: Sorted list of files, or streams of a given file
# """
# objectset = set()
# if file_path is not None:
# for stream in refs_dict[file_path]['streams']:
# objectset.add(stream)
# elif refs_dict:
# for key, value in six.iteritems(refs_dict):
# if value['path_type'] == 'file':
# objectset.add(key)
#
# return sorted(objectset)
#
# def read_md_references(workspace, ref_file):
# """Read all the MD IDs as a dictionary.
#
# :workspace: path to workspace directory
# :ref_file: Metadata reference file
# :returns: A dict of references or None if reference file doesn't
# exist
# """
# reference_file = os.path.join(workspace, ref_file)
#
# if os.path.isfile(reference_file):
# references = {}
# with open(reference_file) as in_file:
# for line in in_file:
# references.update(json.loads(line))
# return references
# return None
#
# Path: siptools/xml/mets.py
# METS_CATALOG = "1.7.3"
#
# METS_PROFILE = {
# 'ch': 'http://digitalpreservation.fi/mets-profiles/cultural-heritage',
# 'tpas': 'http://digitalpreservation.fi/mets-profiles/research-data',
# }
#
# METS_SPECIFICATION = "1.7.3"
#
# NAMESPACES = {
# 'mets': 'http://www.loc.gov/METS/',
# 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
# 'premis': 'info:lc/xmlns/premis-v2',
# 'fi': 'http://digitalpreservation.fi/schemas/mets/fi-extensions',
# 'xlink': 'http://www.w3.org/1999/xlink',
# 'mix': 'http://www.loc.gov/mix/v20',
# 'ead3': 'http://ead3.archivists.org/schema/',
# 'addml': 'http://www.arkivverket.no/standarder/addml',
# 'audiomd': 'http://www.loc.gov/audioMD/',
# 'videomd': 'http://www.loc.gov/videoMD/'
# }
#
# RECORD_STATUS_TYPES = [
# 'submission',
# 'update',
# 'dissemination'
# ]
#
# def mets_extend(mets_root, catalog=METS_CATALOG,
# specification=METS_SPECIFICATION, contentid=None,
# contractid=None):
# """Create METS ElementTree"""
#
# del mets_root.attrib['{%s}schemaLocation' % XSI_NS]
# mets_root.set('{%s}schemaLocation' % XSI_NS,
# NAMESPACES['mets'] + ' ' + METS_SCHEMA)
# mets_root.set('{%s}CATALOG' % FI_NS, catalog)
# mets_root.set('{%s}SPECIFICATION' % FI_NS, specification)
# if contentid:
# mets_root.set('{%s}CONTENTID' % FI_NS, contentid)
# if contractid:
# contractstr = six.text_type(contractid)
# mets_root.set('{%s}CONTRACTID' % FI_NS, contractstr)
#
# return mets_root
. Output only the next line. | type=click.Choice(RECORD_STATUS_TYPES), |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.