text:
/** @file
    @brief Implementation

    @date 2016

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2016 Sensics, Inc.
//
// 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.

// Internal Includes
#include "TrackerThread.h"
#include "AdditionalReports.h"
#include "ImageProcessingThread.h"
#include "ProcessIMUMessage.h"
#include "SpaceTransformations.h"
#include "TrackedBody.h"
#include "TrackedBodyIMU.h"
#include "TrackedBodyTarget.h"

// Library/third-party includes
#include <osvr/Util/EigenInterop.h>
#include <osvr/Util/Finally.h>

// Standard includes
#include <future>
#include <iostream>
#include <type_traits>

#define OSVR_TRACKER_THREAD_WRAP_WITH_TRY

namespace osvr {
namespace vbtracker {
    // 16 and even 32 was too small - we were dropping messages.
    static const uint32_t IMU_MESSAGE_QUEUE_SIZE = 64 + 1;

    TrackerThread::TrackerThread(TrackingSystem &trackingSystem,
                                 ImageSource &imageSource,
                                 BodyReportingVector &reportingVec,
                                 CameraParameters const &camParams,
                                 std::int32_t cameraUsecOffset, bool bufferImu,
                                 bool debugData)
        : m_trackingSystem(trackingSystem), m_cam(imageSource),
          m_reportingVec(reportingVec), m_camParams(camParams),
          m_cameraUsecOffset(cameraUsecOffset), m_bufferImu(bufferImu),
          m_debugData(debugData), m_imuMessages(IMU_MESSAGE_QUEUE_SIZE),
          m_debugDataMessages(32) {
        msg() << "Tracker thread object created." << std::endl;
    }

    TrackerThread::~TrackerThread() {
        if (m_imageThread.joinable()) {
            m_imageThread.join();
        }
    }

    void TrackerThread::permitStart() { m_startupSignal.set_value(); }

    void TrackerThread::threadAction() {
        /// The thread internally is organized around processing video frames,
        /// with arrival of IMU reports internally handled as they come. Thus,
        /// we keep getting frames and processing them until we're told to stop,
        /// doing what we can asynchronously to also process incoming IMU
        /// messages.

        msg() << "Tracker thread object invoked, waiting for permitStart()."
              << std::endl;
        m_startupSignal.get_future().wait();
        /// sleep an extra half a second to give everyone else time to get off
        /// the starting blocks.
        std::this_thread::sleep_for(std::chrono::milliseconds(500));

        /// Initialize reporting vector, as far as we can.
        m_numBodies = m_trackingSystem.getNumBodies();
        setupReportingVectorProcessModels();

        /// Launch the image proc thread in a waiting state.

        ImageProcessingThread imageProcThreadObj{
            m_trackingSystem, m_cam, *this, m_camParams, m_cameraUsecOffset};
        imageProcThreadObj_ = &imageProcThreadObj;
        m_imageThread = std::thread{[&] { imageProcThreadObj.threadAction(); }};

        msg() << "Tracker thread object entering its main execution loop."
              << std::endl;

#ifdef OSVR_TRACKER_THREAD_WRAP_WITH_TRY
        try {
#endif
            bool keepGoing = true;
            while (keepGoing) {
                /// Call the doFrame() method to perform one video frame's worth
                /// of processing.
                doFrame();

                {
                    /// Copy the run flag.
                    std::lock_guard<std::mutex> lock(m_runMutex);
                    keepGoing = m_run;
                }
                if (!keepGoing) {
                    msg() << "Tracker thread object: Just checked our run flag "
                             "and noticed it turned false..."
                          << std::endl;
                }
            }
#ifdef OSVR_TRACKER_THREAD_WRAP_WITH_TRY
        } catch (std::exception const &e) {
            warn() << "Tracker thread object: exiting because of caught "
                      "exception: "
                   << e.what() << std::endl;
            m_run = false;
        }
#endif
        msg() << "Tracker thread object: functor exiting." << std::endl;

        if (!imageProcThreadObj.exiting()) {
            msg() << "Telling image processing thread to exit." << std::endl;
            imageProcThreadObj.signalExit();
        }
        imageProcThreadObj_ = nullptr;
        if (m_imageThread.joinable()) {
            m_imageThread.join();
        }
    }

    void TrackerThread::triggerStop() {
        /// Main thread method!
        msg() << "Tracker thread object: triggerStop() called" << std::endl;
        std::lock_guard<std::mutex> lock(m_runMutex);
        m_run = false;
    }

    bool TrackerThread::submitIMUReport(TrackedBodyIMU &imu,
                                        util::time::TimeValue const &tv,
                                        OSVR_OrientationReport const &report) {
        /// Main thread method!
        if (!m_imuMessages.write(makeImuReport(imu, tv, report))) {
            // no room for IMU message!
            // msg() << "Dropped IMU orientation message!\n";
            return false;
        }
        m_messageCondVar.notify_one();
        return true;
    }

    bool
    TrackerThread::submitIMUReport(TrackedBodyIMU &imu,
                                   util::time::TimeValue const &tv,
                                   OSVR_AngularVelocityReport const &report) {
        /// Main thread method!
        if (!m_imuMessages.write(makeImuReport(imu, tv, report))) {
            // no room for IMU message!
            return false;
        }
        m_messageCondVar.notify_one();
        return true;
    }

    bool TrackerThread::checkForDebugData(DebugArray &data) {
        return m_debugDataMessages.read(data);
    }

    void
    TrackerThread::signalImageProcessingComplete(ImageOutputDataPtr &&imageData,
                                                 cv::Mat const &frame,
                                                 cv::Mat const &frameGray) {
        m_imageData = std::move(imageData);
        m_frame = frame;
        m_frameGray = frameGray;
        {
            std::lock_guard<std::mutex> lock{m_messageMutex};
            m_timeConsumingImageStepComplete = true;
        }
        m_messageCondVar.notify_one();
    }

    std::ostream &TrackerThread::msg() const {
        return std::cout << "[UnifiedTracker] ";
    }

    std::ostream &TrackerThread::warn() const { return msg() << "Warning: "; }

    void TrackerThread::doFrame() {
        // Check camera status.
        if (!m_cam.ok()) {
            // Hmm, camera seems bad. Might regain it? Skip for now...
            warn() << "Camera is reporting it is not OK." << std::endl;
            return;
        }
        // Trigger a grab.
        if (!m_cam.grab()) {
            // Again failing without quitting, in hopes we get better luck
            // next time...
            warn() << "Camera grab failed." << std::endl;
            return;
        }
        // When we triggered the grab was a good guess of the time
        // for the image before that got moved upstream into the ImageSource
        // library.

        /// Launch an asynchronous task to perform the image retrieval and
        /// initial image processing.
        launchTimeConsumingImageStep();
        if (m_bufferImu) {
            setImuOverrideClock();
        }
        /// only used if m_bufferImu
        UpdatedBodyIndices imuIndices;

        bool finishedImage = false;
        do {

            {
                /// Wait for something to do (Completion of image, IMU reports)
                std::unique_lock<std::mutex> lock(m_messageMutex);
                m_messageCondVar.wait(lock, [&] {
                    return m_timeConsumingImageStepComplete ||
                           !m_imuMessages.isEmpty();
                });
                if (m_timeConsumingImageStepComplete) {
                    /// Set a flag to get us out of this innermost loop - we'll
                    /// finish up processing this frame and trigger another grab
                    /// before we look at more IMU data.
                    finishedImage = true;
                }
                // Otherwise we have some IMU reports to keep us busy in the
                // meantime.
            } // unlock

            if (!finishedImage) {
                /// This means we got out of waiting on the condition variable
                /// because of an IMU message. Handle one.

                IMUMessage message = boost::none;
                if (!m_imuMessages.read(message) || message.empty()) {
                    // couldn't read a message, or read an empty message
                    continue;
                }

                // process it.
                BodyId id;
                ImuMessageCategory cat;
                std::tie(id, cat) = processIMUMessage(message);
                if (id.empty()) {
                    // processed but got an empty body ID
                    continue;
                }

                if (m_bufferImu) {
                    // insert index into the list
                    imuIndices.insert(id);

                    // if it's time, send a report even if we haven't gotten a
                    // video frame with useful things in it yet.
                    if (shouldSendImuReport()) {
                        updateReportingVector(imuIndices);
                        imuIndices.clear();
                    }
                } else {

                    /// Immediately update the reporting vector for that body.
                    updateReportingVector(id);
                }
            }
        } while (!finishedImage);

        // OK, once we get here, we know the timeConsumingImageStep is complete.
        if (!m_frame.data || !m_frameGray.data) {
            // but it ended early due to error.
            warn() << "Camera retrieve appeared to fail: frames had null "
                      "pointers!"
                   << std::endl;
            return;
        }

        if (!m_imageData) {
            // but it failed to set the pointer? this is very strange...
            warn() << "Initial image processing failed somehow!" << std::endl;
            return;
        }

        // Submit initial image data to the tracking system.
        auto bodyIds =
            m_trackingSystem.updateBodiesFromVideoData(std::move(m_imageData));
        m_imageData.reset();

        // Sort those body IDs so we can merge them with the body IDs from any
        // IMU messages we're about to process.
        UpdatedBodyIndices sortedBodyIds{begin(bodyIds), end(bodyIds)};
        if (m_bufferImu) {
            for (auto &id : imuIndices) {
                sortedBodyIds.insert(id);
            }
            imuIndices.clear();
        }

        // process those IMU messages and add any unique IDs to the vector
        // returned by the image tracker.
        // We only want to process a fixed number of messages so we don't get
        // stuck here in a loop without servicing the camera.
        std::size_t numMessages = m_imuMessages.sizeGuess();
        {
            IMUMessage message = boost::none;
            for (std::size_t i = 0; i < numMessages; ++i) {
                if (!m_imuMessages.read(message)) {
                    // ran out of messages earlier than expected.
                    break;
                }

                auto id = processIMUMessage(message).first;
                if (!id.empty()) {
                    sortedBodyIds.insert(id);
                }
            }
        }

        updateReportingVector(sortedBodyIds);
    }

    std::pair<BodyId, ImuMessageCategory>
    TrackerThread::processIMUMessage(IMUMessage const &m) {
        return osvr::vbtracker::processImuMessage(m);
    }

    BodyReporting *TrackerThread::getCamPoseReporting() const {
#ifdef OSVR_OUTPUT_CAMERA_POSE
        return m_reportingVec[m_numBodies + extra_outputs::outputCamIndex]
            .get();
#else
        return nullptr;
#endif
    }

    BodyReporting *TrackerThread::getIMUReporting() const {
#ifdef OSVR_OUTPUT_IMU
        return m_reportingVec[m_numBodies + extra_outputs::outputImuIndex]
            .get();
#else
        return nullptr;
#endif
    }

    BodyReporting *TrackerThread::getIMUCamReporting() const {
#ifdef OSVR_OUTPUT_IMU_CAM
        return m_reportingVec[m_numBodies + extra_outputs::outputImuCamIndex]
            .get();
#else
        return nullptr;
#endif
    }

    BodyReporting *TrackerThread::getHMDCamReporting() const {

#ifdef OSVR_OUTPUT_HMD_CAM
        return m_reportingVec[m_numBodies + extra_outputs::outputHMDCamIndex]
            .get();
#else
        return nullptr;
#endif
    }

    void TrackerThread::updateExtraCameraReport() {
#ifndef OSVR_OUTPUT_CAMERA_POSE
        return;
#endif

        using namespace Eigen;
        using namespace std::chrono;
        /// Are we due to report on the camera pose?
        auto rightNow = our_clock::now();
        if (!m_nextCameraPoseReport || rightNow > *m_nextCameraPoseReport) {
            m_nextCameraPoseReport = rightNow + seconds(1);
            BodyState state;
            state.position() = m_trackingSystem.getCameraPose().translation();
            state.setQuaternion(
                Quaterniond(m_trackingSystem.getCameraPose().rotation()));
            getCamPoseReporting()->updateState(util::time::getNow(), state);
        }
    }

    void TrackerThread::updateExtraIMUReports() {

#if !defined(OSVR_OUTPUT_IMU) && !defined(OSVR_OUTPUT_IMU_CAM)
        // Not reporting these special reports, do nothing.
        return;
#endif

        if (!m_trackingSystem.getBody(BodyId(0)).hasIMU()) {
            // no IMU, nothing to report.
            return;
        }
        auto &imu = m_trackingSystem.getBody(BodyId(0)).getIMU();
        if (!imu.hasPoseEstimate()) {
            return;
        }
        Eigen::Quaterniond imuQuat = imu.getPoseEstimate();

#ifdef OSVR_OUTPUT_IMU
        {
            BodyState state;
            state.setQuaternion(imuQuat);
            getIMUReporting()->updateState(imu.getLastUpdate(), state);
        }
#endif

#ifdef OSVR_OUTPUT_IMU_CAM

        {
            BodyState state;
            /// @todo missing the yaw correction factor.
            state.setQuaternion(getCameraRotation(m_trackingSystem) * imuQuat);
            // Put this one up in the air a little so we can tell the
            // difference.
            state.position() = Eigen::Vector3d(0, 0.5, 0);
            getIMUCamReporting()->updateState(imu.getLastUpdate(), state);
        }
#endif
    }

    void TrackerThread::setupReportingVectorProcessModels() {
        for (BodyId::wrapped_type i = 0; i < m_numBodies; ++i) {
            auto bodyId = BodyId{i};
            auto &body = m_trackingSystem.getBody(bodyId);
            m_reportingVec[i]->initProcessModel(body.getProcessModel());
#ifdef OSVR_OUTPUT_HMD_CAM
            if (bodyId == BodyId(0)) {
                getHMDCamReporting()->initProcessModel(body.getProcessModel());
            }
#endif
        }
    }

    bool TrackerThread::setupReportingVectorRoomTransforms() {
        if (!m_trackingSystem.haveCameraPose()) {
            /// can't do this if we haven't got the transform yet...
            return false;
        }
        if (m_setCameraPose) {
            /// It's already been done.
            return true;
        }

        /// Just set the room transform once.
        m_setCameraPose = true;

        /// These functions all return pointers.
        /// If any of these reports are not enabled, they'll return nullptr.
        auto cameraPoseReporting = getCamPoseReporting();
        auto imuAlignedReporting = getIMUReporting();
        auto imuCameraSpaceReporting = getIMUCamReporting();
        auto hmdCameraSpaceReporting = getHMDCamReporting();
        Eigen::Isometry3d trackerToRoomXform = m_trackingSystem.getCameraPose();
        for (auto &reporting : m_reportingVec) {

            /// Skip these special ones, leave them with an identity
            /// transform as their "camera to room" transform
            auto reportingRaw = reporting.get();
            if (reportingRaw == cameraPoseReporting ||
                reportingRaw == imuAlignedReporting ||
                reportingRaw == imuCameraSpaceReporting ||
                reportingRaw == hmdCameraSpaceReporting) {
                continue;
            }

            /// All other tracker reports, set the tracker to room
            /// transform.
            reporting->setTrackerToRoomTransform(trackerToRoomXform);
        }
        return true;
    }

    void
    TrackerThread::updateReportingVector(UpdatedBodyIndices const &bodyIds) {
        if (!setupReportingVectorRoomTransforms()) {
            // false return means that we don't have calibration data yet, so no
            // sense in reporting the other things.
            return;
        }
        for (auto const &bodyId : bodyIds) {
            updateReportingVector(bodyId);
#ifdef OSVR_OUTPUT_HMD_CAM
            if (bodyId == BodyId(0)) {
                auto &body = m_trackingSystem.getBody(bodyId);
                getHMDCamReporting()->updateState(body.getStateTime(),
                                                  body.getState());
            }
#endif
        }

        /// Update the extra reports (if applicable)
        updateExtraCameraReport();
        updateExtraIMUReports();
    }

    void TrackerThread::updateReportingVector(BodyId const bodyId) {
        auto &body = m_trackingSystem.getBody(bodyId);
        m_reportingVec[bodyId.value()]->updateState(body.getStateTime(),
                                                    body.getState());
        if (m_debugData && bodyId == BodyId(0)) {
            DebugArray newDebugArray = {};
            auto &target = *body.getTarget(TargetId(0));
            auto &debugData = target.getBeaconDebugData();
            for (int i = 0; i < MAX_DEBUG_BEACONS; ++i) {
                auto baseIdx = i * DEBUG_ANALOGS_PER_BEACON;
                auto &thisBeacon = debugData[i];
                newDebugArray[baseIdx] = thisBeacon.variance;
                newDebugArray[baseIdx + 1] = thisBeacon.measurement.x;
                newDebugArray[baseIdx + 2] = thisBeacon.measurement.y;
                newDebugArray[baseIdx + 3] = thisBeacon.residual.x;
                newDebugArray[baseIdx + 4] = thisBeacon.residual.y;
            }
            m_debugDataMessages.write(newDebugArray);
        }
    }

    void TrackerThread::launchTimeConsumingImageStep() {
        /// Our thread would be the only one reading or writing this flag at
        /// this point, so it's OK now to write this without protection.
        m_timeConsumingImageStepComplete = false;

        /// Release the thread from waiting.
        imageProcThreadObj_->signalDoFrame();
    }
} // namespace vbtracker
} // namespace osvr


text:
#include "EdgeExprModel.hh"
#include "Region.hh"
#include "Edge.hh"
#include "Vector.hh"
#include "ModelExprEval.hh"
#include "GeometryStream.hh"
#include "dsAssert.hh"

#include "EngineAPI.hh"
#include <set>
#include <string>
#include <sstream>

// Must be valid equation object which is passed
template <typename DoubleType>
EdgeExprModel<DoubleType>::EdgeExprModel(const std::string &nm, const Eqo::EqObjPtr eq, RegionPtr rp, EdgeModel::DisplayType dt, ContactPtr cp) : EdgeModel(nm, rp, dt, cp), equation(eq)
{
#if 0
    os << "creating EdgeExprModel " << nm << " with equation " << eq << "\n";
#endif
    RegisterModels();
}

template <typename DoubleType>
void EdgeExprModel<DoubleType>::RegisterModels()
{
    typedef std::set<std::string> refmodels_t;
    refmodels_t refs;

    if (EngineAPI::getEnumeratedType(equation) == EngineAPI::MODEL_OBJ)
    {
        refs.insert(EngineAPI::getStringValue(equation));
    }
    else if (EngineAPI::getEnumeratedType(equation) == EngineAPI::VARIABLE_OBJ)
    {
        refs.insert(EngineAPI::getStringValue(equation));
    }
    else
    {
        refmodels_t refmodels    = EngineAPI::getReferencedType(equation, EngineAPI::MODEL_OBJ);
        refmodels_t refvariables = EngineAPI::getReferencedType(equation, EngineAPI::VARIABLE_OBJ);

        for (refmodels_t::iterator it = refmodels.begin(); it != refmodels.end(); ++it)
        {
            refs.insert(*it);
        }
        for (refmodels_t::iterator it = refvariables.begin(); it != refvariables.end(); ++it)
        {
            refs.insert(*it);
        }

    }

    for (refmodels_t::iterator it = refs.begin(); it != refs.end(); ++it)
    {
#if 0
    os << "registering callback " << *it << " for EdgeExprModel " << this->GetName() << "\n";
#endif
        RegisterCallback(*it);
    }
}

template <typename DoubleType>
void EdgeExprModel<DoubleType>::calcEdgeScalarValues() const
{
    // need to write the calculator
//    dsAssert(false, "UNEXPECTED");
#if 0
        os << "updating EdgeExprModel " << GetName() << " from expression " << EngineAPI::getStringValue(equation) << "\n";
#endif
    typename MEE::ModelExprEval<DoubleType>::error_t errors;
    const Region *rp = &(this->GetRegion());
    MEE::ModelExprEval<DoubleType> mexp(rp, GetName(), errors);
    MEE::ModelExprData<DoubleType> out = mexp.eval_function(equation);

    if (!errors.empty())
    {
        std::ostringstream os;
        os << "while evaluating edge model " << GetName() <<
        " on Device: " << GetRegion().GetDeviceName() <<
        " on Region: " << GetRegion().GetName()
        << "\n";
        for (typename MEE::ModelExprEval<DoubleType>::error_t::iterator it = errors.begin(); it != errors.end(); ++it)
        {
            os << *it << "\n";
        }
        GeometryStream::WriteOut(OutputStream::OutputType::ERROR, *rp, os.str());
    }

    if (
        (out.GetType() == MEE::datatype::EDGEDATA)
       )
    {
        const MEE::ScalarValuesType<DoubleType> &tval = out.GetScalarValues();
        if (tval.IsUniform())
        {
          SetValues(tval.GetScalar());
        }
        else
        {
          EdgeScalarList<DoubleType> nsl(tval.GetVector());
          SetValues(nsl);
        }
    }
    else if (out.GetType() == MEE::datatype::DOUBLE)
    {
        const DoubleType v = out.GetDoubleValue();
        SetValues(v);
    }
    else
    {
        std::ostringstream os;
        os << "while evaluating model " << GetName() << ": expression "
            << EngineAPI::getStringValue(equation) << " evaluates to " << MEE::datatypename[static_cast<size_t>(out.GetType())]
            << "\n";
        GeometryStream::WriteOut(OutputStream::OutputType::FATAL, *rp, os.str());
    }

}

template <typename DoubleType>
void EdgeExprModel<DoubleType>::Serialize(std::ostream &of) const
{
  of << "COMMAND ";

  if (AtContact())
  {
    of << "contact_edge_model -device \"" << GetDeviceName() << "\" -contact \"" << GetContactName() << "\" ";
  }
  else
  {
    of << "edge_model -device \"" << GetDeviceName() << "\" -region \"" << GetRegionName() << "\" ";
  }

  of << "-name \"" << GetName() << "\" -equation \"" << EngineAPI::getStringValue(equation) << ";\" -display_type \"" << GetDisplayTypeString() << "\"";

}

template class EdgeExprModel<double>;
#ifdef DEVSIM_EXTENDED_PRECISION
#include "Float128.hh"
template class EdgeExprModel<float128>;
#endif

EdgeModelPtr CreateEdgeExprModel(const std::string &nm, const Eqo::EqObjPtr eq, RegionPtr rp, EdgeModel::DisplayType dt, ContactPtr cp)
{
  return create_edge_model<EdgeExprModel<double>, EdgeExprModel<extended_type>>(rp->UseExtendedPrecisionModels(), nm, eq, rp, dt, cp);
}

redpajama_set_name: RedPajamaGithub


text:
Intl
====

Provides utilities to support the management of localized resources (strings and formatting patterns).


text:
package org.apache.taverna.activities.externaltool.manager;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.taverna.lang.observer.Observer;

/**
 *
 *
 * @author David Withers
 */
