text:
#include "me_ct_jacobian_IK.hpp"
#include "me_ct_reach_IK.hpp"
#include "me_ct_locomotion_func.hpp"

#include <sr/sr_alg.h>
#include <algorithm>
#include <boost/foreach.hpp>
#include <sbm/gwiz_math.h>
#include <sb/SBScene.h>

const float PI_CONST = 3.14159265358979323846f;
const MeCtIKJointLimit limb_joint_limit[] = {
	{SrVec2(PI_CONST*0.3f, PI_CONST*0.3f), SrVec2(PI_CONST*0.3f,PI_CONST*0.3f),SrVec2(PI_CONST*0.3f,-PI_CONST*0.3f)} };

using namespace gwiz;
using namespace MeCtUBLAS;

EffectorConstantConstraint& EffectorConstantConstraint::operator=( const EffectorConstantConstraint& rhs )
{
	efffectorName = rhs.efffectorName;
	rootName    = rhs.rootName;
	targetPos = rhs.targetPos;//SrQuat(SrVec(0,1,0),M_PI);
	targetRot = rhs.targetRot;
	return *this;
}

MeCtIKTreeNode::MeCtIKTreeNode()
{
	joint = NULL;
	parent = NULL;
	child = NULL;
	brother = NULL;
	active = true;

	// a temporary hack for testing
	// To-Do : we should provide a way to let user indicate the joint limits parameters via input script or file
	jointLimit = limb_joint_limit[0];
	targetDir = SrQuat(SrVec(0.0,1.5,0.0));//SrQuat(1.f,0.f,0.f,0.f); // set target direction to identity
	nodeLevel  = 0;
	validNodeIdx = -1;
}

SrVec MeCtIKTreeNode::getCoMPos()
{
	SrVec pos = gmat.get_translation();
	if (child)
	{
		pos += child->gmat.get_translation();
		pos *= 0.5;
	}
	return pos;
}

MeCtIKTreeNode::~MeCtIKTreeNode()
{

}

SrQuat& MeCtIKTreeNode::getQuat( NodeQuatType type /*= QUAT_CUR*/ )
{
	if (type < 0 || type >= QUAT_SIZE)
		type = QUAT_DUMMY;
	return nodeQuat[type];
}

bool MeCtIKTreeNode::setQuat( const SrQuat& q, NodeQuatType type /*= QUAT_CUR*/ )
{
	if (type < 0 || type >= QUAT_SIZE)
		return false;

	nodeQuat[type] = q;
	return true;
}

SrVec MeCtIKTreeNode::getParentGlobalPos()
{
	SrVec gPos = SrVec(0,0,0);
	if (parent)
		//gPos = parent->joint->gmat().get_translation();
		gPos = parent->gmat.get_translation();
	return gPos;
}

SrVec MeCtIKTreeNode::getGlobalPos()
{
	return gmat.get_translation();//joint->gmat().get_translation();
}

std::string MeCtIKTreeNode::getNodeName()
{
	if (joint)
		return joint->getMappedJointName();
	return _nodeName;
}

void MeCtIKTreeNode::setNodeName( const std::string& nodeName )
{
	_nodeName = nodeName;
}
/************************************************************************/
/* IK Tree scenario to hold data/parameters for full-body IK            */
/************************************************************************/

MeCtIKTreeScenario::MeCtIKTreeScenario()
{
	ikTreeRoot = NULL;
	ikTreeRootPos = SrVec(0,0,0);
}

MeCtIKTreeScenario::~MeCtIKTreeScenario()
{
	clearNodes();
}
void MeCtIKTreeScenario::updateEndEffectorValidNodes(EffectorConstraint* cons, std::set<MeCtIKTreeNode*>& validNodes)
{
	MeCtIKTreeNode* endNode = findIKTreeNode(cons->efffectorName.c_str());
	if (!endNode)
		return;
	MeCtIKTreeNode* node = endNode->parent;
	bool bStop = false;
	if (endNode->getNodeName() == cons->rootName)
		bStop = true;

	while(node && node->parent && !bStop) // no root node
	{
		int idx = node->nodeIdx;
		float nodeWeight = 1.f;
		if (!node->active)
			nodeWeight = 0.f;
		if (nodeWeight != 0.f)
		{
			validNodes.insert(node);
		}
		if (node->getNodeName() == cons->rootName)
			bStop = true;
		node = node->parent;
	}
}

void MeCtIKTreeScenario::updateValidNodes()
{
	std::set<MeCtIKTreeNode*> validSet;
	ConstraintMap::iterator ci;
	for (unsigned int i=0;i<ikTreeNodes.size();i++)
		ikTreeNodes[i]->validNodeIdx = -1;

	for (ci = ikPosEffectors->begin(); ci != ikPosEffectors->end(); ci++)
	{
		EffectorConstraint* cons = ci->second;
		updateEndEffectorValidNodes(cons, validSet);
	}
	for (ci = ikRotEffectors->begin(); ci != ikRotEffectors->end(); ci++)
	{
		EffectorConstraint* cons = ci->second;
		updateEndEffectorValidNodes(cons, validSet);
	}

	ikValidNodes.clear();
	std::set<MeCtIKTreeNode*>::iterator si;
	for (si = validSet.begin(); si != validSet.end(); si++)
	{
		MeCtIKTreeNode* node = *si;
		node->validNodeIdx = ikValidNodes.size();
		ikValidNodes.push_back(node);
	}
}

bool MeCtIKTreeScenario::checkJointLimit( const SrQuat& q, const MeCtIKJointLimit& limit, const SrQuat& qInit, SrVec& jointOffset )
{
	bool modified = false;
	// feng : for some reason, the twist axis is aligned with local x-axis, instead of z-axis
	// therefore we need to do the "shifted" version of swingTwist conversion.
	// so we map x->z, y->x, z->y for computing swing-twist parameteriation.
	// all of the angle limits are adjust accordingly.
	{
		quat_t quat_st = quat_t(q.w, q.x, q.y, q.z);
		quat_t quat_init = quat_t(qInit.w, qInit.x, qInit.y, qInit.z);
		vector_t st = MeCtReachIK::quat2SwingTwist(quat_st);//quat_st.swingtwist();
		float sw_y = (float)st.x();
		float sw_z = (float)st.y();

		float sw_limit_z, sw_limit_y;
		sw_limit_z = sw_z > 0 ? limit.x_limit[0] : limit.x_limit[1];
		sw_limit_y = sw_y > 0 ? limit.y_limit[0] : limit.y_limit[1];

		// project swing angles onto the joint limit ellipse
		if( sr_in_ellipse( sw_z, sw_y, sw_limit_z, sw_limit_y ) > 0.0 )	{
			modified = true;
			sr_get_closest_on_ellipse( sw_limit_z, sw_limit_y, sw_z, sw_y );
		}
		// handle twist angle limit
  		float tw = (float)st.z();
		if( tw > limit.twist_limit[0] )
		{
			tw = limit.twist_limit[0];
			modified = true;
		}
		if( tw < limit.twist_limit[1] )
		{
			tw = limit.twist_limit[1];
			modified = true;
		}

		vector_t Vect(sw_y, sw_z, tw);
		quat_t ql = MeCtReachIK::swingTwist2Quat( Vect );//quat_t( sw_x, sw_y, tw);
		quat_t q_offset = ql*quat_init.conjugate();//ql*quat_st.conjugate();//ql*quat_init.conjugate();
		vector_t rot = q_offset.axisangle();
		jointOffset = SrVec((float)rot.x(),(float)rot.y(),(float)rot.z());
	}
	return modified;
}

void MeCtIKTreeScenario::updateJointLimit()
{
	ikJointLimitNodes.clear();
	BOOST_FOREACH(MeCtIKTreeNode* node, ikTreeNodes)
	{
		bool violate = checkJointLimit(node->getQuat(QUAT_CUR),node->jointLimit,node->getQuat(QUAT_INIT),node->jointOffset);
		if (violate)
			ikJointLimitNodes.push_back(node);
	}
}

void MeCtIKTreeScenario::buildIKTreeFromJointRoot( SkJoint* root, std::vector<std::string>& stopJoints )
{
	clearNodes(); // clear all existing nodes

	ikTreeRoot = new MeCtIKTreeNode();
	ikTreeRoot->joint = root;
	ikTreeRoot->nodeIdx = ikTreeNodes.size();
	ikTreeRoot->nodeLevel = 0;
	ikTreeRoot->setNodeName(root->getMappedJointName());
	ikTreeNodes.push_back(ikTreeRoot);
	traverseJoint(root,ikTreeRoot,ikTreeNodes, stopJoints);

// 	ikQuatList.resize(ikTreeNodes.size());
// 	ikInitQuatList.resize(ikTreeNodes.size());
// 	ikRefQuatList.resize(ikTreeNodes.size());
}

int MeCtIKTreeScenario::traverseJoint(SkJoint* joint, MeCtIKTreeNode* jointNode, std::vector<MeCtIKTreeNode*>& nodeList, std::vector<std::string>& stopJoints )
{
	int nNodes = 1;
	MeCtIKTreeNode* prevNode = NULL;
	for (int i=0;i<joint->num_children();i++)
	{
		SkJoint* child = joint->child(i);
		MeCtIKTreeNode* childNode = new MeCtIKTreeNode();
		childNode->nodeLevel = jointNode->nodeLevel + 1;
		childNode->joint = child;
		childNode->setNodeName(child->getMappedJointName());
		childNode->nodeIdx = nodeList.size();
		childNode->parent = jointNode;
		nodeList.push_back(childNode);

		if (i==0)
			jointNode->child = childNode;
		if (prevNode)
			prevNode->brother = childNode;

		if ( child->getMappedJointName() == "skullbase" )
// 			strcmp(child->name().get_string(),"l_wrist")==0 ||
// 			strcmp(child->name().get_string(),"r_wrist")==0 )
		{
			nNodes += 1; // don't traverse their children
		}
		else if (std::find(stopJoints.begin(),stopJoints.end(), child->jointName()) != stopJoints.end()) // stop joints
		{
			nNodes += 1;
		}
		else
		{
			nNodes += traverseJoint(child,childNode,nodeList, stopJoints);
		}
		prevNode = childNode;
	}
	return nNodes;
}

void MeCtIKTreeScenario::updateQuat( const dVector& dTheta, bool updateOnlyValidNodes )
{
	IKTreeNodeList& nodeList = (updateOnlyValidNodes) ? ikValidNodes : ikTreeNodes;

	if (dTheta.size() != nodeList.size()*3)
		return;

	for (unsigned int i=0;i<nodeList.size();i++)
	{
		SrVec axisAngle = SrVec((float)dTheta(i*3),(float)dTheta(i*3+1),(float)dTheta(i*3+2));
		MeCtIKTreeNode* node = nodeList[i];
		SrQuat newQuat = SrQuat(axisAngle)*node->getQuat(QUAT_CUR);//ikInitQuatList[i]; // read from initQuat
		newQuat.normalize();
		node->setQuat(newQuat,QUAT_CUR);
	}
}

// feng : this part seems redundant to sk_skeleton. but since a typical skeleton
// contains much more bones like facial bones & fingers, it makes more sense to just update the nodes we are using for IK.
void MeCtIKTreeScenario::updateNodeGlobalMat( MeCtIKTreeNode* jointNode, NodeQuatType quatType )
{
	SrMat pmat = ikGlobalMat;
	int idx = jointNode->nodeIdx;
	if (jointNode->parent)
		pmat = jointNode->parent->gmat;

	SrVec pos = SrVec(0,0,0);
	if (jointNode == ikTreeRoot)
		pos = ikTreeRootPos;

	jointNode->gmat = getLocalMat(jointNode->joint,jointNode->getQuat(quatType),pos)*pmat;
	if (jointNode->brother)
		updateNodeGlobalMat(jointNode->brother, quatType);
	if (jointNode->child)
		updateNodeGlobalMat(jointNode->child, quatType);

}

MeCtIKTreeNode* MeCtIKTreeScenario::findIKTreeNode( const char* jointName )
{
	int idx = findIKTreeNodeInList(jointName,ikTreeNodes);
	if (idx == -1)
		return NULL;
	return ikTreeNodes[idx];
}

int MeCtIKTreeScenario::findIKTreeNodeInList( const char* jointName, IKTreeNodeList& nodeList )
{
	int iCount = 0;
	BOOST_FOREACH(MeCtIKTreeNode* node, nodeList)
	{
		if (strcmp(node->joint->getMappedJointName().c_str(),jointName) == 0)
			return iCount;
		iCount++;
	}
	return -1;
}

void MeCtIKTreeScenario::clearNodes()
{
	for (unsigned int i=0;i<ikTreeNodes.size();i++)
	{
		MeCtIKTreeNode* node = ikTreeNodes[i];
		delete node;
	}
	ikTreeNodes.clear();
	ikTreeRoot = NULL;
}

void MeCtIKTreeScenario::setTreeNodeQuat( const std::vector<SrQuat>& inQuatList, NodeQuatType type )
{
	assert(inQuatList.size() == ikTreeNodes.size());
	for (unsigned int i=0;i<ikTreeNodes.size();i++)
		ikTreeNodes[i]->setQuat(inQuatList[i],type);
}

