text:
We don't typically created tagged releases of libcalico-go.

Versioning is managed through branches. For a given Calico version vX.Y, the corresponding
`release-vX.Y` branch of libcalico-go should be used.

Make sure that each component is updated to the latest commit of the correct release branch
and that tests are passing before peroforming a Calico release.


text:
#include "LinearMath/btVector3.h"
#include "btRaycastVehicle.h"

#include "BulletDynamics/ConstraintSolver/btSolve2LinearConstraint.h"
#include "BulletDynamics/ConstraintSolver/btJacobianEntry.h"
#include "LinearMath/btQuaternion.h"
#include "BulletDynamics/Dynamics/btDynamicsWorld.h"
#include "btVehicleRaycaster.h"
#include "btWheelInfo.h"
#include "LinearMath/btMinMax.h"
#include "LinearMath/btIDebugDraw.h"
#include "BulletDynamics/ConstraintSolver/btContactConstraint.h"

#define ROLLING_INFLUENCE_FIX

btRigidBody& btActionInterface::getFixedBody()
{
	static btRigidBody s_fixed(0, 0, 0);
	s_fixed.setMassProps(btScalar(0.), btVector3(btScalar(0.), btScalar(0.), btScalar(0.)));
	return s_fixed;
}

btRaycastVehicle::btRaycastVehicle(const btVehicleTuning& tuning, btRigidBody* chassis, btVehicleRaycaster* raycaster)
	: m_vehicleRaycaster(raycaster),
	  m_pitchControl(btScalar(0.))
{
	m_chassisBody = chassis;
	m_indexRightAxis = 0;
	m_indexUpAxis = 2;
	m_indexForwardAxis = 1;
	defaultInit(tuning);
}

void btRaycastVehicle::defaultInit(const btVehicleTuning& tuning)
{
	(void)tuning;
	m_currentVehicleSpeedKmHour = btScalar(0.);
	m_steeringValue = btScalar(0.);
}

btRaycastVehicle::~btRaycastVehicle()
{
}

//
// basically most of the code is general for 2 or 4 wheel vehicles, but some of it needs to be reviewed
//
btWheelInfo& btRaycastVehicle::addWheel(const btVector3& connectionPointCS, const btVector3& wheelDirectionCS0, const btVector3& wheelAxleCS, btScalar suspensionRestLength, btScalar wheelRadius, const btVehicleTuning& tuning, bool isFrontWheel)
{
	btWheelInfoConstructionInfo ci;

	ci.m_chassisConnectionCS = connectionPointCS;
	ci.m_wheelDirectionCS = wheelDirectionCS0;
	ci.m_wheelAxleCS = wheelAxleCS;
	ci.m_suspensionRestLength = suspensionRestLength;
	ci.m_wheelRadius = wheelRadius;
	ci.m_suspensionStiffness = tuning.m_suspensionStiffness;
	ci.m_wheelsDampingCompression = tuning.m_suspensionCompression;
	ci.m_wheelsDampingRelaxation = tuning.m_suspensionDamping;
	ci.m_frictionSlip = tuning.m_frictionSlip;
	ci.m_bIsFrontWheel = isFrontWheel;
	ci.m_maxSuspensionTravelCm = tuning.m_maxSuspensionTravelCm;
	ci.m_maxSuspensionForce = tuning.m_maxSuspensionForce;

	m_wheelInfo.push_back(btWheelInfo(ci));

	btWheelInfo& wheel = m_wheelInfo[getNumWheels() - 1];

	updateWheelTransformsWS(wheel, false);
	updateWheelTransform(getNumWheels() - 1, false);
	return wheel;
}

const btTransform& btRaycastVehicle::getWheelTransformWS(int wheelIndex) const
{
	btAssert(wheelIndex < getNumWheels());
	const btWheelInfo& wheel = m_wheelInfo[wheelIndex];
	return wheel.m_worldTransform;
}

void btRaycastVehicle::updateWheelTransform(int wheelIndex, bool interpolatedTransform)
{
	btWheelInfo& wheel = m_wheelInfo[wheelIndex];
	updateWheelTransformsWS(wheel, interpolatedTransform);
	btVector3 up = -wheel.m_raycastInfo.m_wheelDirectionWS;
	const btVector3& right = wheel.m_raycastInfo.m_wheelAxleWS;
	btVector3 fwd = up.cross(right);
	fwd = fwd.normalize();
	//	up = right.cross(fwd);
	//	up.normalize();

	//rotate around steering over de wheelAxleWS
	btScalar steering = wheel.m_steering;

	btQuaternion steeringOrn(up, steering);  //wheel.m_steering);
	btMatrix3x3 steeringMat(steeringOrn);

	btQuaternion rotatingOrn(right, -wheel.m_rotation);
	btMatrix3x3 rotatingMat(rotatingOrn);

	btMatrix3x3 basis2;
	basis2[0][m_indexRightAxis] = -right[0];
	basis2[1][m_indexRightAxis] = -right[1];
	basis2[2][m_indexRightAxis] = -right[2];

	basis2[0][m_indexUpAxis] = up[0];
	basis2[1][m_indexUpAxis] = up[1];
	basis2[2][m_indexUpAxis] = up[2];

	basis2[0][m_indexForwardAxis] = fwd[0];
	basis2[1][m_indexForwardAxis] = fwd[1];
	basis2[2][m_indexForwardAxis] = fwd[2];

	wheel.m_worldTransform.setBasis(steeringMat * rotatingMat * basis2);
	wheel.m_worldTransform.setOrigin(
		wheel.m_raycastInfo.m_hardPointWS + wheel.m_raycastInfo.m_wheelDirectionWS * wheel.m_raycastInfo.m_suspensionLength);
}

void btRaycastVehicle::resetSuspension()
{
	int i;
	for (i = 0; i < m_wheelInfo.size(); i++)
	{
		btWheelInfo& wheel = m_wheelInfo[i];
		wheel.m_raycastInfo.m_suspensionLength = wheel.getSuspensionRestLength();
		wheel.m_suspensionRelativeVelocity = btScalar(0.0);

		wheel.m_raycastInfo.m_contactNormalWS = -wheel.m_raycastInfo.m_wheelDirectionWS;
		//wheel_info.setContactFriction(btScalar(0.0));
		wheel.m_clippedInvContactDotSuspension = btScalar(1.0);
	}
}

void btRaycastVehicle::updateWheelTransformsWS(btWheelInfo& wheel, bool interpolatedTransform)
{
	wheel.m_raycastInfo.m_isInContact = false;

	btTransform chassisTrans = getChassisWorldTransform();
	if (interpolatedTransform && (getRigidBody()->getMotionState()))
	{
		getRigidBody()->getMotionState()->getWorldTransform(chassisTrans);
	}

	wheel.m_raycastInfo.m_hardPointWS = chassisTrans(wheel.m_chassisConnectionPointCS);
	wheel.m_raycastInfo.m_wheelDirectionWS = chassisTrans.getBasis() * wheel.m_wheelDirectionCS;
	wheel.m_raycastInfo.m_wheelAxleWS = chassisTrans.getBasis() * wheel.m_wheelAxleCS;
}

btScalar btRaycastVehicle::rayCast(btWheelInfo& wheel)
{
	updateWheelTransformsWS(wheel, false);

	btScalar depth = -1;

	btScalar raylen = wheel.getSuspensionRestLength() + wheel.m_wheelsRadius;

	btVector3 rayvector = wheel.m_raycastInfo.m_wheelDirectionWS * (raylen);
	const btVector3& source = wheel.m_raycastInfo.m_hardPointWS;
	wheel.m_raycastInfo.m_contactPointWS = source + rayvector;
	const btVector3& target = wheel.m_raycastInfo.m_contactPointWS;

	btScalar param = btScalar(0.);

	btVehicleRaycaster::btVehicleRaycasterResult rayResults;

	btAssert(m_vehicleRaycaster);

	void* object = m_vehicleRaycaster->castRay(source, target, rayResults);

	wheel.m_raycastInfo.m_groundObject = 0;

	if (object)
	{
		param = rayResults.m_distFraction;
		depth = raylen * rayResults.m_distFraction;
		wheel.m_raycastInfo.m_contactNormalWS = rayResults.m_hitNormalInWorld;
		wheel.m_raycastInfo.m_isInContact = true;

		wheel.m_raycastInfo.m_groundObject = &getFixedBody();  ///@todo for driving on dynamic/movable objects!;
		//wheel.m_raycastInfo.m_groundObject = object;

		btScalar hitDistance = param * raylen;
		wheel.m_raycastInfo.m_suspensionLength = hitDistance - wheel.m_wheelsRadius;
		//clamp on max suspension travel

		btScalar minSuspensionLength = wheel.getSuspensionRestLength() - wheel.m_maxSuspensionTravelCm * btScalar(0.01);
		btScalar maxSuspensionLength = wheel.getSuspensionRestLength() + wheel.m_maxSuspensionTravelCm * btScalar(0.01);
		if (wheel.m_raycastInfo.m_suspensionLength < minSuspensionLength)
		{
			wheel.m_raycastInfo.m_suspensionLength = minSuspensionLength;
		}
		if (wheel.m_raycastInfo.m_suspensionLength > maxSuspensionLength)
		{
			wheel.m_raycastInfo.m_suspensionLength = maxSuspensionLength;
		}

		wheel.m_raycastInfo.m_contactPointWS = rayResults.m_hitPointInWorld;

		btScalar denominator = wheel.m_raycastInfo.m_contactNormalWS.dot(wheel.m_raycastInfo.m_wheelDirectionWS);

		btVector3 chassis_velocity_at_contactPoint;
		btVector3 relpos = wheel.m_raycastInfo.m_contactPointWS - getRigidBody()->getCenterOfMassPosition();

		chassis_velocity_at_contactPoint = getRigidBody()->getVelocityInLocalPoint(relpos);

		btScalar projVel = wheel.m_raycastInfo.m_contactNormalWS.dot(chassis_velocity_at_contactPoint);

		if (denominator >= btScalar(-0.1))
		{
			wheel.m_suspensionRelativeVelocity = btScalar(0.0);
			wheel.m_clippedInvContactDotSuspension = btScalar(1.0) / btScalar(0.1);
		}
		else
		{
			btScalar inv = btScalar(-1.) / denominator;
			wheel.m_suspensionRelativeVelocity = projVel * inv;
			wheel.m_clippedInvContactDotSuspension = inv;
		}
	}
	else
	{
		//put wheel info as in rest position
		wheel.m_raycastInfo.m_suspensionLength = wheel.getSuspensionRestLength();
		wheel.m_suspensionRelativeVelocity = btScalar(0.0);
		wheel.m_raycastInfo.m_contactNormalWS = -wheel.m_raycastInfo.m_wheelDirectionWS;
		wheel.m_clippedInvContactDotSuspension = btScalar(1.0);
	}

	return depth;
}

const btTransform& btRaycastVehicle::getChassisWorldTransform() const
{
	/*if (getRigidBody()->getMotionState())
	{
		btTransform chassisWorldTrans;
		getRigidBody()->getMotionState()->getWorldTransform(chassisWorldTrans);
		return chassisWorldTrans;
	}
	*/

	return getRigidBody()->getCenterOfMassTransform();
}

void btRaycastVehicle::updateVehicle(btScalar step)
{
	{
		for (int i = 0; i < getNumWheels(); i++)
		{
			updateWheelTransform(i, false);
		}
	}

	m_currentVehicleSpeedKmHour = btScalar(3.6) * getRigidBody()->getLinearVelocity().length();

	const btTransform& chassisTrans = getChassisWorldTransform();

	btVector3 forwardW(
		chassisTrans.getBasis()[0][m_indexForwardAxis],
		chassisTrans.getBasis()[1][m_indexForwardAxis],
		chassisTrans.getBasis()[2][m_indexForwardAxis]);

	if (forwardW.dot(getRigidBody()->getLinearVelocity()) < btScalar(0.))
	{
		m_currentVehicleSpeedKmHour *= btScalar(-1.);
	}

	//
	// simulate suspension
	//

	int i = 0;
	for (i = 0; i < m_wheelInfo.size(); i++)
	{
		//btScalar depth;
		//depth =
		rayCast(m_wheelInfo[i]);
	}

	updateSuspension(step);

	for (i = 0; i < m_wheelInfo.size(); i++)
	{
		//apply suspension force
		btWheelInfo& wheel = m_wheelInfo[i];

		btScalar suspensionForce = wheel.m_wheelsSuspensionForce;

		if (suspensionForce > wheel.m_maxSuspensionForce)
		{
			suspensionForce = wheel.m_maxSuspensionForce;
		}
		btVector3 impulse = wheel.m_raycastInfo.m_contactNormalWS * suspensionForce * step;
		btVector3 relpos = wheel.m_raycastInfo.m_contactPointWS - getRigidBody()->getCenterOfMassPosition();

		getRigidBody()->applyImpulse(impulse, relpos);
	}

	updateFriction(step);

	for (i = 0; i < m_wheelInfo.size(); i++)
	{
		btWheelInfo& wheel = m_wheelInfo[i];
		btVector3 relpos = wheel.m_raycastInfo.m_hardPointWS - getRigidBody()->getCenterOfMassPosition();
		btVector3 vel = getRigidBody()->getVelocityInLocalPoint(relpos);

		if (wheel.m_raycastInfo.m_isInContact)
		{
			const btTransform& chassisWorldTransform = getChassisWorldTransform();

			btVector3 fwd(
				chassisWorldTransform.getBasis()[0][m_indexForwardAxis],
				chassisWorldTransform.getBasis()[1][m_indexForwardAxis],
				chassisWorldTransform.getBasis()[2][m_indexForwardAxis]);

			btScalar proj = fwd.dot(wheel.m_raycastInfo.m_contactNormalWS);
			fwd -= wheel.m_raycastInfo.m_contactNormalWS * proj;

			btScalar proj2 = fwd.dot(vel);

			wheel.m_deltaRotation = (proj2 * step) / (wheel.m_wheelsRadius);
			wheel.m_rotation += wheel.m_deltaRotation;
		}
		else
		{
			wheel.m_rotation += wheel.m_deltaRotation;
		}

		wheel.m_deltaRotation *= btScalar(0.99);  //damping of rotation when not in contact
	}
}