public interface InvocationGroupManager {

	public void addInvocationGroup(InvocationGroup group);

	public void replaceInvocationGroup(InvocationGroup originalGroup,
			InvocationGroup replacementGroup);

	public void removeInvocationGroup(InvocationGroup group);

	public void replaceInvocationMechanism(InvocationMechanism originalMechanism,
			InvocationMechanism replacementMechanism);

	public void removeMechanism(InvocationMechanism mechanism);

	public HashSet<InvocationGroup> getInvocationGroups();

	public InvocationGroup getDefaultGroup();

	public Set<InvocationMechanism> getMechanisms();

	public void addMechanism(InvocationMechanism mechanism);

	public InvocationMechanism getDefaultMechanism();

	public boolean containsGroup(InvocationGroup group);

	public InvocationMechanism getInvocationMechanism(String defaultMechanismName);

	public void mechanismChanged(InvocationMechanism im);

	/**
	 * Get the directory where the invocation information will be/is saved to.
	 */
	public File getInvocationManagerDirectory();

	public void saveConfiguration();

	public void groupChanged(InvocationGroup group);

	public void addObserver(Observer<InvocationManagerEvent> observer);

	public List<Observer<InvocationManagerEvent>> getObservers();

	public void removeObserver(Observer<InvocationManagerEvent> observer);