void MeCtIKTreeScenario::setTreeNodeQuat( SkSkeleton* skel,NodeQuatType type )
{
	for (unsigned int i=0;i<ikTreeNodes.size();i++)
	{
		MeCtIKTreeNode* node = ikTreeNodes[i];
		SkJoint* joint = skel->search_joint(node->getNodeName().c_str());
		if (joint)
		{
			node->setQuat(joint->quat()->rawValue(),type);
		}
	}
}

void MeCtIKTreeScenario::getTreeNodeQuat( std::vector<SrQuat>& inQuatList, NodeQuatType type )
{
	inQuatList.resize(ikTreeNodes.size());
	for (unsigned int i=0;i<ikTreeNodes.size();i++)
		inQuatList[i] = ikTreeNodes[i]->getQuat(type);
}

void MeCtIKTreeScenario::copyTreeNodeQuat( NodeQuatType typeFrom, NodeQuatType typeTo )
{
	for (unsigned int i=0;i<ikTreeNodes.size();i++)
	{
		MeCtIKTreeNode* node = ikTreeNodes[i];
		node->setQuat(node->getQuat(typeFrom),typeTo);
	}
}

SrMat MeCtIKTreeScenario::getLocalMat( const SkJoint* joint, const SrQuat& q, const SrVec& pos )
{
	SrMat lMat;
	SkJoint* j = const_cast<SkJoint*>(joint);
	SkJointQuat* qu = j->quat();
	lMat = (qu->orientation()*qu->prerot()*q).get_mat(lMat);
	lMat[12] = joint->offset().x + pos.x;
	lMat[13] = joint->offset().y + pos.y;
	lMat[14] = joint->offset().z + pos.z;
	return lMat;
}

float MeCtIKTreeScenario::getIKChainLength( const char* chainRoot, const char* chainEffector )
{
	MeCtIKTreeNode *rootNode, *effectorNode;
	rootNode = findIKTreeNode(chainRoot);
	effectorNode = findIKTreeNode(chainEffector);
	if (!rootNode || !effectorNode) return -1.f;
	float chainLength = 0.f;
	MeCtIKTreeNode* tempNode = effectorNode;
	while (tempNode != rootNode && tempNode->parent)
	{
		chainLength += (tempNode->getGlobalPos() - tempNode->parent->getGlobalPos()).len();
		tempNode = tempNode->parent;
	}
	return chainLength;
}
/************************************************************************/
/* Jacobian based IK                                                    */
/************************************************************************/

MeCtJacobianIK::MeCtJacobianIK(void)
{
	dampJ = 150.0;
	maxOffset = 10.0f;
	refDampRatio = 0.01;
	ikUseBalance = false;
	ikUseReference = true;
}

MeCtJacobianIK::~MeCtJacobianIK(void)
{
}

void MeCtJacobianIK::update( MeCtIKTreeScenario* scenario )
{
	bool useValidNodes = true;
	ikScenario = scenario;
	// don't do anything if there is no end effectors
	if (ikScenario->ikPosEffectors->size() + ikScenario->ikRotEffectors->size() == 0)
		return;

	scenario->updateNodeGlobalMat(scenario->ikTreeRoot);
#if 1
	// solve for initial jacobian
	if (useValidNodes)
	{
		scenario->updateValidNodes();
		computeJacobianReduce(scenario);
	}
	else
		computeJacobian(scenario);

	solveDLS(matJ,dS,dampJ,dTheta, matJInv);
	// update initial dTheta into new joints
	scenario->updateQuat(dTheta,useValidNodes);
#endif
	// check for joint limit violation
// 	scenario->updateJointLimit();
// 	// solve for auxiliary Jacobian
// 	if (updateJointLimitJacobian(scenario))
// 	{
// 		//solveDLS(matJ,dS,dampJ,dTheta, matJInv);
// 		//printf("Solve Joint Limit\n");
// 		solveDLSwithSVD(matJ,dS,dampJ,dTheta, matJInv);
// 		dTheta += dThetaAux;
// 	    scenario->updateQuat(dTheta);
// 	}

	// update null matrix
#if 1
	dMatrix temp;
	matrixMatMult(matJInv,matJ,temp);
	matJnull -= temp;
#endif
	float weight = 1.0;
	if (ikUseReference)
	{
		if (useValidNodes)
			updateReferenceJointJacobianReduce(scenario);
		else
			updateReferenceJointJacobian(scenario);
		//solveDLS(matJnull,dSref,0.01,dThetaAux,matJrefInv);
		//dTheta += dThetaAux;
		scenario->updateQuat(dThetaAux);
	}
}

void MeCtJacobianIK::computeJacobianReduce(MeCtIKTreeScenario* s)
{
	std::vector<MeCtIKTreeNode*>& validNodes = s->ikValidNodes;
	matJ = ublas::zero_matrix<double>(s->ikPosEffectors->size()*3 + s->ikRotEffectors->size()*3  ,(validNodes.size())*3);
	matJnull = ublas::identity_matrix<double>(s->ikValidNodes.size()*3);
	// plus rotation
	dS.resize(s->ikPosEffectors->size()*3 + s->ikRotEffectors->size()*3);
	ConstraintMap::iterator ci;
	int posCount = 0;
	// fill in entries for positional constraint
 	//for (unsigned int i=0;i<s->ikPosEffectors.size();i++)
	for (ci = s->ikPosEffectors->begin(); ci != s->ikPosEffectors->end(); ci++)
	{
		EffectorConstraint* cons = ci->second;
		MeCtIKTreeNode* endNode = s->findIKTreeNode(cons->efffectorName.c_str());
		MeCtIKTreeNode* rootNode = s->findIKTreeNode(cons->rootName.c_str());
		// find the length of IK chain

		const SrMat& endMat = endNode->gmat;
		SrVec endPos = endMat.get_translation();
		SrVec constraintPos = cons->getPosConstraint();
		SrVec constraintOffset = constraintPos - rootNode->getGlobalPos();
		SrVec constraintDir = constraintOffset; constraintDir.normalize();
		float chainLength = s->getIKChainLength(cons->rootName.c_str(), cons->efffectorName.c_str());
		//LOG("rootNodePos = %s, constarintDir = %s, chainLength = %f",rootNode->getGlobalPos().toString().c_str(), constraintDir.toString().c_str(), chainLength);
//   		if (constraintOffset.len() > chainLength)
//   		{
//   			constraintPos = rootNode->getGlobalPos() + constraintDir*chainLength*0.995f; // make sure the target position is not out of reach
//   		}

		SrVec offset = constraintPos - endPos;
		SrVec targetPos;
		//sr_out << "effector offset = " << srnl;
		if (offset.len() > maxOffset)
		{
			offset.normalize();
			targetPos = offset*maxOffset;
		}
		else
			targetPos = offset;
		//sr_out << "target offset = " << targetPos << srnl;

		dS[posCount*3] = targetPos[0];
		dS[posCount*3+1] = targetPos[1];
		dS[posCount*3+2] = targetPos[2];

		MeCtIKTreeNode* node = endNode->parent;
		//float fRatio = 1.f/(float)(endNode->nodeLevel + 1);
		bool bStop = false;
		if (endNode->getNodeName() == cons->rootName)
			bStop = true;

		float consWeight = cons->constraintWeight;

		while(node && node->parent && !bStop) // no root node
		{
			int idx = node->validNodeIdx;
			assert(idx != -1);
			float nodeWeight = 1.f;
			if (node->getNodeName() == "r_acromioclavicular" || node->getNodeName() == "r_forearm" || node->getNodeName() == "l_forearm" || node->getNodeName() == "l_acromioclavicular")
				nodeWeight = 0.f;
			if (!node->active)
				nodeWeight = 0.f;

			const SrMat& nodeMat = node->gmat;
			SrMat parentMat;
			if (node->parent)
				parentMat = node->parent->gmat;
			else
				parentMat = s->ikGlobalMat;

			// fix for prerotation
			SkJointQuat* jquat = node->joint->quat();
			SrQuat prerotQuat = jquat->orientation()*jquat->prerot();
			SrMat prerot; prerotQuat.get_mat(prerot);
			parentMat = prerot*parentMat;
			//parentMat = parentMat*prerot;

			SrVec nodePos = SrVec(nodeMat.get(12),nodeMat.get(13),nodeMat.get(14));
			SrVec axis[3];
			for (int k=0;k<3;k++)
			{
				//axis[k] = SrVec(parentMat.get(k,0),parentMat.get(k,1),parentMat.get(k,2))*node->joint->parent()->gmatZero().get_rotation()*node->joint->gmatZero().get_rotation().inverse();
				axis[k] = SrVec(parentMat.get(k,0),parentMat.get(k,1),parentMat.get(k,2));//*node->joint->parent()->gmatZero().get_rotation().inverse()*node->joint->gmatZero().get_rotation();
				//axis[k] = SrVec(parentMat.get(k,0),parentMat.get(k,1),parentMat.get(k,2))*node->joint->gmatZero().get_rotation()*node->joint->parent()->gmatZero().get_rotation().inverse();

				SrVec jVec = cross(axis[k],(endPos-nodePos));
				matJ(posCount*3+0,idx*3+k) = jVec[0]*nodeWeight*consWeight;
				matJ(posCount*3+1,idx*3+k) = jVec[1]*nodeWeight*consWeight;
				matJ(posCount*3+2,idx*3+k) = jVec[2]*nodeWeight*consWeight;
			}
			if (node->getNodeName() == cons->rootName)
				bStop = true;

			node = node->parent;
		}
		posCount++;
	}

	// fill in entries for rotational constraint
	float maxRotOffset = 0.3f;
	int offset_idx = s->ikPosEffectors->size()*3;
	int rotCount = 0;

	//for (unsigned int i=0;i<s->ikRotEffectors.size();i++)
	for (ci = s->ikRotEffectors->begin(); ci != s->ikRotEffectors->end(); ci++)
	{
		EffectorConstraint* cons = ci->second;
		MeCtIKTreeNode* endNode = s->findIKTreeNode(cons->efffectorName.c_str());
		SrMat& endMat = endNode->gmat;
		//SrMat consMat; cons->getRotConstraint().get_mat(consMat);
		//SrMat zeroConsMat = consMat;//cons->gmatZero.inverse()*consMat*cons->gmatZero;
		SrVec targetRot;
		SrQuat quatOffset = cons->getRotConstraint()*SrQuat(endNode->gmat.inverse());//SrQuat(endNode->parent->gmat.inverse());
		//SrQuat quatOffset = SrQuat(zeroConsMat)*SrQuat(endMat.inverse());
		quatOffset.normalize();
		//sr_out << "Quat Offset = " << quatOffset << srnl;
		float angle = quatOffset.angle();
		targetRot = quatOffset.axis()*angle*0.9f;//*quatOffset.angle()*0.9; // target orientation offset
		if (targetRot.len() > maxRotOffset)
		{
			targetRot.normalize();
			targetRot = targetRot*maxRotOffset;
		}

		dS[offset_idx+rotCount*3] = targetRot[0];
		dS[offset_idx+rotCount*3+1] = targetRot[1];
		dS[offset_idx+rotCount*3+2] = targetRot[2];

		MeCtIKTreeNode* node = endNode->parent;
		float fRatio = 1.f/(float)(endNode->nodeLevel + 1);
		bool bStop = false;
		while(node && node->parent && !bStop) // no root node
		{
			int idx = node->validNodeIdx;
			assert(idx != -1);
			float nodeWeight = 1.f;
			if (node->getNodeName() == "r_acromioclavicular" || node->getNodeName() == "r_forearm" ||  node->getNodeName() == "l_forearm" || node->getNodeName() == "l_acromioclavicular")
				nodeWeight = 0.f;
			if (!node->active)
				nodeWeight = 0.f;

			const SrMat& nodeMat = node->gmat;
			SrMat parentMat;
			if (node->parent)
				parentMat = node->parent->gmat;
			else
				parentMat = s->ikGlobalMat;

			// fix for prerotation
			SkJointQuat* jquat = node->joint->quat();
			SrQuat prerotQuat = jquat->orientation()*jquat->prerot();
			SrMat prerot; prerotQuat.get_mat(prerot);
			parentMat = prerot*parentMat;
			//parentMat = parentMat*prerot;
			//parentMat = node->gmat;
			SrVec axis[3];
			for (int k=0;k<3;k++)
			{
				//axis[k] = SrVec(parentMat.get(k,0),parentMat.get(k,1),parentMat.get(k,2))*node->joint->parent()->gmatZero().get_rotation()*node->joint->gmatZero().get_rotation().inverse();
				axis[k] = SrVec(parentMat.get(k,0),parentMat.get(k,1),parentMat.get(k,2));//*node->joint->parent()->gmatZero().get_rotation().inverse()*node->joint->gmatZero().get_rotation();
				//axis[k] = SrVec(parentMat.get(k,0),parentMat.get(k,1),parentMat.get(k,2))*node->joint->gmatZero().get_rotation()*node->joint->parent()->gmatZero().get_rotation().inverse();
				matJ(offset_idx+rotCount*3+0,idx*3+k) = axis[k][0]*nodeWeight;
				matJ(offset_idx+rotCount*3+1,idx*3+k) = axis[k][1]*nodeWeight;
				matJ(offset_idx+rotCount*3+2,idx*3+k) = axis[k][2]*nodeWeight;
			}
			if (node->getNodeName() == cons->rootName)
				bStop = true;
			node = node->parent;
		}
	}
}