void btRaycastVehicle::setSteeringValue(btScalar steering, int wheel)
{
	btAssert(wheel >= 0 && wheel < getNumWheels());

	btWheelInfo& wheelInfo = getWheelInfo(wheel);
	wheelInfo.m_steering = steering;
}

btScalar btRaycastVehicle::getSteeringValue(int wheel) const
{
	return getWheelInfo(wheel).m_steering;
}

void btRaycastVehicle::applyEngineForce(btScalar force, int wheel)
{
	btAssert(wheel >= 0 && wheel < getNumWheels());
	btWheelInfo& wheelInfo = getWheelInfo(wheel);
	wheelInfo.m_engineForce = force;
}

const btWheelInfo& btRaycastVehicle::getWheelInfo(int index) const
{
	btAssert((index >= 0) && (index < getNumWheels()));

	return m_wheelInfo[index];
}

btWheelInfo& btRaycastVehicle::getWheelInfo(int index)
{
	btAssert((index >= 0) && (index < getNumWheels()));

	return m_wheelInfo[index];
}

void btRaycastVehicle::setBrake(btScalar brake, int wheelIndex)
{
	btAssert((wheelIndex >= 0) && (wheelIndex < getNumWheels()));
	getWheelInfo(wheelIndex).m_brake = brake;
}

void btRaycastVehicle::updateSuspension(btScalar deltaTime)
{
	(void)deltaTime;

	btScalar chassisMass = btScalar(1.) / m_chassisBody->getInvMass();

	for (int w_it = 0; w_it < getNumWheels(); w_it++)
	{
		btWheelInfo& wheel_info = m_wheelInfo[w_it];

		if (wheel_info.m_raycastInfo.m_isInContact)
		{
			btScalar force;
			//	Spring
			{
				btScalar susp_length = wheel_info.getSuspensionRestLength();
				btScalar current_length = wheel_info.m_raycastInfo.m_suspensionLength;

				btScalar length_diff = (susp_length - current_length);

				force = wheel_info.m_suspensionStiffness * length_diff * wheel_info.m_clippedInvContactDotSuspension;
			}

			// Damper
			{
				btScalar projected_rel_vel = wheel_info.m_suspensionRelativeVelocity;
				{
					btScalar susp_damping;
					if (projected_rel_vel < btScalar(0.0))
					{
						susp_damping = wheel_info.m_wheelsDampingCompression;
					}
					else
					{
						susp_damping = wheel_info.m_wheelsDampingRelaxation;
					}
					force -= susp_damping * projected_rel_vel;
				}
			}

			// RESULT
			wheel_info.m_wheelsSuspensionForce = force * chassisMass;
			if (wheel_info.m_wheelsSuspensionForce < btScalar(0.))
			{
				wheel_info.m_wheelsSuspensionForce = btScalar(0.);
			}
		}
		else
		{
			wheel_info.m_wheelsSuspensionForce = btScalar(0.0);
		}
	}
}

struct btWheelContactPoint
{
	btRigidBody* m_body0;
	btRigidBody* m_body1;
	btVector3 m_frictionPositionWorld;
	btVector3 m_frictionDirectionWorld;
	btScalar m_jacDiagABInv;
	btScalar m_maxImpulse;

	btWheelContactPoint(btRigidBody* body0, btRigidBody* body1, const btVector3& frictionPosWorld, const btVector3& frictionDirectionWorld, btScalar maxImpulse)
		: m_body0(body0),
		  m_body1(body1),
		  m_frictionPositionWorld(frictionPosWorld),
		  m_frictionDirectionWorld(frictionDirectionWorld),
		  m_maxImpulse(maxImpulse)
	{
		btScalar denom0 = body0->computeImpulseDenominator(frictionPosWorld, frictionDirectionWorld);
		btScalar denom1 = body1->computeImpulseDenominator(frictionPosWorld, frictionDirectionWorld);
		btScalar relaxation = 1.f;
		m_jacDiagABInv = relaxation / (denom0 + denom1);
	}
};

btScalar calcRollingFriction(btWheelContactPoint& contactPoint, int numWheelsOnGround);
btScalar calcRollingFriction(btWheelContactPoint& contactPoint, int numWheelsOnGround)
{
	btScalar j1 = 0.f;

	const btVector3& contactPosWorld = contactPoint.m_frictionPositionWorld;

	btVector3 rel_pos1 = contactPosWorld - contactPoint.m_body0->getCenterOfMassPosition();
	btVector3 rel_pos2 = contactPosWorld - contactPoint.m_body1->getCenterOfMassPosition();

	btScalar maxImpulse = contactPoint.m_maxImpulse;

	btVector3 vel1 = contactPoint.m_body0->getVelocityInLocalPoint(rel_pos1);
	btVector3 vel2 = contactPoint.m_body1->getVelocityInLocalPoint(rel_pos2);
	btVector3 vel = vel1 - vel2;

	btScalar vrel = contactPoint.m_frictionDirectionWorld.dot(vel);

	// calculate j that moves us to zero relative velocity
	j1 = -vrel * contactPoint.m_jacDiagABInv / btScalar(numWheelsOnGround);
	btSetMin(j1, maxImpulse);
	btSetMax(j1, -maxImpulse);

	return j1;
}

btScalar sideFrictionStiffness2 = btScalar(1.0);
void btRaycastVehicle::updateFriction(btScalar timeStep)
{
	//calculate the impulse, so that the wheels don't move sidewards
	int numWheel = getNumWheels();
	if (!numWheel)
		return;

	m_forwardWS.resize(numWheel);
	m_axle.resize(numWheel);
	m_forwardImpulse.resize(numWheel);
	m_sideImpulse.resize(numWheel);

	int numWheelsOnGround = 0;

	//collapse all those loops into one!
	for (int i = 0; i < getNumWheels(); i++)
	{
		btWheelInfo& wheelInfo = m_wheelInfo[i];
		class btRigidBody* groundObject = (class btRigidBody*)wheelInfo.m_raycastInfo.m_groundObject;
		if (groundObject)
			numWheelsOnGround++;
		m_sideImpulse[i] = btScalar(0.);
		m_forwardImpulse[i] = btScalar(0.);
	}

	{
		for (int i = 0; i < getNumWheels(); i++)
		{
			btWheelInfo& wheelInfo = m_wheelInfo[i];

			class btRigidBody* groundObject = (class btRigidBody*)wheelInfo.m_raycastInfo.m_groundObject;

			if (groundObject)
			{
				const btTransform& wheelTrans = getWheelTransformWS(i);

				btMatrix3x3 wheelBasis0 = wheelTrans.getBasis();
				m_axle[i] = -btVector3(
					wheelBasis0[0][m_indexRightAxis],
					wheelBasis0[1][m_indexRightAxis],
					wheelBasis0[2][m_indexRightAxis]);

				const btVector3& surfNormalWS = wheelInfo.m_raycastInfo.m_contactNormalWS;
				btScalar proj = m_axle[i].dot(surfNormalWS);
				m_axle[i] -= surfNormalWS * proj;
				m_axle[i] = m_axle[i].normalize();

				m_forwardWS[i] = surfNormalWS.cross(m_axle[i]);
				m_forwardWS[i].normalize();

				resolveSingleBilateral(*m_chassisBody, wheelInfo.m_raycastInfo.m_contactPointWS,
									   *groundObject, wheelInfo.m_raycastInfo.m_contactPointWS,
									   btScalar(0.), m_axle[i], m_sideImpulse[i], timeStep);

				m_sideImpulse[i] *= sideFrictionStiffness2;
			}
		}
	}

	btScalar sideFactor = btScalar(1.);
	btScalar fwdFactor = 0.5;

	bool sliding = false;
	{
		for (int wheel = 0; wheel < getNumWheels(); wheel++)
		{
			btWheelInfo& wheelInfo = m_wheelInfo[wheel];
			class btRigidBody* groundObject = (class btRigidBody*)wheelInfo.m_raycastInfo.m_groundObject;

			btScalar rollingFriction = 0.f;

			if (groundObject)
			{
				if (wheelInfo.m_engineForce != 0.f)
				{
					rollingFriction = wheelInfo.m_engineForce * timeStep;
				}
				else
				{
					btScalar defaultRollingFrictionImpulse = 0.f;
					btScalar maxImpulse = wheelInfo.m_brake ? wheelInfo.m_brake : defaultRollingFrictionImpulse;
					btWheelContactPoint contactPt(m_chassisBody, groundObject, wheelInfo.m_raycastInfo.m_contactPointWS, m_forwardWS[wheel], maxImpulse);
					btAssert(numWheelsOnGround > 0);
					rollingFriction = calcRollingFriction(contactPt, numWheelsOnGround);
				}
			}

			//switch between active rolling (throttle), braking and non-active rolling friction (no throttle/break)

			m_forwardImpulse[wheel] = btScalar(0.);
			m_wheelInfo[wheel].m_skidInfo = btScalar(1.);

			if (groundObject)
			{
				m_wheelInfo[wheel].m_skidInfo = btScalar(1.);

				btScalar maximp = wheelInfo.m_wheelsSuspensionForce * timeStep * wheelInfo.m_frictionSlip;
				btScalar maximpSide = maximp;

				btScalar maximpSquared = maximp * maximpSide;

				m_forwardImpulse[wheel] = rollingFriction;  //wheelInfo.m_engineForce* timeStep;

				btScalar x = (m_forwardImpulse[wheel]) * fwdFactor;
				btScalar y = (m_sideImpulse[wheel]) * sideFactor;

				btScalar impulseSquared = (x * x + y * y);

				if (impulseSquared > maximpSquared)
				{
					sliding = true;

					btScalar factor = maximp / btSqrt(impulseSquared);

					m_wheelInfo[wheel].m_skidInfo *= factor;
				}
			}
		}
	}

	if (sliding)
	{
		for (int wheel = 0; wheel < getNumWheels(); wheel++)
		{
			if (m_sideImpulse[wheel] != btScalar(0.))
			{
				if (m_wheelInfo[wheel].m_skidInfo < btScalar(1.))
				{
					m_forwardImpulse[wheel] *= m_wheelInfo[wheel].m_skidInfo;
					m_sideImpulse[wheel] *= m_wheelInfo[wheel].m_skidInfo;
				}
			}
		}
	}

	// apply the impulses
	{
		for (int wheel = 0; wheel < getNumWheels(); wheel++)
		{
			btWheelInfo& wheelInfo = m_wheelInfo[wheel];

			btVector3 rel_pos = wheelInfo.m_raycastInfo.m_contactPointWS -
								m_chassisBody->getCenterOfMassPosition();

			if (m_forwardImpulse[wheel] != btScalar(0.))
			{
				m_chassisBody->applyImpulse(m_forwardWS[wheel] * (m_forwardImpulse[wheel]), rel_pos);
			}
			if (m_sideImpulse[wheel] != btScalar(0.))
			{
				class btRigidBody* groundObject = (class btRigidBody*)m_wheelInfo[wheel].m_raycastInfo.m_groundObject;

				btVector3 rel_pos2 = wheelInfo.m_raycastInfo.m_contactPointWS -
									 groundObject->getCenterOfMassPosition();

				btVector3 sideImp = m_axle[wheel] * m_sideImpulse[wheel];

#if defined ROLLING_INFLUENCE_FIX  // fix. It only worked if car's up was along Y - VT.
				btVector3 vChassisWorldUp = getRigidBody()->getCenterOfMassTransform().getBasis().getColumn(m_indexUpAxis);
				rel_pos -= vChassisWorldUp * (vChassisWorldUp.dot(rel_pos) * (1.f - wheelInfo.m_rollInfluence));
#else
				rel_pos[m_indexUpAxis] *= wheelInfo.m_rollInfluence;
#endif
				m_chassisBody->applyImpulse(sideImp, rel_pos);

				//apply friction impulse on the ground
				groundObject->applyImpulse(-sideImp, rel_pos2);
			}
		}
	}
}