	public void deleteRun(String runId);

	public void persistInvocations();

	public void loadInvocations();

	public boolean containsMechanism(InvocationMechanism invocationMechanism);

	public InvocationGroup getGroupReplacement(InvocationGroup group);

	public InvocationMechanism getMechanismReplacement(String invocationMechanismSpecification);

	public InvocationGroup getImportedGroup(String groupSpecification);

	public InvocationMechanism getImportedMechanism(String mechanismSpecification);

	public void importMechanism(String invocationMechanismSpecification,
			InvocationMechanism createdMechanism);

	public void importInvocationGroup(String invocationGroupSpecification,
			InvocationGroup invocationGroup);

}


text:
@implementation FKFlickrMachinetagsGetPairs

- (BOOL) needsLogin {
    return NO;
}

- (BOOL) needsSigning {
    return NO;
}

- (FKPermission) requiredPerms {
    return -1;
}

- (NSString *) name {
    return @"flickr.machinetags.getPairs";
}

- (BOOL) isValid:(NSError **)error {
    BOOL valid = YES;
	NSMutableString *errorDescription = [[NSMutableString alloc] initWithString:@"You are missing required params: "];

	if(error != NULL) {
		if(!valid) {
			NSDictionary *userInfo = @{NSLocalizedDescriptionKey: errorDescription};
			*error = [NSError errorWithDomain:FKFlickrKitErrorDomain code:FKErrorInvalidArgs userInfo:userInfo];
		}
	}
    return valid;
}