bool MeCtJacobianIK::updateReferenceJointJacobianReduce(MeCtIKTreeScenario* s)
{
	dSref = ublas::zero_vector<double>(s->ikValidNodes.size()*3);
	dVector dThetaTemp;
	dThetaTemp.resize(dSref.size());
	dThetaAux.resize(s->ikTreeNodes.size()*3);

	float maxRotOffset = 0.1f;
	for (unsigned int i=0;i<s->ikTreeNodes.size();i++)
	{
		MeCtIKTreeNode* endNode = s->ikTreeNodes[i];
		SrQuat nodeQuat = endNode->getQuat(QUAT_CUR);//s->ikQuatList[endNode->nodeIdx];
		SrQuat refQuat = endNode->getQuat(QUAT_REF);//s->ikRefQuatList[endNode->nodeIdx];
		SrQuat diff = refQuat*nodeQuat.inverse();
		diff.normalize(); // make sure it is a unit quaternion
		SrVec axis;
		float angle;
		diff.get(axis,angle);
		SrVec offset = axis*angle;//*0.9f
		if (diff.w >= 1.f) // handle the zero rotation cause by rounding error when converting quaternion to axis-angle
		{
			offset = SrVec(diff.x,diff.y,diff.z); // approximated with the quaternion value directly
		}
#if 1
		if (offset.len() > maxRotOffset)
		{
			offset.normalize();
			offset = offset*maxRotOffset;
		}
		if (endNode->validNodeIdx != -1) // need to do the null matrix update
		{
			for (int k=0;k<3;k++)
			{
				dSref(endNode->validNodeIdx*3+k) = offset[k];
			}
		}
		else // otherwise, just copy the joint angles to the result
#endif
		{
			for (int k=0;k<3;k++)
			{
				dThetaAux(endNode->nodeIdx*3+k) = offset[k];
			}
		}
	}
#if 1
	matrixVecMult(matJnull,dSref,dThetaTemp);
	// update the joint angles from IK nodes
	for (unsigned int i=0;i<s->ikValidNodes.size();i++)
	{
		MeCtIKTreeNode* endNode = s->ikValidNodes[i];
		for (int k=0;k<3;k++)
		{
			dThetaAux(endNode->nodeIdx*3+k) = dThetaTemp(i*3+k);
		}
	}
#endif

	return true;
}

bool MeCtJacobianIK::updateReferenceJointJacobian( MeCtIKTreeScenario* s )
{
	dSref = ublas::zero_vector<double>(s->ikTreeNodes.size()*3);
	dThetaAux.resize(dSref.size());

	float maxRotOffset = 0.1f;
	for (unsigned int i=0;i<s->ikTreeNodes.size();i++)
	{
		MeCtIKTreeNode* endNode = s->ikTreeNodes[i];
		SrQuat nodeQuat = endNode->getQuat(QUAT_CUR);//s->ikQuatList[endNode->nodeIdx];
		SrQuat refQuat = endNode->getQuat(QUAT_REF);//s->ikRefQuatList[endNode->nodeIdx];
		SrQuat diff = refQuat*nodeQuat.inverse();

		diff.normalize(); // make sure it is a unit quaternion
		SrVec axis;
		float angle;
		diff.get(axis,angle);
		SrVec offset = axis*angle;//*0.9f;
		if (offset.len() > maxRotOffset)
		{
			offset.normalize();
			offset = offset*maxRotOffset;
		}

		float weight = (float)(endNode->nodeLevel + 1);
		for (int k=0;k<3;k++)
		{
			dSref(i*3+k) = offset[k];
		}
	}
	matrixVecMult(matJnull,dSref,dThetaAux);
	return true;
}

void MeCtJacobianIK::computeJacobian(MeCtIKTreeScenario* s)
{
	matJ = ublas::zero_matrix<double>(s->ikPosEffectors->size()*3 + s->ikRotEffectors->size()*3  ,(s->ikTreeNodes.size())*3);//.resize(s->ikEndEffectors.size()*3,(s->ikTreeNodes.size())*3);
	matJnull = ublas::identity_matrix<double>(s->ikTreeNodes.size()*3);
	dWeight.resize(s->ikTreeNodes.size()*3);
	for (unsigned int i=0;i<dWeight.size();i++)
		dWeight(i) = 1.0;

	// plus rotation
	dS.resize(s->ikPosEffectors->size()*3 + s->ikRotEffectors->size()*3);

	ConstraintMap::iterator ci;
	int posCount = 0;
	// fill in entries for positional constraint
 	//for (unsigned int i=0;i<s->ikPosEffectors.size();i++)
	for (ci = s->ikPosEffectors->begin(); ci != s->ikPosEffectors->end(); ci++)
	{
		EffectorConstraint* cons = ci->second;
		MeCtIKTreeNode* endNode = s->findIKTreeNode(cons->efffectorName.c_str());
		const SrMat& endMat = endNode->gmat;
		SrVec endPos = endMat.get_translation();
		SrVec offset = cons->getPosConstraint() - endPos;
		SrVec targetPos;
		//sr_out << "effector offset = " << srnl;
		if (offset.len() > maxOffset)
		{
			offset.normalize();
			targetPos = offset*maxOffset;
		}
		else
			targetPos = offset;
		//sr_out << "target offset = " << targetPos << srnl;

		dS[posCount*3] = targetPos[0];
		dS[posCount*3+1] = targetPos[1];
		dS[posCount*3+2] = targetPos[2];

		MeCtIKTreeNode* node = endNode->parent;
		//float fRatio = 1.f/(float)(endNode->nodeLevel + 1);
		bool bStop = false;
		if (endNode->getNodeName() == cons->rootName)
			bStop = true;

		while(node && node->parent && !bStop) // no root node
		{
			int idx = node->nodeIdx;
			float nodeWeight = 1.f;//((float)node->nodeLevel+endNode->nodeLevel)/(endNode->nodeLevel*2.f);
			if (node->getNodeName() == "r_acromioclavicular" || node->getNodeName() == "r_forearm" || node->getNodeName() == "l_forearm" || node->getNodeName() == "l_acromioclavicular")
				nodeWeight = 0.f;
			if (!node->active)
				nodeWeight = 0.f;
// 			if (node->nodeName == "r_forearm")
// 				nodeWeight = 0.9;

			const SrMat& nodeMat = node->gmat;
			SrMat parentMat;
			if (node->parent)
				parentMat = node->parent->gmat;
			else
				parentMat = s->ikGlobalMat;

			SrVec nodePos = SrVec(nodeMat.get(12),nodeMat.get(13),nodeMat.get(14));
			SrVec axis[3];
			for (int k=0;k<3;k++)
			{
				//axis[k] = SrVec(parentMat.get(k,0),parentMat.get(k,1),parentMat.get(k,2))*node->joint->parent()->gmatZero().get_rotation()*node->joint->gmatZero().get_rotation().inverse();
				axis[k] = SrVec(parentMat.get(k,0),parentMat.get(k,1),parentMat.get(k,2));//*node->joint->parent()->gmatZero().get_rotation().inverse()*node->joint->gmatZero().get_rotation();
				//axis[k] = SrVec(parentMat.get(k,0),parentMat.get(k,1),parentMat.get(k,2))*node->joint->gmatZero().get_rotation()*node->joint->parent()->gmatZero().get_rotation().inverse();

				SrVec jVec = cross(axis[k],endPos-nodePos);
				matJ(posCount*3+0,idx*3+k) = jVec[0]*nodeWeight;
				matJ(posCount*3+1,idx*3+k) = jVec[1]*nodeWeight;
				matJ(posCount*3+2,idx*3+k) = jVec[2]*nodeWeight;
			}
			if (node->getNodeName() == cons->rootName)
				bStop = true;

			node = node->parent;
		}
		posCount++;
	}

	// fill in entries for rotational constraint
	float maxRotOffset = 0.3f;
	int offset_idx = s->ikPosEffectors->size()*3;
	int rotCount = 0;

	//for (unsigned int i=0;i<s->ikRotEffectors.size();i++)
	for (ci = s->ikRotEffectors->begin(); ci != s->ikRotEffectors->end(); ci++)
	{
		EffectorConstraint* cons = ci->second;
		MeCtIKTreeNode* endNode = s->findIKTreeNode(cons->efffectorName.c_str());
		const SrMat& endMat = endNode->gmat;
		SrVec targetRot;
		SrQuat quatOffset = cons->getRotConstraint()*SrQuat(endNode->gmat.inverse());//SrQuat(endNode->parent->gmat.inverse());
		quatOffset.normalize();
		//sr_out << "Quat Offset = " << quatOffset << srnl;
		float angle = quatOffset.angle();
		targetRot = quatOffset.axis()*angle*0.9f;//*quatOffset.angle()*0.9; // target orientation offset
		if (targetRot.len() > maxRotOffset)
		{
			targetRot.normalize();
			targetRot = targetRot*maxRotOffset;
		}

		dS[offset_idx+rotCount*3] = targetRot[0];
		dS[offset_idx+rotCount*3+1] = targetRot[1];
		dS[offset_idx+rotCount*3+2] = targetRot[2];

		MeCtIKTreeNode* node = endNode->parent;
		float fRatio = 1.f/(float)(endNode->nodeLevel + 1);
		bool bStop = false;
		while(node && node->parent && !bStop) // no root node
		{
			int idx = node->nodeIdx;
			float nodeWeight = 1.f;
			if (node->getNodeName() == "r_acromioclavicular" || node->getNodeName() == "r_forearm" ||  node->getNodeName() == "l_forearm" || node->getNodeName() == "l_acromioclavicular")
				nodeWeight = 0.f;
			if (!node->active)
				nodeWeight = 0.f;

			const SrMat& nodeMat = node->gmat;
			SrMat parentMat;
			if (node->parent)
				parentMat = node->parent->gmat;
			else
				parentMat = s->ikGlobalMat;
			//parentMat = node->gmat;
			SrVec axis[3];
			for (int k=0;k<3;k++)
			{
				//axis[k] = SrVec(parentMat.get(k,0),parentMat.get(k,1),parentMat.get(k,2))*node->joint->parent()->gmatZero().get_rotation()*node->joint->gmatZero().get_rotation().inverse();
				axis[k] = SrVec(parentMat.get(k,0),parentMat.get(k,1),parentMat.get(k,2));//*node->joint->parent()->gmatZero().get_rotation().inverse()*node->joint->gmatZero().get_rotation();
				//axis[k] = SrVec(parentMat.get(k,0),parentMat.get(k,1),parentMat.get(k,2))*node->joint->gmatZero().get_rotation()*node->joint->parent()->gmatZero().get_rotation().inverse();
				matJ(offset_idx+rotCount*3+0,idx*3+k) = axis[k][0]*nodeWeight;
				matJ(offset_idx+rotCount*3+1,idx*3+k) = axis[k][1]*nodeWeight;
				matJ(offset_idx+rotCount*3+2,idx*3+k) = axis[k][2]*nodeWeight;
			}
			if (node->getNodeName() == cons->rootName)
				bStop = true;
			node = node->parent;
		}
	}
}

void MeCtJacobianIK::solveDLS(const dMatrix& mat, const dVector& v, const double damping, dVector& out, dMatrix& matPInv)
{
	dMatrix AtA;
	dMatrix temp(mat);
	dMatrix matJt = ublas::trans(temp);

	matrixMatMult(temp,matJt,AtA);
	dMatrix dampAtA;
	dMatrix invAtA;
	dMatrix matPtInv;
	invAtA.resize(AtA.size1(),AtA.size2());

	//inverseMatrix(AtA,invAtA);
	//matrixMatMult(matJt,invAtA,matPInv);

#if 0
	dMatrix dampMat(AtA.size1(),AtA.size2());
	{
		// test joint weighting when solving least square
		dMatrix tempDamp;
		matrixMatMult(invAtA,matJ,matPtInv);
		matrixMatMult(ublas::diagonal_matrix<double>(dWeight.size(),dWeight.data()),matJt,tempDamp);
		matrixMatMult(matPtInv,tempDamp,dampMat);
	}
#endif

	unsigned int offsetIdx = ikScenario->ikPosEffectors->size()*3;
	dampAtA = AtA;// + dampMat*damping;// + ublas::identity_matrix<double>(AtA.size1())*damping;
  	for (unsigned int i=0;i<dampAtA.size1();i++)
	{
		if (i < offsetIdx)
  			dampAtA(i,i) += damping;
		else
			dampAtA(i,i) += 0.f;
	}

	for (unsigned int i=0;i<AtA.size1();i++)
	{
		if (i < offsetIdx)
			AtA(i,i) += damping*refDampRatio;
		else
			AtA(i,i) += 0.f;
	}

	dVector tempV;
	inverseMatrix(dampAtA,invAtA);
	matrixVecMult(invAtA,v,tempV);
	matrixVecMult(matJt,tempV,out);

	inverseMatrix(AtA,invAtA);
	matrixMatMult(matJt,invAtA,matPInv);
}

