text:
//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * Redistributions in binary form must reproduce the above
//        copyright notice, this list of conditions and the following
//        disclaimer in the documentation and/or other materials provided with
//        the distribution.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "tbb/task.h"
#include "tbb/concurrent_unordered_set.h"

#include "boost/bind.hpp"
#include "boost/algorithm/string/predicate.hpp"

#include "IECore/Light.h"
#include "IECore/CoordinateSystem.h"
#include "IECore/VisibleRenderable.h"
#include "IECore/AngleConversion.h"
#include "IECore/CurvesPrimitive.h"
#include "IECore/MessageHandler.h"

#include "IECoreGL/Renderable.h"
#include "IECoreGL/CachedConverter.h"
#include "IECoreGL/Primitive.h"
#include "IECoreGL/Selector.h"
#include "IECoreGL/CurvesPrimitive.h"
#include "IECoreGL/Group.h"

#include "Gaffer/Node.h"

#include "GafferUI/ViewportGadget.h"

#include "GafferSceneUI/SceneGadget.h"

using namespace std;
using namespace Imath;
using namespace Gaffer;
using namespace GafferUI;
using namespace GafferScene;
using namespace GafferSceneUI;

//////////////////////////////////////////////////////////////////////////
// IECore::Object -> IECoreGL::Renderable conversion
// \todo Expose a registry mechanism to allow this to be customised
// for different types.
//////////////////////////////////////////////////////////////////////////

namespace
{

IECoreGL::ConstRenderablePtr cameraToRenderable( const IECore::Camera *camera )
{
	IECore::CameraPtr fullCamera = camera->copy();
	fullCamera->addStandardParameters();

	IECoreGL::GroupPtr group = new IECoreGL::Group();
	group->getState()->add( new IECoreGL::Primitive::DrawWireframe( true ) );
	group->getState()->add( new IECoreGL::Primitive::DrawSolid( false ) );
	group->getState()->add( new IECoreGL::CurvesPrimitive::UseGLLines( true ) );
	group->getState()->add( new IECoreGL::WireframeColorStateComponent( Color4f( 0, 0.25, 0, 1 ) ) );

	IECore::V3fVectorDataPtr pData = new IECore::V3fVectorData;
	IECore::IntVectorDataPtr vertsPerCurveData = new IECore::IntVectorData;
	vector<V3f> &p = pData->writable();
	vector<int> &vertsPerCurve = vertsPerCurveData->writable();

	// box for the camera body

	const Box3f b( V3f( -0.5, -0.5, 0 ), V3f( 0.5, 0.5, 2.0 ) );

	vertsPerCurve.push_back( 5 );
	p.push_back( b.min );
	p.push_back( V3f( b.max.x, b.min.y, b.min.z ) );
	p.push_back( V3f( b.max.x, b.min.y, b.max.z ) );
	p.push_back( V3f( b.min.x, b.min.y, b.max.z ) );
	p.push_back( b.min );

	vertsPerCurve.push_back( 5 );
	p.push_back( V3f( b.min.x, b.max.y, b.min.z ) );
	p.push_back( V3f( b.max.x, b.max.y, b.min.z ) );
	p.push_back( V3f( b.max.x, b.max.y, b.max.z ) );
	p.push_back( V3f( b.min.x, b.max.y, b.max.z ) );
	p.push_back( V3f( b.min.x, b.max.y, b.min.z ) );

	vertsPerCurve.push_back( 2 );
	p.push_back( b.min );
	p.push_back( V3f( b.min.x, b.max.y, b.min.z ) );

	vertsPerCurve.push_back( 2 );
	p.push_back( V3f( b.max.x, b.min.y, b.min.z ) );
	p.push_back( V3f( b.max.x, b.max.y, b.min.z ) );

	vertsPerCurve.push_back( 2 );
	p.push_back( V3f( b.max.x, b.min.y, b.max.z ) );
	p.push_back( V3f( b.max.x, b.max.y, b.max.z ) );

	vertsPerCurve.push_back( 2 );
	p.push_back( V3f( b.min.x, b.min.y, b.max.z ) );
	p.push_back( V3f( b.min.x, b.max.y, b.max.z ) );

	// frustum

	const std::string &projection = fullCamera->parametersData()->member<IECore::StringData>( "projection" )->readable();
	const Box2f &screenWindow = fullCamera->parametersData()->member<IECore::Box2fData>( "screenWindow" )->readable();
	/// \todo When we're drawing the camera by some means other than creating a primitive for it,
	/// use the actual clippings planes. Right now that's not a good idea as it results in /huge/
	/// framing bounds when the viewer frames a selected camera.
	V2f clippingPlanes( 0, 5 );

	Box2f near( screenWindow );
	Box2f far( screenWindow );

	if( projection == "perspective" )
	{
		float fov = fullCamera->parametersData()->member<IECore::FloatData>( "projection:fov" )->readable();
		float d = tan( IECore::degreesToRadians( fov / 2.0f ) );
		near.min *= d * clippingPlanes[0];
		near.max *= d * clippingPlanes[0];
		far.min *= d * clippingPlanes[1];
		far.max *= d * clippingPlanes[1];
	}

	vertsPerCurve.push_back( 5 );
	p.push_back( V3f( near.min.x, near.min.y, -clippingPlanes[0] ) );
	p.push_back( V3f( near.max.x, near.min.y, -clippingPlanes[0] ) );
	p.push_back( V3f( near.max.x, near.max.y, -clippingPlanes[0] ) );
	p.push_back( V3f( near.min.x, near.max.y, -clippingPlanes[0] ) );
	p.push_back( V3f( near.min.x, near.min.y, -clippingPlanes[0] ) );

	vertsPerCurve.push_back( 5 );
	p.push_back( V3f( far.min.x, far.min.y, -clippingPlanes[1] ) );
	p.push_back( V3f( far.max.x, far.min.y, -clippingPlanes[1] ) );
	p.push_back( V3f( far.max.x, far.max.y, -clippingPlanes[1] ) );
	p.push_back( V3f( far.min.x, far.max.y, -clippingPlanes[1] ) );
	p.push_back( V3f( far.min.x, far.min.y, -clippingPlanes[1] ) );

	vertsPerCurve.push_back( 2 );
	p.push_back( V3f( near.min.x, near.min.y, -clippingPlanes[0] ) );
	p.push_back( V3f( far.min.x, far.min.y, -clippingPlanes[1] ) );

	vertsPerCurve.push_back( 2 );
	p.push_back( V3f( near.max.x, near.min.y, -clippingPlanes[0] ) );
	p.push_back( V3f( far.max.x, far.min.y, -clippingPlanes[1] ) );

	vertsPerCurve.push_back( 2 );
	p.push_back( V3f( near.max.x, near.max.y, -clippingPlanes[0] ) );
	p.push_back( V3f( far.max.x, far.max.y, -clippingPlanes[1] ) );

	vertsPerCurve.push_back( 2 );
	p.push_back( V3f( near.min.x, near.max.y, -clippingPlanes[0] ) );
	p.push_back( V3f( far.min.x, far.max.y, -clippingPlanes[1] ) );

	IECoreGL::CurvesPrimitivePtr curves = new IECoreGL::CurvesPrimitive( IECore::CubicBasisf::linear(), false, vertsPerCurveData );
	curves->addPrimitiveVariable( "P", IECore::PrimitiveVariable( IECore::PrimitiveVariable::Vertex, pData ) );
	group->addChild( curves );

	return group;
}

IECoreGL::ConstRenderablePtr lightToRenderable( const IECore::Light *light )
{
	static IECoreGL::GroupPtr group = NULL;
	if( !group )
	{
		group = new IECoreGL::Group();

		group->getState()->add( new IECoreGL::Primitive::DrawWireframe( true ) );
		group->getState()->add( new IECoreGL::Primitive::DrawSolid( false ) );
		group->getState()->add( new IECoreGL::CurvesPrimitive::UseGLLines( true ) );
		group->getState()->add( new IECoreGL::WireframeColorStateComponent( Color4f( 0.5, 0, 0, 1 ) ) );

		const float a = 0.5f;
		const float phi = 1.0f + sqrt( 5.0f ) / 2.0f;
		const float b = 1.0f / ( 2.0f * phi );

		// icosahedron points
		IECore::V3fVectorDataPtr pData = new IECore::V3fVectorData;
		vector<V3f> &p = pData->writable();
		p.resize( 24 );
		p[0] = V3f( 0, b, -a );
		p[2] = V3f( b, a, 0 );
		p[4] = V3f( -b, a, 0 );
		p[6] = V3f( 0, b, a );
		p[8] = V3f( 0, -b, a );
		p[10] = V3f( -a, 0, b );
		p[12] = V3f( 0, -b, -a );
		p[14] = V3f( a, 0, -b );
		p[16] = V3f( a, 0, b );
		p[18] = V3f( -a, 0, -b );
		p[20] = V3f( b, -a, 0 );
		p[22] = V3f( -b, -a, 0 );

		for( size_t i = 0; i<12; i++ )
		{
			p[i*2] = 2.0f * p[i*2].normalized();
			p[i*2+1] = V3f( 0 );
		}

		IECore::IntVectorDataPtr vertsPerCurve = new IECore::IntVectorData;
		vertsPerCurve->writable().resize( 12, 2 );

		IECoreGL::CurvesPrimitivePtr curves = new IECoreGL::CurvesPrimitive( IECore::CubicBasisf::linear(), false, vertsPerCurve );
		curves->addPrimitiveVariable( "P", IECore::PrimitiveVariable( IECore::PrimitiveVariable::Vertex, pData ) );

		group->addChild( curves );
	}

	return group;
}

IECoreGL::ConstRenderablePtr coordinateSystemToRenderable( const IECore::CoordinateSystem *coordinateSystem )
{
	static IECoreGL::GroupPtr group = NULL;
	if( !group )
	{
		group = new IECoreGL::Group();

		group->getState()->add( new IECoreGL::Primitive::DrawWireframe( true ) );
		group->getState()->add( new IECoreGL::Primitive::DrawSolid( false ) );
		group->getState()->add( new IECoreGL::CurvesPrimitive::UseGLLines( true ) );
		group->getState()->add( new IECoreGL::WireframeColorStateComponent( Color4f( 0.06, 0.2, 0.56, 1 ) ) );
		group->getState()->add( new IECoreGL::CurvesPrimitive::GLLineWidth( 2.0f ) );

		IECore::V3fVectorDataPtr pData = new IECore::V3fVectorData;
		vector<V3f> &p = pData->writable();
		p.reserve( 6 );
		p.push_back( V3f( 0 ) );
		p.push_back( V3f( 1, 0, 0 ) );
		p.push_back( V3f( 0 ) );
		p.push_back( V3f( 0, 1, 0 ) );
		p.push_back( V3f( 0 ) );
		p.push_back( V3f( 0, 0, 1 ) );

		IECore::IntVectorDataPtr vertsPerCurve = new IECore::IntVectorData;
		vertsPerCurve->writable().resize( 3, 2 );

		IECoreGL::CurvesPrimitivePtr curves = new IECoreGL::CurvesPrimitive( IECore::CubicBasisf::linear(), false, vertsPerCurve );
		curves->addPrimitiveVariable( "P", IECore::PrimitiveVariable( IECore::PrimitiveVariable::Vertex, pData ) );
		group->addChild( curves );
	}

	return group;
}

IECoreGL::ConstRenderablePtr visibleRenderableToRenderable( const IECore::VisibleRenderable *visibleRenderable )
{
	IECoreGL::GroupPtr group = new IECoreGL::Group();
	group->getState()->add( new IECoreGL::Primitive::DrawWireframe( true ) );
	group->getState()->add( new IECoreGL::Primitive::DrawSolid( false ) );
	group->getState()->add( new IECoreGL::CurvesPrimitive::UseGLLines( true ) );

	IECore::V3fVectorDataPtr pData = new IECore::V3fVectorData;
	IECore::IntVectorDataPtr vertsPerCurveData = new IECore::IntVectorData;
	vector<V3f> &p = pData->writable();
	vector<int> &vertsPerCurve = vertsPerCurveData->writable();

	// box representing the location of the renderable

	const Box3f b = visibleRenderable->bound();

	vertsPerCurve.push_back( 5 );
	p.push_back( b.min );
	p.push_back( V3f( b.max.x, b.min.y, b.min.z ) );
	p.push_back( V3f( b.max.x, b.min.y, b.max.z ) );
	p.push_back( V3f( b.min.x, b.min.y, b.max.z ) );
	p.push_back( b.min );

	vertsPerCurve.push_back( 5 );
	p.push_back( V3f( b.min.x, b.max.y, b.min.z ) );
	p.push_back( V3f( b.max.x, b.max.y, b.min.z ) );
	p.push_back( V3f( b.max.x, b.max.y, b.max.z ) );
	p.push_back( V3f( b.min.x, b.max.y, b.max.z ) );
	p.push_back( V3f( b.min.x, b.max.y, b.min.z ) );

	vertsPerCurve.push_back( 2 );
	p.push_back( b.min );
	p.push_back( V3f( b.min.x, b.max.y, b.min.z ) );

	vertsPerCurve.push_back( 2 );
	p.push_back( V3f( b.max.x, b.min.y, b.min.z ) );
	p.push_back( V3f( b.max.x, b.max.y, b.min.z ) );

	vertsPerCurve.push_back( 2 );
	p.push_back( V3f( b.max.x, b.min.y, b.max.z ) );
	p.push_back( V3f( b.max.x, b.max.y, b.max.z ) );

	vertsPerCurve.push_back( 2 );
	p.push_back( V3f( b.min.x, b.min.y, b.max.z ) );
	p.push_back( V3f( b.min.x, b.max.y, b.max.z ) );

	IECoreGL::CurvesPrimitivePtr curves = new IECoreGL::CurvesPrimitive( IECore::CubicBasisf::linear(), false, vertsPerCurveData );
	curves->addPrimitiveVariable( "P", IECore::PrimitiveVariable( IECore::PrimitiveVariable::Vertex, pData ) );
	group->addChild( curves );

	return group;
}

IECoreGL::ConstRenderablePtr clippingPlaneToRenderable( const IECore::Object *clippingPlane )
{
	static IECoreGL::GroupPtr group = NULL;
	if( !group )
	{
		group = new IECoreGL::Group();

		group->getState()->add( new IECoreGL::Primitive::DrawWireframe( true ) );
		group->getState()->add( new IECoreGL::Primitive::DrawSolid( false ) );
		group->getState()->add( new IECoreGL::CurvesPrimitive::UseGLLines( true ) );
		group->getState()->add( new IECoreGL::WireframeColorStateComponent( Color4f( 0.06, 0.2, 0.56, 1 ) ) );
		group->getState()->add( new IECoreGL::CurvesPrimitive::GLLineWidth( 1.0f ) );

		IECore::V3fVectorDataPtr pData = new IECore::V3fVectorData;
		IECore::IntVectorDataPtr vertsPerCurveData = new IECore::IntVectorData;
		vector<V3f> &p = pData->writable();
		vector<int> &vertsPerCurve = vertsPerCurveData->writable();
		p.reserve( 11 );
		vertsPerCurve.reserve( 4 );
		// square
		p.push_back( V3f( -0.5, -0.5, 0 ) );
		p.push_back( V3f( -0.5, 0.5, 0 ) );
		p.push_back( V3f( 0.5, 0.5, 0 ) );
		p.push_back( V3f( 0.5, -0.5, 0 ) );
		p.push_back( V3f( -0.5, -0.5, 0 ) );
		vertsPerCurve.push_back( 5 );
		// cross
		p.push_back( V3f( -0.5, -0.5, 0 ) );
		p.push_back( V3f( 0.5, 0.5, 0 ) );
		vertsPerCurve.push_back( 2 );
		p.push_back( V3f( -0.5, 0.5, 0 ) );
		p.push_back( V3f( 0.5, -0.5, 0 ) );
		vertsPerCurve.push_back( 2 );
		// normal
		p.push_back( V3f( 0, 0, 0 ) );
		p.push_back( V3f( 0, 0, 0.5 ) );
		vertsPerCurve.push_back( 2 );

		IECoreGL::CurvesPrimitivePtr curves = new IECoreGL::CurvesPrimitive( IECore::CubicBasisf::linear(), false, vertsPerCurveData );
		curves->addPrimitiveVariable( "P", IECore::PrimitiveVariable( IECore::PrimitiveVariable::Vertex, pData ) );
		group->addChild( curves );
	}

	return group;
}

IECoreGL::ConstRenderablePtr objectToRenderable( const IECore::Object *object )
{
	switch( object->typeId() )
	{
		case IECore::CameraTypeId :
			return cameraToRenderable( static_cast<const IECore::Camera *>( object ) );
		case IECore::LightTypeId :
			return lightToRenderable( static_cast<const IECore::Light *>( object ) );
		case IECore::CoordinateSystemTypeId :
			return coordinateSystemToRenderable( static_cast<const IECore::CoordinateSystem *>( object ) );
		case IECore::ExternalProceduralTypeId :
			return visibleRenderableToRenderable( static_cast<const IECore::VisibleRenderable *>( object ) );
		case IECore::ClippingPlaneTypeId :
			return clippingPlaneToRenderable( object );
		default :
			try
			{
				IECore::ConstRunTimeTypedPtr glObject = IECoreGL::CachedConverter::defaultCachedConverter()->convert( object );
				return IECore::runTimeCast<const IECoreGL::Renderable>( glObject.get() );
			}
			catch( ... )
			{
				return NULL;
			}
	}
}

} // namespace