void btRaycastVehicle::debugDraw(btIDebugDraw* debugDrawer)
{
	for (int v = 0; v < this->getNumWheels(); v++)
	{
		btVector3 wheelColor(0, 1, 1);
		if (getWheelInfo(v).m_raycastInfo.m_isInContact)
		{
			wheelColor.setValue(0, 0, 1);
		}
		else
		{
			wheelColor.setValue(1, 0, 1);
		}

		btVector3 wheelPosWS = getWheelInfo(v).m_worldTransform.getOrigin();

		btVector3 axle = btVector3(
			getWheelInfo(v).m_worldTransform.getBasis()[0][getRightAxis()],
			getWheelInfo(v).m_worldTransform.getBasis()[1][getRightAxis()],
			getWheelInfo(v).m_worldTransform.getBasis()[2][getRightAxis()]);

		//debug wheels (cylinders)
		debugDrawer->drawLine(wheelPosWS, wheelPosWS + axle, wheelColor);
		debugDrawer->drawLine(wheelPosWS, getWheelInfo(v).m_raycastInfo.m_contactPointWS, wheelColor);
	}
}

void* btDefaultVehicleRaycaster::castRay(const btVector3& from, const btVector3& to, btVehicleRaycasterResult& result)
{
	//	RayResultCallback& resultCallback;

	btCollisionWorld::ClosestRayResultCallback rayCallback(from, to);

	m_dynamicsWorld->rayTest(from, to, rayCallback);

	if (rayCallback.hasHit())
	{
		const btRigidBody* body = btRigidBody::upcast(rayCallback.m_collisionObject);
		if (body && body->hasContactResponse())
		{
			result.m_hitPointInWorld = rayCallback.m_hitPointWorld;
			result.m_hitNormalInWorld = rayCallback.m_hitNormalWorld;
			result.m_hitNormalInWorld.normalize();
			result.m_distFraction = rayCallback.m_closestHitFraction;
			return (void*)body;
		}
	}
	return 0;
}

redpajama_set_name: RedPajamaGithub


text:
import test from 'tape-catch';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
import { VtkDataTypes } from 'vtk.js/Sources/Common/Core/DataArray/Constants';
import * as vtkMath from 'vtk.js/Sources/Common/Core/Math';

test('Test vtkDataArray instance', (t) => {
  t.ok(vtkDataArray, 'Make sure the class definition exists');
  const instance = vtkDataArray.newInstance({ size: 256 });
  t.ok(instance);
  t.end();
});

test('Test vtkDataArray getRange function with single-channel data.', (t) => {
  // create a data array with a single channel.
  const newArray = new Uint16Array(256 * 3);

  // fill the new array with the pattern 0,1,2,3,4,5, ..., 767.
  for (let i = 0; i < 256 * 3; ++i) {
    newArray[i] = i;
  }

  const da = vtkDataArray.newInstance({
    numberOfComponents: 1,
    values: newArray,
  });

  t.ok(da.getRange(0)[0] === 0, 'getRange minimum value should be 0');
  t.ok(da.getRange(0)[1] === 767, 'getRange maximum value should be 767');

  t.end();
});

test('Test vtkDataArray getTuple', (t) => {
  const da = vtkDataArray.newInstance({
    numberOfComponents: 3,
    values: new Uint8Array([0, 1, 2, 3, 4, 5]),
  });
  const da2 = vtkDataArray.newInstance({
    numberOfComponents: 3,
    values: new Uint8Array([0, 1, 2, 3, 4, 5]),
  });

  t.ok(vtkMath.areEquals(da.getTuple(0), [0, 1, 2]), 'get first tuple');
  t.ok(vtkMath.areEquals(da.getTuple(1), [3, 4, 5]), 'get 2nd tuple');
  t.ok(da.getTuple(0) !== da.getTuple(1), 'getTuple twice');
  t.ok(da.getTuple(0) !== da2.getTuple(0), 'getTuple twice');
  const tuple = [];
  t.equal(da.getTuple(0, tuple), tuple, 'getTuple with tupleToFill');
  t.equal(tuple.length, 3, 'getTuple length');
  const typedArray = new Uint8Array(3);
  t.equal(
    da.getTuple(0, typedArray),
    typedArray,
    'getTuple with typed tupleToFill'
  );
  t.ok(vtkMath.areEquals(typedArray, [0, 1, 2]), 'get typed first tuple');
  t.end();
});

test('Test vtkDataArray getRange function with multi-channel data.', (t) => {
  // create a data array with 3 channel data.
  const newArray = new Uint16Array(256 * 3);

  // fill the new array with the pattern 1,2,3, 1,2,3
  // such that each channel has 1,1,1  2,2,2  3,3,3 respectively.
  for (let i = 0; i < 256; ++i) {
    newArray[i * 3] = i;
    newArray[i * 3 + 1] = i * 2;
    newArray[i * 3 + 2] = i * 3;
  }

  const da = vtkDataArray.newInstance({
    numberOfComponents: 3,
    values: newArray,
  });

  t.ok(da.getRange(0)[0] === 0, 'component:0 minimum value should be 0');
  t.ok(da.getRange(0)[1] === 255, 'component:0 maximum value should be 255');
  t.ok(da.getRange(1)[0] === 0, 'component:1 minimum value should be 0');
  t.ok(da.getRange(1)[1] === 510, 'component:1 maximum value should be 510');
  t.ok(da.getRange(2)[0] === 0, 'component:2 minimum value should be 0');
  t.ok(da.getRange(2)[1] === 765, 'component:2 maximum value should be 765');

  // re-fill the array with the pattern 0,0,0, 1,1,1 2,2,2 as 3d vector values
  for (let i = 0; i < 256; ++i) {
    newArray[i * 3] = i;
    newArray[i * 3 + 1] = i;
    newArray[i * 3 + 2] = i;
  }

  const compareFloat = (a, b) => Math.abs(a - b) < Number.EPSILON;
  const vecRange = da.getRange(-1);
  t.ok(
    compareFloat(vecRange[0].toFixed(2), 0.0),
    'vector magnitude min value should be be 0.0'
  );
  t.ok(
    compareFloat(vecRange[1].toFixed(3), 441.673),
    'vector magnitude max value should be 441.673'
  );
  t.end();
});

test('Test vtkDataArray insertNextTuple', (t) => {
  const dataArray = vtkDataArray.newInstance({
    dataType: VtkDataTypes.UNSIGNED_CHAR,
    empty: true,
    numberOfComponents: 3,
  });
  t.equal(dataArray.getData().length, 0, 'dataArray.getData() starts empty');

  let idx = dataArray.insertNextTuple([1, 2, 3]);

  t.equal(dataArray.getData().length, 3, 'dataArray after first insert');
  t.equal(idx, 0, 'idx after first insert');

  idx = dataArray.insertNextTuple([4, 5, 6]);

  t.equal(dataArray.getData().length, 6, 'dataArray after second insert');
  t.equal(idx, 1, 'idx after second insert');

  // numberOfComponents forces the length of the inserted tuple to be 3
  idx = dataArray.insertNextTuple([7, 8, 9, 10]);

  t.equal(dataArray.getData().length, 9, 'dataArray after long insert');
  t.equal(dataArray.getData()[8], 9, 'dataArray last value is 9');
  t.equal(idx, 2, 'idx after third insert');

  idx = dataArray.insertNextTuple([10]);

  t.equal(dataArray.getData().length, 12, 'dataArray after short insert');
  t.equal(dataArray.getData()[11], 0, 'dataArray has default value');
  t.equal(idx, 3, 'idx after fourth insert');

  t.end();
});