#ifdef TEST_IK_EXPERIMENT
void MeCtJacobianIK::solveWeightDLS( const dMatrix& mat, const dVector& v, const double damping, dVector& out, dMatrix& matPInv )
{
	dMatrix AtA;
	dMatrix temp(mat);
	dMatrix matJt = ublas::trans(temp);

	matrixMatMult(matJt,temp,AtA);
	dMatrix dampAtA;
	dMatrix invAtA;
	dMatrix matPtInv;
	invAtA.resize(AtA.size1(),AtA.size2());

	inverseMatrix(AtA,invAtA);
	matrixMatMult(invAtA,matJt,matPInv);
	dMatrix dampMat(AtA.size1(),AtA.size2());
	if (0)
	{
		// test joint weighting when solving least square
		dMatrix tempDamp;
		matrixMatMult(invAtA,matJ,matPtInv);
		matrixMatMult(ublas::diagonal_matrix<double>(dWeight.size(),dWeight.data()),matJt,tempDamp);
		matrixMatMult(matPtInv,tempDamp,dampMat);
	}

	dampAtA = AtA;// + dampMat*damping;// + ublas::identity_matrix<double>(AtA.size1())*damping;
	for (unsigned int i=0;i<dampAtA.size1();i++)
		dampAtA(i,i) += damping*dWeight(i);
	dVector tempV;
	inverseMatrix(dampAtA,invAtA);
	matrixVecMult(matJt,v,tempV);
	matrixVecMult(invAtA,tempV,out);
}

void MeCtJacobianIK::solveDLSwithSVD( const dMatrix& mat, const dVector& v, const double damping, dVector& out, dMatrix& matPInv )
{
	dMatrix matIn;
	if (mat.size1() > mat.size2())
		matIn = ublas::trans(mat);
	else
		matIn = mat;

	dMatrix U,V;
	dVector vS(matIn.size1()), vSDamp(matIn.size1());
	U.resize(matIn.size1(),matIn.size1());
	V.resize(matIn.size2(),matIn.size2());
	lapack::gesvd(matIn,vS,U,V);
	//lapack::gesdd(matIn,vS,U,V);
	double maxSingular = vS(0);
	double minSingular = vS(vS.size()-1);
	// 	//printf("maxSingular = %f, minSingular = %f\n",maxSingular,minSingular);
	double d = sqrtf(ublas::norm_2(v))/0.1;///minSingular;//
	double damp = d;
	double alpha = 1.0;//*std::min(0.25,minSingular);
	if (minSingular > d)
		damp = 0.0;
	else if (minSingular >= d*0.5 && minSingular <= d)
		damp = sqrtf(minSingular*(d - minSingular));
	else if (minSingular <= d*0.5)
		damp = d*0.5;

	solveDLS(mat,v,damp*damp,out,matPInv);

	return;

	/*
	for (int i=0;i<vS.size();i++)
	{
	//vS(i) = 1.0/vS(i);
	vSDamp(i) = alpha*vS(i)/(vS(i)*vS(i) + damp*damp);// + (1.0-alpha)*vS(i)*0.0001;//vS(i)/(vS(i)*vS(i) + damp*damp);
	}
	ublas::diagonal_matrix<double> matS;
	matS = ublas::diagonal_matrix<double>(U.size1(),V.size1());
	for (int i=0;i<vSDamp.size();i++)
	matS(i,i) = vSDamp(i);

	dMatrix temp(V.size2(),matS.size2());
	out.resize(mat.size2());
	//dMatrix invAtA;
	//axpy_prod(ublas::trans(V),ublas::trans(matS),temp);
	matrixMatMult(ublas::trans(V),ublas::trans(matS),temp);
	//matPInv.resize(temp.size1(),U.size1());
	matrixMatMult(temp,ublas::trans(U),matPInv);
	matrixVecMult(matPInv,v,out);

	dMatrix Vt = ublas::trans(V);
	matPInv.resize(Vt.size1(),V.size2());
	matrixMatMult(Vt,V,matPInv);
	*/

}

bool MeCtJacobianIK::updateJointLimitJacobian( MeCtIKTreeScenario* scenario )
{
	int numJointLimit = scenario->ikJointLimitNodes.size();
	int numPinnedJoint = 0;//scenario->ikPinNodes.size();

	int numTotalAux = numJointLimit + numPinnedJoint;

	if (numTotalAux == 0)
		return false;
	dThetaAux.resize(matJ.size2());
	dThetaAux.clear();
	for (int i=0;i<numJointLimit;i++)
	{
		MeCtIKTreeNode* node = scenario->ikJointLimitNodes[i];
		for (int k=0;k<3;k++)
		{
			matJnull(node->nodeIdx*3+k,node->nodeIdx*3+k) = 0.0001;
			dThetaAux(node->nodeIdx*3+k) = node->jointOffset[k];
		}
	}

	updateNullSpace(matJnull,matJ,dThetaAux,dS);

	return true;
}

bool MeCtJacobianIK::updateBalanceJacobian( MeCtIKTreeScenario* s )
{
	matJbal = ublas::zero_matrix<double>(2,(s->ikTreeNodes.size())*3);
	dSbal = ublas::zero_vector<double>(2);
	float massSum = 0.f;
	for (unsigned int i=0;i<s->ikTreeNodes.size();i++)
		massSum += s->ikTreeNodes[i]->joint->mass();

	SrVec curComPos = SrVec(0,0,0);
	SrVec comPos = s->ikTreeRoot->getCoMPos();

	for (unsigned int i=0;i<s->ikTreeNodes.size();i++)
	{
		MeCtIKTreeNode* endNode = s->ikTreeNodes[i];
		float nodeMass = endNode->joint->mass()/massSum;
		SrVec endPos = endNode->getCoMPos();
		curComPos += endPos*nodeMass;
		MeCtIKTreeNode* node = endNode->parent;
		while(node && node->parent)
		{
			int idx = node->nodeIdx;
			const SrMat& nodeMat = node->gmat;
			SrMat parentMat;
			if (node->parent)
				parentMat = node->parent->gmat;
			else
				parentMat = s->ikGlobalMat;

			SrVec nodePos = SrVec(nodeMat.get(12),nodeMat.get(13),nodeMat.get(14));
			SrVec axis[3];
			for (int k=0;k<3;k++)
			{
				axis[k] = SrVec(parentMat.get(k,0),parentMat.get(k,1),parentMat.get(k,2));
				SrVec jVec = cross(axis[k],endPos-nodePos);
				matJbal(0,idx*3+k) += jVec[0]*nodeMass;
				matJbal(1,idx*3+k) += jVec[2]*nodeMass;
			}
			node = node->parent;
		}
	}

	dSbal(0) = comPos[0] - curComPos[0];
	dSbal(1) = comPos[2] - curComPos[2];

	updateNullSpace(matJnull,matJbal,dTheta,dSbal);

	return true;
}

void MeCtJacobianIK::updateNullSpace( dMatrix& Jnull, dMatrix& Ji, dVector& dQ, dVector& dX )
{
	dVector temp;
	matrixVecMult(Ji,dQ,temp);
	dX -= temp;
	dMatrix tempJ;
	matrixMatMult(Ji,Jnull,tempJ);
	Ji = tempJ;
}

#endif


text:
package com.sequenceiq.consumption.service;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

import javax.ws.rs.BadRequestException;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.core.Response;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import com.sequenceiq.cloudbreak.common.exception.CloudbreakServiceException;
import com.sequenceiq.cloudbreak.common.exception.WebApplicationExceptionMessageExtractor;
import com.sequenceiq.cloudbreak.service.secret.model.SecretResponse;
import com.sequenceiq.cloudbreak.service.secret.service.SecretService;
import com.sequenceiq.consumption.dto.Credential;
import com.sequenceiq.environment.api.v1.credential.endpoint.CredentialEndpoint;
import com.sequenceiq.environment.api.v1.credential.model.response.CredentialResponse;

public class CredentialServiceTest {

    private static final String ENVIRONMENT_CRN = "envCrn";

    private static final String CRN = "crn";

    private static final String NAME = "name";

    private static final String ATTRIBUTES = "attributes";

    private static final String ACCOUNT_ID = "accountId";

    private static final String CLOUD_PLATFORM = "cloudPlatform";

    private static final String OTHER_CLIENT_ERROR = "someError";

    @Mock
    private CredentialEndpoint credentialEndpoint;

    @Mock
    private SecretService secretService;

    @Mock
    private SecretResponse secretResponse;

    @Mock
    private WebApplicationExceptionMessageExtractor webApplicationExceptionMessageExtractor;

    @InjectMocks
    private CredentialService underTest;

    @Before
    public void setUp() {
        MockitoAnnotations.openMocks(this);
        when(secretService.getByResponse(secretResponse)).thenReturn(ATTRIBUTES);
        when(webApplicationExceptionMessageExtractor.getErrorMessage(any())).thenReturn(OTHER_CLIENT_ERROR);
    }

    @Test
    public void testGetCredentialByEnvCrnSuccessful() {
        CredentialResponse credentialResponse = new CredentialResponse();
        credentialResponse.setCrn(CRN);
        credentialResponse.setName(NAME);
        credentialResponse.setAccountId(ACCOUNT_ID);
        credentialResponse.setCloudPlatform(CLOUD_PLATFORM);
        credentialResponse.setAttributes(secretResponse);
        when(credentialEndpoint.getByEnvironmentCrn(ENVIRONMENT_CRN)).thenReturn(credentialResponse);

        Credential credential = underTest.getCredentialByEnvCrn(ENVIRONMENT_CRN);

        assertEquals(CRN, credential.getCrn());
        assertEquals(NAME, credential.getName());
        assertEquals(ACCOUNT_ID, credential.getAccountId());
        assertEquals(CLOUD_PLATFORM, credential.getCloudPlatform());
        assertEquals(ATTRIBUTES, credential.getAttributes());
    }

    @Test
    public void testCredentialNotFound() {
        Response response = Response.status(Response.Status.NOT_FOUND).build();
        when(credentialEndpoint.getByEnvironmentCrn(ENVIRONMENT_CRN)).thenThrow(new ClientErrorException(response));

        BadRequestException result = assertThrows(BadRequestException.class, () -> underTest.getCredentialByEnvCrn(ENVIRONMENT_CRN));
        assertEquals(String.format("Credential not found by environment CRN: %s", ENVIRONMENT_CRN), result.getMessage());
    }

    @Test
    public void testOtherClientError() {
        Response response = Response.status(Response.Status.BAD_REQUEST).build();
        when(credentialEndpoint.getByEnvironmentCrn(ENVIRONMENT_CRN)).thenThrow(new ClientErrorException(response));

        CloudbreakServiceException result = assertThrows(CloudbreakServiceException.class, () -> underTest.getCredentialByEnvCrn(ENVIRONMENT_CRN));
        assertEquals(String.format("Failed to get credential: %s", OTHER_CLIENT_ERROR), result.getMessage());
    }

    @Test
    public void testOtherError() {
        when(credentialEndpoint.getByEnvironmentCrn(ENVIRONMENT_CRN)).thenThrow(new RuntimeException("error"));

        RuntimeException result = assertThrows(RuntimeException.class, () -> underTest.getCredentialByEnvCrn(ENVIRONMENT_CRN));
        assertEquals(result.getMessage(), "error");
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* ========================================================================
 * DOM-based Routing
 * Based on http://goo.gl/EUTi53 by Paul Irish
 *
 * Only fires on body classes that match. If a body class contains a dash,
 * replace the dash with an underscore when adding it to the object below.
 *
 * .noConflict()
 * The routing is enclosed within an anonymous function so that you can
 * always reference jQuery with $, even when in .noConflict() mode.
 * ======================================================================== */

(function($) {

  // Use this variable to set up the common and page specific functions. If you
  // rename this variable, you will also need to rename the namespace below.
  var Sage = {
    // All pages
    'common': {
      init: function() {
        // JavaScript to be fired on all pages
      },
      finalize: function() {
        // JavaScript to be fired on all pages, after page specific JS is fired
      }
    },
    // Home page
    'home': {
      init: function() {
        // JavaScript to be fired on the home page
      },
      finalize: function() {
        // JavaScript to be fired on the home page, after the init JS

        var new_message = '';
        var string_end = false;
        var message_id = 0;

        var showText = function (target, message, index) {

            var interval = 100;

            $(target).html(new_message);

            if ( index === message[message_id].length ) {

                string_end = true;
                interval = 3000;

            }

            if ( index === 0 ) {
                string_end = false;

                if ( message_id === message.length - 1 ) {

                    message_id = 0;

                } else {

                    message_id++;

                }
            }

            if ( !string_end ) {

                new_message = new_message + message[message_id][index++];

            }

            if ( string_end ) {

                new_message = new_message.slice(0,-1);

                index--;

            }

            setTimeout( function () { showText(target, message, index); }, interval );

        };

        showText(".home .section-hero .hero-text strong span", ["cookies", "cakes", "brownies", "cupcakes", "fudge"], 0);

      }
    },
    // About us page, note the change from about-us to about_us.
    'about_us': {
      init: function() {
        // JavaScript to be fired on the about us page
      }
    }
  };

  // The routing fires all common scripts, followed by the page specific scripts.
  // Add additional events for more control over timing e.g. a finalize event
  var UTIL = {
    fire: function(func, funcname, args) {
      var fire;
      var namespace = Sage;
      funcname = (funcname === undefined) ? 'init' : funcname;
      fire = func !== '';
      fire = fire && namespace[func];
      fire = fire && typeof namespace[func][funcname] === 'function';

      if (fire) {
        namespace[func][funcname](args);
      }
    },
    loadEvents: function() {
      // Fire common init JS
      UTIL.fire('common');

      // Fire page-specific init JS, and then finalize JS
      $.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
        UTIL.fire(classnm);
        UTIL.fire(classnm, 'finalize');
      });

      // Fire common finalize JS
      UTIL.fire('common', 'finalize');
    }
  };

  // Load Events
  $(document).ready(UTIL.loadEvents);

})(jQuery); // Fully reference jQuery after this point.