//////////////////////////////////////////////////////////////////////////
// Mechanism for deferred destruction of OpenGL resources.
// We use threads to update our scene graph in parallel, and as part of
// that we need to throw away IECoreGL objects that are no longer needed.
// We can only actually destroy them on the main thread when the GL context
// is active though, so we use this mechanism to defer the destruction till
// an appropriate time.
// \todo Similar ad-hoc mechanisms exist in IECoreGL (see removeObjectWalk
// in IECoreGL/Renderer.cpp, IECoreGL::CachedConverter::clearUnused() and
// IECoreGL::ShaderLoader::clearUnused()). Perhaps we could do this properly
// once and for all in IECoreGL, at the same time as introducing proper
// OpenGL context management?
//////////////////////////////////////////////////////////////////////////

namespace
{

tbb::concurrent_unordered_set<IECore::ConstRefCountedPtr> g_pendingReferenceRemovals;

template<typename T>
void deferReferenceRemoval( boost::intrusive_ptr<T> &o )
{
	// insert() can be called concurrently with other inserts.
	g_pendingReferenceRemovals.insert( o );
	o = NULL;
}

void doPendingReferenceRemovals()
{
	// clear() cannot be called concurrently with inserts, but
	// we only call this method from doRender(), which we know
	// is single threaded.
	g_pendingReferenceRemovals.clear();
	IECoreGL::CachedConverter::defaultCachedConverter()->clearUnused();
}

} // namespace

//////////////////////////////////////////////////////////////////////////
// SceneGraph implementation
//
// This is effectively a replacement for IECoreGL::Scene, tailored
// specifically to work well with Gaffer. Our only good means of generating
// IECoreGL::Scenes is to use IECoreGL::Renderer, which would mean regenerating
// the entire scene for any change in Gaffer. By maintaining our own scene graph,
// we are able to make in-place edits to minimally reflect changes in Gaffer,
// yielding much improved performance.
//
// In the longer term, the following might be a good course of action :
//
// - Refactor SceneGraph into an IECoreGL::GLScene class which maps well
//   to Gaffer, but doesn't have direct Gaffer dependencies. It seems
//   promising to have this class implement IECore::SceneInterface, or
//   a future version tailored a little for broader use cases such as this
//   (the existing interface is a little file-specific).
// - Refactor UpdateTask into a class which couples Gaffer to
//   IECore::SceneInterfaces, performing minimal edits as necessary to
//   reflect changes in Gaffer.
// - Implement our renderer backends for RenderMan, Arnold etc as
//   SceneInterfaces. This is the most challenging part of this approach,
//   but the hope is that the SceneInterface is a better API for performing
//   render edits for IPR, rather than the nasty RI style API we currently
//   have.
// - Reuse the new UpdateTask in the InteractiveRender node.
//
//////////////////////////////////////////////////////////////////////////

class SceneGadget::SceneGraph
{

	public :

		SceneGraph()
			:	m_selected( false ), m_visible( true ), m_expanded( false )
		{
		}

		~SceneGraph()
		{
			clear();
		}

		void render( IECoreGL::State *currentState, IECoreGL::Selector *selector = NULL ) const
		{
			if( !m_visible || !valid() )
			{
				return;
			}

			const bool haveTransform = m_transform != M44f();
			if( haveTransform )
			{
				glPushMatrix();
				glMultMatrixf( m_transform.getValue() );
			}

				{
					IECoreGL::State::ScopedBinding scope( *m_state, *currentState );
					IECoreGL::State::ScopedBinding selectionScope( selectionState(), *currentState, m_selected );

					if( selector )
					{
						m_selectionId = selector->loadName();
					}

					if( m_renderable )
					{
						m_renderable->render( currentState );
					}

					if( m_boundRenderable )
					{
						IECoreGL::State::ScopedBinding wireframeScope( wireframeState(), *currentState );
						m_boundRenderable->render( currentState );
					}

					for( std::vector<SceneGraph *>::const_iterator it = m_children.begin(), eIt = m_children.end(); it != eIt; ++it )
					{
						(*it)->render( currentState, selector );
					}
				}

			if( haveTransform )
			{
				glPopMatrix();
			}
		}

		void applySelection( const PathMatcher &selection )
		{
			ScenePlug::ScenePath rootPath;
			applySelectionWalk( selection, rootPath, true );
		}

		bool pathFromSelectionId( GLuint selectionId, ScenePlug::ScenePath &path ) const
		{
			path.clear();
			const bool result = pathFromSelectionIdWalk( selectionId, path );
			std::reverse( path.begin(), path.end() );
			return result;
		}

		const Box3f &bound() const
		{
			return m_bound;
		}

		Box3f selectionBound() const
		{
			if( m_selected )
			{
				return m_bound;
			}
			else
			{
				Box3f childSelectionBound;
				for( std::vector<SceneGraph *>::const_iterator it = m_children.begin(), eIt = m_children.end(); it != eIt; ++it )
				{
					const Box3f childBound = transform( (*it)->selectionBound(), (*it)->m_transform );
					childSelectionBound.extendBy( childBound );
				}
				return childSelectionBound;
			}
		}

		bool valid() const
		{
			// Our m_state can be null if an exception occurred during update,
			// in which case we're not valid.
			return m_state;
		}

		void clear()
		{
			deferReferenceRemoval( m_state );
			deferReferenceRemoval( m_renderable );
			deferReferenceRemoval( m_boundRenderable );
			clearChildren();
			m_objectHash = m_attributesHash = IECore::MurmurHash();
		}

	private :

		friend class UpdateTask;

		void clearChildren()
		{
			for( std::vector<SceneGraph *>::const_iterator it = m_children.begin(), eIt = m_children.end(); it != eIt; ++it )
			{
				delete *it;
			}
			m_children.clear();
		}

		void applySelectionWalk( const PathMatcher &selection, const ScenePlug::ScenePath &path, bool check )
		{
			const unsigned m = check ? selection.match( path ) : 0;

			m_selected = m & Filter::ExactMatch;

			ScenePlug::ScenePath childPath = path;
			childPath.push_back( IECore::InternedString() ); // space for the child name
			for( std::vector<SceneGraph *>::const_iterator it = m_children.begin(), eIt = m_children.end(); it != eIt; ++it )
			{
				childPath.back() = (*it)->m_name;
				(*it)->applySelectionWalk( selection, childPath, m & Filter::DescendantMatch );
			}
		}

		bool pathFromSelectionIdWalk( GLuint selectionId, ScenePlug::ScenePath &path ) const
		{
			if( m_selectionId == selectionId )
			{
				path.push_back( m_name );
				return true;
			}
			else
			{
				for( std::vector<SceneGraph *>::const_iterator it = m_children.begin(), eIt = m_children.end(); it != eIt; ++it )
				{
					/// \todo Should be able to prune recursion based on knowledge that child
					/// selection ids are always greater than parent selection ids.
					if( (*it)->pathFromSelectionIdWalk( selectionId, path ) )
					{
						if( m_name != IECore::InternedString() )
						{
							path.push_back( m_name );
						}
						return true;
					}
				}
			}

			return false;
		}