- (NSDictionary *) args {
    NSMutableDictionary *args = [NSMutableDictionary dictionary];
	if(self.namespace) {
		[args setValue:self.namespace forKey:@"namespace"];
	}
	if(self.predicate) {
		[args setValue:self.predicate forKey:@"predicate"];
	}
	if(self.per_page) {
		[args setValue:self.per_page forKey:@"per_page"];
	}
	if(self.page) {
		[args setValue:self.page forKey:@"page"];
	}

    return [args copy];
}

- (NSString *) descriptionForError:(NSInteger)error {
    switch(error) {
		case FKFlickrMachinetagsGetPairsError_NotAValidNamespace:
			return @"Not a valid namespace";
		case FKFlickrMachinetagsGetPairsError_NotAValidPredicate:
			return @"Not a valid predicate";
		case FKFlickrMachinetagsGetPairsError_InvalidAPIKey:
			return @"Invalid API Key";
		case FKFlickrMachinetagsGetPairsError_ServiceCurrentlyUnavailable:
			return @"Service currently unavailable";
		case FKFlickrMachinetagsGetPairsError_FormatXXXNotFound:
			return @"Format \"xxx\" not found";
		case FKFlickrMachinetagsGetPairsError_MethodXXXNotFound:
			return @"Method \"xxx\" not found";
		case FKFlickrMachinetagsGetPairsError_InvalidSOAPEnvelope:
			return @"Invalid SOAP envelope";
		case FKFlickrMachinetagsGetPairsError_InvalidXMLRPCMethodCall:
			return @"Invalid XML-RPC Method Call";
		case FKFlickrMachinetagsGetPairsError_BadURLFound:
			return @"Bad URL found";

		default:
			return @"Unknown error code";
    }
}