text:
<?php

/*
 * This file is part of Gush package.
 *
 * (c) Luis Cordova <cordoval@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Gush\Command\PullRequest;

use Gush\Command\BaseCommand;
use Gush\Feature\GitDirectoryFeature;
use Gush\Feature\GitRepoFeature;
use Gush\Helper\GitConfigHelper;
use Gush\Helper\GitHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class PullRequestSwitchBaseCommand extends BaseCommand implements GitRepoFeature, GitDirectoryFeature
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('pull-request:switch-base')
            ->setDescription('Switch the base of the PR to another one')
            ->addArgument('pr_number', InputArgument::REQUIRED, 'PR number to be switched')
            ->addArgument(
                'base_branch',
                InputArgument::OPTIONAL,
                'Name of the new base branch to switch the PR to',
                'master'
            )
            ->addOption(
                'force-new-pr',
                null,
                InputOption::VALUE_NONE,
                'Create a new PR, even when the used adapter supports switching the base'
            )
            ->setHelp(
                <<<EOF
The <info>%command.name%</info> command switches the base of the given pull request
to the given base. This will preserve all commits made after the current base.

    <info>$ gush %command.name% 12 2.3</info>

When switching the base is not supported by the used adapter, a new pull request is
created instead. You can overwrite this behaviour with <comment>--force-new-pr</comment> to create
a new pull request (even if the adapter supports switching).

    <info>$ gush %command.name% --force-new-pr 12 2.3</info>

<fg=yellow;options=bold>To ensure a proper rebase process it's advised to make sure the
pull-request branch is up-to-date with the current base!</>
EOF
            )
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $prNumber = $input->getArgument('pr_number');
        $baseBranch = $input->getArgument('base_branch');

        $adapter = $this->getAdapter();
        $pr = $adapter->getPullRequest($prNumber);

        $currentBase = $pr['base']['ref'];
        $branchName = $pr['head']['ref'];
        $sourceOrg = $pr['head']['user'];

        if ($currentBase === $baseBranch) {
            $this->getHelper('gush_style')->error(
                sprintf('Pull-request base-branch is already based on %s!', $baseBranch)
            );

            return self::COMMAND_SUCCESS;
        }

        /** @var GitConfigHelper $gitConfigHelper */
        $gitConfigHelper = $this->getHelper('git_config');
        $gitConfigHelper->ensureRemoteExists($pr['base']['user'], $pr['base']['repo']);
        $gitConfigHelper->ensureRemoteExists($sourceOrg, $pr['head']['repo']);

        /** @var GitHelper $gitHelper */
        $gitHelper = $this->getHelper('git');
        $gitHelper->remoteUpdate($sourceOrg);
        $gitHelper->remoteUpdate($pr['base']['user']);
        $gitHelper->switchBranchBase(
            $branchName,
            $pr['base']['user'].'/'.$currentBase,
            $pr['base']['user'].'/'.$baseBranch,
            $branchName.'-switched'
        );

        $gitHelper->pushToRemote($sourceOrg, $branchName.'-switched', true);
        $gitHelper->pushToRemote($sourceOrg, ':'.$branchName);

        $switchPr = $adapter->switchPullRequestBase(
            $prNumber,
            $baseBranch,
            $sourceOrg.':'.$branchName.'-switched',
            $input->getOption('force-new-pr')
        );

        if ($prNumber === $switchPr['number']) {
            $adapter->createComment($prNumber, sprintf('(PR base switched to %s)', $baseBranch));

            $this->getHelper('gush_style')->success('Pull-request base-branch has been switched!');
        } else {
            $adapter->createComment($prNumber, sprintf('(PR replaced by %s)', $switchPr['html_url']));
            $adapter->closePullRequest($prNumber);

            $this->getHelper('gush_style')->success(
                [
                    'Pull-request base-branch could not be switched, a new pull-request has been opened instead: ',
                    $switchPr['html_url'],
                ]
            );
        }

        return self::COMMAND_SUCCESS;
    }
}


text:
<template name="root">

                {{typed}}

                {{ dict 'root.introSupportingMissionBold' 'µTool' }}
                {{ dict 'root.introSupportingMissionBold' '(/mu:tool/)' }}
                {{ dict 'root.introSupportingMissionVerb' 'creates' }}
                {{ dict 'root.introSupportingMissionHighlight' 'data-driven' }}
                {{ dict 'root.introSupportingMission' 'digital products and services that give brands a competitive edge.' }}

                {{ dict 'root.benefitsStatement' 'Attract customers with more' }}

            {{> benefits}}

                {{ dict 'root.figuresStatement' 'Recent track record' }}

            {{> figures}}
            See our work

                {{ dict 'root.clientsStatement' 'Trusted by' }}

            {{> clients}}

                {{ dict 'root.ctaStatement' 'Get Similar Results' }}

                    {{ dict 'root.ctaSupportingStatement' 'Reserve a free consultation' }}

            {{> members}}

                {{ dict 'root.toolsStatement' 'Latest Tools' }}

            {{> tools}}

                {{ dict 'root.postsStatement' 'From the Blog' }}

            {{> posts}}

</template>


text:
/**
 * @file OGV/client/views/menu.js
 * Helpers and events for primary menu
 */

Template.menu.events({
    'click #log-out':function(e,t)
    {
	Meteor.logout(function() {
	     throwError('Bye!, See you back soon');
	});

	return false;
    }
});


text:
QUnit.jsDump.HTML = false;

$(function(){ // START CLOSURE

$('#jq_version').html( $.fn.jquery );

var events = [
  // Default "outside" events.
  { outside: 'clickoutside',      originating: 'click' },
  { outside: 'dblclickoutside',   originating: 'dblclick' },
  { outside: 'focusoutside',      originating: 'focusin' },
  { outside: 'bluroutside',       originating: 'focusout' },
  { outside: 'mousemoveoutside',  originating: 'mousemove' },
  { outside: 'mousedownoutside',  originating: 'mousedown' },
  { outside: 'mouseupoutside',    originating: 'mouseup' },
  { outside: 'mouseoveroutside',  originating: 'mouseover' },
  { outside: 'mouseoutoutside',   originating: 'mouseout' },
  { outside: 'keydownoutside',    originating: 'keydown' },
  { outside: 'keypressoutside',   originating: 'keypress' },
  { outside: 'keyupoutside',      originating: 'keyup' },
  { outside: 'changeoutside',     originating: 'change' },
  { outside: 'selectoutside',     originating: 'select' },
  { outside: 'submitoutside',     originating: 'submit' },

  // A custom "outside" event.
  { outside: 'super-duper-awesome-outside', originating: 'omg-ponies' }
];

test( '$.addOutsideEvent', function() {
  expect( 1 );

  $.addOutsideEvent( 'omg-ponies', 'super-duper-awesome-outside' );

  ok( !!$.event.special[ 'super-duper-awesome-outside' ], 'custom super-duper-awesome-outside event has been initialized' );
});

$.map( events, function(e){
  var event_name = e.outside,
    originating_event_name = e.originating;

  test( event_name, function() {
    expect( 21 );

    var div = $('

').appendTo( 'body' ),
      bound = div.find('*'),
      a    = $('#a')[0],
      a1   = $('#a1')[0],
      b    = $('#b')[0],
      b1   = $('#b1')[0],
      b2   = $('#b2')[0],
      c    = $('#c')[0],
      body = $('body')[0],
      elems,
      targets;

    ok( $.data( document, 'events' ) == undefined, event_name + '-specific ' + originating_event_name + ' event should not be bound to document yet' );

    bound.bind( event_name, function(e){
      elems.push( this );
      targets.push( e.target );
    });

    equals( $.data( document, 'events' )[ originating_event_name ][0].namespace, event_name +'-special-event', event_name + '-specific ' + originating_event_name + ' event should be bound to document' );

    elems = [];
    targets = [];
    $(a).trigger( originating_event_name );
    same( targets, [a,a,a,a,a], 'target should be the ' + originating_event_name + ' event target element' );
    same( elems, [a1,b,b1,b2,c], 'event should have been triggered on these elements' );

    elems = [];
    targets = [];
    $(a1).trigger( originating_event_name );
    same( targets, [a1,a1,a1,a1], 'target should be the ' + originating_event_name + ' event target element' );
    same( elems, [b,b1,b2,c], 'event should have been triggered on these elements' );

    elems = [];
    targets = [];
    $(b).trigger( originating_event_name );
    same( targets, [b,b,b,b,b], 'target should be the ' + originating_event_name + ' event target element' );
    same( elems, [a,a1,b1,b2,c], 'event should have been triggered on these elements' );

    elems = [];
    targets = [];
    $(b1).trigger( originating_event_name );
    same( targets, [b1,b1,b1,b1], 'target should be the ' + originating_event_name + ' event target element' );
    same( elems, [a,a1,b2,c], 'event should have been triggered on these elements' );

    elems = [];
    targets = [];
    $(b2).trigger( originating_event_name );
    same( targets, [b2,b2,b2], 'target should be the ' + originating_event_name + ' event target element' );
    same( elems, [a,a1,c], 'event should have been triggered on these elements' );

    elems = [];
    targets = [];
    $(c).trigger( originating_event_name );
    same( targets, [c,c,c,c,c], 'target should be the ' + originating_event_name + ' event target element' );
    same( elems, [a,a1,b,b1,b2], 'event should have been triggered on these elements' );

    elems = [];
    targets = [];
    $(body).trigger( originating_event_name );
    same( targets, [body,body,body,body,body,body], 'target should be the ' + originating_event_name + ' event target element' );
    same( elems, [a,a1,b,b1,b2,c], 'event should have been triggered on these elements' );

    $(a).add(a1).unbind( event_name );

    elems = [];
    targets = [];
    $(body).trigger( originating_event_name );
    same( targets, [body,body,body,body], 'target should be the ' + originating_event_name + ' event target element' );
    same( elems, [b,b1,b2,c], 'event should have been triggered on these elements' );

    bound.unbind( event_name );

    ok( $.data( document, 'events' ) == undefined, event_name +'-specific ' + originating_event_name + ' event should no longer be bound to document' );

    elems = [];
    targets = [];
    $(body).trigger( originating_event_name );
    same( targets, [], 'event should not trigger' );
    same( elems, [], 'event should not trigger' );

    div.remove();
  });

});

}); // END CLOSURE


text:
package org.chronologicalthought.modula.osgi.test.activator

import org.osgi.framework.{BundleContext, BundleActivator}
import org.chronologicalthought.modula.osgi.test.api.TestService

/**
 * @author David Savage
 */
class TestActivator extends BundleActivator {
  def start(ctx: BundleContext) = {
    ctx.registerService(classOf[TestService].getName, new TestService(), null)
  }

  def stop(ctx: BundleContext) = {}
}


text:
package org.caleydo.view.bicluster.elem.layout;

/**
 * @author Samuel Gratzl
 *
 */
public interface ILayoutToolBar {

	/**
	 * @param name
	 *            name of this parameter
	 * @param label
	 * @param value
	 * @param min
	 * @param max
	 */
	void addSlider(String name, String label, float value, float min, float max);

}


text: Rails.application.config.session_store :cookie_store, key: '_test-2_2_3-22424_session'


text:
// <copyright file="SolutionExtensions.cs" company="nBuildKit">
// Copyright (c) nBuildKit. All rights reserved.
// Licensed under the Apache License, Version 2.0 license. See LICENCE.md file in the project root for full license information.
// </copyright>

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Build.Construction;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace NBuildKit.MsBuild.Tasks.Code
{
    /// <summary>
    /// Defines utility methods for dealing with Visual Studio solutions.
    /// </summary>
    public static class SolutionExtensions
    {
        /// <summary>
        /// Gets the paths for the project files in the solution.
        /// </summary>
        /// <param name="path">The full path to the solution file.</param>
        /// <param name="log">The MsBuild logger.</param>
        /// <returns>A collection containing the full paths to the projects in the solution.</returns>
        public static IEnumerable<ITaskItem> GetProjects(string path, Core.ILogger log = null)
        {
            // The loaded version of Microsoft.Build might not be the version we're compiled against so we need to
            // find the correct assembly first
            var microsoftBuildAssembly = AppDomain.CurrentDomain.GetAssemblies()
                .FirstOrDefault(a => string.Equals(a.GetName().Name, "Microsoft.Build", StringComparison.Ordinal));

            var solutionParserType = Type.GetType(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "Microsoft.Build.Construction.SolutionFile, {0}",
                    microsoftBuildAssembly.FullName),
                true,
                false);

            if (solutionParserType == null)
            {
                throw new InvalidOperationException("Can not find solution file type.");
            }

            log?.LogMessage(
                MessageImportance.Low,
                "Using the MsBuild solution parser from '{0}' with type '{1}'",
                microsoftBuildAssembly.FullName,
                solutionParserType);

            var parseSolutionMethod = solutionParserType.GetMethod("Parse", BindingFlags.Public | BindingFlags.Static);
            dynamic solutionFile = parseSolutionMethod.Invoke(null, new object[] { path });

            var projects = (IReadOnlyList<ProjectInSolution>)solutionFile.ProjectsInOrder;
            log?.LogMessage(
                MessageImportance.Low,
                "Found {0} projects. Project paths:",
                projects.Count);
            if (log != null)
            {
                foreach (var project in projects)
                {
                    log?.LogMessage(
                        MessageImportance.Low,
                        (string)project.RelativePath);
                }
            }

            return projects
                .Where(
                    p =>
                    {
                        var projectType = ((object)p.ProjectType).ToString();
                        var result = string.Equals(projectType, "KnownToBeMSBuildFormat", StringComparison.OrdinalIgnoreCase);

                        log?.LogMessage(
                            MessageImportance.Low,
                            result
                                ? "Project {0} is an MsBuild project"
                                : "Project {0} is not an MsBuild project",
                            (string)p.RelativePath);

                        return result;
                    })
                .Select(
                    p =>
                    {
                        var projectRelativePath = (string)p.RelativePath;
                        var projectAbsolutePath = Path.Combine(Path.GetDirectoryName(path), projectRelativePath);

                        log?.LogMessage(
                            MessageImportance.Low,
                            "Project {0} has absolute path {1}",
                            projectRelativePath,
                            projectAbsolutePath);

                        return projectAbsolutePath;
                    })
                .Select(
                    p =>
                    {
                        var item = new TaskItem(p);
                        return item;
                    })
                .ToArray();
        }
    }
}