		static const IECoreGL::State &selectionState()
		{
			static IECoreGL::StatePtr s;
			if( !s )
			{
				s = new IECoreGL::State( false );
				s->add( new IECoreGL::Primitive::DrawWireframe( true ), /* override = */ true );
				s->add( new IECoreGL::WireframeColorStateComponent( Color4f( 0.466f, 0.612f, 0.741f, 1.0f ) ), /* override = */ true );
			}
			return *s;
		}

		static const IECoreGL::State &wireframeState()
		{
			static IECoreGL::StatePtr s;
			if( !s )
			{
				s = new IECoreGL::State( false );
				s->add( new IECoreGL::Primitive::DrawWireframe( true ), /* override = */ true );
				s->add( new IECoreGL::Primitive::DrawSolid( false ), /* override = */ true );
				s->add( new IECoreGL::CurvesPrimitive::UseGLLines( true ), /* override = */ true );
			}
			return *s;
		}

		Imath::Box3f m_bound;
		Imath::M44f m_transform;
		IECore::InternedString m_name;
		IECoreGL::ConstStatePtr m_state;
		IECoreGL::ConstRenderablePtr m_renderable;
		IECoreGL::ConstRenderablePtr m_boundRenderable;
		std::vector<SceneGraph *> m_children;
		mutable GLuint m_selectionId;
		bool m_selected;
		bool m_visible;
		bool m_expanded;

		IECore::MurmurHash m_objectHash;
		IECore::MurmurHash m_attributesHash;

};

class SceneGadget::UpdateTask : public tbb::task
{

	public :

		enum DirtyFlags
		{
			NothingDirty = 0,
			BoundDirty = 1,
			TransformDirty = 2,
			AttributesDirty = 4,
			ObjectDirty = 8,
			ChildNamesDirty = 16,
			ExpansionDirty = 32,
			AllDirty = BoundDirty | TransformDirty | AttributesDirty | ObjectDirty | ChildNamesDirty | ExpansionDirty
		};

		UpdateTask( const SceneGadget *sceneGadget, SceneGraph *sceneGraph, unsigned dirtyFlags, const ScenePlug::ScenePath &scenePath )
			:	m_sceneGadget( sceneGadget ),
				m_sceneGraph( sceneGraph ),
				m_dirtyFlags( dirtyFlags ),
				m_scenePath( scenePath )
		{
		}

		virtual task *execute()
		{
			ContextPtr context = new Context( *m_sceneGadget->m_context, Context::Borrowed );
			context->set( ScenePlug::scenePathContextName, m_scenePath );
			Context::Scope scopedContext( context.get() );

			// Update attributes, and compute visibility.

			const bool previouslyVisible = m_sceneGraph->m_visible;
			if( m_dirtyFlags & AttributesDirty )
			{
				const IECore::MurmurHash attributesHash = m_sceneGadget->m_scene->attributesPlug()->hash();
				if( attributesHash != m_sceneGraph->m_attributesHash )
				{
					IECore::ConstCompoundObjectPtr attributes = m_sceneGadget->m_scene->attributesPlug()->getValue( &attributesHash );
					const IECore::BoolData *visibilityData = attributes->member<IECore::BoolData>( "scene:visible" );
					m_sceneGraph->m_visible = visibilityData ? visibilityData->readable() : true;

					IECore::ConstRunTimeTypedPtr glState = IECoreGL::CachedConverter::defaultCachedConverter()->convert( attributes.get() );
					deferReferenceRemoval( m_sceneGraph->m_state );
					m_sceneGraph->m_state = IECore::runTimeCast<const IECoreGL::State>( glState );

					m_sceneGraph->m_attributesHash = attributesHash;
				}
			}

			if( !m_sceneGraph->m_visible )
			{
				// No need to update further since we're not visible.
				return NULL;
			}
			else if( !previouslyVisible )
			{
				// We didn't perform any updates when we were invisible,
				// so we need to update everything now.
				m_dirtyFlags = AllDirty;
			}

			// Update the object - converting it into an IECoreGL::Renderable

			if( m_dirtyFlags & ObjectDirty )
			{
				const IECore::MurmurHash objectHash = m_sceneGadget->m_scene->objectPlug()->hash();
				if( objectHash != m_sceneGraph->m_objectHash )
				{
					IECore::ConstObjectPtr object = m_sceneGadget->m_scene->objectPlug()->getValue( &objectHash );
					deferReferenceRemoval( m_sceneGraph->m_renderable );
					if( !object->isInstanceOf( IECore::NullObjectTypeId ) )
					{
						m_sceneGraph->m_renderable = objectToRenderable( object.get() );
					}
					m_sceneGraph->m_objectHash = objectHash;
				}
			}

			// Update the transform and bound

			if( m_dirtyFlags & TransformDirty )
			{
				m_sceneGraph->m_transform = m_sceneGadget->m_scene->transformPlug()->getValue();
			}

			m_sceneGraph->m_bound = m_sceneGraph->m_renderable ? m_sceneGraph->m_renderable->bound() : Box3f();

			// Update the expansion state

			const bool previouslyExpanded = m_sceneGraph->m_expanded;
			if( m_dirtyFlags & ExpansionDirty )
			{
				m_sceneGraph->m_expanded = m_sceneGadget->m_minimumExpansionDepth >= m_scenePath.size();
				if( !m_sceneGraph->m_expanded )
				{
					m_sceneGraph->m_expanded = m_sceneGadget->m_expandedPaths->readable().match( m_scenePath ) & Filter::ExactMatch;
				}
			}

			// If we're not expanded, then we can early out after creating a bounding box.

			deferReferenceRemoval( m_sceneGraph->m_boundRenderable );
			if( !m_sceneGraph->m_expanded )
			{
				// We're not expanded, so we early out before updating the children.
				// We do however need to see if we have any children, and arrange to
				// draw their bounding box if we do.
				bool haveChildren = m_sceneGraph->m_children.size();
				if( m_dirtyFlags & ChildNamesDirty || !previouslyExpanded )
				{
					IECore::ConstInternedStringVectorDataPtr childNamesData = m_sceneGadget->m_scene->childNamesPlug()->getValue();
					haveChildren = childNamesData->readable().size();
				}

				m_sceneGraph->clearChildren();

				m_sceneGraph->m_bound.extendBy( m_sceneGadget->m_scene->boundPlug()->getValue() );

				if( haveChildren )
				{
					IECore::CurvesPrimitivePtr curvesBound = IECore::CurvesPrimitive::createBox( m_sceneGraph->m_bound );
					m_sceneGraph->m_boundRenderable = boost::static_pointer_cast<const IECoreGL::Renderable>(
						IECoreGL::CachedConverter::defaultCachedConverter()->convert( curvesBound.get() )
					);
				}
				return NULL;
			}

			// We are expanded, so we need to visit all the children
			// and update those too.

			if( !previouslyExpanded )
			{
				m_dirtyFlags = AllDirty;
			}

			// Make sure we have a child for each child name

			if( m_dirtyFlags & ChildNamesDirty )
			{
				IECore::ConstInternedStringVectorDataPtr childNamesData = m_sceneGadget->m_scene->childNamesPlug()->getValue();
				const std::vector<IECore::InternedString> &childNames = childNamesData->readable();
				if( !existingChildNamesValid( childNames ) )
				{
					m_sceneGraph->clearChildren();

					for( std::vector<IECore::InternedString>::const_iterator it = childNames.begin(), eIt = childNames.end(); it != eIt; ++it )
					{
						SceneGraph *child = new SceneGraph();
						child->m_name = *it;
						m_sceneGraph->m_children.push_back( child );
					}

					m_dirtyFlags = AllDirty; // We've made brand new children, so they need a full update.
				}
			}

			// And then update each child

			if( m_sceneGraph->m_children.size() )
			{
				set_ref_count( 1 + m_sceneGraph->m_children.size() );

				ScenePlug::ScenePath childPath = m_scenePath;
				childPath.push_back( IECore::InternedString() ); // space for the child name
				for( std::vector<SceneGraph *>::const_iterator it = m_sceneGraph->m_children.begin(), eIt = m_sceneGraph->m_children.end(); it != eIt; ++it )
				{
					childPath.back() = (*it)->m_name;
					UpdateTask *t = new( allocate_child() ) UpdateTask( m_sceneGadget, *it, m_dirtyFlags, childPath );
					spawn( *t );
				}

				wait_for_all();
			}

			// Finally compute our bound from the child bounds.

			for( std::vector<SceneGraph *>::const_iterator it = m_sceneGraph->m_children.begin(), eIt = m_sceneGraph->m_children.end(); it != eIt; ++it )
			{
				const Box3f childBound = transform( (*it)->m_bound, (*it)->m_transform );
				m_sceneGraph->m_bound.extendBy( childBound );
			}

			return NULL;
		}

	private :

		bool existingChildNamesValid( const vector<IECore::InternedString> &childNames )
		{
			if( m_sceneGraph->m_children.size() != childNames.size() )
			{
				return false;
			}
			for( size_t i = 0, e = childNames.size(); i < e; ++i )
			{
				if( m_sceneGraph->m_children[i]->m_name != childNames[i] )
				{
					return false;
				}
			}
			return true;
		}

		const SceneGadget *m_sceneGadget;
		SceneGraph *m_sceneGraph;
		unsigned m_dirtyFlags;
		ScenePlug::ScenePath m_scenePath;

};

//////////////////////////////////////////////////////////////////////////
// SceneGadget implementation
//////////////////////////////////////////////////////////////////////////

SceneGadget::SceneGadget()
	:	Gadget( defaultName<SceneGadget>() ),
		m_scene( NULL ),
		m_context( NULL ),
		m_dirtyFlags( UpdateTask::AllDirty ),
		m_expandedPaths( new PathMatcherData ),
		m_minimumExpansionDepth( 0 ),
		m_baseState( new IECoreGL::State( true ) ),
		m_sceneGraph( new SceneGraph ),
		m_selection( new PathMatcherData )
{
	setContext( new Context );
}

SceneGadget::~SceneGadget()
{
}

void SceneGadget::setScene( GafferScene::ConstScenePlugPtr scene )
{
	if( scene == m_scene )
	{
		return;
	}

	m_scene = scene;
	if( Gaffer::Node *node = const_cast<Gaffer::Node *>( scene->node() ) )
	{
		m_plugDirtiedConnection = node->plugDirtiedSignal().connect( boost::bind( &SceneGadget::plugDirtied, this, ::_1 ) );
	}
	else
	{
		m_plugDirtiedConnection.disconnect();
	}

	m_dirtyFlags = UpdateTask::AllDirty;
	requestRender();
}

const GafferScene::ScenePlug *SceneGadget::getScene() const
{
	return m_scene.get();
}

void SceneGadget::setContext( Gaffer::ContextPtr context )
{
	if( context == m_context )
	{
		return;
	}

	m_context = context;
	m_contextChangedConnection = m_context->changedSignal().connect( boost::bind( &SceneGadget::contextChanged, this, ::_2 ) );
	requestRender();
}

Gaffer::Context *SceneGadget::getContext()
{
	return m_context.get();
}

const Gaffer::Context *SceneGadget::getContext() const
{
	return m_context.get();
}

void SceneGadget::setExpandedPaths( GafferScene::ConstPathMatcherDataPtr expandedPaths )
{
	m_expandedPaths = expandedPaths;
	m_dirtyFlags |= UpdateTask::ExpansionDirty;
	requestRender();
}

const GafferScene::PathMatcherData *SceneGadget::getExpandedPaths() const
{
	return m_expandedPaths.get();
}

void SceneGadget::setMinimumExpansionDepth( size_t depth )
{
	if( depth == m_minimumExpansionDepth )
	{
		return;
	}
	m_minimumExpansionDepth = depth;
	m_dirtyFlags |= UpdateTask::ExpansionDirty;
	requestRender();
}

size_t SceneGadget::getMinimumExpansionDepth() const
{
	return m_minimumExpansionDepth;
}

IECoreGL::State *SceneGadget::baseState()
{
	return m_baseState.get();
}