@end


text:
using System;
using System.Collections.Concurrent;
using PubNub.Async.Services.Access;
using PubNub.Async.Services.Crypto;
using PubNub.Async.Services.History;
using PubNub.Async.Services.Publish;
using PubNub.Async.Services.Subscribe;

namespace PubNub.Async.Configuration
{
	public class DefaultPubNubEnvironment : AbstractPubNubEnvironment, IRegisterService
	{
		private static readonly object AccessRegistrySyncRoot = new object();
		private static IAccessRegistry _accessRegistry;
		public static IAccessRegistry AccessRegistryInstance
		{
			get
			{
				if (_accessRegistry == null)
				{
					lock (AccessRegistrySyncRoot)
					{
						if (_accessRegistry == null)
						{
                            _accessRegistry = new AccessRegistry();
						}
					}
				}
				return _accessRegistry;
			}
		}

		private static readonly object CryptoSyncRoot = new object();
		private static ICryptoService _crypto;
		public static ICryptoService CryptoInstance
		{
			get
			{
				if (_crypto == null)
				{
					lock (CryptoSyncRoot)
					{
						if (_crypto == null)
						{
							_crypto = new CryptoService();
						}
					}
				}
				return _crypto;
			}
		}

	    private static readonly object SubscriptionRegistrySyncRoot = new object();
	    private static ISubscriptionRegistry _subscriptionRegistry;