text:
void FinalRgbFunctionStruct::ZeroOut()
{
    RegisterEnum zero;
    zero.word = RCP_ZERO;
    a.Init(zero, GL_UNSIGNED_IDENTITY_NV);
    b.Init(zero, GL_UNSIGNED_IDENTITY_NV);
    c.Init(zero, GL_UNSIGNED_IDENTITY_NV);
    d.Init(zero, GL_UNSIGNED_IDENTITY_NV);
}

void FinalAlphaFunctionStruct::ZeroOut()
{
    RegisterEnum zero;
    zero.word = RCP_ZERO;
    g.Init(zero, GL_UNSIGNED_IDENTITY_NV);
}

void FinalProductStruct::ZeroOut()
{
    RegisterEnum zero;
    zero.word = RCP_ZERO;
    e.Init(zero, GL_UNSIGNED_IDENTITY_NV);
    f.Init(zero, GL_UNSIGNED_IDENTITY_NV);
}
void FinalCombinerStruct::Validate()
{
    if (hasProduct &&
        (GL_E_TIMES_F_NV == product.e.reg.bits.name ||
         GL_SPARE0_PLUS_SECONDARY_COLOR_NV == product.e.reg.bits.name ||
         GL_DISCARD_NV == product.e.reg.bits.name ||
         GL_E_TIMES_F_NV == product.f.reg.bits.name ||
         GL_SPARE0_PLUS_SECONDARY_COLOR_NV == product.f.reg.bits.name ||
         GL_DISCARD_NV == product.f.reg.bits.name))
        errors.set("invalid input register for final_product");

    if (hasProduct &&
        (RCP_BLUE == product.e.reg.bits.channel ||
         RCP_BLUE == product.f.reg.bits.channel))
        errors.set("blue register used in final_product");

    if (GL_E_TIMES_F_NV == alpha.g.reg.bits.name ||
        GL_SPARE0_PLUS_SECONDARY_COLOR_NV == alpha.g.reg.bits.name ||
        GL_DISCARD_NV == alpha.g.reg.bits.name)
        errors.set("invalid input register for final alpha");

    if (RCP_RGB == alpha.g.reg.bits.channel)
        errors.set("rgb register used in final alpha");

    if (GL_SPARE0_PLUS_SECONDARY_COLOR_NV == rgb.a.reg.bits.name &&
        GL_SPARE0_PLUS_SECONDARY_COLOR_NV != rgb.b.reg.bits.name &&
        GL_ZERO == rgb.c.reg.bits.name && GL_UNSIGNED_IDENTITY_NV == rgb.c.map)
    {
        MappedRegisterStruct temp;
        temp = rgb.a;
        rgb.a = rgb.b;
        rgb.b = temp;
    }

    if (GL_SPARE0_PLUS_SECONDARY_COLOR_NV == rgb.a.reg.bits.name &&
        GL_ZERO == rgb.b.reg.bits.name && GL_UNSIGNED_INVERT_NV == rgb.b.map &&
        GL_ZERO == rgb.c.reg.bits.name && GL_UNSIGNED_IDENTITY_NV == rgb.c.map &&
        GL_SPARE0_PLUS_SECONDARY_COLOR_NV != rgb.d.reg.bits.name)
    {
        MappedRegisterStruct temp;
        temp = rgb.a;
        rgb.a = rgb.d;
        rgb.d = temp;
    }

    if (GL_SPARE0_PLUS_SECONDARY_COLOR_NV == rgb.a.reg.bits.name ||
        GL_DISCARD_NV == rgb.a.reg.bits.name ||
        GL_DISCARD_NV == rgb.b.reg.bits.name ||
        GL_DISCARD_NV == rgb.c.reg.bits.name ||
        GL_DISCARD_NV == rgb.d.reg.bits.name)
        errors.set("invalid input register for final rgb");

    if (RCP_BLUE == rgb.a.reg.bits.channel ||
        RCP_BLUE == rgb.b.reg.bits.channel ||
        RCP_BLUE == rgb.c.reg.bits.channel ||
        RCP_BLUE == rgb.d.reg.bits.channel)
        errors.set("blue register used in final rgb");

    if ((GL_E_TIMES_F_NV == rgb.a.reg.bits.name ||
        GL_E_TIMES_F_NV == rgb.b.reg.bits.name ||
        GL_E_TIMES_F_NV == rgb.c.reg.bits.name ||
        GL_E_TIMES_F_NV == rgb.d.reg.bits.name) && !hasProduct)
        errors.set("final_product used but not set");

    if (RCP_NONE == rgb.a.reg.bits.channel)
        rgb.a.reg.bits.channel = RCP_RGB;
    if (RCP_NONE == rgb.b.reg.bits.channel)
        rgb.b.reg.bits.channel = RCP_RGB;
    if (RCP_NONE == rgb.c.reg.bits.channel)
        rgb.c.reg.bits.channel = RCP_RGB;
    if (RCP_NONE == rgb.d.reg.bits.channel)
        rgb.d.reg.bits.channel = RCP_RGB;
    if (RCP_NONE == product.e.reg.bits.channel)
        product.e.reg.bits.channel = RCP_RGB;
    if (RCP_NONE == product.f.reg.bits.channel)
        product.f.reg.bits.channel = RCP_RGB;
    if (RCP_NONE == alpha.g.reg.bits.channel)
        alpha.g.reg.bits.channel = RCP_ALPHA;
}

void FinalCombinerStruct::Invoke()
{
    if(clamp)
        glCombinerParameteriNV(GL_COLOR_SUM_CLAMP_NV, GL_TRUE);
    else
        glCombinerParameteriNV(GL_COLOR_SUM_CLAMP_NV, GL_FALSE);

    glFinalCombinerInputNV(
        GL_VARIABLE_A_NV,
        rgb.a.reg.bits.name,
        rgb.a.map,
        MAP_CHANNEL(rgb.a.reg.bits.channel));

    glFinalCombinerInputNV(
        GL_VARIABLE_B_NV,
        rgb.b.reg.bits.name,
        rgb.b.map,
        MAP_CHANNEL(rgb.b.reg.bits.channel));

    glFinalCombinerInputNV(
        GL_VARIABLE_C_NV,
        rgb.c.reg.bits.name,
        rgb.c.map,
        MAP_CHANNEL(rgb.c.reg.bits.channel));

    glFinalCombinerInputNV(
        GL_VARIABLE_D_NV,
        rgb.d.reg.bits.name,
        rgb.d.map,
        MAP_CHANNEL(rgb.d.reg.bits.channel));

    glFinalCombinerInputNV(
        GL_VARIABLE_E_NV,
        product.e.reg.bits.name,
        product.e.map,
        MAP_CHANNEL(product.e.reg.bits.channel));

    glFinalCombinerInputNV(
        GL_VARIABLE_F_NV,
        product.f.reg.bits.name,
        product.f.map,
        MAP_CHANNEL(product.f.reg.bits.channel));

    glFinalCombinerInputNV(
        GL_VARIABLE_G_NV,
        alpha.g.reg.bits.name,
        alpha.g.map,
        MAP_CHANNEL(alpha.g.reg.bits.channel));
}


text:
package com.zero.debloper.kaddu;

import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

/**
 * Created by debloper on 20/9/15.
 */
public class ProfileRecyclerViewAdapter extends RecyclerView.Adapter<ProfileRecyclerViewAdapter.ProfileViewHolder>  {
    public static class ProfileViewHolder extends RecyclerView.ViewHolder {

        CardView cv;
        ImageView profileIcon;
        TextView profileName;
        SwitchCompat switchCompatButton;

        ProfileViewHolder(View itemView) {
            super(itemView);
            cv = (CardView)itemView.findViewById(R.id.cv);
            profileIcon = (ImageView) itemView.findViewById(R.id.profile_icon);
            profileName = (TextView) itemView.findViewById(R.id.profile_name);
            switchCompatButton = (SwitchCompat) itemView.findViewById(R.id.switch_compat);
        }
    }

    List<Profile> profiles;
    Context context;

    ProfileRecyclerViewAdapter(List<Profile> profiles, Context context){
        this.profiles = profiles;
        this.context = context;
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public ProfileViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.profile_card_view, viewGroup, false);
        ProfileViewHolder pvh = new ProfileViewHolder(v);
        return pvh;
    }

    @Override
    public void onBindViewHolder(ProfileViewHolder personViewHolder, int i) {
        personViewHolder.profileIcon.setImageResource(profiles.get(i).iconId);
        personViewHolder.profileName.setText(profiles.get(i).name);
        personViewHolder.switchCompatButton.setChecked(profiles.get(i).isEnabled);
        personViewHolder.switchCompatButton.setOnCheckedChangeListener(new SwitchButtonStateChangeListener(i, context));
    }

    @Override
    public int getItemCount() {
        return profiles.size();
    }
}


text:
import styled from 'styled-components'

import css from '@/utils/css'

export const Wrapper = styled.div`
  ${css.flexColumn('align-both')}
  margin-top: -50px;
`
export const Desc = styled.div`
  font-size: 18px;
  opacity: 0.8;
  padding: 0 10%;
  margin-bottom: 10px;
`

export const NumWrapper = styled.div`
  position: relative;
  margin-bottom: 15px;
  color: #139c9e;
`
export const Num = styled.div`
  font-size: 45px;
  font-weight: bold;
`
export const Unit = styled.div`
  position: absolute;
  font-size: 16px;
  font-weight: bold;
  opacity: 0.6;
  bottom: 14px;
  right: -22px;
`


text:
module HtmlRoutes
  VERSION = '1.1'
end


text:
module Atheme::ParserHelper
  def match(expression)
    expression.match(raw_services_output)[1]
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<data>
    <xpath expr="/form/field[@name='carrier_cost_method']" position="after">
        <newline/>
        <group id='gls_unibox_config' string="GLS Unibox Configuration"
            states="{'invisible': Not(Eval('carrier_cost_method') == 'gls')}"
            colspan="4">
          <label name="gls_server"/>
          <field name="gls_server"/>
          <label name="gls_port"/>
          <field name="gls_port"/>
          <label name="gls_contract"/>
          <field name="gls_contract"/>
          <label name="gls_customer_id"/>
          <field name="gls_customer_id"/>
          <label name="gls_customer_number"/>
          <field name="gls_customer_number"/>
          <label name="gls_location"/>
          <field name="gls_location"/>
          <label name="gls_shipping_depot_number"/>
          <field name="gls_shipping_depot_number"/>
          <label name="gls_shipping_service_type"/>
          <field name="gls_shipping_service_type"/>
          <label name="gls_customer_label"/>
          <field name="gls_customer_label"/>
          <label name="gls_customer_id_label"/>
          <field name="gls_customer_id_label"/>
          <label name="gls_consignor_label"/>
          <field name="gls_consignor_label"/>
          <label name="gls_printer_resolution"/>
          <field name="gls_printer_resolution"/>
          <newline/>
          <label name="gls_is_test"/>
          <field name="gls_is_test"/>
        </group>
    </xpath>
</data>


text:
<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_3.dtd">

<!-- ============================================================= -->
<!-- Configure a HTTPS connector.                                  -->
<!-- This configuration must be used in conjunction with jetty.xml -->
<!-- and jetty-ssl.xml.                                            -->
<!-- ============================================================= -->
<Configure id="sslConnector" class="org.eclipse.jetty.server.ServerConnector">

  <Call name="addIfAbsentConnectionFactory">
    <Arg>
      <New class="org.eclipse.jetty.server.SslConnectionFactory">
        <Arg name="next">http/1.1</Arg>
        <Arg name="sslContextFactory"><Ref refid="sslContextFactory"/></Arg>
      </New>
    </Arg>
  </Call>

  <Call name="addConnectionFactory">
    <Arg>
      <New class="org.eclipse.jetty.server.HttpConnectionFactory">
        <Arg name="config"><Ref refid="sslHttpConfig" /></Arg>
      </New>
    </Arg>
  </Call>

</Configure>


text:
module Data.Discrimination.IEEE754
  (
  -- * Groups
  -- $groups
    groupingFloat, groupingDouble
  -- * Sorts
  -- $sorts
  , sortingFloat, sortingDouble
  ) where