bool SceneGadget::objectAt( const IECore::LineSegment3f &lineInGadgetSpace, GafferScene::ScenePlug::ScenePath &path ) const
{
	updateSceneGraph();

	std::vector<IECoreGL::HitRecord> selection;
	{
		ViewportGadget::SelectionScope selectionScope( lineInGadgetSpace, this, selection, IECoreGL::Selector::IDRender );
		renderSceneGraph( selectionScope.baseState() );
	}

	if( !selection.size() )
	{
		return false;
	}

	return m_sceneGraph->pathFromSelectionId( selection[0].name, path );
}

size_t SceneGadget::objectsAt(
	const Imath::V3f &corner0InGadgetSpace,
	const Imath::V3f &corner1InGadgetSpace,
	GafferScene::PathMatcher &paths
) const
{
	updateSceneGraph();

	std::vector<IECoreGL::HitRecord> selection;
	{
		ViewportGadget::SelectionScope selectionScope( corner0InGadgetSpace, corner1InGadgetSpace, this, selection, IECoreGL::Selector::OcclusionQuery );
		renderSceneGraph( selectionScope.baseState() );
	}

	size_t result = 0;
	ScenePlug::ScenePath path;
	for( std::vector<IECoreGL::HitRecord>::const_iterator it = selection.begin(), eIt = selection.end(); it != eIt; ++it )
	{
		if( m_sceneGraph->pathFromSelectionId( it->name, path ) )
		{
			result += paths.addPath( path );
		}
	}

	return result;
}

const GafferScene::PathMatcherData *SceneGadget::getSelection() const
{
	return m_selection.get();
}

void SceneGadget::setSelection( ConstPathMatcherDataPtr selection )
{
	m_selection = selection;
	m_sceneGraph->applySelection( m_selection->readable() );
	requestRender();
}

Imath::Box3f SceneGadget::selectionBound() const
{
	updateSceneGraph();
	return m_sceneGraph->selectionBound();
}

std::string SceneGadget::getToolTip( const IECore::LineSegment3f &line ) const
{
	std::string result = Gadget::getToolTip( line );
	if( result.size() )
	{
		return result;
	}

	ScenePlug::ScenePath path;
	if( objectAt( line, path ) )
	{
		ScenePlug::pathToString( path, result );
	}

	return result;
}

Imath::Box3f SceneGadget::bound() const
{
	updateSceneGraph();
	return m_sceneGraph->bound();
}

void SceneGadget::doRender( const GafferUI::Style *style ) const
{
	if( !m_scene || IECoreGL::Selector::currentSelector() )
	{
		return;
	}

	updateSceneGraph();
	renderSceneGraph( m_baseState.get() );

	doPendingReferenceRemovals();
}

void SceneGadget::plugDirtied( const Gaffer::Plug *plug )
{
	if( plug == m_scene->boundPlug() )
	{
		m_dirtyFlags |= UpdateTask::BoundDirty;
	}
	else if( plug == m_scene->transformPlug() )
	{
		m_dirtyFlags |= UpdateTask::TransformDirty;
	}
	else if( plug == m_scene->attributesPlug() )
	{
		m_dirtyFlags |= UpdateTask::AttributesDirty;
	}
	else if( plug == m_scene->objectPlug() )
	{
		m_dirtyFlags |= UpdateTask::ObjectDirty;
	}
	else if( plug == m_scene->childNamesPlug() )
	{
		m_dirtyFlags |= UpdateTask::ChildNamesDirty;
	}
	else
	{
		return;
	}

	requestRender();
}

void SceneGadget::contextChanged( const IECore::InternedString &name )
{
	if( !boost::starts_with( name.string(), "ui:" ) )
	{
		m_dirtyFlags = UpdateTask::AllDirty;
		requestRender();
	}
}

void SceneGadget::updateSceneGraph() const
{
	if( !m_dirtyFlags )
	{
		return;
	}

	if( !m_sceneGraph->valid() )
	{
		// The previous attempt at an update failed - so
		// we need to update everything this time.
		m_dirtyFlags = UpdateTask::AllDirty;
	}

	try
	{
		UpdateTask *task = new( tbb::task::allocate_root() ) UpdateTask( this, m_sceneGraph.get(), m_dirtyFlags, ScenePlug::ScenePath() );
		tbb::task::spawn_root_and_wait( *task );

		if( m_dirtyFlags && UpdateTask::ChildNamesDirty )
		{
			m_sceneGraph->applySelection( m_selection->readable() );
		}
	}
	catch( const std::exception& e )
	{
		m_sceneGraph->clear();
		IECore::msg( IECore::Msg::Error, "SceneGadget::updateSceneGraph", e.what() );
	}

	// Even if an error occurred when updating the scene, we clear
	// the dirty flags. This prevents us from repeating the same
	// error over and over when nothing has been done to prevent it.
	// When something is next dirtied we'll turn on all the dirty
	// flags (see above) to ensure that the next update is a complete
	// one.
	m_dirtyFlags = UpdateTask::NothingDirty;
}

void SceneGadget::renderSceneGraph( const IECoreGL::State *stateToBind ) const
{
	GLint prevProgram;
	glGetIntegerv( GL_CURRENT_PROGRAM, &prevProgram );
	glPushAttrib( GL_ALL_ATTRIB_BITS );

	try
	{
		IECoreGL::State::bindBaseState();
		stateToBind->bind();
		m_sceneGraph->render( const_cast<IECoreGL::State *>( stateToBind ), IECoreGL::Selector::currentSelector() );
	}
	catch( const std::exception& e )
	{
		IECore::msg( IECore::Msg::Error, "SceneGadget::renderSceneGraph", e.what() );
	}

	glPopAttrib();
	glUseProgram( prevProgram );
}


text:
<md-nav-list md-layout="column" md-fill>
    <md-list-item  md-2-line *ngFor="let dataset of datasets; let i = index;" (click)="connectToPreset(i, false)"
        [class.accent]="(activeDataset.name === dataset.name)">

{{ dataset.name }}

{{ dataset.databases.length }} Database

    </md-list-item>
</md-nav-list>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Threading.Tasks;
using Windows.Storage;

namespace CodePush.ReactNative
{
    internal class FileUtils
    {
        internal async static Task MergeFoldersAsync(StorageFolder source, StorageFolder target)
        {
            foreach (StorageFile sourceFile in await source.GetFilesAsync().AsTask().ConfigureAwait(false))
            {
                await sourceFile.CopyAndReplaceAsync(await target.CreateFileAsync(sourceFile.Name, CreationCollisionOption.OpenIfExists).AsTask().ConfigureAwait(false)).AsTask().ConfigureAwait(false);
            }

            foreach (StorageFolder sourceDirectory in await source.GetFoldersAsync().AsTask().ConfigureAwait(false))
            {
                StorageFolder nextTargetSubDir = await target.CreateFolderAsync(sourceDirectory.Name, CreationCollisionOption.OpenIfExists).AsTask().ConfigureAwait(false);
                await MergeFoldersAsync(sourceDirectory, nextTargetSubDir).ConfigureAwait(false);
            }
        }

        internal async static Task ClearReactDevBundleCacheAsync()
        {
            var devBundleCacheFile = (StorageFile)await ApplicationData.Current.LocalFolder.TryGetItemAsync(CodePushConstants.ReactDevBundleCacheFileName).AsTask().ConfigureAwait(false);
            if (devBundleCacheFile != null)
            {
                await devBundleCacheFile.DeleteAsync().AsTask().ConfigureAwait(false);
            }
        }

        internal async static Task<long> GetBinaryResourcesModifiedTimeAsync(string fileName)
        {
            var assetJSBundleFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(CodePushConstants.AssetsBundlePrefix + fileName)).AsTask().ConfigureAwait(false);
            var fileProperties = await assetJSBundleFile.GetBasicPropertiesAsync().AsTask().ConfigureAwait(false);
            return fileProperties.DateModified.ToUnixTimeMilliseconds();
        }

    }
}


text:
<?php

namespace HiPay\Fullservice\HTTP\Configuration;

/**
 * Client configuration interface.
 *
 * This contains needed get methods.
 * Get methods are used by HTTP client to do authentication and know which endpoint to use
 *
 * @category    HiPay
 * @package     HiPay\Fullservice
 * @author      HiPay <support.tpp@hipay.com>
 * @copyright   Copyright (c) 2019 - HiPay
 * @license     http://www.apache.org/licenses/LICENSE-2.0 Apache 2.0 License
 * @link        https://github.com/hipay/hipay-fullservice-sdk-php
 * @api
 */
interface ConfigurationInterface
{
    /**
     * Return merchant api username
     *
     * @return string Username for authentication
     */
    public function getApiUsername();

    /**
     * Return merchant api password
     *
     * @return string Password for authentication
     */
    public function getApiPassword();

    /**
     * Return API Environment
     *
     * @return string *stage* or *production*
     */
    public function getApiEnv();

    /**
     * Return production api endpoint
     *
     * @return string $_apiEndpointProd Production api endpoint
     */
    public function getApiEndpointProd();

    /**
     * Return stage api endpoint
     *
     * @return string $_apiEndpointStage Stage api endpoint
     */
    public function getApiEndpointStage();

    /**
     * Return api endpoint based on API_ENV
     *
     * If API_ENV is equals to *stage*, we return value of API_ENDPOINT_STAGE
     * else we return value of API_ENDPOINT_PROD
     *
     * @return string API_ENDPOINT Final api endpoint
     */
    public function getApiEndpoint();

    /**
     * Return production api endpoint v2
     *
     * @return string $_apiEndpointProdV2 Production api endpoint
     */
    public function getApiEndpointV2Prod();

    /**
     * Return stage api endpoint v2
     *
     * @return string $_apiEndpointStageV2 Stage api endpoint
     */
    public function getApiEndpointV2Stage();

    /**
     * Return api endpoint v2 based on API_ENV
     *
     * If API_ENV is equals to *stage*, we return value of API_ENDPOINT_V2_STAGE
     * else we return value of API_ENDPOINT_V2_PROD
     *
     * @return string API_ENDPOINT_V2 Final api endpoint from GPC
     */
    public function getApiEndpointV2();

    /**
     * Return production data api endpoint
     *
     * @return string $_dataApiEndpointProd Production data api endpoint
     */
    public function getDataApiEndpointProd();

    /**
     * Return stage data api endpoint
     *
     * @return string $_dataApiEndpointStage Stage data api endpoint
     */
    public function getDataApiEndpointStage();

    /**
     * Return data api endpoint based on API_ENV
     *
     * If API_ENV is equals to *stage*, we return value of DATA_API_ENDPOINT_STAGE
     * else we return value of DATA_API_ENDPOINT_PRODUCTION
     *
     * @return string DATA_API_ENDPOINT Final data api endpoint
     */
    public function getDataApiEndpoint();

    /**
     * Returns user agent used for data api
     *
     * @return string DATA_API_HTTP_USER_AGENT User agent for data API
     */
    public function getDataApiHttpUserAgent();

    /**
     * Return production secure vault endpoint
     *
     * @return string $_secureVaultEndpointProd Production vault endpoint
     */
    public function getSecureVaultEndpointProd();

    /**
     * Return stage vault endpoint
     *
     * @return string $_secureVaultEndpointStage Stage vault endpoint
     */
    public function getSecureVaultEndpointStage();

    /**
     * Return vault endpoint based on API_ENV
     *
     * If API_ENV is equals to *stage*, we return value of SECURE_VAULT_ENDPOINT_STAGE
     * else we return value of SECURE_VAULT_ENDPOINT_PRODUCTION
     *
     * @return string SECURE_VAULT_ENDPOINT Final vault endpoint
     */
    public function getSecureVaultEndpoint();

    /**
     * Return Header Accept.
     *
     * @return string $_apiHTTPHeaderAccept Header Accept value (Default: application/json)
     */
    public function getApiHTTPHeaderAccept();

    /**
     * Return proxy configuration
     *
     * @return array<string, mixed> with keys "host", "port", "user", "password"
     */
    public function getProxy();

    /**
     * Return Curl timeout configuration
     *
     * @return int
     */
    public function getCurlTimeout();

    /**
     * Return Curl connect timeout configuration
     *
     * @return int
     */
    public function getCurlConnectTimeout();