	    public static ISubscriptionRegistry SubscriptionRegistryInstance
        {
	        get
	        {
	            if (_subscriptionRegistry == null)
	            {
	                lock (SubscriptionRegistrySyncRoot)
	                {
	                    if (_subscriptionRegistry == null)
	                    {
	                        _subscriptionRegistry = new SubscriptionRegistry(ResolveSubscriptionInstance);
	                    }
	                }
	            }
	            return _subscriptionRegistry;
	        }
        }

        private static readonly object SubscriptionMonitorSyncRoot = new object();
        private static ISubscriptionMonitor _subscriptionMonitor;

        public static ISubscriptionMonitor SubscriptionMonitorInstance
        {
            get
            {
                if (_subscriptionMonitor == null)
                {
                    lock (SubscriptionMonitorSyncRoot)
                    {
                        if (_subscriptionMonitor == null)
                        {
                            _subscriptionMonitor = new SubscriptionMonitor(
                                (env, channel) => new AccessManager(env, channel, AccessRegistryInstance),
                                SubscriptionRegistryInstance);
                        }
                    }
                }
                return _subscriptionMonitor;
            }
        }

        private static readonly object ResolveSubscriptionSyncRoot = new object();
        private static IResolveSubscription _resolveSubscription;

        public static IResolveSubscription ResolveSubscriptionInstance
        {
            get
            {
                if (_resolveSubscription == null)
                {
                    lock (ResolveSubscriptionSyncRoot)
                    {
                        if (_resolveSubscription == null)
                        {
                            _resolveSubscription = new DefaultResolveSubscription(CryptoInstance);
                        }
                    }
                }
                return _resolveSubscription;
            }
        }