import Data.Binary.IEEE754 (floatToWord, doubleToWord)
import Data.Bits (xor, setBit, shift)
import Data.Discrimination (Grouping(..), Group, Sorting(..), Sort)
import Data.Functor.Contravariant (Contravariant(contramap))
import Data.Word (Word32, Word64)

sortableFloat32 :: Float -> Word32
sortableFloat32 x = w `xor` mask
  where
    w = floatToWord x
    mask = setBit (negate (shift w (-31))) 31

sortableFloat64 :: Double -> Word64
sortableFloat64 x = w `xor` mask
  where
    w = doubleToWord x
    mask = setBit (negate (shift w (-63))) 63

discFloat :: Contravariant f => f Word32 -> f Float
discFloat = contramap sortableFloat32

discDouble :: Contravariant f => f Word64 -> f Double
discDouble = contramap sortableFloat64

-- $groups
-- Group values according to the IEEE754 total order.
--
-- This means that values will be in the same group if and only if they compare
-- equal under the IEEE754 total order.  In particular, bit-wise-identical NaNs
-- will be grouped together.

groupingFloat :: Group Float
groupingFloat = discFloat grouping

groupingDouble :: Group Double
groupingDouble = discDouble grouping

-- $sorts
-- Sort values according to the IEEE754 total order.
--
-- This matches the 'Ord' instance for non-NaN values, but orders NaNs
-- according to their sign bit and mantissa (negated if the sign bit is set).
-- Positive NaNs are greater than +Infinity, and negative NaNs are less than
-- -Infinity.

sortingFloat :: Sort Float
sortingFloat = discFloat sorting

sortingDouble :: Sort Double
sortingDouble = discDouble sorting


text:
package com.myt.pmg.controller;

import java.io.IOException;
import java.security.Principal;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myt.pmg.common.UtilFunction;
import com.myt.pmg.dto.ContributorData;
import com.myt.pmg.model.Account;
import com.myt.pmg.model.FAQ;
import com.myt.pmg.model.Ip;
import com.myt.pmg.model.User;
import com.myt.pmg.service.AccountService;
import com.myt.pmg.service.FaqService;
import com.myt.pmg.service.GridFSService;
import com.myt.pmg.service.IpService;
import com.myt.pmg.service.UserService;

@Controller
public class HomeController {
	static final Logger logger = Logger.getLogger(HomeController.class);

	@Autowired
	private UserService userService;

	@Autowired
	private AccountService accountService;

	@Autowired
	private IpService ipService;

	@Autowired
	GridFSService gridFSService;

	private FaqService faqService;

	private static String SESSION_OBJ = "SessionObj";

	@PreAuthorize(value = "hasRole('ROLE_USER')")
	@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
	public String home(Model model, Principal principal, HttpServletRequest request, HttpSession session)
			throws IOException {

		User user = userService.findByEmail(principal.getName());
		Account account = accountService.findByUserId(user.getEmail());
		logger.info("On COntroller Login!!!!!!!!!!" + user);
		if (session.getAttribute(SESSION_OBJ) == null) {
			UtilFunction.setCurrentUser(session, user);
			String ipAddress = request.getHeader("X-FORWARDED-FOR");

			/*
			 * if (accountService.findByUserId(user.getId()) != null) {
			 * accountService.saveAccount(account); }
			 */
			if (ipAddress == null) {
				ipAddress = request.getRemoteAddr();
			}
			Ip ip1 = ipService.findByIp(ipAddress, user.getId());
			if (ip1 == null) {
				Ip ip = new Ip();
				ip.setAccessTime(new Date());
				ip.setIp(ipAddress);
				ip.setUserid(user.getId());
				ipService.saveIp(ip);

			} else {
				ip1.setAccessTime(new Date());
				ipService.updateIp(ip1);
				if (ip1.isBanned()) {
					session.invalidate();
					return "redirect:/login?error=true&ipban=true";
				}
			}
		}
		model.addAttribute("user", user);
		model.addAttribute("account", account);
		logger.info("Logon" + user);

		String path = (String) session.getAttribute("path");

		System.out.println(":::::::::::::Path from the Session Object:::::::::::" + path);
		if (path == null)
			path = gridFSService.getpic(user, session);

		System.out.println("::::::::::::::::Image File Name:::::::::" + path);
		if (path != null) {
			model.addAttribute("path", path);
		}

		return "dashboard";
	}