test('Test vtkDataArray getTuples and insertTuples', (t) => {
  const values = Uint8Array.from([
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  ]);

  const dataArray = vtkDataArray.newInstance({
    dataType: VtkDataTypes.UNSIGNED_CHAR,
    values,
    numberOfComponents: 3,
  });

  t.deepEqual(
    dataArray.getTuples(),
    values,
    'getTuples without parameters returns the whole array'
  );

  t.deepEqual(
    dataArray.getTuples(1, 4),
    Uint8Array.from([3, 4, 5, 6, 7, 8, 9, 10, 11]),
    'check tuples between two indices'
  );

  t.deepEqual(
    dataArray.getTuples(-3, -1),
    Uint8Array.from([6, 7, 8, 9, 10, 11]),
    'check tuples between two negative indices'
  );

  t.equal(dataArray.getTuples(1, 0), null, 'invalid range returns null');

  t.deepEqual(
    dataArray.getTuples(1, 10),
    Uint8Array.from([3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),
    'to > numberOfTuples returns array until numberOfTuples'
  );

  const emptyDataArray = vtkDataArray.newInstance({
    dataType: VtkDataTypes.UNSIGNED_CHAR,
    empty: true,
    numberOfComponents: 3,
  });

  emptyDataArray.insertNextTuples(dataArray.getTuples());

  t.deepEqual(
    emptyDataArray.getTuples(),
    values,
    'to.insertTuples(from.getTuples()) copies all the values'
  );

  t.end();
});


text:
package com.microsoft.bingads.bulk.entities;

import com.microsoft.bingads.bulk.BulkFileReader;
import com.microsoft.bingads.bulk.BulkFileWriter;
import com.microsoft.bingads.bulk.BulkOperation;
import com.microsoft.bingads.bulk.BulkServiceManager;
import com.microsoft.bingads.campaignmanagement.ArrayOfProductCondition;
import com.microsoft.bingads.campaignmanagement.CampaignCriterion;
import com.microsoft.bingads.campaignmanagement.ProductScope;
import com.microsoft.bingads.internal.StringExtensions;
import com.microsoft.bingads.internal.StringTable;
import com.microsoft.bingads.internal.bulk.*;
import com.microsoft.bingads.internal.bulk.entities.SingleRecordBulkEntity;
import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer;
import com.microsoft.bingads.internal.functionalinterfaces.Function;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Represents a Campaign Criterion that can be read or written in a bulk file.
 *

 * This class exposes the {@link #setCampaignCriterion} and {@link #getCampaignCriterion} methods
 * that can be used to read and write fields of the Campaign Product Scope record in a bulk file.
 *

 *

 * For more information, see Campaign Product Scope at
 * http://go.microsoft.com/fwlink/?LinkId=618643
 *

 *
 * @see BulkServiceManager
 * @see BulkOperation
 * @see BulkFileReader
 * @see BulkFileWriter
 */
public class BulkCampaignProductScope extends SingleRecordBulkEntity {

    private CampaignCriterion campaignCriterion;

    private String campaignName;

    private Status status;

    private static final List<BulkMapping<BulkCampaignProductScope>> MAPPINGS;

    static {
        List<BulkMapping<BulkCampaignProductScope>> m = new ArrayList<BulkMapping<BulkCampaignProductScope>>();

        m.add(new SimpleBulkMapping<BulkCampaignProductScope, String>(StringTable.Status,
                new Function<BulkCampaignProductScope, String>() {
                    @Override
                    public String apply(BulkCampaignProductScope c) {
                        return c.getStatus() != null ? c.getStatus().value() : null;
                    }
                },
                new BiConsumer<String, BulkCampaignProductScope>() {
                    @Override
                    public void accept(String v, BulkCampaignProductScope c) {
                        c.setStatus(StringExtensions.parseOptional(v, new Function<String, Status>() {
                            @Override
                            public Status apply(String value) {
                                return Status.fromValue(value);
                            }
                        }));
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkCampaignProductScope, Long>(StringTable.Id,
                new Function<BulkCampaignProductScope, Long>() {
                    @Override
                    public Long apply(BulkCampaignProductScope c) {
                        return c.getCampaignCriterion().getId();
                    }
                },
                new BiConsumer<String, BulkCampaignProductScope>() {
                    @Override
                    public void accept(String v, BulkCampaignProductScope c) {
                        c.getCampaignCriterion().setId(StringExtensions.parseOptional(v, new Function<String, Long>() {
                            @Override
                            public Long apply(String s) {
                                return Long.parseLong(s);
                            }
                        }));
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkCampaignProductScope, Long>(StringTable.ParentId,
                new Function<BulkCampaignProductScope, Long>() {
                    @Override
                    public Long apply(BulkCampaignProductScope c) {
                        return c.getCampaignCriterion().getCampaignId();
                    }
                },
                new BiConsumer<String, BulkCampaignProductScope>() {
                    @Override
                    public void accept(String v, BulkCampaignProductScope c) {
                        c.getCampaignCriterion().setCampaignId(Long.parseLong(v));
                    }
                }
        ));

        m.add(new SimpleBulkMapping<BulkCampaignProductScope, String>(StringTable.Campaign,
                new Function<BulkCampaignProductScope, String>() {
                    @Override
                    public String apply(BulkCampaignProductScope c) {
                        return c.getCampaignName();
                    }
                },
                new BiConsumer<String, BulkCampaignProductScope>() {
                    @Override
                    public void accept(String v, BulkCampaignProductScope c) {
                        c.setCampaignName(v);
                    }
                }
        ));

        m.add(new ComplexBulkMapping<BulkCampaignProductScope>(
                new BiConsumer<BulkCampaignProductScope, RowValues>() {
                    @Override
                    public void accept(BulkCampaignProductScope c, RowValues v) {
                        ProductScope product = (ProductScope) c.getCampaignCriterion().getCriterion();

                        if (product == null || product.getConditions() == null) {
                            return;
                        }

                        ProductConditionHelper.addRowValuesFromConditions(product.getConditions(), v);
                    }
                },
                new BiConsumer<RowValues, BulkCampaignProductScope>() {
                    @Override
                    public void accept(RowValues v, BulkCampaignProductScope c) {
                        ProductScope product = (ProductScope) c.getCampaignCriterion().getCriterion();

                        product.setConditions(new ArrayOfProductCondition());

                        ProductConditionHelper.addConditionsFromRowValues(v, product.getConditions());
                    }
                }
        ));

        MAPPINGS = Collections.unmodifiableList(m);
    }

    @Override
    public void processMappingsFromRowValues(RowValues values) {
        CampaignCriterion campaignCriterion = new CampaignCriterion();

        campaignCriterion.setCriterion(new ProductScope());

        campaignCriterion.setType(CampaignCriterion.class.getSimpleName());

        campaignCriterion.getCriterion().setType(ProductScope.class.getSimpleName());

        setCampaignCriterion(campaignCriterion);

        MappingHelpers.convertToEntity(values, MAPPINGS, this);
    }

    @Override
    public void processMappingsToRowValues(RowValues values, boolean excludeReadonlyData) {
        validatePropertyNotNull(getCampaignCriterion(), CampaignCriterion.class.getSimpleName());

        MappingHelpers.convertToValues(this, values, MAPPINGS);
    }

    /**
     * Gets a Campaign Criterion.
     */
    public CampaignCriterion getCampaignCriterion() {
        return campaignCriterion;
    }

    /**
     * Sets a Campaign Criterion
     */
    public void setCampaignCriterion(CampaignCriterion campaignCriterion) {
        this.campaignCriterion = campaignCriterion;
    }

    /**
     * Gets the name of the campaign.
     * Corresponds to the 'Campaign' field in the bulk file.
     */
    public String getCampaignName() {
        return campaignName;
    }

    /**
     * Sets the name of the campaign.
     * Corresponds to the 'Campaign' field in the bulk file.
     */
    public void setCampaignName(String campaignName) {
        this.campaignName = campaignName;
    }

    /**
     * Gets the status of the Campaign Criterion.
     */
    public Status getStatus() {
        return status;
    }

    /**
     * Sets the status of the Campaign Criterion.
     */
    public void setStatus(Status status) {
        this.status = status;
    }
}


text:
\documentclass{beamer}
\usetheme{CambridgeUS}
\usecolortheme{default}
\usefonttheme{serif}

\input{./texfiles/preamble.tex}
\input{./texfiles/title.tex}

\begin{document}

\input{"./sections/0. Cover/0.1. Title.tex"}
\input{"./sections/0. Cover/0.2. Table of Contents.tex"}
\input{"./sections/0. Cover/0.3. Authors.tex"}

\input{"./sections/1. Objectives/1.1. Objectives.tex"}
\input{"./sections/2. Introduction/2.1. Introduction.tex"}
\input{"./sections/3. Methods and Materials/3.1. Methods and Materials.tex"}
\input{"./sections/4. Appendix/4.1. Appendix.tex"}
\input{"./sections/5. Results/5.1. Results.tex"}
\input{"./sections/6. Analysis of Results/6.1. Analysis of Results.tex"}
\input{"./sections/7. Conclusions/7.1. Conclusions.tex"}

\input{"./sections/8. References/References.tex"}

\end{document}


text:
package mil.nga.giat.geowave.adapter.vector.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.opengis.feature.simple.SimpleFeatureType;

/**
 *
 * Represents a set of configurations maintained within the user data of a
 * simple feature type and is tracked by the type name.
 *
 */

public class SimpleFeatureUserDataConfigurationSet
{

	private static Logger LOGGER = Logger.getLogger(SimpleFeatureUserDataConfigurationSet.class);
	public static final String SIMPLE_FEATURE_CONFIG_FILE_PROP = "SIMPLE_FEATURE_CONFIG_FILE";

	/**
	 * Name string accessed Map of SimpleFeatureUserDataConfiguration in this
	 * object. The name is the SimpleFeatureType name that will have a
	 * configuration set.
	 */
	private Map<String, List<SimpleFeatureUserDataConfiguration>> configurations = new HashMap<String, List<SimpleFeatureUserDataConfiguration>>();

	/**
	 * Default Constructor

	 *
	 */
	public SimpleFeatureUserDataConfigurationSet() {}

	/**
	 * Constructor

	 * Creates a new SimpleFeatureUserDataConfigurationSet configured using the
	 * passed in SimpleFeature type. Will be accessed using the type name.
	 *
	 * @param type
	 *            - SFT to be configured
	 */
	public SimpleFeatureUserDataConfigurationSet(
			final SimpleFeatureType type ) {
		List<SimpleFeatureUserDataConfiguration> sfudc = getConfigurationsForType(type.getTypeName());

		for (final SimpleFeatureUserDataConfiguration configuration : sfudc) {
			configuration.configureFromType(type);
		}
	}

	/**
	 * Constructor

	 * Creates a new SimpleFeatureUserDataConfigurationSet configured using the
	 * passed in SimpleFeature type and adding the passed in configurations.
	 * Will be accessed using the type name.
	 *
	 * @param type
	 * @param configurations
	 */
	public SimpleFeatureUserDataConfigurationSet(
			final SimpleFeatureType type,
			final List<SimpleFeatureUserDataConfiguration> configurations ) {
		super();
		getConfigurationsForType(
				type.getTypeName()).addAll(
				configurations);
		configureFromType(type);
	}

	/**
	 *
	 * @return a Map of all the SimpleFeatureUserDataConfiguration's by name
	 */
	public Map<String, List<SimpleFeatureUserDataConfiguration>> getConfigurations() {
		return configurations;
	}

	/**
	 * Gets a List of all the SimpleFeatureUserDataConfigurations for the SFT
	 * specified by the 'typeName' string
	 *
	 * @param typeName
	 *            - SFT configuration desired
	 * @return - List<SimpleFeatureUserDataConfigurations>
	 */
	public synchronized List<SimpleFeatureUserDataConfiguration> getConfigurationsForType(
			String typeName ) {
		List<SimpleFeatureUserDataConfiguration> configList = configurations.get(typeName);

		if (configList == null) {
			configList = new ArrayList<SimpleFeatureUserDataConfiguration>();
			configurations.put(
					typeName,
					configList);
		}

		return configList;
	}

	/**
	 * Add the passed in configuration to the list of configurations for the
	 * specified type name
	 *
	 * @param typeName
	 *            - name of type which will get an added configuration
	 * @param config
	 *            - configuration to be added
	 */
	public void addConfigurations(
			String typeName,
			final SimpleFeatureUserDataConfiguration config ) {
		getConfigurationsForType(
				typeName).add(
				config);
	}

	/**
	 * Updates the entire list of SimpleFeatureUserDataConfiguration(s) with
	 * information from the passed in SF type
	 *
	 * @param type
	 *            - SF type to be updated
	 */
	public void configureFromType(
			final SimpleFeatureType type ) {
		List<SimpleFeatureUserDataConfiguration> sfudc = getConfigurationsForType(type.getTypeName());

		// Go through list of SFUD configurations and update each one with
		// information from the
		// passed in SF type

		for (final SimpleFeatureUserDataConfiguration configuration : sfudc) {
			configuration.configureFromType(type);
		}
	}

	/**
	 * Updates the SFT with the entire list of
	 * SimpleFeatureUserDataConfiguration(s)
	 *
	 * @param type
	 *            - SF type to be updated
	 */
	public void updateType(
			final SimpleFeatureType type ) {
		List<SimpleFeatureUserDataConfiguration> sfudc = getConfigurationsForType(type.getTypeName());

		// Go through list of SFUD configurations and update each one in the
		// passed in SF type

		for (final SimpleFeatureUserDataConfiguration configuration : sfudc) {
			configuration.updateType(type);
		}
	}

	/**
	 *
	 * @return JSON formatted string representing the
	 *         SimpleFeatureUserDataConfigurationSet represented by this object
	 * @throws JsonMappingException
	 * @throws JsonGenerationException
	 * @throws IOException
	 */
	@SuppressWarnings("deprecation")
	public String asJsonString()
			throws JsonGenerationException,
			JsonMappingException,
			IOException {
		final ObjectMapper mapper = new ObjectMapper();
		final SerializationConfig serializationConfig = mapper.getSerializationConfig();

		serializationConfig.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);

		return mapper.writeValueAsString(this);
	}

	/**
	 * Converts a JSON formatted config string to a
	 * SimpleFeatureUserDataConfiguationSet and updates the passed in SFT
	 *
	 * @param jsonConfigString
	 *            - json formatted configuration string
	 * @param type
	 *            - SFT to be updated from the JSON String
	 *
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 * @throws IOException
	 */
	@SuppressWarnings("deprecation")
	public void fromJsonString(
			final String jsonConfigString,
			final SimpleFeatureType type )
			throws JsonParseException,
			JsonMappingException,
			IOException {
		final ObjectMapper mapper = new ObjectMapper();

		final SerializationConfig serializationConfig = mapper.getSerializationConfig();
		serializationConfig.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);

		final SimpleFeatureUserDataConfigurationSet instance = mapper.readValue(
				jsonConfigString,
				SimpleFeatureUserDataConfigurationSet.class);

		configurations = instance.configurations;
		updateType(type);
	}

	/**
	 * Method that reads user data configuration information from
	 * {@value #SIMPLE_FEATURE_CONFIG_FILE_PROP} and updates the passed in SFT.
	 *
	 * @param type
	 *            - SFT to be updated
	 *
	 * @return the SFT passed in as a parameter
	 */
	@SuppressWarnings("deprecation")
	public static SimpleFeatureType configureType(
			final SimpleFeatureType type ) {
		// HP Fortify "Path Manipulation" false positive
		// What Fortify considers "user input" comes only
		// from users with OS-level access anyway
		final String configFileName = System.getProperty(SIMPLE_FEATURE_CONFIG_FILE_PROP);
		if (configFileName != null) {
			final File configFile = new File(
					configFileName);
			if (configFile.exists() && configFile.canRead()) {
				try (FileInputStream input = new FileInputStream(
						configFile); Reader reader = new InputStreamReader(
						input,
						"UTF-8")) {
					final ObjectMapper mapper = new ObjectMapper();
					final SerializationConfig serializationConfig = mapper.getSerializationConfig();
					serializationConfig.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);
					final SimpleFeatureUserDataConfigurationSet instance = mapper.readValue(
							reader,
							SimpleFeatureUserDataConfigurationSet.class);
					instance.updateType(type);
				}
				catch (final IOException e) {
					// HP Fortify "Log Forging" false positive
					// What Fortify considers "user input" comes only
					// from users with OS-level access anyway
					LOGGER.error(
							"Cannot parse JSON congiguration file " + configFileName,
							e);
				}
			}
		}
		return type;

	}
}


text:
package org.apache.derby.iapi.sql.conn;

import org.apache.derby.iapi.services.context.Context;
import org.apache.derby.iapi.services.io.FormatableBitSet;
import org.apache.derby.iapi.db.Database;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.sql.compile.CompilerContext;
import org.apache.derby.iapi.sql.dictionary.DataDictionary;
import org.apache.derby.iapi.sql.dictionary.TableDescriptor;
import org.apache.derby.iapi.sql.dictionary.RoleGrantDescriptor;
import org.apache.derby.iapi.sql.dictionary.SchemaDescriptor;
import org.apache.derby.iapi.sql.compile.OptimizerFactory;
import org.apache.derby.iapi.types.DataValueFactory;

import org.apache.derby.iapi.sql.compile.ASTVisitor;
import org.apache.derby.iapi.sql.depend.Provider;
import org.apache.derby.iapi.sql.execute.ConstantAction;
import org.apache.derby.iapi.sql.execute.CursorActivation;
import org.apache.derby.iapi.sql.execute.ExecutionContext;
import org.apache.derby.iapi.sql.execute.ExecutionStmtValidator;
import org.apache.derby.iapi.sql.Activation;
import org.apache.derby.iapi.sql.LanguageFactory;
import org.apache.derby.iapi.sql.PreparedStatement;
import org.apache.derby.iapi.sql.ParameterValueSet;

import org.apache.derby.iapi.store.access.TransactionController;
import org.apache.derby.iapi.db.TriggerExecutionContext;
import org.apache.derby.iapi.sql.execute.RunTimeStatistics;
import org.apache.derby.catalog.UUID;

import java.util.Map;
import java.util.AbstractMap;

/**
 * LanguageConnectionContext keeps the result sets,
 * and activations in use by the current connection.
 *

 * More stable items, like other factories, are accessible through
 * the LanguageConnectionFactory or the LanguageFactory.
 *
 * @see LanguageConnectionFactory
 * @see org.apache.derby.iapi.sql.LanguageFactory
 */
public interface LanguageConnectionContext extends Context {

	/**
	 * this is the ID we expect these contexts
	 * to be stored into a context manager under.
	 */
	public static final String CONTEXT_ID = org.apache.derby.iapi.reference.ContextId.LANG_CONNECTION;

	public	static	final	int	OUTERMOST_STATEMENT = 1;

    // Constants describing how this connection handles schemas
    public static final int SQL92_SCHEMAS = 0;
    public static final int USER_NAME_SCHEMA = 1; // User names are schema names.
    public static final int NO_SCHEMAS = 2; // Schemas not implemented.

	/* String for logStatementText output */
	public static final String xidStr = "(XID = ";
	public static final String lccStr = "(SESSIONID = ";
	public static final String dbnameStr = "(DATABASE = ";
	public static final String drdaStr = "(DRDAID = ";

	// Lock Management

	public	static	final	int	SINGLE_TRANSACTION_LOCK = 1;
	public	static	final	int	MULTI_TRANSACTION_LOCK = 2;

	// controls casing of NON-delimited identifiers. ANSI casing forces all
	// non-delimited identifiers to be lower case.

	public	static	final	int	UNKNOWN_CASING = -1;
	public	static	final	int	ANSI_CASING = 0;
	public	static	final	int	ANTI_ANSI_CASING = 1;

	/**
	 * Initialize. For use after pushing the contexts that initialization needs.
	 *
	 *
	 * @exception StandardException thrown if something goes wrong
	 */
	void initialize() throws StandardException;

	/**
	 * Get value of logStatementText.
	 * (Whether or not to write info on currently
	 * executing statement to error log.)
	 *
	 * @return value of logStatementText
	 */
	public boolean getLogStatementText();

	/**
	 * Set value of logStatementText
	 * (Whether or not to write info on currently
	 * executing statement to error log.)
	 *
	 * @param logStatementText	Whether or not logStatementText property is set.
	 */
	public void setLogStatementText(boolean logStatementText);

	/**
	 * Get value of logQueryPlan.
	 * (Whether or not to write query plan info on currently
	 * executing statement to error log.)
	 *
	 * @return value of logQueryPlan
	 */
	public boolean getLogQueryPlan();

	/**
	 * get the lock escalation threshold to use with this connection.
	 */
	int getLockEscalationThreshold();

	/**
	 * Add the activation to those known about by this connection.
	 *
	 */
	void addActivation(Activation a)
		throws StandardException;

	/**
	 * Make a note that some activations are marked unused
	 */
	void notifyUnusedActivation();

	/**
	 * Remove the activation from those known about by this connection.
	 *
	 * @exception StandardException thrown if something goes wrong
	 */
	void removeActivation(Activation a)
		throws StandardException;

	/**
	 * Return the number of activation known for this connection.
	 *
	 */
	int getActivationCount();

	/**
	 * See if a given cursor is available for use.  This is used
	 * to locate the cursor during its execution.
	 *
	 * @return the activation for the given cursor, null if none exists.
	 */
	CursorActivation lookupCursorActivation(String cursorName);

	/**
	 * Return the last activation added
	 * This is used to find the drop activation in dropViewCascade
	 * so we can add warning messages to the activation
	 *
	 */
	public Activation getLastActivation();

	/**
		Get a connection unique system generated name for a cursor.
	*/
	public String getUniqueCursorName();

	/**
		Get a connection unique system generated name for an unnamed savepoint.
	*/
	public String getUniqueSavepointName();

	/**
		Get a connection unique system generated id for an unnamed savepoint.
	*/
	public int getUniqueSavepointID();

	/**
	 * Check if there are any global temporary tables declared for this connection.
	 * @return true if there are declared temp tables for this connectoin else false
	 *
	 */
	public boolean checkIfAnyDeclaredGlobalTempTablesForThisConnection();

	/**
	 * Mark the passed temporary table as modified in the current unit of work. That information will be used at rollback time
	 * The compile phase will generate code to call this method if the DML is on a temporary table
	 *
	 * @param tableName Mark the passed temporary table name as modified
	 */
	public void markTempTableAsModifiedInUnitOfWork(String tableName);

	/**
	 * Add the declared global temporary table to the list of temporary tables known by this connection.
	 * @param td Corresponding to the temporary table
	 *
	 */
	public void addDeclaredGlobalTempTable(TableDescriptor td) throws StandardException;

	/**
	 * Drop (mark the declared global temporary table for dropping) from the list of temporary tables known by this connection.
	 * @param tableName look for this table name in the saved list and drop it if found
	 * @return true if dropped the temporary table. False if no such temporary table exists.
	 *
	 * @see org.apache.derby.impl.sql.conn.TempTableInfo
	 */
	public boolean dropDeclaredGlobalTempTable(String tableName);

	/**
	 * Get table descriptor for the declared global temporary table from the list of temporary
	 * tables known by this connection.
	 * @param tableName Get table descriptor for the passed table name
	 * @return TableDescriptor if found the temporary table. Else return null
	 *
	 */
	public TableDescriptor getTableDescriptorForDeclaredGlobalTempTable(String tableName);

	/**
		Reset the connection before it is returned (indirectly) by
		a PooledConnection object. See EmbeddedConnection.
	 */
	public void resetFromPool()
		 throws StandardException;

	/**
		Do a commit, as internally needed by Derby.  E.g.
	 	a commit for sync, or a commit for autocommit.  Skips
		checks that a user isn't doing something bad like issuing
		a commit in a nested xact.

		@param	commitStore	true if we should commit the Store transaction

		@exception StandardException thrown if something goes wrong
	 */
	void internalCommit( boolean commitStore )
		 throws StandardException;

	/**
		Similar to internalCommit() but has logic for an unsynchronized commit

		@param	commitflag	the flags to pass to commitNoSync in the store's
							TransactionController

		@exception StandardException	thrown if something goes wrong
	 */
	void internalCommitNoSync(int commitflag) throws StandardException;

	/**
		Do a commit, as issued directly by a user (e.g. via Connection.commit()
		or the JSQL 'COMMIT' statement.

		@exception StandardException thrown if something goes wrong
	 */
	void userCommit() throws StandardException;

	/**
		Commit a distrubuted transaction.

		@param onePhase if true, allow it to commit without first going thru a
		prepared state.

		@exception StandardException	thrown if something goes wrong
	 */
	void xaCommit(boolean onePhase) throws StandardException;

	/**
		Do a rollback, as internally needed by Derby.  E.g.
	 	a rollback for sync, or a rollback for an internal error.  Skips
		checks that a user isn't doing something bad like issuing
		a rollback in a nested xact.

		@exception StandardException thrown if something goes wrong
	 */
	void internalRollback() throws StandardException;

	/**
		Do a rollback, as issued directly by a user (e.g. via Connection.rollback()
		or the JSQL 'ROLLBACK' statement.

		@exception StandardException thrown if something goes wrong
	 */
	void userRollback() throws StandardException;

	/**
	 * Let the context deal with a rollback to savepoint
	 *
	 * @param	savepointName	Name of the savepoint that needs to be rolled back
	 * @param	refreshStyle	boolean indicating whether or not the controller should close
	 * open conglomerates and scans. Also used to determine if language should close
	 * open activations.
	 * @param	kindOfSavepoint	 A NULL value means it is an internal savepoint (ie not a user defined savepoint)
	 * Non NULL value means it is a user defined savepoint which can be a SQL savepoint or a JDBC savepoint
	 *   A String value for kindOfSavepoint would mean it is SQL savepoint
	 *   A JDBC Savepoint object value for kindOfSavepoint would mean it is JDBC savepoint
	 *
	 * @exception StandardException thrown if something goes wrong
	 */
	void internalRollbackToSavepoint
	( String savepointName, boolean refreshStyle, Object kindOfSavepoint ) throws StandardException;

	/**
	 * Let the context deal with a release of a savepoint
	 *
	 * @param	savepointName	Name of the savepoint that needs to be released
	 * @param	kindOfSavepoint	 A NULL value means it is an internal savepoint (ie not a user defined savepoint)
	 * Non NULL value means it is a user defined savepoint which can be a SQL savepoint or a JDBC savepoint
	 *   A String value for kindOfSavepoint would mean it is SQL savepoint
	 *   A JDBC Savepoint object value for kindOfSavepoint would mean it is JDBC savepoint
	 *
	 * @exception StandardException thrown if something goes wrong
	 */
	void releaseSavePoint ( String savepointName, Object kindOfSavepoint ) throws StandardException;

	/**
		Roll back a distrubuted transaction.

		@exception StandardException	thrown if something goes wrong
	 */
	void xaRollback() throws StandardException;

	/**
	  Sets a savepoint. Causes the Store to set a savepoint.

	  @param	savepointName	name of savepoint
	  @param	kindOfSavepoint	 A NULL value means it is an internal savepoint (ie not a user defined savepoint)
	  Non NULL value means it is a user defined savepoint which can be a SQL savepoint or a JDBC savepoint
	  A String value for kindOfSavepoint would mean it is SQL savepoint
	  A JDBC Savepoint object value for kindOfSavepoint would mean it is JDBC savepoint

		@exception StandardException thrown if something goes wrong
	  */
	void	languageSetSavePoint( String savepointName, Object kindOfSavepoint )  throws StandardException;

	/**
	 * Begin a nested transaction.
	 *
	 * @param readOnly The nested transaction would be read only if param value true
	 *
	 * @exception StandardException on error.
	 * @see TransactionController#startNestedUserTransaction
	 */

	void beginNestedTransaction(boolean readOnly) throws StandardException;

	/**
	 * commit a nested transaction.
	 * We do not provide a abortNestedTransaction.
	 * If a nested xaction is aborted, then this results in the parent xaction
	 * also being aborted. This is not what we need for releasing
	 * compile time locks or autoincrement-- hence we do not provide
	 * abortNestedTransaction.
	 *
	 * @exception StandardException thrown on erro
	 *
	 * @see TransactionController#startNestedUserTransaction
	 */
	void commitNestedTransaction() throws StandardException;

	/**
		Get the transaction controller to use with this language connection
		context at compile time.
	 */
	TransactionController getTransactionCompile();

	/**
		Get the transaction controller to use with this language connection
		context during execute time.
	 */

	TransactionController getTransactionExecute();

	/**
		Get the data dictionary

		@return the data dictionary

	 */
	public DataDictionary getDataDictionary();

	/**
		Get the data value factory to use with this language connection
		context.
	 */
	DataValueFactory getDataValueFactory();

	/**
		Get the language factory to use with this language connection
		context.
	 */
	LanguageFactory getLanguageFactory();

	/**
	 * get the optimizer factory to use with this language connection context.
	 */
	OptimizerFactory getOptimizerFactory();

	/**
		Get the language connection factory to use with this language connection
		context.
	 */
	LanguageConnectionFactory getLanguageConnectionFactory();

    /**
     * Get the Authorization Id of the current user
     *
     * @param a activation
     * @return String the authorization id
     */
    public String getCurrentUserId(Activation a);

    /**
     *  Get the Authorization Id of the session user
     *
     * @return String   the authorization id
     */
    public String getSessionUserId();

	/**
	 * Get the default schema (used at compile-time when no activation
	 * is yet available, cf. the activation argument overload version.
	 *
	 * @return SchemaDescriptor	the default schema
	 */
	public SchemaDescriptor getDefaultSchema();

	/**
	 * Get the default schema (used at execution time).  At execution
	 * time, the current statement context is not always a reliable
	 * place to find the correct SQL session context, viz. when a
	 * dynamic result set referencing CURRENT SCHEMA is accessed after
	 * a called procedure has returned only the activation of the call
	 * is live and still holds the correct session context.
	 * @param a current activation
	 *
	 * @return SchemaDescriptor	the default schema
	 */
	public SchemaDescriptor getDefaultSchema(Activation a);

	/**
	 * Set the default schema (at compile-time, see explanations for
	 * getDefaultSchema overloads).
	 *
	 * @param sd the new default schema.
	 * If null, then the default schema descriptor is used.
	 *
	 * @exception StandardException thrown on failure
	 */
	public void setDefaultSchema(SchemaDescriptor sd)
		throws StandardException;

	/**
	 * Set the default schema (at execution time, see explanations for
	 * getDefaultSchema overloads); This version is used by SET SCHEMA.
	 *
	 * @param a current activation
	 * @param sd the new default schema.
	 * If null, then the default schema descriptor is used.
	 *
	 * @exception StandardException thrown on failure
	 */
	public void setDefaultSchema(Activation a, SchemaDescriptor sd)
		throws StandardException;

	/**
	 * Reset any occurence of schemaName as current default schema in
	 * the SQLSessionContext stack to the initial default,
	 * because schemaName is no longer a valid schema.
	 *
	 * @param activation current activation
	 * @param schemaName the schema name occurences of which is to be reset
	 *
	 * @throws StandardException
	 */
	public void resetSchemaUsages(Activation activation, String schemaName)
		throws StandardException;

	/**
	 *	Get the current schema name (at compile-time, see explanations for
	 * getDefaultSchema overloads).
	 *
	 * @return SchemaDescriptor	the current schema
	 */
	public String getCurrentSchemaName();

	/**
	 * Get the current schema name (at execution time, see explanations for
	 * getDefaultSchema overloads); This version is used by CURRENT SCHEMA.
	 *
	 * @return SchemaDescriptor	the current schema
	 */
	public String getCurrentSchemaName(Activation a);

	/**
	 * Return true if this schema name is the initial default schema for the
	 * current session.
	 * @param schemaName
	 * @return true
	 */
	public boolean isInitialDefaultSchema(String schemaName);

	/**
	 * Get the identity column value most recently generated.
	 *
	 * @return the generated identity column value
	 */
	public Long getIdentityValue();

	/**
	 * Set the field of most recently generated identity column value.
	 *
	 * @param val the generated identity column value
	 */
	public void setIdentityValue(long val);

	/**
	 * Verify that there are no activations with open result sets
	 * on the specified prepared statement.
	 *
	 * @param pStmt		The prepared Statement
	 * @param provider	The object precipitating a possible invalidation
	 * @param action	The action causing the possible invalidation
	 *
	 * @return Nothing.
	 *
	 * @exception StandardException thrown on failure
	 */
	boolean verifyNoOpenResultSets(PreparedStatement pStmt, Provider provider,
									   int action)
			throws StandardException;

	/**
	 * Verify that there are no activations with open held result sets.
	 *
	 * @return boolean  Found no open resultsets.
	 *
	 * @exception StandardException thrown on failure
	 */
	public boolean verifyAllHeldResultSetsAreClosed()
			throws StandardException;

	/**
	 * Push a CompilerContext on the context stack with
	 * the current default schema as the default schema
	 * which we compile against.
	 *
	 * @return the compiler context
	 *
	 * @exception StandardException thrown on failure
	 */
	public	CompilerContext pushCompilerContext();

	/**
	 * Push a CompilerContext on the context stack with
	 * the passed in default schema as the default schema
	 * we compile against.
	 *
	 * @param sd the default schema
	 *
	 * @return the compiler context
	 *
	 * @exception StandardException thrown on failure
	 */
	public	CompilerContext pushCompilerContext(SchemaDescriptor sd);

	/**
	 * Pop a CompilerContext off the context stack.
	 *
	 * @param compilerContext  The compiler context.
	 *
	 * @exception StandardException thrown on failure
	 */
	public void popCompilerContext(CompilerContext compilerContext);

	/**
	 * Push a StatementContext on the context stack.
	 *
	 * @param isAtomic whether a commit/rollback is permitted
	 *	from a nested connection under this statement
	 *
	 * @param stmtText the text of the statement.  Needed for any language
	 * 	statement (currently, for any statement that can cause a trigger
	 * 	to fire).  Please set this unless you are some funky jdbc setXXX
	 *	method or something.
	 *
	 * @param pvs parameter value set, if it has one
	 *
	 * @param rollbackParentContext True if 1) the statement context is
	 * 	NOT a top-level context, AND 2) in the event of a statement-level
	 *	exception, the parent context needs to be rolled back, too.
     *
     * @param timeoutMillis Timeout value for this statement, in milliseconds.
     *  Zero means no timeout.
	 *
	 * @return StatementContext The statement context.
	 *
	 */
	StatementContext pushStatementContext(boolean isAtomic, boolean isForReadOnly, String stmtText,
		ParameterValueSet pvs, boolean rollbackParentContext, long timeoutMillis);

	/**
	 * Pop a StatementContext of the context stack.
	 *
	 * @param statementContext  The statement context.
	 * @param error				The error, if any  (Only relevant for DEBUG)
	 */
	public void popStatementContext(StatementContext statementContext,
									Throwable error);

	/**
	 * Push a new execution statement validator.  An execution statement
	 * validator is an object that validates the current statement to
	 * ensure that it is permitted given the current execution context.
	 * An example of a validator a trigger ExecutionStmtValidator that
	 * doesn't allow ddl on the trigger target table.
	 *

	 * Multiple ExecutionStmtValidators may be active at any given time.
	 * This mirrors the way there can be multiple connection nestings
	 * at a single time.  The validation is performed by calling each
	 * validator's validateStatement() method.  This yields the union
	 * of all validations.
	 *
	 * @param validator the validator to add
	 */
	public void pushExecutionStmtValidator(ExecutionStmtValidator validator);

	/**
	 * Remove the validator.  Does an object identity (validator == validator)
 	 * comparison.  Asserts that the validator is found.
	 *
	 * @param validator the validator to remove
	 *
	 * @exception StandardException on error
	 */
	public void popExecutionStmtValidator(ExecutionStmtValidator validator)
		throws StandardException;

	/**
	 * Validate a statement.  Does so by stepping through all the validators
	 * and executing them.  If a validator throws and exception, then the
	 * checking is stopped and the exception is passed up.
	 *
	 * @param constantAction the constantAction that is about to be executed (and
	 *	should be validated
 	 *
	 * @exception StandardException on validation failure
	 */
	public void validateStmtExecution(ConstantAction constantAction)
		throws StandardException;

	/**
	 * Push a new trigger execution context.
	 *

	 * Multiple TriggerExecutionContexts may be active at any given time.
	 *
	 * @param tec the trigger execution context
	 *
	 * @exception StandardException on trigger recursion error
	 */
	public void pushTriggerExecutionContext(TriggerExecutionContext tec)
		throws StandardException;

	/**
	 * Remove the tec.  Does an object identity (tec == tec)
 	 * comparison.  Asserts that the tec is found.
	 *
	 * @param tec the tec to remove
	 *
	 * @exception StandardException on error
	 */
	public void popTriggerExecutionContext(TriggerExecutionContext tec)
		throws StandardException;

	/**
	 * Get the topmost tec.
	 *
	 * @return the tec
	 */
	public TriggerExecutionContext getTriggerExecutionContext();

	/**
	 * Set the trigger table descriptor.  Used to compile
	 * statements that may special trigger pseudo tables.
	 *
	 * @param td the table that the trigger is
	 * defined upon
	 *
	 */
	public void pushTriggerTable(TableDescriptor td);

	/**
	 * Remove the trigger table descriptor.
	 *
	 * @param td the table to remove from the stack.
	 */
	public void popTriggerTable(TableDescriptor td);

	/**
	 * Get the topmost trigger table descriptor
	 *
	 * @return the table descriptor, or null if we
	 * aren't in the middle of compiling a create
	 * trigger.
	 */
	public TableDescriptor getTriggerTable();

	/**
	 * Increment the DataDictionary bind count.  This is for keeping track
	 * of nested binding, which can happen if SQL statements are bound from
	 * within static initializers.
	 *
	 * @return	The new bind count
	 */
	int incrementBindCount();

	/**
	 * Decrement the DataDictionary bind count.
	 *
	 * @return	The new bind count
	 */
	int decrementBindCount();

	/**
	 * Get the DataDictionary bind count.
	 *
	 * @return	The current bind count.
	 */
	int getBindCount();

	/**
	 * Remember that the DataDictionary is in write mode, so we can take
	 * it out of write mode at the end of the transaction.
	 */
	void setDataDictionaryWriteMode();

	/**
	 * Return true if the data dictionary is in write mode (that is, this
	 * context was informed that is is in write mode by the method call
	 * setDataDictionaryWriteMode().
	 */
	boolean dataDictionaryInWriteMode();

	/**
	 * Turn RUNTIMESTATISTICS  on or off.
	 */
	public void setRunTimeStatisticsMode(boolean onOrOff);

	/**
	 * Get the RUNTIMESTATISTICS mode.
	 */
	public boolean getRunTimeStatisticsMode();

	/**
	 * Turn STATISTICS TIMING on or off.
	 */
	public void setStatisticsTiming(boolean onOrOff);

	/**
	 * Get the STATISTICS TIMING mode.
	 */
	public boolean getStatisticsTiming();

	/**
	 * Set the RUNTIMESTATISTICS object.
	 */
	public void setRunTimeStatisticsObject(RunTimeStatistics runTimeStatisticsObject);

	/**
	 * Get the RUNTIMESTATISTICS object.
	 */
	public RunTimeStatistics getRunTimeStatisticsObject();

    /**
	  *	Reports how many statement levels deep we are.
	  *
	  *	@return	a statement level >= OUTERMOST_STATEMENT
	  */
	public	int		getStatementDepth();

	/**
	  Returns the Database of this connection.
     */
    public Database getDatabase();

	/**
	 * Returns true if isolation level has been set using JDBC/SQL.
	 */
	public boolean isIsolationLevelSetUsingSQLorJDBC();
	/**
	 * Reset the isolation level flag used to keep correct isolation level
	 * state in BrokeredConnection. This resetting will happen at the start
	 * and end of a global transaction, after the BrokeredConection's
	 * isolation level state is brought upto date with the EmbedConnection's
	 * isolation state.
	 * The flag gets set to true when isolation level is set using JDBC/SQL.
	 */
	public void resetIsolationLevelFlagUsedForSQLandJDBC();

	/**
	 * Set current isolation level.
	 *
	 * @param isolationLevel	The new isolationLevel.
	 */
	public void setIsolationLevel(int isolationLevel) throws StandardException;

	/**
	 * Get the current isolation level.
	 *
	 * @return The current isolation level.
	 */
	public int getCurrentIsolationLevel();

	/**
	 * Get the current isolation level in DB2 format.
	 *
	 * @return The current isolation level as a 2 character string.
	 */
	public String getCurrentIsolationLevelStr();
	public void setPrepareIsolationLevel(int isolationLevel) ;

	/**
	 * Get the prepare isolation level.
	 * If the isolation level has been explicitly set with a SQL statement or
	 * embedded call to setTransactionIsolation, this will return
	 * ExecutionContext.UNSPECIFIED_ISOLATION_LEVEL
	 * SET ISOLATION always takes priority.
	 *
	 */
	public int getPrepareIsolationLevel();

	/**
	 * Set the readOnly status for the current connection. This can
	 * only be called when the current transaction has not done
	 * any work.
	 *
	 * @param onOrOff true sets the connection to be readOnly and
	 *                false sets it to readWrite.
	 *
	 * @exception StandardException The call failed and the readOnly
	 *                status has not changed.
	 */
	public void setReadOnly(boolean onOrOff) throws StandardException;

	/**
	  * Get the readOnly status for the current connection.
	  */
	public boolean isReadOnly();

	/**
	 * Get an Authorizer for this connection.
	 */
	public Authorizer getAuthorizer();

	/**
	 *	Get the current StatementContext.
	 */
	StatementContext getStatementContext();

    /**
	 * Return a PreparedStatement object for the query.
	 * This method first tries to locate the PreparedStatement object from a statement
	 * cache.  If the statement is not found in the cache, the query will be compiled and
	 * put into the cache.
	 * @param compilationSchema schema
	 * @param sqlText sql query string
	 * @param isForReadOnly read only status for resultset. Set to true if the concurrency mode for the resultset
	 *                      is CONCUR_READ_ONLY
	 * @param allowInternalSyntax If true, then this query is allowed to use internal
	 *                      sql syntax. One instance where this will be true is if a
	 *                      metadata query is getting executed.
	 */
         public PreparedStatement prepareInternalStatement(SchemaDescriptor compilationSchema,
         		String sqlText, boolean isForReadOnly, boolean allowInternalSyntax)
	    throws StandardException;

        /**
	 * Return a PreparedStatement object for the query.
	 * This method first tries to locate the PreparedStatement object from a statement
	 * cache.  If the statement is not found in the cache, the query will be compiled and
	 * put into the cache.
	 * The schema used when compiling the statement is the same schema as returned by
	 * getDefaultSchema().  For internal statements, the read only status is set to
	 * true.
	 * Calling this method is equivalent to calling
	 * prepareExternalStatement(lcc.getDefaultSchema(), sqlText, true);
	 *
	 * @param sqlText sql query string
	 */
        public PreparedStatement prepareInternalStatement(String sqlText)
	    throws StandardException;

	/**
	 * Control whether or not optimizer trace is on.
	 *
	 * @param onOrOff    Whether to turn optimizer trace on (true) or off (false).
	 *
	 * @return Whether or not the call was successful.  (false will be returned when optimizer tracing is not supported.)
	 */
	public boolean setOptimizerTrace(boolean onOrOff);

	/**
	 * Get whether or not optimizer trace is on.
	 *
	 * @return Whether or not optimizer trace is on.
	 */
	public boolean getOptimizerTrace();

	/**
	 * Control whether or not optimizer trace is generated in html.
	 *
	 * @param onOrOff    Whether or not optimizer trace will be in html (true) or not (false).
	 *
	 * @return Whether or not the call was successful.  (false will be returned when optimizer tracing is not supported.)
	 */
	public boolean setOptimizerTraceHtml(boolean onOrOff);

	/**
	 * Get whether or not optimizer trace html is on.
	 *
	 * @return Whether or not optimizer trace html is on.
	 */
	public boolean getOptimizerTraceHtml();

	/**
	 * Get the optimizer trace output for the last optimized query as a String.  If optimizer trace
	 * html is on, then the String will contain the html tags.
	 *
	 * @return The optimizer trace output for the last optimized query as a String.
	 *    Null will be returned if optimizer trace output is off or not supported
	 *    or no trace output was found or an exception occurred.
	 */
	public String getOptimizerTraceOutput();

	/**
	 * Set the optimizer trace output to the specified String.
	 * (Done at the beginning of each statement.)
	 */
	public void setOptimizerTraceOutput(String startingText);

	/**
	 * Append the latest output to the optimizer trace output.
	 */
	public void appendOptimizerTraceOutput(String output);

    /**
	  *	Reports whether there is any outstanding work in the transaction.
	  *
	  *	@return		true if there is outstanding work in the transaction
	  *				false otherwise
	  */
	public	boolean	isTransactionPristine();

	/**
	 * Returns the last autoincrement value inserted by this connection.
	 * If no values have been inserted into the given column a NULL value
	 * is returned.
	 *
	 * @param schemaName
	 * @param tableName
	 * @param columnName
	 */
	public Long lastAutoincrementValue(String schemaName,
									   String tableName,
									   String columnName);

	/**
	 * Sets autoincrementUpdate-- this variable allows updates to autoincrement
	 * columns if it is set to true. The default is ofcourse false; i.e
	 * ai columns cannot be directly modified by the user. This is set to
	 * true by AlterTableConstantAction, when a new ai column is being added
	 * to an existing table.
	 *
	 * @param flag 	the value for autoincrementUpdate (TRUE or FALSE)
	 * @see org.apache.derby.impl.sql.execute.AlterTableConstantAction#updateNewAutoincrementColumn
	 *
	 */
	public void setAutoincrementUpdate(boolean flag);

	/**
	 * Returns the current value of autoincrementUpdate.
	 *
	 * @return true if updates to autoincrement columns is permitted.
	 */
	public boolean getAutoincrementUpdate();

	/**
	 * Copy a map of autoincrement key value pairs into the cache of
	 * ai values stored in the language connection context.
	 */
	public void copyHashtableToAIHT(Map from);

	/**
	 * returns the next value to be inserted into an autoincrement col.
	 * This is used internally by the system to generate autoincrement values
	 * which are going to be inserted into a autoincrement column. This is
	 * used when as autoincrement column is added to a table by an alter
	 * table statemenet and during bulk insert.
	 *
	 * @param schemaName
	 * @param tableName
	 * @param columnName identify the column uniquely in the system.
	 *
	 * @exception StandardException on error.
	 */
	public long nextAutoincrementValue(String schemaName, String tableName,
									   String columnName)
		throws StandardException;

	/**
	 * Flush the cache of autoincrement values being kept by the lcc.
	 * This will result in the autoincrement values being written to the
	 * SYSCOLUMNS table as well as the mapping used by lastAutoincrementValue
	 *
	 * @param tableUUID the table which is being flushed; we need this value to
	 * identify the table for which the autoincrement counter is being
	 * maintained.
	 *
	 * @exception StandardException thrown on error.
	 *
	 * @see LanguageConnectionContext#lastAutoincrementValue
	 * @see org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext#lastAutoincrementValue
	 * @see org.apache.derby.iapi.db.ConnectionInfo#lastAutoincrementValue
	 */
	public void autoincrementFlushCache(UUID tableUUID)
		throws StandardException;

	/**
	 * Create an autoincrement counter to be used on behalf of a SQL-J
	 * statement. The counter is identified by (schemaName, tableName,
	 * columnName). The counter must be freed up by calling
	 * autoincrementFlushCache at the end of the statement. It is expected
	 * that a ai-counter with the same signaure doesn't exist when the
	 * method is called.
	 *
	 * @param 		s					SchemaName
	 * @param		t					TableName
	 * @param		c					ColumnName
	 * @param		initialValue		initial value of the counter.
	 * @param		increment			increment for the counter.
	 * @param		position			column position (1-based).
	 */
	public void autoincrementCreateCounter(String s, String t, String c,
										   Long initialValue, long increment,
										   int position);

	/**
	 * Get the instance number of this LCC.
	 *
	 * @return instance number of this LCC.
	 */
	public int getInstanceNumber();

	/**
	 * Get the DRDA ID of this LCC.
	 *
	 * @return DRDA ID this LCC.
	 */
	public String getDrdaID();

	/**
	 * Set the DRDA ID of this LCC.
	 *
	 * @param drdaID DRDA ID.
	 */
	public void setDrdaID(String drdaID);

	/**
	 * Get the database name of this LCC.
	 *
	 * @return database name of this LCC.
	 */
	public String getDbname();

	/**
	 * Check if in SQL standard mode, with support for Grant & Revoke
	 *
	 * @return True if SQL standard permissions are being used
	 */
	public boolean usesSqlAuthorization();

	/**
	 * Close any unused activations in this connection context.
	 */
	public void closeUnusedActivations() throws StandardException;

	/**
	 * Set the current role
	 *
	 * @param a activation of set role statement
	 * @param role  the id of the role to be set to current
	 */
    public void setCurrentRole(Activation a, String role);

	/**
	 * Get the current role authorization identifier of the dynamic
	 * call context associated with this activation.
	 *
	 * @param a activation of statement needing current role
	 * @return String	the role id
	 */
	public String getCurrentRoleId(Activation a);

	/**
	 * Get the current role authorization identifier in external delimited form
	 * (not case normal form) of the dynamic call context associated with this
	 * activation.
	 * @param a activation of statement needing current role
	 * @return String the role id in delimited form (i.e. not
	 * internal case normal form)
	 *
	 * @throws StandardException  standard exception policy
	 */
	public String getCurrentRoleIdDelimited(Activation a)
			throws StandardException;

	/**
	 * Checks whether the given role can be legally set for the current user.
	 *
	 * This method will read (potentially) the dictionary, so it needs
	 * a transaction context.
	 *
     * @param a activation
	 * @param role string containing role name
	 *
	 * @return true if the role can be set
	 * @throws StandardException standard exception policy
	 */
    public boolean roleIsSettable(Activation a, String role)
            throws StandardException;

	/**
	 * Create a new SQL session context for the current activation on the basis
	 * of the existing SQL session context. This happens when a stored
	 * procedure or function that can contain SQL is invoked, cf. SQL 2003
	 * section 4.27.3, since this gives rise to a nested connection.
	 *

	 * Called from generated code, see
	 * {@code StaticMethodCallNode#generateSetupNestedSessionContext}.
	 *

	 * The new SQL session context is also set in the current statement
	 * context (of the invocation).
	 *
	 * @see org.apache.derby.impl.sql.compile.StaticMethodCallNode#generateSetupNestedSessionContext
	 * @see StatementContext#getSQLSessionContext
	 * @see #setupSubStatementSessionContext
	 *
	 * @param a activation of the statement which performs the call.
     * @param definersRights if the method should run with definer's rights
     * @param definer authorization id of the definer
	 */
    public void setupNestedSessionContext(Activation a,
                                          boolean definersRights,
                                          String definer)
            throws StandardException;

	/**
	 * Get the value of top level session context of the top level connection.
	 */
	public SQLSessionContext getTopLevelSQLSessionContext();

	/**
	 * Used when a statement as part of its operation executes an other
	 * statement. In contrast to setupNestedSessionContext, the activation (for
	 * the substatement) just inherits the current session context from the
	 * parent statements activation, it does not push a new copy on the
	 * stack of session contexts.
	 *
	 * Currently, this is used in the following situations:
	 *

	 *
With {@code ALTER TABLE} adding a column which has a default
	 *         values, the default value for all the existing rows is added
	 *         using an {@code UPDATE} substatement.
	 *
With {@code ALTER TABLE} adding a a check constraint, we will use
	 *         a substatement {@code SELECT} to check if all rows satisfy the
	 *         constraint.
	 *
{@code ResultSet.insertRow}, {@code updateRow}
	 *         and {@code deleteRow}.
	 *
During trigger body execution.
	 *

	 * @see #setupNestedSessionContext
	 */
    public void setupSubStatementSessionContext(Activation a)
            throws StandardException;

	/**
	 * Create a fresh SQLSessionContext for this connection.
	 * @return new SQLSessionContext
	 */
	public SQLSessionContext createSQLSessionContext();

	/**
     * Debug method for remembering the last query tree.
	 */
    public  void    setLastQueryTree( Object queryTree );

	/**
     * Debug method for retrieving the last query tree.
	 */
    public  Object    getLastQueryTree();

	/**
	 * Return a map of AST nodes that have already been printed during a
	 * compiler phase, so as to be able to avoid printing a node more than once.
	 * @see org.apache.derby.impl.sql.compile.QueryTreeNode#treePrint(int)
	 * @return the map
	 */
    public Map getPrintedObjectsMap();

    /**
     * sets the XplainOnlyMode.
     *
     * If a connection is in XplainOnlyMode, then the statements are not
     * actually being executed, but are just being compiled and the
     * runtime statistics collected into the XPLAIN tables. This can be
     * set on and off by calling SYSCS_SET_XPLAIN_MODE.
     *
     * @param onOrOff true if statements are to be XPLAINed only.
     */
    public void setXplainOnlyMode(boolean onOrOff);

    /**
     * gets the current set XplainOnlyMode
     */
    public boolean getXplainOnlyMode();

    /**
     * sets the XplainSchema
     * @param schema the schema to use for storing XPLAIN'd statements
     * null means don't store the xplain information
     * non-null means persistent style, use the indicated schema
     */
    public void setXplainSchema(String schema);

    /**
     * gets the current set XplainSchema
     * @return the Schema of Xplain, may be null.
     */
    public String getXplainSchema();
    public void setXplainStatement(Object key, Object stmt);
    public Object getXplainStatement(Object key);

    /**
     * Set a Visitor which walks the AST at various stages. This is useful
     * for poking user-written inspectors into the parse, bind, and optimize phases.
     *
     * @param visitor The Visitor which should walk the tree. Could be null.
     */
    public void setASTVisitor( ASTVisitor visitor );

    /**
     * Get the Visitor which should walk the AST.
     *
     * @return The Visitor for that phase. Could be null.
     */
    public ASTVisitor getASTVisitor( );

    /**
     * Set the exception created and associated with the detected interruped
     * status flag.
     *
     * @param e the created exception
     */
    public void setInterruptedException(StandardException e);

    /**
     * Get exception created when we detected interruped status
     * flag.
     *
     * @return saved exception
     */
    public StandardException getInterruptedException();

    /**
     * Get the referenced column map for a table
     *
     * @return the map
     */
    public FormatableBitSet getReferencedColumnMap(TableDescriptor td);

    /**
     * Set the referenced column map for a table
     *
     * @param td the table descriptor
     * @param map the map
     */
    public void setReferencedColumnMap(TableDescriptor td,
                                       FormatableBitSet map);
}


text:
package fv_test

import (
	"testing"

	"github.com/projectcalico/felix/fv/connectivity"

	"github.com/onsi/gomega/format"

	. "github.com/onsi/ginkgo"
	"github.com/onsi/ginkgo/reporters"
	. "github.com/onsi/gomega"

	"github.com/projectcalico/felix/fv/infrastructure"
	"github.com/projectcalico/libcalico-go/lib/testutils"
)

func init() {
	testutils.HookLogrusForGinkgo()

	// Avoid truncating diffs when Equals assertions fail.
	format.TruncatedDiff = false
}

func TestFv(t *testing.T) {
	RegisterFailHandler(Fail)
	junitReporter := reporters.NewJUnitReporter("../report/fv_suite.xml")
	RunSpecsWithDefaultAndCustomReporters(t, "FV Suite", []Reporter{junitReporter})
}

var _ = AfterEach(func() {
	defer connectivity.UnactivatedCheckers.Clear()
	if CurrentGinkgoTestDescription().Failed {
		// If the test has already failed, ignore any connectivity checker leak.
		return
	}
	Expect(connectivity.UnactivatedCheckers.Len()).To(BeZero(),
		"Test bug: ConnectivityChecker was created but not activated.")
})

var _ = AfterSuite(func() {
	if infrastructure.K8sInfra != nil {
		infrastructure.TearDownK8sInfra(infrastructure.K8sInfra)
		infrastructure.K8sInfra = nil
	}
	infrastructure.RemoveTLSCredentials()
})


text:
<?php
//23/02/2013
class Musicians_model extends CI_Model
{
    public function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    /**
     * Insert model.
     *
     * @param string $table
     * @param array  $data
     *
     * @return int $id
     **/
    public function insert($table, $data)
    {
        $this->db->set($data);
        $this->db->insert($table);

        return $this->db->insert_id();
    }
    /**
     * Update Where.
     *
     * @param string $table
     * @param array  $data
     * @param array  $where
     **/
    public function updateWhere($table, $data, $where)
    {
        $this->db->update($table, $data, $where);
    }
    /**
     * Get all Events musicians_bands.
     *
     * @return array $musicians_bands
     **/
    public function getAllEvents()
    {
        $query = $this->db->get('musicians_bands');
        $results = $query->result();

        return $results;
    }
    /**
     * Get Item with where.
     *
     * @param string $table
     * @param array  $where
     *
     * @return array $musicians_bands
     **/
    public function getItemWithWhere($table, $where)
    {
        return $this->db->get_where($table, $where)->result();
    }

    public function deleteWhere($id)
    {
        $this->db->where('musicians_bands_id', $id);
        $this->db->delete('musicians_bands');

        return true;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="newVersion">There is a newer version for you. Please update this APP to get the better service.</string>
 	<string name="lblLine">Choose which traffic line you would like:</string>
	<string name="pleaseChoose"><Please pick one></string>
	<string name="myPersonal"><My prefer list></string>
	<string name="noWhatINeed"><No one I like></string>
	<string name="ratingLine">Traffic Name:</string>
	<string name="ratingStop">Stop Name:</string>
	<string name="lblDestination">Choose where you would like to get off:</string>
	<string name="createNewOne">There is no what you want?</string>
 	<string name="txtNewLine">What is the name of the traffic line you would like now?</string>
	<string name="cancel">CANCEL</string>
 	<string name="next">NEXT</string>
 	<string name="currentLocNotAvailable">No available your location information now</string>
	<string name="btnBeginDetect">BEGIN TO DETECT</string>
	<string name="enterEditingMode">You are entering editing mode that you can remove the stop you established or any one in <My prefer list></string>
	<string name="exitEditingMode">You are quitting from editing mode</string>
	<string name="removeStop">Are you sure you are going to remove this?</string>
	<string name="errorNotRemove">Not removable due to you may not be the owner of this stop.</string>
	<string name="stopRemoved">The stop has been removed.</string>
	<string name="editPersonal">Remove Stop</string>
	<string name="exitEditPersonal">Quit from editing mode</string>
</resources>


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_phalcon.h"
#include "phalcon.h"

#include "kernel/main.h"

/**
 * Phalcon\Cache\BackendInterface initializer
 */
PHALCON_INIT_CLASS(Phalcon_Cache_BackendInterface){

	PHALCON_REGISTER_INTERFACE(Phalcon\\Cache, BackendInterface, cache_backendinterface, phalcon_cache_backendinterface_method_entry);

	return SUCCESS;
}

/**
 * Starts a cache. The $keyname allows to identify the created fragment
 *
 * @param int|string $keyName
 * @param   long $lifetime
 * @return  mixed
 */
PHALCON_DOC_METHOD(Phalcon_Cache_BackendInterface, start);

/**
 * Stops the frontend without store any cached content
 *
 * @param boolean $stopBuffer
 */
PHALCON_DOC_METHOD(Phalcon_Cache_BackendInterface, stop);

/**
 * Returns front-end instance adapter related to the back-end
 *
 * @return mixed
 */
PHALCON_DOC_METHOD(Phalcon_Cache_BackendInterface, getFrontend);

/**
 * Returns the backend options
 *
 * @return array
 */
PHALCON_DOC_METHOD(Phalcon_Cache_BackendInterface, getOptions);

/**
 * Checks whether the last cache is fresh or cached
 *
 * @return boolean
 */
PHALCON_DOC_METHOD(Phalcon_Cache_BackendInterface, isFresh);

/**
 * Checks whether the cache has starting buffering or not
 *
 * @return boolean
 */
PHALCON_DOC_METHOD(Phalcon_Cache_BackendInterface, isStarted);

/**
 * Sets the last key used in the cache
 *
 * @param string $lastKey
 */
PHALCON_DOC_METHOD(Phalcon_Cache_BackendInterface, setLastKey);

/**
 * Gets the last key stored by the cache
 *
 * @return string
 */
PHALCON_DOC_METHOD(Phalcon_Cache_BackendInterface, getLastKey);

/**
 * Returns a cached content
 *
 * @param int|string $keyName
 * @param   long $lifetime
 * @return  mixed
 */
PHALCON_DOC_METHOD(Phalcon_Cache_BackendInterface, get);

/**
 * Stores cached content into the file backend and stops the frontend
 *
 * @param int|string $keyName
 * @param string $content
 * @param long $lifetime
 * @param boolean $stopBuffer
 */
PHALCON_DOC_METHOD(Phalcon_Cache_BackendInterface, save);

/**
 * Deletes a value from the cache by its key
 *
 * @param int|string $keyName
 * @return boolean
 */
PHALCON_DOC_METHOD(Phalcon_Cache_BackendInterface, delete);

/**
 * Query the existing cached keys
 *
 * @param string $prefix
 * @return array
 */
PHALCON_DOC_METHOD(Phalcon_Cache_BackendInterface, queryKeys);

/**
 * Checks if cache exists and it hasn't expired
 *
 * @param  string $keyName
 * @param  long $lifetime
 * @return boolean
 */
PHALCON_DOC_METHOD(Phalcon_Cache_BackendInterface, exists);


text:
/**
 * Created by nlivni on 11/14/2014.
 */

$(function() {

    function update_preview() {
        var title = document.getElementById("id_title").value;
//        var template = document.getElementById("id_template").value;
        var template = CKEDITOR.instances['id_template'].getData();
        var preview = document.getElementById("preview");
        var var_fields = $(".var-field");
        var var_array = [];

        for (i = 0; i < var_fields.length; i++) {
            var_array.push(var_fields[i].value);
        }

        //console.log(var_array);

        for (i=0; i < var_array.length; i++) {
            var v = var_array[i];
            var v_div = "" + v + "";
            template = template.replace(/%s/i, v_div);
        }
        //console.log(template);
        preview.innerHTML = "
" + title + "
" + template;
        console.log("update_preview")
    };
//    @todo id_#template is for textarea not ckeditor. needs to be changed for update to work. seems to work when variables are updated though....
//    $('#id_template').change(update_preview);
    CKEDITOR.instances['id_template'].on('change', update_preview);
    $(document).keyup(update_preview);
    $(document).ready(update_preview);

    var add_var_btn = document.getElementById("add_var_btn");

    function story_harvest() {

        //get an array containing the var_field inputs
        var var_fields = $(".var-field");

        var var_list = "[";
        // add values from var_fields array to a list string
        for (i = 0; i < var_fields.length; i++) {
            if (i) var_list += ",";
            //escape apostrophes to avoid malformed list
            // @todo - currently looks ugly in var_field, fix to make conversation too and from var_field
            if (var_fields[i].value.search("'")) {
                var_fields[i].value = var_fields[i].value.replace("'","&#x27");
            }

            var_list += "'" + var_fields[i].value + "'";
        }
        // test to make sure there's variables, otherwise the extra comma will throw python error
        if (var_list === "[,") {
            var_list = "[]"
        }
        else {
            var_list += "]";
        }
        // update bound variables field
        var variables = $("#id_variables");
        variables.val(var_list);

        // print what you did
        console.log("story_harvest ");
    }

    $(document).ready(story_harvest);
    $(document).on('change','.var-field',story_harvest);

 //-------------------------------new junk (remove variable) ------sb 11/17/14----------------//
    //when user clicks on anything within the div with id = "var_fields" and with a class of "remove_var" it will trigger this function
    $("#var_fields").on("click", ".remove_var", function(event){
     //  get the index number of the variable that has been clicked on.
      var array_index = $(this).attr("data-var");
      //call the function and pass the array_index value needed to take this variable out of the textarea we are using to submit the "array" of variables
      removeFromVarList(array_index);
    //remove the input and any children elements of the input field
$(this).parent().parent().remove();
        //update view
        story_harvest();
        update_preview();
      });
    //this function modifies the list of variables that will be submitted to match the list that exists in the input fields above.  var_to_remove is just text, not an object.
    function removeFromVarList( array_index)
    {
        //get the existing string with #id-variables
 var variables_string = $("#id_variables").val();
        //remove containing brackets
 variables_string=variables_string.replace("['","")
 variables_string=variables_string.replace("']","")
        //split string into an array object
 var variables_array = variables_string.split(/','/);
        //remove the item in the array with the index number passed into this function
variables_array.splice(array_index, 1);
        //loop through array and add single quotes before and after
        for(i=0;i<variables_array.length;i++)
        {
        variables_array[i] = "'"+ variables_array[i] +"'";
        }

        //convert array back to a string
var updated_text = variables_array.toString();
        //put containing brackets back
updated_text = "[" + updated_text + "]";
        //assign value of #id_variables to updated string
        $("#id_variables").val(updated_text);
        //update the preview

    }

  //-------------------------------end new junk----------------------//

    $(add_var_btn).click(function() {

        // define last field
        var last_field = $( "#var_fields .form-group" ).last();

        // get count of fields
        var field_count = $('.var_input').length;

        // insert new field after last field
        $(last_field).after('

<input class="form-control var-field" id="var-field-'+ field_count + '" type="text" value=""><button data-var="'+ field_count + '" class ="remove_var btn btn-default" ></button>

');

        // get new field count
        var field_count = $('.var_input').length;

        // print field count (for validation)
        console.log("field count: " + field_count);
        //$(".var-field").trigger("keyup");

    });

    //story_harvest();
    //console.log("harvest called");

//    @todo: thought about escaping on submit rather than before. see below:
//    function escape_submit() {
//        submit_val =  $('#submit-id-submit').val();
//        $('#id_template').val(htmlEscape($('#id_template').value))
//        $('#id_variables').val(htmlEscape($('#id_variables').value))
//
//    }

    $('#submit-id-submit').click( {

    }
    )

});


text:
<?xml version="1.0" encoding="UTF-8" ?>

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>

      <title>marcin-chwedczuk.github.io/</title>

   <link>http://blog.marcinchwedczuk.pl</link>
   <description>A place where I share my thoughts about programming.</description>
   <language>en-uk</language>
   <managingEditor>mc</managingEditor>
   <atom:link href="rss" rel="self" type="application/rss+xml" />

	<item>
	  <title>Continuations in Java</title>
	  <link>http://blog.marcinchwedczuk.pl/continuations-in-java</link>
	  <author>mc</author>
	  <pubDate>2020-06-27T02:00:01+02:00</pubDate>
	  <guid>http://blog.marcinchwedczuk.pl/continuations-in-java</guid>

		<description>
CSP or Continuation-Passing Style is a style of programming in which
functions return results via callbacks.
For example + operator is a function that takes two numbers and
returns their sum. In CSP + operator becomes a function that takes
three arguments, two terms and a callback, usually called a continuation in
the context of CSP.
In Java we can express this as:

</description>

	</item>

</channel>
</rss>