    /**
     * Sets Merchant API Username
     *
     * @param string $apiUsername
     * @return void
     */
    public function setApiUsername($apiUsername);

    /**
     * Sets Merchant API Password
     *
     * @param string $apiPassword
     * @return void
     */
    public function setApiPassword($apiPassword);

    /**
     * Sets targeted environment
     *
     * @param string $apiEnv
     * @return void
     */
    public function setApiEnv($apiEnv);

    /**
     * Sets HTTP Accept header for requests
     * @param string $apiHTTPHeaderAccept
     * @return void
     */
    public function setApiHTTPHeaderAccept($apiHTTPHeaderAccept);

    /**
     * Sets proxy configuration
     *
     * @param array<string, mixed> $proxy
     * @return void
     */
    public function setProxy($proxy);

    /**
     * Sets Main timeout value for cUrl calls
     *
     * @param int $curl_timeout
     * @return void
     */
    public function setCurlTimeout($curl_timeout);

    /**
     * Sets connect timeout value for cUrl calls
     *
     * @param int $curl_connect_timeout
     * @return void
     */
    public function setCurlConnectTimeout($curl_connect_timeout);

    /**
     * Returns override sorting payment products parameter
     *
     * @return bool
     */
    public function isOverridePaymentProductSorting();

    /**
     * Sets override sorting payment products parameter
     *
     * @param bool $overridePaymentProductSorting
     * @return void
     */
    public function setOverridePaymentProductSorting($overridePaymentProductSorting);

    /**
     * Returns hostedpage v2 parameter
     *
     * @return bool
     */
    public function isHostedPageV2();

    /**
     * Sets hostedpage v2 parameter
     *
     * @param bool $hostedPageV2
     * @return void
     */
    public function setHostedPageV2($hostedPageV2);
}


text:
#ifndef TESTMATLABTHREAD_H
#define TESTMATLABTHREAD_H

#include "MatlabThread.h"

#include <QCryptographicHash>

#include <iostream>

class TestMatlabThread
{
public:
    TestMatlabThread();

    /**********************************************************************/
    /*************************** Test Functions ***************************/
    /**********************************************************************/

    /*************** Script ***************/
    bool Test_InitMatlabScript( QString refMatlabScriptPath );

    bool Test_SetHeader();

    bool Test_SetMVCMPath();

    bool Test_SetFiberName();

    bool Test_SetDiffusionProperties();

    bool Test_SetInputFiles();

    bool Test_SetCovariates();

    bool Test_SetNbrPermutation();

    bool Test_SetOmnibus();

    bool Test_SetPostHoc();

    bool Test_SetConfidenceBandsThreshold();

    bool Test_SetPvalueThreshold();

    bool Test_GenerateMFiles( QString myFDR,  QString outputDir );

private:
    /**********************************************************************/
    /********************** Functions Used For Testing ********************/
    /**********************************************************************/
    QByteArray GetHashFile( QString filePath );

    bool CompareFile( QString filePath1, QString filePath2 );

    void DisplayError( QString expectedString, QString setString );
};

#endif // TESTMATLABTHREAD_H