        private ConcurrentDictionary<Type, Func<IPubNubClient, object>> Services { get; }

		/// <summary>
		/// DefaultPubNubEnvironment utilizes a flavor of the infamous service locator pattern.
		/// Since we all know this to be an anti-pattern, check out one of pubnub.async's IoC
		/// packages like pubnub.async.autofac.
		/// </summary>
		public DefaultPubNubEnvironment()
		{
			Services = new ConcurrentDictionary<Type, Func<IPubNubClient, object>>();

			Register<ICryptoService>(client => CryptoInstance);
            Register<IAccessRegistry>(client => AccessRegistryInstance);
            Register<ISubscriptionRegistry>(client => SubscriptionRegistryInstance);
            Register<ISubscriptionMonitor>(client => SubscriptionMonitorInstance);
            Register<IResolveSubscription>(client => ResolveSubscriptionInstance);

            Register<IAccessManager>(client => new AccessManager(client.Environment, client.Channel, Resolve<IAccessRegistry>(client)));
			Register<IHistoryService>(client => new HistoryService(client, Resolve<ICryptoService>(client), Resolve<IAccessManager>(client)));
			Register<IPublishService>(client => new PublishService(client, Resolve<ICryptoService>(client), Resolve<IAccessManager>(client)));

            Register<ISubscribeService>(client => new SubscribeService(
                client,
                Resolve<IAccessManager>(client),
                Resolve<ISubscriptionMonitor>(client),
                Resolve<ISubscriptionRegistry>(client)));
        }

        public void Register<TService>(Func<IPubNubClient, TService> resolver)
		{
			Services[typeof (TService)] = client => resolver(client);
		}

		public override TService Resolve<TService>(IPubNubClient client)
		{
			return (TService) Services[typeof (TService)](client);
        }
    }
}


text:
<form action="page2-backend.php" method="" onsubmit="return false;">

2. Lifelines

2.1 Electric supply

You may select 0 or more.

<input type="checkbox" name="_2-1[]" value="a" id='_2-1_a_-5'> Cable is taught between house and pole

2.2 Water supply

You may select 0 or more.

<input type="checkbox" name="_2-2[]" value="a" id='_2-2_a_-5'> Pipeline is rigidly held between house and mains

2.3 Sewage

You may select 0 or more.

<input type="checkbox" name="_2-3[]" value="a" id='_2-3_a_-5'> Sewage line is rigidly held between house and mains

<button onclick="show()">Show</button>
</form>