	@RequestMapping(value = "/topusers", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public List<User> getTopUsers() {
		return userService.getTopUsers(5);
	}

	@RequestMapping(value = "/topcontributors", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public List<ContributorData> getTopContributors(HttpSession session) {
		User user = UtilFunction.getCurrentUser(session);
		return userService.getTopContributors(user.getId(), 5);
	}

	@RequestMapping(value = "/allcontributors", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public List<ContributorData> getAllContributors(HttpSession session) {
		User user = UtilFunction.getCurrentUser(session);
		return userService.getTopContributors(user.getId(), -1);
	}

	@RequestMapping(value = "/faqs", method = RequestMethod.GET)
	public String getFaq(HttpSession session, Model model) {
		User user = UtilFunction.getCurrentUser(session);
		model.addAttribute("user", user);
		List<FAQ> faqList = faqService.getActiveFaqs();
		model.addAttribute("faqList", faqList);
		return "faqs";
	}

	@RequestMapping(value = "/denied", method = RequestMethod.GET)
	public String deny() {
		return "denied";
	}

	@RequestMapping(value = "/saveip", method = RequestMethod.POST)
	public void saveLastAccessIp(@RequestParam("ip") String accessip, HttpSession session) {
		User user = UtilFunction.getCurrentUser(session);
		Ip ip = new Ip();
		ip.setIp(accessip);
		ip.setUserid(user.getId());
		ip.setAccessTime(new Date());
		ipService.saveIp(ip);
	}
}


text:
@charset "utf-8";
/*
1.改模板的颜色.panel .panelContent { border-color:#}全部为目标颜色
2.改body的background
3.改图片的路径
4.改 #sidebar_s .collapse和#sidebar_s .collapse:hover颜色
5.改.tree .selected { background:#d0fc68;}颜色
*/
/* Icon */
.tabsHeader li.main a span span, #taskbar li .taskbutton span { background:url(../default/images/icon.png) no-repeat;}

/* Panel */
.panel,
.panel .panelHeader, .panel .panelHeaderContent, .panel .panelHeaderContent h1,
.panel .panelFooter, .panel .panelFooterContent { background:url(../purple/images/panel/panel.png) no-repeat;}
.panel .expandable, .panel .collapsable { background:url(../purple/images/panel/panel_icon.png) no-repeat;}
.panel .panelHeaderContent h1 { color:#2d3f00; }
.panel .panelContent { border-color:#e29de2; background:#F9E8F9;}

.panel .grid { border-color:#E29DE2;}

/* Tabs */
.tabs, .tabsHeader, .tabsHeaderContent,
.tabs .tabsHeader ul, .tabs .tabsHeader li, .tabs .tabsHeader li a, .tabs .tabsHeader li span,
.tabs .tabsFooter, .tabs .tabsFooterContent { background:url(../purple/images/tabs/tabspanel.png) no-repeat;}

.tabs .tabsHeader li a { color:#2d3f00;}
.tabs .tabsHeader li span { color:#2d3f00;}
.tabs .tabsContent { border-color:#e29de2; background:#F9E8F9;}

/* TabsPage */
.tabsPage .tabsPageHeader, .tabsPage .tabsPageHeader li, .tabsPage .tabsPageHeader li a, .tabsPage .tabsPageHeader li span { background:url(../purple/images/tabs/tabspage.png) no-repeat;}
.tabsPage .tabsPageHeader { background-color:#e9f0f2;}
.tabsPage .tabsPageHeader { border-color:#e29de2;}
.tabsPage .tabsPageHeader li a { color:#2d3f00;}
.tabsPage .tabsPageHeader li .close,
.tabsPage .tabsPageHeader li.hover .close,
.tabsPage .tabsPageHeader li.selected .close { background:url(../purple/images/tabs/tabspage_icon.png) no-repeat;}
.tabsPage .tabsLeft, .tabsPage .tabsRight, .tabsPage .tabsMore { background:url(../purple/images/tabs/tabscontrol.png) no-repeat;}
.tabsPage .tabsMoreList { border-color:#E29DE2; background:#FFF;}
.tabsPage .tabsPageHeader .home_icon { background:url(../default/images/icon.png) no-repeat;}
.tabsPage .tabsPageContent { border-color:#e29de2; background:#FFF;}

/* Alert */
.alert .alertFooter, .alert .alertFooter_r, .alert .alertFooter_c { background:url(../purple/images/alert/alertpanel.png) no-repeat;}
.alert .alertContent { border-color:#b8d0d6; background:#eef4f5;}
.alert .warn .alertInner { border-color:#e83e09; background:#fefacf;}
.alert .error .alertInner { border-color:#e50000; background:#fefacf;}
.alert .correct .alertInner, .alert .info .alertInner { border-color:#b8d0d6; background:#fefacf;}
.alert .confirm .alertInner { border-color:#b8d0d6; background:#fefacf;}
.alert h1 { background:url(../default/images/alert/alertpanel_icon.png) no-repeat;}

/* Dialog */
.dialog .dialogHeader, .dialog .dialogHeader_r, .dialog .dialogHeader_c,
.dialog .dialogFooter, .dialog .dialogFooter_r, .dialog .dialogFooter_c { background:url(../purple/images/dialog/dialogpanel.png) no-repeat;}
.dialog .dialogHeader h1, .dialog .dialogHeader .close, .dialog .dialogHeader .maximize, .dialog .dialogHeader .restore, .dialog .dialogHeader .minimize, .resizable_f_r { background:url(../purple/images/dialog/dialogpanel_icon.png) no-repeat;}
.dialog .dialogHeader h1 { color:#2d3f00;}
.dialog .dialogContent { border-color:#e29de2; background:#F9E8F9;}

.resizable { border-color:#3b6200; background:#aae31d;}

/* Shadow */
.shadow .shadow_h_l { background:url(../default/images/shadow/shadow_h_l.png) no-repeat;}
.shadow .shadow_h_r { background:url(../default/images/shadow/shadow_h_r.png) no-repeat;}
.shadow .shadow_h_c { background:url(../default/images/shadow/shadow_h_c.png) repeat-x;}
.shadow .shadow_c_l { background:url(../default/images/shadow/shadow_c_l.png) repeat-y;}
.shadow .shadow_c_r { background:url(../default/images/shadow/shadow_c_r.png) repeat-y;}
.shadow .shadow_c_c { background:url(../default/images/shadow/shadow_c_c.png) repeat;}
.shadow .shadow_f_l { background:url(../default/images/shadow/shadow_f_l.png) no-repeat;}
.shadow .shadow_f_r { background:url(../default/images/shadow/shadow_f_r.png) no-repeat;}
.shadow .shadow_f_c { background:url(../default/images/shadow/shadow_f_c.png) repeat-x;}

/* Tree */
.tree div div { background:url(../default/images/tree/tree.png) no-repeat;}
.tree .folder_collapsable, .tree .folder_expandable, .tree .file {background:transparent url(../default/images/tree/folder.png) no-repeat scroll 0 0;}
.tree .checked, .tree .unchecked, .tree .indeterminate { background:url(../default/images/tree/check.png) no-repeat;}
.tree ul { background:#FFF;}
.tree li a, .tree li span { color:#2d3f00;}
.tree .hover { background:#f6f6f6;}
.tree .selected { background:#F9E8F9;}
/* Accordion */
.accordion .accordionHeader, .accordion .accordionHeader h2, .accordion .accordionHeader h2 span { color:#2d3f00; background:url(../purple/images/accordion/accordion.png);}
.accordion { border-color:#e29de2; background:#FFF;}
.accordion .accordionHeader { background-color:#eaf4ff;}
.accordion .accordionContent { border-color:#e29de2;}

/* Grid */
.panelBar,
.toolBar li.hover, .toolBar li.hover a, .toolBar li.hover span, .toolBar span,
.panelBar .pagination, .panelBar .pagination li.hover, .panelBar .pagination li.hover a, .panelBar .pagination li span,
.panelBar .pagination li.disabled span span,
.panelBar .line, .panelBar .pagination li.jumpto, .panelBar .pagination li.jumpto .goto { background:url(../purple/images/grid/grid.png) no-repeat;}

.panelBar { border-color:#e29de2; background-color:#efefef;}

.grid .gridHeader { background:#EEE;}
.grid { background:#FFF;}
.grid table { border-color:#d0d0d0;}
.grid .gridHeader, .grid .gridHeader th { border-color:#d0d0d0; background:#f0eff0 url(../default/images/grid/tableth.png) repeat-x;}
.grid table th div { border-left-color:#EEE; border-right-color:#d0d0d0;}
.grid table td { border-color:#ededed;}

.grid .resizeMarker, .grid .resizeProxy { background:url(../default/images/grid/resizeCol.png) repeat-y;}

.grid .gridRowBg { background:#f7f7f7;}
.grid .hover { background:#f6f6f6;}
.grid .selected { border-color:#C00; background:#e29de2;}
.grid .error{background:#fb7e81;}

/* ProgressBar */
.progressBar { border:solid 2px #86a5ad; background:#FFF url(../default/images/progressBar/progressBar_m.gif) no-repeat 10px 10px;}

/* ----------------------------------------------------------------- Form */
/* TextInput */
.textInput, input.focus, input.required, input.error, input.readonly, input.disabled,
textarea.focus, textarea.required, textarea.error, textarea.readonly, textarea.disabled { background:url(../default/images/form/input_bg.png) no-repeat scroll;}

.textInput, .textArea { border-color:#a2bac0 #b8d0d6 #b8d0d6 #a2bac0; background-color:#FFF;}
input.required, textarea.required { border-color:#a2bac0 #b8d0d6 #b8d0d6 #a2bac0; background-color:#FFF;}
input.error, textarea.error { border-color:#F80C11 #FB7E81 #FB7E81 #F80C11;}
input.focus, textarea.focus { border-color:#64aabc #a9d7e3 #a9d7e3 #64aabc; background-color:#f8fafc;}
input.readonly, textarea.readonly { border-color:#9eabb3 #d5dbdf #d5dbdf #9eabb3; background-color:#F6F6F6;}
input.disabled, textarea.disabled { border-color:#9eabb3 #d5dbdf #d5dbdf #9eabb3; background-color:#F6F6F6;}

.inputButton, .inputDateButton { background:url(../default/images/form/input_bt.png) no-repeat;}

/* Button */
.button, .button span,
.buttonDisabled, .buttonDisabled span,
.buttonActive, .buttonActive span,
.button .buttonContent, .buttonHover, .buttonHover .buttonContent,
.buttonActive .buttonContent, .buttonActiveHover, .buttonActiveHover .buttonContent,
.buttonDisabled .buttonContent { background:url(../purple/images/button/button_s.png) no-repeat;}

.button span, .buttonDisabled span, .buttonActive span,
.button .buttonContent, .buttonHover, .buttonHover .buttonContent,
.buttonActive .buttonContent, .buttonDisabled .buttonContent,
.button button, .buttonHover button,
.buttonActive button, .buttonDisabled button { color:#2d3f00;}

.buttonDisabled span, .buttonDisabled:hover span,
.buttonDisabled button { color:#999;}

/* ----------------------------------------------------------------- Pages */
/* Layout */
body, #splitBar { background:#F9E8F9;}
#splitBarProxy { border-color:#c0c0c0; background:#CCC;}

#header, #header .headerNav { background:url(../purple/images/header_bg.png) repeat-x;}
#header { background-color:#5b9700;}
#header .logo { background:url(../default/images/logo.png) no-repeat;}
#header .nav li { float:left; margin-left:-1px; padding:0 8px; line-height:11px; background:url(../purple/images/listLine.png) no-repeat;}
#header .nav li a { color:#FFF;}
#header .themeList li div { background:url(../default/images/themeButton.png) no-repeat;}

.toggleCollapse, .toggleCollapse div { background:url(../purple/images/layout/toggleSidebar.png) no-repeat;}
.toggleCollapse { border-style:solid; border-width:1px 1px 0 1px; border-color:#e29de2; background-color:#e7eff0;}
.toggleCollapse h2 { color:#2d3f00;}
#sidebar_s .collapse { border:solid 1px #e29de2; background:#F9E8F9;}
#sidebar_s .collapse:hover { background:#F9E8F9;}

#taskbar, #taskbar li, #taskbar li .taskbutton { background:url(../default/images/layout/taskbar.png) no-repeat;}
#taskbar .close, #taskbar .restore, #taskbar .minimize { background:url(../default/images/layout/taskbar_icon.png) no-repeat;}
#taskbar li .taskbutton span { color:#FFF;}
#taskbar .taskbarLeft, #taskbar .taskbarRight { background:url(../default/images/layout/taskbar_control.png) no-repeat;}

/* Menu */
#navMenu, #navMenu li, #navMenu li.selected a, #navMenu li.selected span { background:url(../default/images/menu/menu.png) no-repeat;}
#navMenu { background-color:#1871dd; }
#navMenu li a, #navMenu li span { color:#FFF; }
#navMenu li.selected span { color:#000; }

/* Homepage */
.sidebarContent { display:block; overflow:auto; height:500px; border:solid 1px #86B4EC; background:#FFF;}
.accountInfo { display:block; overflow:hidden; height:60px; padding:0 10px; background:url(../default/images/account_info_bg.png) repeat-x}
.accountInfo p { padding:8px 0 0 0; line-height:19px;}
.accountInfo p span { font-size:14px; font-weight:bold;}
.accountInfo .right { float:right; padding-right:10px; text-align:right;}
.accountInfo .alertInfo { float:right; width:300px; height:60px; padding-left:10px; border-left:solid 1px #accdf4;}
.accountInfo .alertInfo h2 { padding:8px 0; line-height:17px;}
.accountInfo .alertInfo a { padding:6px 0 0 0; line-height:21px;}

/* Pages */
.pageForm .inputInfo { color:#999;}

/* Pages dialog */
.dialog .pageHeader, .dialog .pageContent { border-color:#E29DE2;}
.dialog .pageContent .pageFormContent { border-color:#E29DE2; background:#FFF;}

/* Pages default */
.page .pageHeader, .formBar { border-color:#E29DE2; background:#ebf0f5 url(../default/images/pageHeader_bg.png) repeat-x;}
.page .searchBar label { color:#183152;}

/* Pages Form */
.formBar { border-color:#E29DE2;}
.divider { border-color:#E29DE2;}

/* combox */
.combox .select a  { color:#183152; }
.comboxop { border-color:#B8D0D6; }
.combox, .combox div, .combox div a { background:url(../default/images/search-bg.gif) no-repeat; }


text:
import six

import cupy
from cupy import internal

zip_longest = six.moves.zip_longest
six_zip = six.moves.zip

def atleast_1d(*arys):
    """Converts arrays to arrays with dimensions >= 1.

    Args:
        arys (tuple of arrays): Arrays to be converted. All arguments must be
            cupy.ndarray objects. Only zero-dimensional array is affected.

    Returns:
        If there are only one input, then it returns its converted version.
        Otherwise, it returns a list of converted arrays.

    .. seealso:: :func:`numpy.atleast_1d`

    """
    res = []
    for a in arys:
        if not isinstance(a, cupy.ndarray):
            raise TypeError('Only cupy arrays can be atleast_1d')
        if a.ndim == 0:
            a = a.reshape(1)
        res.append(a)
    if len(res) == 1:
        res = res[0]
    return res

def atleast_2d(*arys):
    """Converts arrays to arrays with dimensions >= 2.

    If an input array has dimensions less than two, then this function inserts
    new axes at the head of dimensions to make it have two dimensions.

    Args:
        arys (tuple of arrays): Arrays to be converted. All arguments must be
            cupy.ndarray objects.

    Returns:
        If there are only one input, then it returns its converted version.
        Otherwise, it returns a list of converted arrays.

    .. seealso:: :func:`numpy.atleast_2d`

    """
    res = []
    for a in arys:
        if not isinstance(a, cupy.ndarray):
            raise TypeError('Only cupy arrays can be atleast_2d')
        if a.ndim == 0:
            a = a.reshape(1, 1)
        elif a.ndim == 1:
            a = a[cupy.newaxis, :]
        res.append(a)
    if len(res) == 1:
        res = res[0]
    return res

def atleast_3d(*arys):
    """Converts arrays to arrays with dimensions >= 3.

    If an input array has dimensions less than three, then this function
    inserts new axes to make it have three dimensions. The place of the new
    axes are following:

    - If its shape is ``()``, then the shape of output is ``(1, 1, 1)``.
    - If its shape is ``(N,)``, then the shape of output is ``(1, N, 1)``.
    - If its shape is ``(M, N)``, then the shape of output is ``(M, N, 1)``.
    - Otherwise, the output is the input array itself.

    Args:
        arys (tuple of arrays): Arrays to be converted. All arguments must be
            cupy.ndarray objects.

    Returns:
        If there are only one input, then it returns its converted version.
        Otherwise, it returns a list of converted arrays.

    .. seealso:: :func:`numpy.atleast_3d`

    """
    res = []
    for a in arys:
        if not isinstance(a, cupy.ndarray):
            raise TypeError('Only cupy arrays can be atleast_3d')
        if a.ndim == 0:
            a = a.reshape(1, 1, 1)
        elif a.ndim == 1:
            a = a[cupy.newaxis, :, cupy.newaxis]
        elif a.ndim == 2:
            a = a[:, :, cupy.newaxis]
        res.append(a)
    if len(res) == 1:
        res = res[0]
    return res

class broadcast(object):
    """Object that performs broadcasting.

    CuPy actually uses this class to support broadcasting in various
    operations. Note that this class does not provide an iterator.

    Args:
        arrays (tuple of arrays): Arrays to be broadcasted.

    Attributes:
        shape (tuple of ints): The broadcasted shape.
        nd (int): Number of dimensions of the broadcasted shape.
        size (int): Total size of the broadcasted shape.
        values (list of arrays): The broadcasted arrays.

    .. seealso:: :class:`numpy.broadcast`

    """

    def __init__(self, *arrays):
        ndarray = cupy.ndarray
        rev = slice(None, None, -1)
        shape_arr = [a._shape[rev] for a in arrays
                     if isinstance(a, ndarray)]
        r_shape = [max(ss) for ss in zip_longest(*shape_arr, fillvalue=0)]

        self.shape = shape = tuple(r_shape[rev])
        self.size = size = internal.prod(shape)
        self.nd = ndim = len(shape)

        broadcasted = list(arrays)
        for i, a in enumerate(broadcasted):
            if not isinstance(a, ndarray):
                continue

            a_shape = a.shape
            if a_shape == shape:
                continue

            r_strides = [
                a_st if sh == a_sh else (0 if a_sh == 1 else None)
                for sh, a_sh, a_st
                in six_zip(r_shape, a._shape[rev], a._strides[rev])]

            if None in r_strides:
                raise RuntimeError('Broadcasting failed')

            offset = (0,) * (ndim - len(r_strides))

            broadcasted[i] = view = a.view()
            view._shape = shape
            view._strides = offset + tuple(r_strides[rev])
            view._size = size
            view._c_contiguous = -1
            view._f_contiguous = -1

        self.values = tuple(broadcasted)

def broadcast_arrays(*args):
    """Broadcasts given arrays.

    Args:
        args (tuple of arrays): Arrays to broadcast for each other.

    Returns:
        list: A list of broadcasted arrays.

    .. seealso:: :func:`numpy.broadcast_arrays`

    """
    return broadcast(*args).values

def expand_dims(a, axis):
    """Expands given arrays.

    Args:
        a (cupy.ndarray): Array to be expanded.
        axis (int): Position where new axis is to be inserted.

    Returns:
        cupy.ndarray: The number of dimensions is one greater than that of
            the input array.

    .. seealso:: :func:`numpy.expand_dims`

    """
    shape = a.shape
    if axis < 0:
        axis = axis + len(shape) + 1
    return a.reshape(shape[:axis] + (1,) + shape[axis:])

def squeeze(a, axis=None):
    """Removes size-one axes from the shape of an array.

    Args:
        a (cupy.ndarray): Array to be reshaped.
        axis (int or tuple of ints): Axes to be removed. This function removes
            all size-one axes by default. If one of the specified axes is not
            of size one, an exception is raised.

    Returns:
        cupy.ndarray: An array without (specified) size-one axes.

    .. seealso:: :func:`numpy.squeeze`

    """
    if axis is None:
        axis = tuple(i for i, n in enumerate(a._shape) if n == 1)
    elif isinstance(axis, int):
        axis = axis,

    new_shape = []
    new_strides = []
    j = 0
    for i, n in enumerate(a._shape):
        if j < len(axis) and i == axis[j]:
            if n != 1:
                raise RuntimeError('Cannot squeeze dimension of size > 1')
            j += 1
        else:
            new_shape.append(n)
            new_strides.append(a._strides[i])

    v = a.view()
    v._shape = tuple(new_shape)
    v._strides = tuple(new_strides)
    v._c_contiguous = -1
    v._f_contiguous = -1
    return v


text:
define('views/questions-list', [
	'view',
	'composer',
	'views/types/row',
	'views/types/section',
	'views/types/choice',
	'lang'
], function (
	View,
	Composer,
	Row,
	Section,
	Choice,
	__
) {

	function QuestionsList() {
		Composer.apply(this, arguments);

		this.callbacks = {};
	}

	Composer.extend({
		constructor: QuestionsList,

		ui: {
			components: '[data-questions]'
		},

		data: function () {
			return {
				componentsProp: 'questions',
				componentDataProp: 'question',
				componentTypeProp: 'type',
				questions: [],
				types: [
					{
						title: __('question.row'),
						id:   Row.id,
						view: Row,
						data: Row.data
					},
					{
						title: __('question.section'),
						id:   Section.id,
						view: Section,
						data: Section.data
					},
					{
						title: __('question.choice'),
						id:   Choice.id,
						view: Choice,
						data: Choice.data
					}
				]
			};
		},

		template: {
			'@toolbar': null,

			'[data-types]': {
				each: {
					prop: 'types',
					view: MenuItem,
					dataProp: 'type'
				}
			}
		}
	});

	function MenuItem() {
		View.apply(this, arguments);
	}

	View.extend({
		constructor: MenuItem,

		addQuestion: function () {
			this.parent.callbacks.addQuestion(this.data.type, this.parent);
		},

		template: {
			'[data-title]': {
				text: '=type.title',

				on: {
					'click': '!addQuestion'
				}
			}
		}
	});

	return QuestionsList;
});