text:
    <link rel="stylesheet" type="text/css" href="../style.css" />

    <canvas id="canvas" width="300" height="500"></canvas>


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Bork.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    public class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Bork.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to images/test1.png.
        /// </summary>
        public static string DummyImg1 {
            get {
                return ResourceManager.GetString("DummyImg1", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to images/test2.png.
        /// </summary>
        public static string DummyImg2 {
            get {
                return ResourceManager.GetString("DummyImg2", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to images/beam_test.png.
        /// </summary>
        public static string LazerTest {
            get {
                return ResourceManager.GetString("LazerTest", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to images/image.jpg.
        /// </summary>
        public static string TestAru {
            get {
                return ResourceManager.GetString("TestAru", resourceCulture);
            }
        }
    }
}


text:
package app

import (
	"context"
	"fmt"
	"io"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"github.com/pkg/errors"
	"github.com/tsuru/tsuru/builder"
	"github.com/tsuru/tsuru/db"
	"github.com/tsuru/tsuru/event"
	tsuruIo "github.com/tsuru/tsuru/io"
	"github.com/tsuru/tsuru/log"
	"github.com/tsuru/tsuru/permission"
	"github.com/tsuru/tsuru/provision"
	"github.com/tsuru/tsuru/router/rebuild"
	"github.com/tsuru/tsuru/servicemanager"
	"github.com/tsuru/tsuru/set"
	appTypes "github.com/tsuru/tsuru/types/app"
	permTypes "github.com/tsuru/tsuru/types/permission"
)

type DeployKind string

const (
	DeployArchiveURL   DeployKind = "archive-url"
	DeployGit          DeployKind = "git"
	DeployImage        DeployKind = "image"
	DeployBuildedImage DeployKind = "imagebuild"
	DeployRollback     DeployKind = "rollback"
	DeployUpload       DeployKind = "upload"
	DeployUploadBuild  DeployKind = "uploadbuild"
	DeployRebuild      DeployKind = "rebuild"
)

var reImageVersion = regexp.MustCompile(":v([0-9]+)$")

type DeployData struct {
	ID          bson.ObjectId `bson:"_id,omitempty"`
	App         string
	Timestamp   time.Time
	Duration    time.Duration
	Commit      string
	Error       string
	Image       string
	Version     int
	Log         string
	User        string
	Origin      string
	CanRollback bool
	Diff        string
	Message     string
}

func findValidImages(ctx context.Context, appNames []string) (set.Set, error) {
	validImages := set.Set{}

	allVersions, err := servicemanager.AppVersion.AllAppVersions(ctx, appNames...)
	if err != nil {
		return nil, err
	}

	for _, av := range allVersions {
		for _, version := range av.Versions {
			if version.DeploySuccessful && version.DeployImage != "" {
				validImages.Add(version.DeployImage)
			}
		}
	}
	return validImages, nil
}

// ListDeploys returns the list of deploy that match a given filter.
func ListDeploys(ctx context.Context, filter *Filter, skip, limit int) ([]DeployData, error) {
	var rawFilter bson.M
	if !filter.IsEmpty() {
		appsList, err := List(ctx, filter)
		if err != nil {
			return nil, err
		}
		apps := make([]string, len(appsList))
		for i, a := range appsList {
			apps[i] = a.GetName()
		}
		rawFilter = bson.M{"target.value": bson.M{"$in": apps}}
	}
	evts, err := event.List(&event.Filter{
		Target:    event.Target{Type: event.TargetTypeApp},
		Raw:       rawFilter,
		KindNames: []string{permission.PermAppDeploy.FullName()},
		KindType:  event.KindTypePermission,
		Limit:     limit,
		Skip:      skip,
	})
	if err != nil {
		return nil, err
	}
	if len(evts) == 0 {
		return []DeployData{}, nil
	}
	appsInEvents := set.Set{}
	for _, evt := range evts {
		appsInEvents.Add(evt.Target.Value)
	}
	validImages, err := findValidImages(ctx, appsInEvents.ToList())
	if err != nil {
		return nil, err
	}
	list := make([]DeployData, len(evts))
	for i := range evts {
		list[i] = *eventToDeployData(evts[i], validImages, false)
	}
	return list, nil
}

func GetDeploy(id string) (*DeployData, error) {
	if !bson.IsObjectIdHex(id) {
		return nil, errors.Errorf("id parameter is not ObjectId: %s", id)
	}
	objID := bson.ObjectIdHex(id)
	evt, err := event.GetByID(objID)
	if err != nil {
		return nil, err
	}
	return eventToDeployData(evt, nil, true), nil
}

func eventToDeployData(evt *event.Event, validImages set.Set, full bool) *DeployData {
	data := &DeployData{
		ID:        evt.UniqueID,
		App:       evt.Target.Value,
		Timestamp: evt.StartTime,
		Duration:  evt.EndTime.Sub(evt.StartTime),
		Error:     evt.Error,
		User:      evt.Owner.Name,
	}
	var err error
	var deployOptions DeployOptions
	if err = evt.StartData(&deployOptions); err == nil {
		data.Commit = deployOptions.Commit
		data.Origin = deployOptions.GetOrigin()
		data.Message = deployOptions.Message
	} else {
		log.Errorf("cannot decode the event's start custom data value: event %s - %v", evt.UniqueID, err)
	}
	if full {
		data.Log = evt.Log()
		var otherData map[string]string
		if err = evt.OtherData(&otherData); err == nil {
			data.Diff = otherData["diff"]
		} else {
			log.Errorf("cannot decode the event's other custom data value: event %s - %v", evt.UniqueID, err)
		}
	}
	var endData map[string]string
	if err = evt.EndData(&endData); err == nil {
		data.Image = endData["image"]
		if reImageVersion.MatchString(data.Image) {
			parts := reImageVersion.FindStringSubmatch(data.Image)
			data.Version, _ = strconv.Atoi(parts[1])
		}
		if validImages != nil {
			data.CanRollback = validImages.Includes(data.Image)
		}
	} else {
		log.Errorf("cannot decode the event's end custom data value: event %s - %v", evt.UniqueID, err)
	}
	return data
}

type DeployOptions struct {
	App              *App
	Commit           string
	BuildTag         string
	ArchiveURL       string
	FileSize         int64
	File             io.ReadCloser `bson:"-"`
	OutputStream     io.Writer     `bson:"-"`
	User             string
	Image            string
	Origin           string
	Event            *event.Event `bson:"-"`
	Kind             DeployKind
	Message          string
	Rollback         bool
	Build            bool
	NewVersion       bool
	OverrideVersions bool
}

func (o *DeployOptions) GetOrigin() string {
	if o.Origin != "" {
		return o.Origin
	}
	if o.Commit != "" {
		return "git"
	}
	return ""
}

func (o *DeployOptions) GetKind() (kind DeployKind) {
	defer func() {
		o.Kind = kind
	}()
	if o.Rollback {
		return DeployRollback
	}
	if o.Image != "" {
		return DeployImage
	}
	if o.File != nil {
		if o.Build {
			return DeployUploadBuild
		}
		return DeployUpload
	}
	if o.Commit != "" {
		return DeployGit
	}
	return DeployArchiveURL
}

func Build(ctx context.Context, opts DeployOptions) (string, error) {
	if opts.Event == nil {
		return "", errors.Errorf("missing event in build opts")
	}
	logWriter := LogWriter{AppName: opts.App.Name}
	logWriter.Async()
	defer logWriter.Close()
	opts.Event.SetLogWriter(io.MultiWriter(&tsuruIo.NoErrorWriter{Writer: opts.OutputStream}, &logWriter))
	prov, err := opts.App.getProvisioner()
	if err != nil {
		return "", err
	}
	if opts.App.GetPlatform() == "" {
		return "", errors.Errorf("can't build app without platform")
	}
	builder, ok := prov.(provision.BuilderDeploy)
	if !ok {
		return "", errors.Errorf("provisioner don't implement builder interface")
	}
	version, err := builderDeploy(ctx, builder, &opts, opts.Event)
	if err != nil {
		return "", err
	}
	vi := version.VersionInfo()
	if vi.DeployImage != "" {
		return vi.DeployImage, nil
	}
	return vi.BuildImage, nil
}

type errorWithLog struct {
	err    error
	action string
	logs   []appTypes.Applog
}

func newErrorWithLog(base error, app *App, action string) *errorWithLog {
	logErr := &errorWithLog{
		err:    base,
		action: action,
	}
	if startupErr, ok := provision.IsStartupError(base); ok {
		logErr.logs = startupErr.CrashedUnitsLogs
		if logErr.logs != nil {
			return logErr
		}

		tokenValue := app.Env["TSURU_APP_TOKEN"].Value
		token, _ := AuthScheme.Auth(app.ctx, tokenValue)

		logErr.logs, _ = app.LastLogs(app.ctx, servicemanager.AppLog, appTypes.ListLogArgs{
			Source:       "tsuru",
			InvertSource: true,
			Units:        startupErr.CrashedUnits,
			Token:        token,
			Limit:        10,
		})
	}
	return logErr
}

func (e *errorWithLog) Cause() error {
	return e.err
}

func (e *errorWithLog) formatLogLines() string {
	const timeFormat = "2006-01-02 15:04:05 -0700"
	linesStr := make([]string, len(e.logs))
	for i, l := range e.logs {
		linesStr[i] = fmt.Sprintf("    %s [%s][%s]: %s", l.Date.Local().Format(timeFormat), l.Source, l.Unit, l.Message)
	}
	return strings.Join(linesStr, "\n")
}

func (e *errorWithLog) Error() string {
	var logPart string
	if len(e.logs) > 0 {
		logPart = fmt.Sprintf("\n---- Last %d log messages: ----\n%s", len(e.logs), e.formatLogLines())
	}
	return fmt.Sprintf("\n---- ERROR during %s: ----\n%v\n%s", e.action, e.err, logPart)
}

func validateVersions(ctx context.Context, opts DeployOptions) error {
	if opts.NewVersion && opts.OverrideVersions {
		return errors.New("conflicting deploy flags, new-version and override-old-versions")
	}
	if opts.NewVersion || opts.OverrideVersions {
		return nil
	}
	multi, err := opts.App.hasMultipleVersions(ctx)
	if err != nil {
		return err
	}
	if multi {
		return errors.New("multiple versions currently deployed, either new-version or override-old-versions must be set")
	}
	return nil
}

// Deploy runs a deployment of an application. It will first try to run an
// archive based deploy (if opts.ArchiveURL is not empty), and then fallback to
// the Git based deployment.
func Deploy(ctx context.Context, opts DeployOptions) (string, error) {
	if opts.Event == nil {
		return "", errors.Errorf("missing event in deploy opts")
	}
	err := validateVersions(ctx, opts)
	if err != nil {
		return "", err
	}
	logWriter := LogWriter{AppName: opts.App.Name}
	logWriter.Async()
	defer logWriter.Close()
	opts.Event.SetLogWriter(io.MultiWriter(&tsuruIo.NoErrorWriter{Writer: opts.OutputStream}, &logWriter))
	imageID, err := deployToProvisioner(ctx, &opts, opts.Event)
	rebuild.RoutesRebuildOrEnqueueWithProgress(opts.App.Name, opts.Event)
	if err != nil {
		return "", newErrorWithLog(err, opts.App, "deploy")
	}
	err = incrementDeploy(opts.App)
	if err != nil {
		log.Errorf("WARNING: couldn't increment deploy count, deploy opts: %#v", opts)
	}
	if opts.Kind == DeployImage || opts.Kind == DeployRollback {
		if !opts.App.UpdatePlatform {
			opts.App.SetUpdatePlatform(true)
		}
	} else if opts.App.UpdatePlatform {
		opts.App.SetUpdatePlatform(false)
	}
	return imageID, nil
}

func RollbackUpdate(ctx context.Context, app *App, imageID, reason string, disableRollback bool) error {
	version, err := servicemanager.AppVersion.VersionByImageOrVersion(ctx, app, imageID)
	if err != nil {
		return err
	}
	return version.ToggleEnabled(!disableRollback, reason)
}

func deployToProvisioner(ctx context.Context, opts *DeployOptions, evt *event.Event) (string, error) {
	prov, err := opts.App.getProvisioner()
	if err != nil {
		return "", err
	}
	if opts.Kind == "" {
		opts.GetKind()
	}
	if opts.App.GetPlatform() == "" && opts.Kind != DeployImage && opts.Kind != DeployRollback {
		return "", errors.Errorf("can't deploy app without platform, if it's not an image or rollback")
	}

	deployer, ok := prov.(provision.BuilderDeploy)
	if !ok {
		return "", provision.ProvisionerNotSupported{Prov: prov, Action: fmt.Sprintf("%s deploy", opts.Kind)}
	}

	var version appTypes.AppVersion
	if opts.Kind == DeployRollback {
		version, err = servicemanager.AppVersion.VersionByImageOrVersion(ctx, opts.App, opts.Image)
		if err != nil {
			return "", err
		}
		versionInfo := version.VersionInfo()
		if versionInfo.MarkedToRemoval {
			return "", appTypes.ErrVersionMarkedToRemoval
		} else if versionInfo.Disabled {
			return "", errors.Errorf("the selected version is disabled for rollback: %s", version.VersionInfo().DisabledReason)
		}
	} else {
		version, err = builderDeploy(ctx, deployer, opts, evt)
		if err != nil {
			return "", err
		}
	}
	return deployer.Deploy(ctx, provision.DeployArgs{
		App:              opts.App,
		Version:          version,
		Event:            evt,
		PreserveVersions: opts.NewVersion,
		OverrideVersions: opts.OverrideVersions,
	})
}

func builderDeploy(ctx context.Context, prov provision.BuilderDeploy, opts *DeployOptions, evt *event.Event) (appTypes.AppVersion, error) {
	isRebuild := opts.Kind == DeployRebuild
	buildOpts := builder.BuildOpts{
		BuildFromFile: opts.Build,
		ArchiveURL:    opts.ArchiveURL,
		ArchiveFile:   opts.File,
		ArchiveSize:   opts.FileSize,
		Rebuild:       isRebuild,
		ImageID:       opts.Image,
		Tag:           opts.BuildTag,
		Message:       opts.Message,
	}
	builder, err := opts.App.getBuilder()
	if err != nil {
		return nil, err
	}
	version, err := builder.Build(ctx, prov, opts.App, evt, &buildOpts)
	if buildOpts.IsTsuruBuilderImage {
		opts.Kind = DeployBuildedImage
	}
	return version, err
}

func ValidateOrigin(origin string) bool {
	originList := []string{"app-deploy", "git", "rollback", "drag-and-drop", "image", "rebuild"}
	for _, ol := range originList {
		if ol == origin {
			return true
		}
	}
	return false
}

func incrementDeploy(app *App) error {
	conn, err := db.Conn()
	if err != nil {
		return err
	}
	defer conn.Close()
	err = conn.Apps().Update(
		bson.M{"name": app.Name},
		bson.M{"$inc": bson.M{"deploys": 1}},
	)
	if err == nil {
		app.Deploys += 1
	}
	return err
}

func deployDataToEvent(data *DeployData) error {
	var evt event.Event
	evt.UniqueID = data.ID
	evt.Target = event.Target{Type: event.TargetTypeApp, Value: data.App}
	evt.Owner = event.Owner{Type: event.OwnerTypeUser, Name: data.User}
	evt.Kind = event.Kind{Type: event.KindTypePermission, Name: permission.PermAppDeploy.FullName()}
	evt.StartTime = data.Timestamp
	evt.EndTime = data.Timestamp.Add(data.Duration)
	evt.Error = data.Error
	evt.StructuredLog = []event.LogEntry{
		{Message: data.Log},
	}
	a, err := GetByName(context.TODO(), data.App)
	if err == nil {
		evt.Allowed = event.Allowed(permission.PermAppReadEvents, append(permission.Contexts(permTypes.CtxTeam, a.Teams),
			permission.Context(permTypes.CtxApp, a.Name),
			permission.Context(permTypes.CtxPool, a.Pool),
		)...)
	} else {
		evt.Allowed = event.Allowed(permission.PermAppReadEvents)
	}
	startOpts := DeployOptions{
		Commit: data.Commit,
		Origin: data.Origin,
	}
	var otherData map[string]string
	if data.Diff != "" {
		otherData = map[string]string{"diff": data.Diff}
	}
	endData := map[string]string{"image": data.Image}
	err = evt.RawInsert(startOpts, otherData, endData)
	if mgo.IsDup(err) {
		return nil
	}
	return err
}

func MigrateDeploysToEvents() error {
	conn, err := db.Conn()
	if err != nil {
		return err
	}
	defer conn.Close()
	oldDeploysColl := conn.Collection("deploys")
	iter := oldDeploysColl.Find(nil).Iter()
	var data DeployData
	for iter.Next(&data) {
		err = deployDataToEvent(&data)
		if err != nil {
			return err
		}
	}
	return iter.Close()
}


text:
TensorLayer Implementation of [YOLOv4: Optimal Speed and Accuracy of Object Detection][1]

TensorLayer Implementation of [Optimizing Network Structure for 3D Human Pose Estimation][2](ICCV2019)

## YOLOv4

Yolov4 was trained on COCO 2017 Dataset in this demo.

### Data

Download yolov4.weights file [yolov4_model.npz][3], Password: `idsz`, and put yolov4.weights under the folder `./examples/app_tutorials/model/`. Your directory structure should look like this:

```
${root}/examples
    └── app_tutorials
            └── model
                ├── yolov4_model.npz
                ├── coco.names
                └── yolov4_weights_congfig.txt

```

You can put an image or a video under the folder `./examples/app_tutorials/data/`,like:
```
${root}/examples
    └──app_tutorials
            └──data
                └── *.jpg/*.png/*.mp4/..
```
### demo

1. Image

   Modify `image_path` in `./examples/app_tutorials/tutorial_object_detection_yolov4_image.py` according to your demand, then

```bash
python tutorial_object_detection_yolov4_image.py
```
2. Video

   Modify `video_path` in `./examples/app_tutorials/tutorial_object_detection_yolov4_video.py` according to your demand, then

```bash
python tutorial_object_detection_yolov4_video.py
```
3. Output

   -Image

   -Video

## 3D Human Pose Estimation

### Data

Download 3D Human Pose Estimation model weights [lcn_model.npz][4], Password:`ec07`,and put it under the folder `./examples/app_tutorials/model/`, Your directory structure should look like this:

```
${root}/examples
    └── app_tutorials
            └── model
                ├── lcn_model.npz
                └── pose_weights_config.txt
```
Download finetuned Stacked Hourglass detections and preprocessed H3.6M data([H36M.rar][5],Password:`kw9i`), then uncompress and put them under the folder `./examples/app_tutorials/data/`, like:
```
${root}/examples
    └──app_tutorials
            └──data
                ├── h36m_sh_dt_ft.pkl
                ├── h36m_test.pkl
                └── h36m_train.pkl
```
Each sample is a list with the length of 34 in three `.pkl` files. The list represents `[x,y]` of 17 human pose points:

If you would like to know how to prepare the H3.6M data, please have a look at the [pose_lcn][6].

### Demo

For a quick demo, simply run

```bash
python tutorial_human_3dpose_estimation_LCN.py
```
This will produce a visualization similar to this:

This demo maps 2D poses to 3D space. Each 3D space result list represents `[x,y,z]` of 17 human pose points.

# Acknowledgement

Yolov4 is bulit on https://github.com/AlexeyAB/darknet and https://github.com/hunglc007/tensorflow-yolov4-tflite.
3D Human Pose Estimation is bulit on https://github.com/rujiewu/pose_lcn and https://github.com/una-dinosauria/3d-pose-baseline.
We would like to thank the authors for publishing their code.

[1]:https://arxiv.org/abs/2004.10934
[2]:https://openaccess.thecvf.com/content_ICCV_2019/papers/Ci_Optimizing_Network_Structure_for_3D_Human_Pose_Estimation_ICCV_2019_paper.pdf
[3]:https://pan.baidu.com/s/1MC1dmEwpxsdgHO1MZ8fYRQ
[4]:https://pan.baidu.com/s/1HBHWsAfyAlNaavw0iyUmUQ
[5]:https://pan.baidu.com/s/1nA96AgMsvs1sFqkTs7Dfaw
[6]:https://github.com/rujiewu/pose_lcn


text:
// *********************************************************
//
// Copyright © Microsoft Corporation
//
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES
// OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED,
// INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES
// OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache 2 License for the specific language
// governing permissions and limitations under the License.
//
// *********************************************************

using System.Collections.Generic;
using Roslyn.Compilers.CSharp;

namespace CSharpToVisualBasicConverter.Cleanup
{
    internal class WhiteSpaceCleanup : SyntaxRewriter
    {
        private readonly SyntaxTree syntaxTree;

        public WhiteSpaceCleanup(SyntaxTree syntaxTree)
        {
            this.syntaxTree = syntaxTree;
        }

        public override SyntaxToken VisitToken(SyntaxToken token)
        {
            token = base.VisitToken(token);
            if (token.IsMissing)
            {
                return token;
            }

            bool changed;

            do
            {
                changed = false;
                if ((token.HasTrailingTrivia && token.TrailingTrivia.Count >= 3) ||
                    (token.HasLeadingTrivia && token.LeadingTrivia.Count >= 3))
                {
                    var newLeadingTrivia = RemoveBlankLineTrivia(token.LeadingTrivia, ref changed);
                    var newTrailingTrivia = RemoveBlankLineTrivia(token.TrailingTrivia, ref changed);

                    if (changed)
                    {
                        token = token.WithLeadingTrivia(Syntax.TriviaList(newLeadingTrivia));
                        token = token.WithTrailingTrivia(Syntax.TriviaList(newTrailingTrivia));
                    }
                }
            }
            while (changed);

            return token;
        }

        private static List<SyntaxTrivia> RemoveBlankLineTrivia(SyntaxTriviaList trivia, ref bool changed)
        {
            var newTrivia = new List<SyntaxTrivia>();

            for (int i = 0; i < trivia.Count;)
            {
                var trivia1 = trivia[i];
                newTrivia.Add(trivia1);

                if (i < trivia.Count - 2)
                {
                    var trivia2 = trivia[i + 1];
                    var trivia3 = trivia[i + 2];

                    if (trivia1.Kind == SyntaxKind.EndOfLineTrivia &&
                        trivia2.Kind == SyntaxKind.WhitespaceTrivia &&
                        trivia3.Kind == SyntaxKind.EndOfLineTrivia)
                    {
                        // Skip the whitespace with a newline.
                        newTrivia.Add(trivia3);
                        changed = true;
                        i += 3;
                        continue;
                    }
                }

                i++;
            }

            return newTrivia;
        }
    }
}


text:
namespace _05.MoldorsCrueltyPlan
{
    public class Mushrooms : Food
    {
        private const int MushroomsHappiness = -10;

        public Mushrooms()
            :base(MushroomsHappiness)
        {

        }
    }
}


text:
package org.nd4j.autodiff.functions.impl.unary.transform;

import org.nd4j.autodiff.ArrayField;
import org.nd4j.autodiff.functions.AbstractUnaryFunction;
import org.nd4j.autodiff.functions.DifferentialFunction;
import org.nd4j.autodiff.samediff.SameDiff;

public class ASin extends AbstractUnaryFunction<ArrayField> {

    public ASin(SameDiff sameDiff, DifferentialFunction<ArrayField> i_v, Object[] extraArgs) {
        super(sameDiff, i_v, extraArgs);
    }

    @Override
    public ArrayField doGetValue() {
        return sameDiff.getArrayFactory().asin(arg().getValue(true));
    }

    @Override
    public double getReal() {
        return Math.asin(arg().getReal());
    }

    @Override
    public DifferentialFunction<ArrayField> diff(DifferentialFunction<ArrayField> i_v) {
        return sameDiff.getFunctionFactory().one(getResultShape()).div(sameDiff.getFunctionFactory()
                .sqrt(sameDiff.getFunctionFactory()
                .one(getResultShape()).sub(arg().pow(2))));
    }

    @Override
    public String functionName() {
        return new org.nd4j.linalg.api.ops.impl.transforms.ASin().name();
    }
}


text:
//---------------------------------------------------------------------------
//	Greenplum Database
//	Copyright (C) 2013 Pivotal, Inc.
//
//	@filename:
//		CLogicalInnerIndexApply.cpp
//
//	@doc:
//		Implementation of index apply operator
//---------------------------------------------------------------------------

#include "gpos/base.h"

#include "gpopt/operators/CLogicalInnerIndexApply.h"

#include "naucrates/statistics/CStatisticsUtils.h"

using namespace gpopt;

//---------------------------------------------------------------------------
//	@function:
//		CLogicalInnerIndexApply::CLogicalInnerIndexApply
//
//	@doc:
//		Ctor - for patterns
//
//---------------------------------------------------------------------------
CLogicalInnerIndexApply::CLogicalInnerIndexApply
	(
	IMemoryPool *pmp
	)
	:
	CLogicalApply(pmp),
	m_pdrgpcrOuterRefs(NULL)
{
	m_fPattern = true;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalInnerIndexApply::CLogicalInnerIndexApply
//
//	@doc:
//		Ctor
//
//---------------------------------------------------------------------------
CLogicalInnerIndexApply::CLogicalInnerIndexApply
	(
	IMemoryPool *pmp,
	DrgPcr *pdrgpcrOuterRefs
	)
	:
	CLogicalApply(pmp),
	m_pdrgpcrOuterRefs(pdrgpcrOuterRefs)
{
	GPOS_ASSERT(NULL != pdrgpcrOuterRefs);
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalInnerIndexApply::~CLogicalInnerIndexApply
//
//	@doc:
//		Dtor
//
//---------------------------------------------------------------------------
CLogicalInnerIndexApply::~CLogicalInnerIndexApply()
{
	CRefCount::SafeRelease(m_pdrgpcrOuterRefs);
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalInnerIndexApply::Maxcard
//
//	@doc:
//		Derive max card
//
//---------------------------------------------------------------------------
CMaxCard
CLogicalInnerIndexApply::Maxcard
	(
	IMemoryPool *, // pmp
	CExpressionHandle &exprhdl
	)
	const
{
	return CLogical::Maxcard(exprhdl, 2 /*ulScalarIndex*/, MaxcardDef(exprhdl));
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalInnerIndexApply::PxfsCandidates
//
//	@doc:
//		Get candidate xforms
//
//---------------------------------------------------------------------------
CXformSet *
CLogicalInnerIndexApply::PxfsCandidates
	(
	IMemoryPool *pmp
	)
	const
{
	CXformSet *pxfs = GPOS_NEW(pmp) CXformSet(pmp);
	(void) pxfs->FExchangeSet(CXform::ExfImplementInnerIndexApply);

	return pxfs;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalInnerIndexApply::FMatch
//
//	@doc:
//		Match function
//
//---------------------------------------------------------------------------
BOOL
CLogicalInnerIndexApply::FMatch
	(
	COperator *pop
	)
	const
{
	GPOS_ASSERT(NULL != pop);

	if (pop->Eopid() == Eopid())
	{
		return m_pdrgpcrOuterRefs->FEqual(CLogicalInnerIndexApply::PopConvert(pop)->PdrgPcrOuterRefs());
	}

	return false;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalInnerIndexApply::PopCopyWithRemappedColumns
//
//	@doc:
//		Return a copy of the operator with remapped columns
//
//---------------------------------------------------------------------------
COperator *
CLogicalInnerIndexApply::PopCopyWithRemappedColumns
	(
	IMemoryPool *pmp,
	HMUlCr *phmulcr,
	BOOL fMustExist
	)
{
	DrgPcr *pdrgpcr = CUtils::PdrgpcrRemap(pmp, m_pdrgpcrOuterRefs, phmulcr, fMustExist);

	return GPOS_NEW(pmp) CLogicalInnerIndexApply(pmp, pdrgpcr);
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalInnerIndexApply::PstatsDerive
//
//	@doc:
//		Derive statistics
//
//---------------------------------------------------------------------------
IStatistics *
CLogicalInnerIndexApply::PstatsDerive
	(
	IMemoryPool *pmp,
	CExpressionHandle &exprhdl,
	DrgPstat* // pdrgpstatCtxt
	)
	const
{
	GPOS_ASSERT(EspNone < Esp(exprhdl));

	IStatistics *pstatsOuter = exprhdl.Pstats(0);
	IStatistics *pstatsInner = exprhdl.Pstats(1);
	CExpression *pexprScalar = exprhdl.PexprScalarChild(2 /*ulChildIndex*/);

	// join stats of the children
	DrgPstat *pdrgpstat = GPOS_NEW(pmp) DrgPstat(pmp);
	pstatsOuter->AddRef();
	pdrgpstat->Append(pstatsOuter);
	pstatsInner->AddRef();
	pdrgpstat->Append(pstatsInner);
	IStatistics *pstats = CStatisticsUtils::PstatsJoinArray(pmp, false /*fOuterJoin*/, pdrgpstat, pexprScalar);
	pdrgpstat->Release();

	return pstats;
}

// EOF


text:
$(document).ready(function ()
{
    'use strict';
    console.log('use strict');

    var solventField = $('#mesd_filterbundle_filter_filterRow');
    if (solventField !== undefined) {
        var solvent = solventField.val();
        if ('' !== solvent) {
            var dropdown = $('#mesd_filterbundle_filter_filterEntity');
            changeModalsBasedOnDropdown(dropdown);
        }

        // when category is changed
        $('#mesd_filterbundle_filter_filterEntity').on('change', function () {
            console.log('category is changed');
            var dropdown = this;

            changeInterfaceBasedOnDropdown(dropdown);

        });
    }
});

function changeInterfaceBasedOnDropdown (dropdown)
{
    console.log('change interface based on dropdown');

    var url = $(dropdown).attr('data-url');
    url = url.replace('-1', $(dropdown).val());
    $.ajax({
        url: url
    }).done(function (data) {
        initializeSingleRow(data.associations);
        checkIfAddButtonIsNeeded(data.associations);
        initializeModals(data.associations);
    });
}

function changeModalsBasedOnDropdown (dropdown)
{
    console.log('change modals based on dropdown');

    if ('' !== $(dropdown).val()) {
        var url = $(dropdown).attr('data-url');
        url = url.replace('-1', $(dropdown).val());
        $.ajax({
            url: url
        }).done(function (data) {
            checkIfAddButtonIsNeeded(data.associations);
            initializeModals(data.associations);
        });
    }
}

function checkIfAddButtonIsNeeded (associations)
{
    console.log('check if add button is needed');

    var column = $('#filter-interface-table').attr('data-columns');
    if (1 < parseInt(column)) {
        var html = '';
        html += '';
        html += 'Add Row';
        html += '';
        $('#filter-interface').append(
            html
        );

        $('#filter-row-add').on('click', function (event) {
            event.preventDefault();
            var html = '';
            html += '
';
            html += 'OR	';
            html += '
';
            html += addSingleRow(associations);
            var table = $('#filter-interface-table');
            table.append(
                html
            );
            addDeleteListeners();
        });
    }
}

function initializeSingleRow (associations)
{
    console.log('initialize a single row');

    var html = '
';
    html += '
';
    html += '
';
    var i = 0;
    for (var key in associations) {
        if (0 < i) {
            html += '	';
        }
        html += '' + associations[key].name + '	';
        i++;
    }
    if (1 < n) {
        html += 'Delete Row	'
    }
    html += '
';
    html += addSingleRow(associations);
    html += '
';
    html += '
';
    $('#filter-interface').html(
        html
    );
}

function initializeModals (associations)
{
    console.log('initialize modals');

    var html = '';
    for (var key in associations) {
        html += '
';
        html += '
';
        html += '
';
        html += '
';
        html += '<button type="button"';
        html += ' class="close"';
        html += ' data-dismiss="modal"';
        html += ' aria-label="Close">';
        html += '×</button>';
        html += '
Edit ' + associations[key].name + '
';
        html += '
';
        html += '
';
        html += '<form';
        html += ' id="' + associations[key].code + 'Form"';
        html += '>';
        html += '
';
        html += '' + associations[key].name + ':';
        html += '<select';
        html += ' class="form-control change-cell-dropdown"';
        html += ' id="' + associations[key].code + '-cell-join"';
        html += ' name="cell-join"';
        html += ' data-association-id="' + associations[key].associationId + '"';
        html += '>';
        html += '<option></option>';
        for (var i = 0; i < associations[key].cells.length; i++) {
            html += '<option value="' + JSON.stringify(associations[key].cells[i].solvent) + '">';
            html += associations[key].cells[i].description;
            html += '</option>';
        }
        html += '<option';
        html += ' value="-1">Other</option>';
        html += '</select>';
        html += '
';
        html += '
';
        html += '<input';
        html += ' type="hidden"';
        html += ' id="' + associations[key].code + '-new-cell"';
        html += ' name="new-cell[]"';
        html += ' class="new-cell form-control"';
        html += ' data-entity-data-url="' + associations[key].entityDataUrl + '"'
        html += ' />';
        html += '
';
        html += '<input type="hidden"';
        html += ' name="trail-entity-id"';
        html += ' value="' + associations[key].trailEntityId + '" />';
        html += '<input type="hidden"';
        html += ' name="association-id"';
        html += ' value="' + associations[key].associationId + '" />';
        html += '</form>';
        html += '
';
        html += '
';
        html += '<button type="button"';
        html += ' class="btn btn-default"';
        html += ' data-dismiss="modal">Close</button>';
        html += '<button type="button"';
        html += ' class="btn btn-primary modal-save"';
        html += ' data-code="' + associations[key].code + '"';
        html += ' >Set ' + associations[key].name + '</button>';
        html += '
';
        html += '
';
        html += '
';
        html += '
';
    }
    $('#modals').html(
        html
    );

    addModalListeners();
    addDeleteListeners();
}

function addSingleRow(association)
{
    console.log('add single row');

    var html = '';
    html += '
';
    var i = 0;
    var row = $('#filter-interface-table').attr('data-rows');
    if (undefined === row) {
        row = 0;
    }
    for (var key in association) {
        if (0 < i) {
            html += 'AND	';
        }
        html += '';
        html += '
';
        html += 'No ' + association[key].name + ' selected';
        html += '
';
        html += '
';
        html += '<button';
        html += ' type="button"';
        html += ' class="btn btn-default"';
        html += ' data-toggle="modal"';
        html += ' data-target="#' + association[key].code + 'Modal"';
        html += ' data-div-id="' + association[key].code + '-' + row + '" >';
        html += 'Edit ' + association[key].name;
        html += '</button>';
        html += '
';
        html += '	';
        i++;
    }
    var n = 0;
    for (var key in association) {
        n++;
    }
    if (1 < n) {
        html += '<button id="delete-row-' + row + '"';
        html += ' "type="button"';
        html += ' class="btn btn-default delete-row no-listener"';
        html += ' >Delete Row</button>	';
    }
    $('#filter-interface-table').attr('data-rows', parseInt(row) + 1);
    html += '
';

    return html;
}

function updateSolvent()
{
    console.log ('update solvent');

    var rows = $('.filter-row');
    var n = rows.length;
    var rowSolvent = [];
    for (var i = 0; i < n; i++) {
        var cells = $(rows[i]).find('.filter-cell');
        var n2 = cells.length;
        var cellSolvent = [];
        for (var i2 = 0; i2 < n2; i2++) {
            var cell = $(cells[i2]);
            var solvent = JSON.parse(cell.attr('data-cell-solvent'));
            var associationId = cell.attr('data-association-id');
            var json = {
                associationId: associationId,
                solvent: solvent
            };
            cellSolvent.push(json);
        }
        rowSolvent.push(cellSolvent);
    }
    var value = JSON.stringify(rowSolvent);
    $('#mesd_filterbundle_filter_filterRow').val(value);
}

function formatResult(item) {

   return item.text;
}

function formatSelection(item) {

   return item.text;
}

function addModalListeners()
{
    console.log('add modal listeners');

    $('.new-cell').each(function() {
        newCell = $(this);
        newCell.select2({
            placeholder: "Search",
            // minimumInputLength: 1,
            multiple: true,
            ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
                url: newCell.attr('data-entity-data-url'),
                dataType: 'json',
                quietMillis: 250,
                data: function (term, page) {
                    return {
                        searchTerm: term, // search term
                        page: page // page number
                    };
                },
                results: function (data, page) {
                    var more = (page * 30) < data.total_count; // whether or not there are more results available

                    // notice we return the value of more so Select2 knows if more results can be loaded
                    return { results: data.items, more: more };
                },
                cache: true
            },
            // initSelection: function(element, callback) {
            //     // the input tag has a value attribute preloaded that points to a preselected repository's id
            //     // this function resolves that id attribute to an object that select2 can render
            //     // using its formatResult renderer - that way the repository name is shown preselected
            //     var id = $(element).val();
            //     if (id !== "") {
            //         $.ajax("https://api.github.com/repositories/" + id, {
            //             dataType: "json"
            //         }).done(function(data) { callback(data); });
            //     }
            // },
            formatResult: formatResult, // omitted for brevity, see the source of this page
            formatSelection: formatSelection,  // omitted for brevity, see the source of this page
            dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
            escapeMarkup: function (m) { return m; }, // we do not want to escape markup since we are displaying html in results
            'width':'resolve'
        });
    });

    $('.change-cell-dropdown').on('change', function () {
        console.log('cell dropdown changed');

        var dropdown = $(
            '#' + $(this).attr('id').replace('-cell-join', '-new-cell')
        );
        if ('Other' === $(this).children(':selected').text()) {
            console.log('other is selected');

            dropdown.parent().removeClass('hidden');
        } else {
            console.log('other is not selected');

            dropdown.parent().addClass('hidden');
        }
    });

    $('.modal').on('show.bs.modal', function (event) {
        console.log('on modal show');

        var button = $(event.relatedTarget);
        var divId = button.attr('data-div-id');
        var modal = $(this);
        modal.find('.new-cell option').removeAttr('selected');
        modal.find('.modal-save').attr('data-div-id', divId);
    });

    $('.modal-save').on('click', function (event) {
        event.preventDefault();
        console.log('on modal save');

        var button = $(this);
        var modal = $('#' + button.attr('data-code') + 'Modal');
        var form = $('#' + button.attr('data-code') + 'Form');
        var div = $('#' + button.attr('data-div-id'));
        var associationId = div.attr('data-association-id');
        var data = form.serializeArray();
        var cellJoin = $('#' + button.attr('data-code') + '-cell-join');
        var description = '';
        var selectedValues = '';
        var selectedValuesString = '';
        var selectedText = cellJoin.children(':selected').text();
        if ('Other' === selectedText) {
            console.log('other was selected');

            var newCell = $('#' + button.attr('data-code') + '-new-cell');
            selectedValues = newCell.val().split(',');
            n = selectedValues.length;
            for (var i = 0; i < n; i++) {
                selectedValues[i] = parseInt(selectedValues[i]);
            }
            selectedValues.sort(function (a, b)
            {
                return a - b;
            });
            selectedValuesString = JSON.stringify(selectedValues);
            var selectedOptions = newCell.parent().find('.select2-search-choice div');
            description = '';
            i = 0;
            var n = selectedOptions.length;
            selectedOptions.each(function() {
                if (0 < i) {
                    description += ', ';
                    if ((i + 1) === n) {
                        description += 'or ';
                    }
                }
                description += $(this).html();
                i++;
            });
        } else {
            console.log('other was not selected');

            description = selectedText;
            selectedValuesString = cellJoin.val();
        }
        div.html(description);
        div.attr('data-cell-solvent', selectedValuesString);
        updateSolvent();
        modal.modal('hide');
    });
}

function addDeleteListeners()
{
    console.log('add delete listeners');

    $('.delete-row.no-listener').on('click', function(event) {
        event.preventDefault();
        console.log('on delete row');

        var previousSibling = $(this).parent().parent().prev();
        if (previousSibling.hasClass('or')) {
            previousSibling.remove();
        }
        $(this).parent().parent().remove();
    });
    $(this).removeClass('no-listener');
}


text:
The Cisco Spark API uses a user token and enables:
* Create a room and invite people
* Search for people in your company
* Post messages into a room
* Get room history
* All the other actions which are described in the docs

For more information, please visit: [https://developer.ciscospark.com/getting-started.html](https://developer.ciscospark.com/getting-started.html).

The API key is displayed in the "Getting Started" page, after logging in.


text:
package main;

public class Preferences {

    //preferences !!!!!!!!
    private boolean Automatic_preview_when_filter=true;

    public boolean menubar_on=false;

	public boolean isAutomatic_preview_when_filter() {
		return Automatic_preview_when_filter;
	}

	public void setAutomatic_preview_when_filter(
			boolean automatic_preview_when_filter) {
		Automatic_preview_when_filter = automatic_preview_when_filter;
	}
}


text:
package com.lmax.disruptor;

/**
 * Coordinates claiming sequences for access to a data structure while tracking dependent {@link Sequence}s
 */
public interface Sequencer extends Cursored {
    /** Set to -1 as sequence starting point */
    long INITIAL_CURSOR_VALUE = -1L;

    /**
     * The capacity of the data structure to hold entries.
     *
     * @return the size of the RingBuffer.
     */
    int getBufferSize();

    /**
     * Has the buffer got capacity to allocate another sequence.  This is a concurrent
     * method so the response should only be taken as an indication of available capacity.
     * @param requiredCapacity in the buffer
     * @return true if the buffer has the capacity to allocate the next sequence otherwise false.
     */
    boolean hasAvailableCapacity(final int requiredCapacity);

    /**
     * Claim the next event in sequence for publishing.
     * @return the claimed sequence value
     */
    long next();

    /**
     * Claim the next n events in sequence for publishing.  This is for batch event producing.  Using batch producing
     * requires a little care and some math.
     *

     * int n = 10;
     * long hi = sequencer.next(n);
     * long lo = hi - (n - 1);
     * for (long sequence = lo; sequence <= hi; sequence++) {
     *     // Do work.
     * }
     * sequencer.publish(lo, hi);
     *

     *
     * @param n the number of sequences to claim
     * @return the highest claimed sequence value
     */
    // ³¢ÊÔÇëÇón¸öÐòºÅÓÃÓÚ·¢²¼Ê¼þ¡£
    long next(int n);

    /**
     * Attempt to claim the next event in sequence for publishing.  Will return the
     * number of the slot if there is at least requiredCapacity slots
     * available.
     * @return the claimed sequence value
     * @throws InsufficientCapacityException
     */
    long tryNext() throws InsufficientCapacityException;

    /**
     * Attempt to claim the next n events in sequence for publishing.  Will return the
     * highest numbered slot if there is at least requiredCapacity slots
     * available.  Have a look at {@link Sequencer#next()} for a description on how to
     * use this method.
     *
     * @param n the number of sequences to claim
     * @return the claimed sequence value
     * @throws InsufficientCapacityException
     */
    long tryNext(int n) throws InsufficientCapacityException;

    /**
     * Get the remaining capacity for this sequencer.
     * @return The number of slots remaining.
     */
    long remainingCapacity();

    /**
     * Claim a specific sequence.  Only used if initialising the ring buffer to
     * a specific value.
     *
     * @param sequence The sequence to initialise too.
     */
    void claim(long sequence);

    /**
     * Publishes a sequence. Call when the event has been filled.
     *
     * @param sequence
     */
    void publish(long sequence);

    /**
     * Batch publish sequences.  Called when all of the events have been filled.
     *
     * @param lo first sequence number to publish
     * @param hi last sequence number to publish
     */
    void publish(long lo, long hi);

    /**
     * Confirms if a sequence is published and the event is available for use; non-blocking.
     *
     * @param sequence of the buffer to check
     * @return true if the sequence is available for use, false if not
     */
    boolean isAvailable(long sequence);

    /**
     * Add the specified gating sequences to this instance of the Disruptor.  They will
     * safely and atomically added to the list of gating sequences.
     *
     * @param gatingSequences The sequences to add.
     */
    void addGatingSequences(Sequence... gatingSequences);

    /**
     * Remove the specified sequence from this sequencer.
     *
     * @param sequence to be removed.
     * @return <tt>true</tt> if this sequence was found, <tt>false</tt> otherwise.
     */
    boolean removeGatingSequence(Sequence sequence);

    /**
     * Create a new SequenceBarrier to be used by an EventProcessor to track which messages
     * are available to be read from the ring buffer given a list of sequences to track.
     *
     * @see SequenceBarrier
     * @param sequencesToTrack
     * @return A sequence barrier that will track the specified sequences.
     */
    SequenceBarrier newBarrier(Sequence... sequencesToTrack);

    /**
     * Get the minimum sequence value from all of the gating sequences
     * added to this ringBuffer.
     *
     * @return The minimum gating sequence or the cursor sequence if
     * no sequences have been added.
     */
    long getMinimumSequence();

    long getHighestPublishedSequence(long sequence, long availableSequence);
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>UberFire Showcase</title>
    <link rel="stylesheet" href="org.uberfire.KieUberfireJS/css/uberfire-loading.css">
    <link rel="stylesheet" href="org.uberfire.KieUberfireJS/css/uberfire-showcase.css">
    <link rel="stylesheet" href="org.uberfire.KieUberfireJS/css/ruleflow.css">

        Please wait
Loading application...

    Eder
    <input type="text" ng-model="sometext"/>

Hello {{ sometext }}!

    <uberfirecomponent id="id1" name="Eder" uf-component="welcome"></uberfirecomponent>