text:
package net.digitalid.utility.annotations.ownership;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import net.digitalid.utility.annotations.parameter.Modified;
import net.digitalid.utility.annotations.parameter.Unmodified;
import net.digitalid.utility.validation.annotations.type.Mutable;

/**
 * This annotation indicates that the annotated parameter may not be captured by the callee.
 * This means that the callee may not keep or leak the reference to the annotated parameter.
 * Whether a parameter is modified, is indicated by {@link Modified} and {@link Unmodified}.
 * (This annotation only makes sense for {@link Mutable mutable} objects.)
 *
 * @see Captured
 * @see Capturable
 * @see NonCapturable
 */
@Documented
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface NonCaptured {}


text:
- infos = Information about path plugin is in keys below
- infos/author = Markus Raab <elektra@libelektra.org>
- infos/licence = BSD
- infos/placements = presetstorage
- infos/needs =
- infos/provides = check
- infos/status = maintained nodep libc nodoc
- infos/metadata = check/path check/path/mode check/path/user
- infos/description = Checks if keys enriched with appropriate metadata contain valid paths as values as well
  as correct permissions

## Introduction

This plugin checks whether the value of a key is a valid file system path and optionally if
correct permissions are set for a certain user.

## Installation

See [installation](/doc/INSTALL.md).
The package is called `libelektra5-extra`.

## Purpose

The motivation to write this plugin is given by the two paths that exist
in /etc/fstab: the device file and the mountpoint. A missing file is
not necessarily an error, because the device file may appear later when
a device is plugged in and the mountpoint may be there when another
subsequent mount was executed. So only warnings are yielded in that
case. One situation, however, presents an error: Only an absolute path
is allowed to occur for both device and mountpoint. When checking for
relative files, it is not enough to look at the first character if it is
a `/`, because remote file systems and some special names are valid, too.

If `check/path/mode = <permission>` is also present it will check for the correct permissions
of the file/directory. Optionally, you can also add `check/path/user = <user>"` which then checks the permissions
for the given user. When calling `kdb set` on the actual key, you have to run as `root` user
or the file permissions cannot be checked (you will receive an error message). It is also possible to leave the
`check/path/user` empty (just provide an empty string) which then takes the executing user as target to check.
So for example `sudo kdb set ...` will check if `root` can access the target file/directory whereas `kdb set ...`
will take the current executing process/user. If `check/path/user` is not given at all, the plugin
will check accessibility for the `root` user only (which again requires `sudo`)

`check/path/mode = rw` and `check/path/user = tomcat` for example will check if the user
`tomcat` has read and write access to the path which was set for the key. Please note that the file has to exist already
and it is not checked if the user has the right to create a file in the directory.

Permissions available:

- `r`: **R**ead
- `w`: **W**rite
- `x`: e**X**ecute

## Usage

If the metakey `check/path` is present, it is checked if the value is a
valid absolute file system path. If a metavalue is present, an additional
check will be done if it is a directory or device file.

## Examples

An example on which the user should have no permission at all for the root directory.

```sh
sudo kdb mount test.dump user:/tests path dump
sudo kdb set user:/tests/path "$HOME"
sudo kdb meta-set user:/tests/path check/path ""
sudo kdb meta-set user:/tests/path check/path/user ""
sudo kdb meta-set user:/tests/path check/path/mode "rw"

# Standard users should not be able to read/write the root folder
[ $(id -u) = 0 ] && printf >&2 'User is root\n' || kdb set user:/tests/path "/root"
# STDERR: User is root|.*C03200.*

# Set something which the current user can access for sure
kdb set user:/tests/path "$HOME"
# STDOUT-REGEX: .*Set string to "/.*".*

#cleanup
sudo kdb rm -r user:/tests
sudo kdb umount user:/tests
```

An example where part of the permissions are missing for a tmp file

```sh
sudo kdb mount test.dump user:/tests path dump
sudo kdb set user:/tests/path "$HOME"
sudo kdb meta-set user:/tests/path check/path ""
sudo kdb meta-set user:/tests/path check/path/user ""
sudo kdb meta-set user:/tests/path check/path/mode "rwx"

# Standard users should not be able to read/write the root folder
kdb set user:/tests/path/tempfile $(mktemp)
chmod +rw `kdb get user:/tests/path/tempfile`
kdb set user:/tests/path `kdb get user:/tests/path/tempfile`
# ERROR:C03200

# Set something which the current user can access for sure
chmod +x `kdb get user:/tests/path/tempfile`
kdb set user:/tests/path `kdb get user:/tests/path/tempfile`
# STDOUT-REGEX: Set string to "/.*".*

#cleanup
sudo rm -rf `kdb get user:/tests/path/tempfile`
sudo kdb rm -r user:/tests
sudo kdb umount user:/tests
```

## Future work

Add a check which ensures that the given path is a file/directory/symbolic link/hard link/etc.