text:
const float PI_2 = 1.570796325f;

#define ARRAY_COUNT( array ) (sizeof( array ) / (sizeof( array[0] ) * (sizeof( array ) != sizeof(void*) || sizeof( array[0] ) <= sizeof(void*))))

namespace glutil
{
	ObjectPole::ObjectPole( const ObjectData &initialData, float rotateScale,
		MouseButtons actionButton, const ViewProvider *pLookatProvider )
		: m_pView(pLookatProvider)
		, m_po(initialData)
		, m_initialPo(initialData)
		, m_rotateScale(rotateScale)
		, m_actionButton(actionButton)
		, m_bIsDragging(false)
	{}

	glm::mat4 ObjectPole::CalcMatrix() const
	{
		glm::mat4 translateMat(1.0f);
		translateMat[3] = glm::vec4(m_po.position, 1.0f);

		return translateMat * glm::mat4_cast(m_po.orientation);
	}

	void ObjectPole::SetRotationScale( float rotateScale )
	{
		m_rotateScale = rotateScale;
	}

	void ObjectPole::Reset()
	{
		if(!m_bIsDragging)
			m_po = m_initialPo;
	}

	namespace
	{
		///ObjectPole::NUM_AXES
		glm::vec3 g_axisVectors[] =
		{
			glm::vec3(1.0, 0.0, 0.0),
			glm::vec3(0.0, 1.0, 0.0),
			glm::vec3(0.0, 0.0, 1.0),
		};

		glm::fquat CalcRotationQuat(int eAxis, float degAngle)
		{
			return glm::angleAxis(degAngle, g_axisVectors[eAxis]);
		}
	}

	void ObjectPole::RotateWorldDegrees( const glm::fquat &rot, bool bFromInitial )
	{
		if(!m_bIsDragging)
			bFromInitial = false;

		m_po.orientation = glm::normalize(rot * (bFromInitial ? m_startDragOrient : m_po.orientation));
	}

	void ObjectPole::RotateLocalDegrees( const glm::fquat &rot, bool bFromInitial )
	{
		if(!m_bIsDragging)
			bFromInitial = false;

		m_po.orientation = glm::normalize((bFromInitial ? m_startDragOrient : m_po.orientation) * rot);
	}

	void ObjectPole::RotateViewDegrees( const glm::fquat &rot, bool bFromInitial )
	{
		if(!m_bIsDragging)
			bFromInitial = false;

		if(m_pView)
		{
			glm::fquat viewQuat = glm::quat_cast(m_pView->CalcMatrix());
			glm::fquat invViewQuat = glm::conjugate(viewQuat);
			m_po.orientation = glm::normalize((invViewQuat * rot * viewQuat) *
				(bFromInitial ? m_startDragOrient : m_po.orientation));
		}
		else
			RotateWorldDegrees(rot, bFromInitial);
	}

	void ObjectPole::MouseMove( const glm::ivec2 &position )
	{
		if(m_bIsDragging)
		{
			glm::ivec2 iDiff = position - m_prevMousePos;

			switch(m_RotateMode)
			{
			case RM_DUAL_AXIS:
				{
					glm::fquat rot = CalcRotationQuat(AXIS_Y, iDiff.x * m_rotateScale);
					rot = glm::normalize(
						CalcRotationQuat(AXIS_X, iDiff.y * m_rotateScale) * rot);
					RotateViewDegrees(rot);
				}
				break;
			case RM_BIAXIAL:
				{
					glm::ivec2 iInitDiff = position - m_startDragMousePos;

					Axis eAxis;
					float degAngle;
					if(abs(iInitDiff.x) > abs(iInitDiff.y))
					{
						eAxis = AXIS_Y;
						degAngle = iInitDiff.x * m_rotateScale;
					}
					else
					{
						eAxis = AXIS_X;
						degAngle = iInitDiff.y * m_rotateScale;
					}

					glm::fquat rot = CalcRotationQuat(eAxis, degAngle);
					RotateViewDegrees(rot, true);
				}
				break;
			case RM_SPIN:
				RotateViewDegrees(CalcRotationQuat(AXIS_Z, -iDiff.x * m_rotateScale));
				break;
			}

			m_prevMousePos = position;
		}
	}

	void ObjectPole::MouseClick( MouseButtons button, bool isPressed,
		int modifiers, const glm::ivec2 &position )
	{
		if(isPressed)
		{
			//Ignore button presses when dragging.
			if(!m_bIsDragging)
			{
				if(button == m_actionButton)
				{
					if(modifiers & MM_KEY_ALT)
						m_RotateMode = RM_SPIN;
					else if(modifiers & MM_KEY_CTRL)
						m_RotateMode = RM_BIAXIAL;
					else
						m_RotateMode = RM_DUAL_AXIS;

					m_prevMousePos = position;
					m_startDragMousePos = position;
					m_startDragOrient = m_po.orientation;

					m_bIsDragging = true;
				}
			}
		}
		else
		{
			//Ignore up buttons if not dragging.
			if(m_bIsDragging)
			{
				if(button == m_actionButton)
				{
					MouseMove(position);

					m_bIsDragging = false;
				}
			}
		}
	}

	void ObjectPole::MouseWheel( int direction, int modifiers, const glm::ivec2 &position )
	{

	}

	void ObjectPole::CharPress( char key )
	{

	}

	ViewPole::ViewPole( const ViewData &initialView, const ViewScale &viewScale,
		MouseButtons actionButton, bool bRightKeyboardCtrls )
		: m_currView(initialView)
		, m_viewScale(viewScale)
		, m_initialView(initialView)
		, m_actionButton(actionButton)
		, m_bRightKeyboardCtrls(bRightKeyboardCtrls)
		, m_bIsDragging(false)
	{}

	glm::mat4 ViewPole::CalcMatrix() const
	{
		glm::mat4 theMat(1.0f);

		//Remember: these transforms are in reverse order.

		//In this space, we are facing in the correct direction. Which means that the camera point
		//is directly behind us by the radius number of units.
		theMat = glm::translate(theMat, glm::vec3(0.0f, 0.0f, -m_currView.radius));

		//Rotate the world to look in the right direction..
		glm::fquat fullRotation = glm::angleAxis(m_currView.degSpinRotation, glm::vec3(0.0f, 0.0f, 1.0f)) *
			m_currView.orient;
		theMat = theMat * glm::mat4_cast(fullRotation);

		//Translate the world by the negation of the lookat point, placing the origin at the
		//lookat point.
		theMat = glm::translate(theMat, -m_currView.targetPos);

		return theMat;
	}

	void ViewPole::Reset()
	{
		if(!m_bIsDragging)
			m_currView = m_initialView;
	}

	void ViewPole::SetRotationScale( float rotateScale )
	{
		m_viewScale.rotationScale = rotateScale;
	}

	void ViewPole::ProcessXChange( int iXDiff, bool bClearY )
	{
		float degAngleDiff = (iXDiff * m_viewScale.rotationScale);

		//Rotate about the world-space Y axis.
		m_currView.orient = m_startDragOrient * glm::angleAxis(degAngleDiff, glm::vec3(0.0f, 1.0f, 0.0f));
	}

	void ViewPole::ProcessYChange( int iYDiff, bool bClearXZ )
	{
		float degAngleDiff = (iYDiff * m_viewScale.rotationScale);

		//Rotate about the local-space X axis.
		m_currView.orient = glm::angleAxis(degAngleDiff, glm::vec3(1.0f, 0.0f, 0.0f)) * m_startDragOrient;
	}

	void ViewPole::ProcessXYChange( int iXDiff, int iYDiff )
	{
		float degXAngleDiff = (iXDiff * m_viewScale.rotationScale);
		float degYAngleDiff = (iYDiff * m_viewScale.rotationScale);

		//Rotate about the world-space Y axis.
		m_currView.orient = m_startDragOrient * glm::angleAxis(degXAngleDiff, glm::vec3(0.0f, 1.0f, 0.0f));
		//Rotate about the local-space X axis.
		m_currView.orient = glm::angleAxis(degYAngleDiff, glm::vec3(1.0f, 0.0f, 0.0f)) * m_currView.orient;
	}

	void ViewPole::ProcessSpinAxis( int iXDiff, int iYDiff )
	{
		float degSpinDiff = (iXDiff * m_viewScale.rotationScale);
		m_currView.degSpinRotation = degSpinDiff + m_degStarDragSpin;
	}

	void ViewPole::BeginDragRotate( const glm::ivec2 &ptStart, RotateMode rotMode )
	{
		m_RotateMode = rotMode;

		m_startDragMouseLoc = ptStart;

		m_degStarDragSpin = m_currView.degSpinRotation;

		m_startDragOrient = m_currView.orient;

		m_bIsDragging = true;
	}

	void ViewPole::OnDragRotate( const glm::ivec2 &ptCurr )
	{
		glm::ivec2 iDiff = ptCurr - m_startDragMouseLoc;

		switch(m_RotateMode)
		{
		case RM_DUAL_AXIS_ROTATE:
			ProcessXYChange(iDiff.x, iDiff.y);
			break;
		case RM_BIAXIAL_ROTATE:
			if(abs(iDiff.x) > abs(iDiff.y))
				ProcessXChange(iDiff.x, true);
			else
				ProcessYChange(iDiff.y, true);
			break;
		case RM_XZ_AXIS_ROTATE:
			ProcessXChange(iDiff.x);
			break;
		case RM_Y_AXIS_ROTATE:
			ProcessYChange(iDiff.y);
			break;
		case RM_SPIN_VIEW_AXIS:
			ProcessSpinAxis(iDiff.x, iDiff.y);
		default:
			break;
		}
	}

	void ViewPole::EndDragRotate( const glm::ivec2 &ptEnd, bool bKeepResults )
	{
		if(bKeepResults)
		{
			OnDragRotate(ptEnd);
		}
		else
		{
			m_currView.orient = m_startDragOrient;
		}

		m_bIsDragging = false;
	}

	void ViewPole::MoveCloser( bool bLargeStep )
	{
		if(bLargeStep)
			m_currView.radius -= m_viewScale.largeRadiusDelta;
		else
			m_currView.radius -= m_viewScale.smallRadiusDelta;

		if(m_currView.radius < m_viewScale.minRadius)
			m_currView.radius = m_viewScale.minRadius;
	}

	void ViewPole::MoveAway( bool bLargeStep )
	{
		if(bLargeStep)
			m_currView.radius += m_viewScale.largeRadiusDelta;
		else
			m_currView.radius += m_viewScale.smallRadiusDelta;

		if(m_currView.radius > m_viewScale.maxRadius)
			m_currView.radius = m_viewScale.maxRadius;
	}

	void ViewPole::MouseMove( const glm::ivec2 &position )
	{
		if(m_bIsDragging)
			OnDragRotate(position);
	}

	void ViewPole::MouseClick( MouseButtons button, bool isPressed, int modifiers,
		const glm::ivec2 &position )
	{
		if(isPressed)
		{
			//Ignore all other button presses when dragging.
			if(!m_bIsDragging)
			{
				if(button == m_actionButton)
				{
					if(modifiers & MM_KEY_CTRL)
						this->BeginDragRotate(position, ViewPole::RM_BIAXIAL_ROTATE);
					else if(modifiers & MM_KEY_ALT)
						this->BeginDragRotate(position, ViewPole::RM_SPIN_VIEW_AXIS);
					else
						this->BeginDragRotate(position, ViewPole::RM_DUAL_AXIS_ROTATE);
				}
			}
		}
		else
		{
			//Ignore all other button releases when not dragging
			if(m_bIsDragging)
			{
				if(button == m_actionButton)
				{
					if(m_RotateMode == ViewPole::RM_DUAL_AXIS_ROTATE ||
						m_RotateMode == ViewPole::RM_SPIN_VIEW_AXIS ||
						m_RotateMode == ViewPole::RM_BIAXIAL_ROTATE)
						this->EndDragRotate(position);
				}
			}
		}
	}

	void ViewPole::MouseWheel( int direction, int modifiers,
		const glm::ivec2 &position )
	{
		if(direction > 0)
			this->MoveCloser(!(modifiers & MM_KEY_SHIFT));
		else
			this->MoveAway(!(modifiers & MM_KEY_SHIFT));

	}

	void ViewPole::CharPress( char key )
	{
		if(m_bRightKeyboardCtrls)
		{
			switch(key)
			{
			case 'i': OffsetTargetPos(ViewPole::DIR_FORWARD, m_viewScale.largePosOffset); break;
			case 'k': OffsetTargetPos(ViewPole::DIR_BACKWARD, m_viewScale.largePosOffset); break;
			case 'l': OffsetTargetPos(ViewPole::DIR_RIGHT, m_viewScale.largePosOffset); break;
			case 'j': OffsetTargetPos(ViewPole::DIR_LEFT, m_viewScale.largePosOffset); break;
			case 'o': OffsetTargetPos(ViewPole::DIR_UP, m_viewScale.largePosOffset); break;
			case 'u': OffsetTargetPos(ViewPole::DIR_DOWN, m_viewScale.largePosOffset); break;

			case 'I': OffsetTargetPos(ViewPole::DIR_FORWARD, m_viewScale.smallPosOffset); break;
			case 'K': OffsetTargetPos(ViewPole::DIR_BACKWARD, m_viewScale.smallPosOffset); break;
			case 'L': OffsetTargetPos(ViewPole::DIR_RIGHT, m_viewScale.smallPosOffset); break;
			case 'J': OffsetTargetPos(ViewPole::DIR_LEFT, m_viewScale.smallPosOffset); break;
			case 'O': OffsetTargetPos(ViewPole::DIR_UP, m_viewScale.smallPosOffset); break;
			case 'U': OffsetTargetPos(ViewPole::DIR_DOWN, m_viewScale.smallPosOffset); break;
			}
		}
		else
		{
			switch(key)
			{
			case 'w': OffsetTargetPos(ViewPole::DIR_FORWARD, m_viewScale.largePosOffset); break;
			case 's': OffsetTargetPos(ViewPole::DIR_BACKWARD, m_viewScale.largePosOffset); break;
			case 'd': OffsetTargetPos(ViewPole::DIR_RIGHT, m_viewScale.largePosOffset); break;
			case 'a': OffsetTargetPos(ViewPole::DIR_LEFT, m_viewScale.largePosOffset); break;
			case 'e': OffsetTargetPos(ViewPole::DIR_UP, m_viewScale.largePosOffset); break;
			case 'q': OffsetTargetPos(ViewPole::DIR_DOWN, m_viewScale.largePosOffset); break;

			case 'W': OffsetTargetPos(ViewPole::DIR_FORWARD, m_viewScale.smallPosOffset); break;
			case 'S': OffsetTargetPos(ViewPole::DIR_BACKWARD, m_viewScale.smallPosOffset); break;
			case 'D': OffsetTargetPos(ViewPole::DIR_RIGHT, m_viewScale.smallPosOffset); break;
			case 'A': OffsetTargetPos(ViewPole::DIR_LEFT, m_viewScale.smallPosOffset); break;
			case 'E': OffsetTargetPos(ViewPole::DIR_UP, m_viewScale.smallPosOffset); break;
			case 'Q': OffsetTargetPos(ViewPole::DIR_DOWN, m_viewScale.smallPosOffset); break;
			}
		}

	}

	namespace
	{
		glm::vec3 g_offsets[] =
		{
			glm::vec3( 0.0f,  1.0f,  0.0f),
			glm::vec3( 0.0f, -1.0f,  0.0f),
			glm::vec3( 0.0f,  0.0f, -1.0f),
			glm::vec3( 0.0f,  0.0f,  1.0f),
			glm::vec3( 1.0f,  0.0f,  0.0f),
			glm::vec3(-1.0f,  0.0f,  0.0f),
		};
	}

	void ViewPole::OffsetTargetPos( TargetOffsetDir eDir, float worldDistance )
	{
		glm::vec3 offsetDir = g_offsets[eDir];
		OffsetTargetPos(offsetDir * worldDistance);
	}

	void ViewPole::OffsetTargetPos( const glm::vec3 &cameraOffset )
	{
		glm::mat4 currMat = CalcMatrix();
		glm::fquat orientation = glm::quat_cast(currMat);

		glm::fquat invOrient = glm::conjugate(orientation);
		glm::vec3 worldOffset = invOrient * cameraOffset;

		m_currView.targetPos += worldOffset;
	}
}


text:
{{{<header.html}}}

Summary

{{{SCRIPTS widgets/burndownChart.js burndown.js }}}

{{{<footer.html}}}

redpajama_set_name: RedPajamaGithub


text:
using Nethereum.JsonRpc.Client;
using Nethereum.RPC.Eth.DTOs;
using Nethereum.RPC.Eth.Transactions;

namespace Nethereum.Contracts.QueryHandlers
{
#if !DOTNET35

    public class QueryToSimpleTypeHandler<TFunctionMessage, TFunctionOutput> :
        QueryDecoderBaseHandler<TFunctionMessage, TFunctionOutput> where TFunctionMessage : FunctionMessage, new()
    {

        public QueryToSimpleTypeHandler(IClient client, string defaultAddressFrom = null, BlockParameter defaultBlockParameter = null):base(client, defaultAddressFrom, defaultBlockParameter)
        {
            QueryRawHandler = new QueryRawHandler<TFunctionMessage>(client, defaultAddressFrom, defaultBlockParameter);
        }

        public QueryToSimpleTypeHandler(IEthCall ethCall, string defaultAddressFrom = null, BlockParameter defaultBlockParameter = null) : base(ethCall, defaultAddressFrom, defaultBlockParameter)
        {
            QueryRawHandler = new QueryRawHandler<TFunctionMessage>(ethCall, defaultAddressFrom, defaultBlockParameter);
        }

        protected override TFunctionOutput DecodeOutput(string output)
        {
            return QueryRawHandler.FunctionMessageEncodingService.DecodeSimpleTypeOutput<TFunctionOutput>(output);
        }
    }
#endif
}


text:
package org.guzz.dialect;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.guzz.exception.DataTypeException;
import org.guzz.orm.type.BigDecimalSQLDataType;
import org.guzz.orm.type.BigIntObjectSQLDataType;
import org.guzz.orm.type.BigIntSQLDataType;
import org.guzz.orm.type.BlobSQLDataType;
import org.guzz.orm.type.BooleanObjectSQLDataType;
import org.guzz.orm.type.BooleanSQLDataType;
import org.guzz.orm.type.ByteSQLDataType;
import org.guzz.orm.type.BytesSQLDataType;
import org.guzz.orm.type.CalendarSQLDataType;
import org.guzz.orm.type.ClobSQLDataType;
import org.guzz.orm.type.DateSQLDataType;
import org.guzz.orm.type.DateTimeSQLDataType;
import org.guzz.orm.type.DialectAware;
import org.guzz.orm.type.DoubleObjectSQLDataType;
import org.guzz.orm.type.DoubleSQLDataType;
import org.guzz.orm.type.EnumOrdinalSQLDataType;
import org.guzz.orm.type.EnumStringSQLDataType;
import org.guzz.orm.type.FloatObjectSQLDataType;
import org.guzz.orm.type.FloatSQLDataType;
import org.guzz.orm.type.IntegerObjectSQLDataType;
import org.guzz.orm.type.IntegerSQLDataType;
import org.guzz.orm.type.JavaUtilDateSQLDataType;
import org.guzz.orm.type.ParameteredType;
import org.guzz.orm.type.SQLDataType;
import org.guzz.orm.type.ShortObjectSQLDataType;
import org.guzz.orm.type.ShortSQLDataType;
import org.guzz.orm.type.StringSQLDataType;
import org.guzz.orm.type.TimeSQLDataType;

/**
 *
 *
 *
 * @author liukaixuan(liukaixuan@gmail.com)
 */
public abstract class AbstractDialect implements Dialect {
	protected transient final Log log = LogFactory.getLog(getClass()) ;

	protected final Map sqlTypes = new HashMap() ;

	public AbstractDialect(){
		regSystemTypes() ;
	}

	protected void regSystemTypes(){
		sqlTypes.put("int", IntegerSQLDataType.class) ;
		sqlTypes.put("Integer", IntegerObjectSQLDataType.class) ;
		sqlTypes.put(Integer.class.getName(), IntegerObjectSQLDataType.class) ;

		sqlTypes.put("string", StringSQLDataType.class) ;
		sqlTypes.put("varchar", StringSQLDataType.class) ;
		sqlTypes.put("nvarchar", StringSQLDataType.class) ;
		sqlTypes.put("char", StringSQLDataType.class) ;
		sqlTypes.put("nchar", StringSQLDataType.class) ;
		sqlTypes.put("text", StringSQLDataType.class) ;
		sqlTypes.put("tinytext", StringSQLDataType.class) ;
		sqlTypes.put(String.class.getName(), StringSQLDataType.class) ;

		//java.sql.Timestamp
		sqlTypes.put("datetime", DateTimeSQLDataType.class) ;
		sqlTypes.put("timestamp", DateTimeSQLDataType.class) ;
		sqlTypes.put(java.util.Date.class.getName(), JavaUtilDateSQLDataType.class) ;
		sqlTypes.put(java.sql.Timestamp.class.getName(), DateTimeSQLDataType.class) ;

		//java.sql.Date
		sqlTypes.put("date", DateSQLDataType.class) ;
		sqlTypes.put(java.sql.Date.class.getName(), DateSQLDataType.class) ;

		//java.util.Calendar
		sqlTypes.put(java.util.Calendar.class.getName(), CalendarSQLDataType.class) ;

		//java.sql.Time
		sqlTypes.put("time", TimeSQLDataType.class) ;
		sqlTypes.put(java.sql.Time.class.getName(), TimeSQLDataType.class) ;

		//boolean
		sqlTypes.put("bool", BooleanSQLDataType.class) ;
		sqlTypes.put("boolean", BooleanSQLDataType.class) ;
		sqlTypes.put(Boolean.class.getName(), BooleanObjectSQLDataType.class) ;

		sqlTypes.put("bigint", BigIntSQLDataType.class) ;
		sqlTypes.put("long", BigIntSQLDataType.class) ;
		sqlTypes.put(Long.class.getName(), BigIntObjectSQLDataType.class) ;

		sqlTypes.put("double", DoubleSQLDataType.class) ;
		sqlTypes.put(Double.class.getName(), DoubleObjectSQLDataType.class) ;

		sqlTypes.put("money", BigDecimalSQLDataType.class) ;
		sqlTypes.put("decimal", BigDecimalSQLDataType.class) ;
		sqlTypes.put(BigDecimal.class.getName(), BigDecimalSQLDataType.class) ;

		sqlTypes.put("float", FloatSQLDataType.class) ;
		sqlTypes.put(Float.class.getName(), FloatObjectSQLDataType.class) ;

		sqlTypes.put("short", ShortSQLDataType.class) ;
		sqlTypes.put("smallint", ShortSQLDataType.class) ;
		sqlTypes.put("tinyint", ShortSQLDataType.class) ;
		sqlTypes.put(Short.class.getName(), ShortObjectSQLDataType.class) ;

		//bit
		sqlTypes.put("byte", ByteSQLDataType.class) ;
		sqlTypes.put("bit", ByteSQLDataType.class) ;
		sqlTypes.put(java.lang.Byte.class.getName(), ByteSQLDataType.class) ;

		//byte[]
		sqlTypes.put("bytes", BytesSQLDataType.class) ;
		sqlTypes.put("[B", BytesSQLDataType.class) ;//byte[]
		sqlTypes.put("[Ljava.lang.Byte;", BytesSQLDataType.class) ;//Byte[]
		sqlTypes.put("binary", BytesSQLDataType.class) ;
		sqlTypes.put("varbinary", BytesSQLDataType.class) ;

		//clob
		sqlTypes.put("clob", ClobSQLDataType.class) ;
		sqlTypes.put(java.sql.Clob.class.getName(), ClobSQLDataType.class) ;
		sqlTypes.put(org.guzz.pojo.lob.TranClob.class.getName(), ClobSQLDataType.class) ;

		//blob
		sqlTypes.put("blob", BlobSQLDataType.class) ;
		sqlTypes.put(java.sql.Blob.class.getName(), BlobSQLDataType.class) ;
		sqlTypes.put(org.guzz.pojo.lob.TranBlob.class.getName(), BlobSQLDataType.class) ;

		//enum
		sqlTypes.put("enum.ordinal", EnumOrdinalSQLDataType.class) ;
		sqlTypes.put("enum.string", EnumStringSQLDataType.class) ;

	}

	public void registerUserDefinedTypes(String typeName, Class dataType){
		sqlTypes.put(typeName, dataType) ;
	}

	/**
	 * @param colType 字段类型,如varchar, bigint, int, org.guzz.xxx.POJO
	 * @return 用于处理@param数据类型的处理类,如果不支持抛出异常@link DataTypeException。
	 */
	public SQLDataType getDataType(String colType){
		String param = null ;
		int pos = colType.indexOf('|') ;

		if(pos != -1){
			param = colType.substring(pos + 1) ;
			colType = colType.substring(0, pos) ;
		}

		if(colType.indexOf('(') > 0){ //handle varchar(255), number(10, 4)...
			colType = colType.substring(0, colType.indexOf('(')) ;
		}

		Class type = (Class) sqlTypes.get(colType) ;

		if(type == null){
			Iterator i = this.sqlTypes.entrySet().iterator() ;
			while(i.hasNext()){
				Map.Entry e = (Entry) i.next() ;
				if(colType.equalsIgnoreCase((String) e.getKey())){
					type = (Class) e.getValue() ;
				}
			}
		}

		if(type != null){
			SQLDataType typeInstance ;
			try {
				typeInstance = (SQLDataType) type.newInstance() ;
			} catch (InstantiationException e) {
				throw new DataTypeException("unable to instance type class[" + type.getName() + "] for type:[" + colType + "].") ;
			} catch (IllegalAccessException e) {
				throw new DataTypeException("unable to instance type class[" + type.getName() + "] for type:[" + colType + "].") ;
			}

			if(typeInstance instanceof DialectAware){
				((DialectAware) typeInstance).setDialect(this) ;
			}

			if(typeInstance instanceof ParameteredType){
				((ParameteredType) typeInstance).setParameter(param) ;
			}else if(param != null){
				log.warn("data type class[" + type.getName() + "] for type:[" + colType + "] doesn't support parameterization. parameter:[" + param + "] is ignored.") ;
			}

			return typeInstance ;
		}else{
			throw new DataTypeException("column type[" + colType + "] is not supported.") ;
		}
	}

	public String getForUpdateNoWaitString(String sql) {
		return getForUpdateString(sql) ;
	}

	public String getForUpdateString(String sql) {
		return sql + " for update" ;
	}

	public boolean useStreamToInsertLob(){
		return true ;
	}

}


text:
package org.typemeta.funcj.parser.enumexpr;

import org.junit.*;

public class GrammarTest {

    static  {
        Grammar.parser.acceptsEmpty();
        Grammar.parser.firstSet();
    }

    private static void assertSuccess(Token[] tokens, String expected) {
        final String result = Grammar.parse(tokens).getOrThrow().toString();
        Assert.assertEquals(expected, result);
        //System.out.println(result);
        //Assert.assertEquals(expected, Grammar.parse(result).getOrThrow().toString());
    }

    private static void assertFailure(Token[] tokens, Object position) {
        Grammar.parse(tokens).handle(
            ok -> {
                throw new RuntimeException("Expected parse to fail");
            },
            error -> {
                Assert.assertEquals("", error.input().position(), position);
            }
        );
    }

    @Test
    public void testSuccess() {
        assertSuccess(
                new Token[]{
                        Token.number(123.456),
                        Token.MULT,
                        Token.number(4),
                        Token.PLUS,
                        Token.OPEN,
                        Token.number(5),
                        Token.PLUS,
                        Token.variable('x'),
                        Token.CLOSE,
                        Token.MINUS,
                        Token.number(1)
                },
            "(((123.456*4.0)+(5.0+x))-1.0)");
    }

    @Test
    public void testFailure() {
        assertFailure(
                new Token[]{
                        Token.number(3),
                        Token.MULT,
                        Token.number(4),
                        Token.PLUS,
                        Token.OPEN,
                        Token.number(5),
                        Token.PLUS,
                        Token.CLOSE,
                        Token.MINUS,
                        Token.number(1)
                },
                7
        );
    }
}


text: default_app_config = "eventkit_cloud.user_requests.apps.EventKitUserRequests"


text:
require 'spec_helper'
require 'ostruct'
require_relative '../../../../apps/web/views/books/new'

describe Web::Views::Books::New do
  let(:params)    { OpenStruct.new(valid?: false, error_messages: ['Isbn must be filled', 'Title must be filled', 'Price must be filled']) }
  let(:exposures) { Hash[params: params] }
  let(:template)  { Hanami::View::Template.new('apps/web/templates/books/new.html.erb') }
  let(:view)      { Web::Views::Books::New.new(template, exposures) }
  let(:rendered)  { view.render }

  it 'displays a list of errors when params contains errors' do
    rendered.must_include('Your form submisson has some problems')
    rendered.must_include('Isbn must be filled')
    rendered.must_include('Title must be filled')
    rendered.must_include('Price must be filled')
  end
end


text:
/** what the heck **/
/**

Here is a block comment

**/
/*hello*/
div {
  /* another property */
  border: 1px solid red;
  color: url('http://mage-page.com');
  string: "hello /* this is not a comment */";
  world: "// neither is this";
  /*what if this is a comment */
  string: 'hello /* this is not a comment */';
  world: '// neither is this';
  what-ever: 100px;
  /*this is not a comment?*/
  background: url(); }


text:
$packageId		= '{{PackageName}}'
$packageName	= 'X2Go Client'
$installerType	= 'EXE'
$url			= '{{DownloadUrl}}'
$silentArgs		= '/S'

Install-ChocolateyPackage "$packageName" "$installerType" "$silentArgs" "$url"


text:
using namespace std;

// Value

JsonValue * JsonValue::fromString(string message) {
    int i = 0;
    return JsonValue::fromString(message, i);
}

JsonValue * JsonValue::fromString(string message, int & i) {
    while (i < message.length()) {
        i += skip_whitespace(message, i);
        switch (message[i]) {
            case '{':
                return JsonDict::fromString(message, i);
                break;
            case '[':
                return JsonList::fromString(message, i);
                break;
            case '"':
                return JsonString::fromString(message, i);
                break;
            case 't':
            case 'f':
                return JsonBool::fromString(message, i);
            case 'n':
                return JsonNull::fromString(message, i);
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                return JsonInt::fromString(message, i);
                break;
            default:
                throw PARSE_ERROR("unknwown value. Got '" + string(1, message[i]) + "'", i);
        }
    }
    throw PARSE_ERROR("no value found", i);
}

// String

JsonString::JsonString(string val) {
    replace_all(val, "\\\\", '\\');
    replace_all(val, "\\\"", '"');
    replace_all(val, "\\t", '\t');
    replace_all(val, "\\n", '\n');
    replace_all(val, "\\r", '\r');
    replace_all(val, "\\b", '\b');
    replace_all(val, "\\f", '\f');
    // TODO : replace \u four-hex-digits
    value = val;
}

JsonString::operator string() const {
    return value;
}

JsonString * JsonString::fromString(string message, int & i) {
    i++;
    int start = i;
    while (i < message.length()) {
        switch (message[i]) {
            case '\\':
                i++;
                break;
            case '"':
                string s = message.substr(start, i - start);
                i++;
                return new JsonString(s);
        }
        i++;
    }
    throw PARSE_ERROR("No \" ending string", i);
}

string JsonString::toString() {
    string infos = "\"" + this->value + "\"";
    return infos;
}

// Dict

JsonDict::~JsonDict() {
    for (std::map<std::string, JsonValue *>::iterator iter = dict.begin(); iter != dict.end(); ++iter) {
        delete iter->second;
        iter->second = NULL;
    }
}

JsonDict * JsonDict::fromString(string message, int & i) {
    i++;
    JsonDict * r = new JsonDict();
    i += skip_whitespace(message, i);

    if (message[i] == '}') {
        i++;
        return r;
    }

    while (1) {
        JsonString * key = NULL;
        JsonValue * value = NULL;

        i += skip_whitespace(message, i);
        key = JsonString::fromString(message, i);
        string key_str = *key;
        delete key;
        i += skip_whitespace(message, i);
        i += skip_colon(message, i);
        i += skip_whitespace(message, i);
        value = JsonValue::fromString(message, i);
        r->add(key_str, value);

        i += skip_whitespace(message, i);
        if (message[i] == ',') {
            i++;
        }
        else if (message[i] == '}') {
            i++;
            return r;
        }
        else {
            throw PARSE_ERROR("expected } or , found '" + string(1, message[i]) + "'", i);
        }
    }
}

string JsonDict::toString() {
    string infos = "{";
    for (map<string, JsonValue *>::iterator index = this->dict.begin(); index != this->dict.end(); ++index) {
        infos += "\"" + ((string) index->first) + "\"" + " : ";
        infos += index->second->toString();
        infos += ", ";
    }
    infos = infos.substr(0, infos.size() - 2) + "}";
    return infos;
}

void JsonDict::add(string key, JsonValue * value) {
    dict[key] = value;
}

size_t JsonDict::size() {
    return dict.size();
}

JsonValue * JsonDict::operator[](const string & str) {
    return this->dict[str];
}

// List

JsonList::~JsonList() {
    for (int i = 0; i < content.size(); i++) {
        delete content[i];
        content[i] = NULL;
    }
}

JsonList * JsonList::fromString(string message, int & i) {
    i++;
    JsonList * r = new JsonList();
    i += skip_whitespace(message, i);

    if (message[i] == ']') {
        i++;
        return r;
    }

    while (1) {
        JsonValue * value = NULL;

        i += skip_whitespace(message, i);
        value = JsonValue::fromString(message, i);
        r->add(value);

        i += skip_whitespace(message, i);

        switch (message[i]) {
            case ',':
                i++;
                break;
            case ']':
                i++;
                return r;
                break;
            default:
                throw PARSE_ERROR("expected ] or , found " + string(1, message[i]), i);
        }
    }
}

string JsonList::toString() {
    string infos = "[";
    int index = 0;
    while (index < this->content.size()) {
        infos += this->content[index]->toString();
        index++;
        infos += ", ";
    }

    infos = infos.substr(0, infos.size() - 2) + "]";
    return infos;
}

void JsonList::add(JsonValue * value) {
    content.push_back(value);
}

size_t JsonList::size() {
    return content.size();
}

JsonValue * JsonList::operator[](const int & i) {
    return content.at(i);
}

// Int

JsonInt::JsonInt(int val) {
    value = val;
}

JsonInt * JsonInt::fromString(string message, int & i) {
    JsonInt * r = new JsonInt();
    bool end = false;
    int start = i;
    while (!end) {
        switch (message[i]) {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                i++;
                break;
            default:
                end = true;
                break;
        }
    }
    r->setValue(message.substr(start, i));
    return r;
}

string JsonInt::toString() {
    return (string) * this;
}

int JsonInt::getValue() {
    return value;
}

void JsonInt::setValue(int val) {
    value = val;
}

void JsonInt::setValue(string val) {
    try {
        value = stoi(val);
    }
    catch (out_of_range) {
        throw ParseError("Int too big to be parsed");
    }
}

JsonInt::operator string() const {
    return to_string(value);
}

JsonInt::operator int() const {
    return value;
}

// Null

string JsonNull::toString() {
    return "null";
}

JsonNull * JsonNull::fromString(string message, int & i) {
    if (message.substr(i, 4) != "null") {
        throw PARSE_ERROR("expected null, got '" + message.substr(i, 4) + "'", i);
    }
    i += 4;
    return new JsonNull();
}

bool JsonNull::operator ==(const int * i) {
    return i == 0;
}

// Bool

JsonBool::JsonBool(bool val) {
    value = val;
}

JsonBool * JsonBool::fromString(string message, int & i) {
    JsonBool * r = NULL;
    if (message[i] == 't') {
        if (message.substr(i, 4) != "true") {
            throw PARSE_ERROR("expected true, got '" + message.substr(i, 4) + "'", i);
        }
        r = new JsonBool(true);
        i += 4;
    }
    else {
        if (message.substr(i, 5) != "false") {
            throw PARSE_ERROR("expected false, got '" + message.substr(i, 5) + "'", i);
        }
        r = new JsonBool(false);
        i += 5;
    }

    return r;
}

string JsonBool::toString() {
    if (value) {
        return "true";
    }
    else {
        return "false";
    }
}

bool JsonBool::operator ==(const bool i) {
    return value == i;
}

JsonBool::operator bool() const {
    return value;
}


text:
<!DOCTYPE html>
<html>
<head lang="zh-cn">
  <meta charset="utf-8">
  <meta http-equiv="Access-Control-Allow-Origin" content="*"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="description" content="">
  <meta name="keywords" content="">
  <meta name="viewport"
        content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
  <title>GeStore</title>
  <meta name="renderer" content="webkit">
  <!-- No Baidu Siteapp-->
  <meta http-equiv="Cache-Control" content="no-siteapp"/>
  <!--<link rel="alternate icon" type="image/png" href="favicon.png">-->
  <!--<link rel="apple-touch-icon-precomposed" href="app-icon72x72@2x.png">-->
  <meta name="apple-mobile-web-app-title" content="GeStore"/>
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <!-- <script src="libs.baidu.com/jquery/1.11.3/jquery.min.js"></script> -->
  <script src="cdn.amazeui.org/amazeui/2.5.0/jquery/jquery.min.js"></script>
  <script src="cdn.amazeui.org/amazeui/2.5.0/js/amazeui.min.js"></script>
  <link rel="stylesheet" href="cdn.amazeui.org/amazeui/2.5.0/css/amazeui.min.css"/>
  <link rel="stylesheet" href="dist/common.js.css"/>
  <link rel="stylesheet" href="dist/admin.css"/>
</head>
<body>
<router-view></router-view>
<script src="dist/common.js"></script>
<script src="dist/admin.js"></script>
</body>
</html>


text:
cask 'tankix' do
  version '11091'
  sha256 '87f3f5af5ab1c6ac5e08c76b96a292d9cc9f12ae6a0be4e7d1160397f7cb981d'

  url "https://static.tankix.com/app/StandaloneOSXIntel64/master-#{version}/TankiX.dmg"
  name 'Tanki X'
  homepage 'https://www.tankix.com/'

  auto_updates true

  app 'tankix.app'

  zap trash: [
               '/Library/Logs/DiagnosticReports/tankix*',
               '~/Library/Application Support/CrashReporter/tankix*',
               '~/Library/Preferences/unity.AlternativaPlatform.TankiX.plist',
               '~/Library/Saved Application State/unity.AlternativaPlatform.TankiX.savedState',
             ]
end


text:
import BaseHTTPServer
import sys
import time
import json
import boto3
from irc_hooky.entrypoint import handler

HOST_NAME = sys.argv[1]
PORT_NUMBER = int(sys.argv[2])

def handle_webhook(payload, headers, resource_path):
    event = {
        "X-Hub-Signature": headers.get("X-Hub-Signature"),
        "X-Github-Event": headers.get("X-Github-Event"),
        "resource-path": resource_path,
        "irc-server": "chat.freenode.net",
        "irc-port": 6667,
        "irc-channel": "##testtest",
        "irchooky-sns-arn": get_sns_topic_arn("irc-hooky"),
        "payload": payload
    }
    return handler(event, {})

def get_sns_topic_arn(search_string):
    """
    The purpose of this function is to avoid hardcoding an SNS ARN into the
    event payload (above) for local testing.
    """
    client = boto3.client('sns')
    response = client.list_topics()
    for topic in response['Topics']:
        if search_string in topic['TopicArn']:
            return topic['TopicArn']
    raise Exception("Could not find %s SNS topic ARN" % search_string)

class LocalIRCHooky(BaseHTTPServer.BaseHTTPRequestHandler):

    server_version = "LocalIRCHooky/0.1"

    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write("Nothing to see here!")

    def do_POST(self):
        length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(length)
        payload = json.loads(post_data)
        result = handle_webhook(payload, self.headers, self.path)
        self.send_response(200)
        self.send_header("Content-type", "application/json")
        self.end_headers()
        self.wfile.write(result)

if __name__ == '__main__':
    server_class = BaseHTTPServer.HTTPServer
    httpd = server_class((HOST_NAME, PORT_NUMBER), LocalIRCHooky)
    print(time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER))
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print(time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER))


text:
namespace EnvelopeCollide { namespace System {

/// Pre-filter class using tafle intersection method method with planes parallel to projector coordinate system (definition of taflas in "CollisionFilter.h").
class ProjectorMoveVectorFilter : public FilterFunction
{
public:
    ProjectorMoveVectorFilter();

    inline virtual void init(const Entry& entry);
    inline virtual bool isOk(const Entry& entry, const Mesh& mesh);

    /// Projector which transform global coordinates to another coordinate system.
    Projector proj;

    /// Returns left, down, bottom cuboid coordinates
    PKT min;

    /// Returns right, up, top cuboid coordinates
    PKT max;
};

}}

namespace EnvelopeCollide { namespace System {

inline ProjectorMoveVectorFilter::ProjectorMoveVectorFilter() : proj(Projector(PKT0, Punkt(1, 0, 0), Punkt(0,1,0)))
{
}

inline void ProjectorMoveVectorFilter::init(const EnvelopeCollide::Entry &entry)
{
    proj = EnvelopeCollide::Functions::makeCubeProjectorFromMoveVector(entry.vec);
    min = proj.transform(entry.mesh.p[0]);
    max = min;
    for(int l1 = 0; l1 <= entry.mesh.pCount(); l1++)
    {
        Functions::getProjectorMinMax(proj, entry.mesh.p[l1]+entry.vec*entry.back_max, min, max);
        Functions::getProjectorMinMax(proj, entry.mesh.p[l1]+entry.vec*entry.front_max, min, max);
    }
}

inline bool ProjectorMoveVectorFilter::isOk(const EnvelopeCollide::Entry &entry, const EnvelopeCollide::Mesh &mesh)
{
    bool filter = false;
    float r = entry.mesh.r + mesh.r + EnvelopeCollide::COLLISION_MIN_R;
    switch(mesh.type)
    {
    case EnvelopeCollide::POINT: filter = Functions::checkMoveVectorProjectorFilterPoint(proj, min, max, r, mesh.p[0]); break;
    case EnvelopeCollide::LINE: filter = Functions::checkMoveVectorProjectorFilterSegment(proj, min, max, r, Segment(mesh.p[0], mesh.p[1])); break;
    case EnvelopeCollide::TRIANGLE: filter = Functions::checkMoveVectorProjectorFilterTriangle(proj, min, max, r, Triangle(mesh.p[0], mesh.p[1], mesh.p[2])); break;
    default: break;
    }
    return filter;
}

}}

#endif // PROJECTORMOVEVECTORFILTER_H


text:
package org.devdom.influencer.model.dto;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Carlos Vasquez Polanco
 */
@Entity
@Table(name = "dev_dom_user_work")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Work.findAll", query = "SELECT w FROM Work w"),
    @NamedQuery(name = "Work.findByFromId", query = "SELECT w FROM Work w WHERE w.workPK.fromId = :fromId"),
    @NamedQuery(name = "Work.findByWorkId", query = "SELECT w FROM Work w WHERE w.workPK.workId = :workId"),
    @NamedQuery(name = "Work.findByCreatedTime", query = "SELECT w FROM Work w WHERE w.createdTime = :createdTime")})
public class Work implements Serializable {
    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected WorkPK workPK;
    @Basic(optional = false)
    @NotNull
    @Column(name = "created_time")
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdTime;

    public Work() {
    }

    public Work(WorkPK workPK) {
        this.workPK = workPK;
    }

    public Work(WorkPK workPK, Date createdTime) {
        this.workPK = workPK;
        this.createdTime = createdTime;
    }

    public Work(String fromId, String workId) {
        this.workPK = new WorkPK(fromId, workId);
    }

    public WorkPK getWorkPK() {
        return workPK;
    }

    public void setWorkPK(WorkPK workPK) {
        this.workPK = workPK;
    }

    public Date getCreatedTime() {
        return createdTime;
    }

    public void setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (workPK != null ? workPK.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        if (!(object instanceof Work)) {
            return false;
        }
        Work other = (Work) object;
        return (this.workPK != null || other.workPK == null) && (this.workPK == null || this.workPK.equals(other.workPK));
    }

    @Override
    public String toString() {
        return "Work{" + "workPK=" + workPK + ", createdTime=" + createdTime + '}';
    }

}


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved.							  */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib.  */
/*----------------------------------------------------------------------------*/

#include "ADXL345_I2C.h"
#include "I2C.h"
#include "HAL/HAL.hpp"

const uint8_t ADXL345_I2C::kAddress;
const uint8_t ADXL345_I2C::kPowerCtlRegister;
const uint8_t ADXL345_I2C::kDataFormatRegister;
const uint8_t ADXL345_I2C::kDataRegister;
constexpr double ADXL345_I2C::kGsPerLSB;

/**
 * Constructor.
 *
 * @param port The I2C port the accelerometer is attached to
 * @param range The range (+ or -) that the accelerometer will measure.
 */
ADXL345_I2C::ADXL345_I2C(Port port, Range range):
		I2C(port, kAddress)
{
		//m_i2c = new I2C((I2C::Port)port, kAddress);

		// Turn on the measurements
		Write(kPowerCtlRegister, kPowerCtl_Measure);
		// Specify the data format to read
		SetRange(range);

		HALReport(HALUsageReporting::kResourceType_ADXL345, HALUsageReporting::kADXL345_I2C, 0);
}

/**
 * Destructor.
 */
ADXL345_I2C::~ADXL345_I2C()
{
	//delete m_i2c;
	//m_i2c = NULL;
}

/** {@inheritdoc} */
void ADXL345_I2C::SetRange(Range range)
{
	Write(kDataFormatRegister, kDataFormat_FullRes | (uint8_t)range);
}

/** {@inheritdoc} */
double ADXL345_I2C::GetX()
{
	return GetAcceleration(kAxis_X);
}

/** {@inheritdoc} */
double ADXL345_I2C::GetY()
{
	return GetAcceleration(kAxis_Y);
}

/** {@inheritdoc} */
double ADXL345_I2C::GetZ()
{
	return GetAcceleration(kAxis_Z);
}

/**
 * Get the acceleration of one axis in Gs.
 *
 * @param axis The axis to read from.
 * @return Acceleration of the ADXL345 in Gs.
 */
double ADXL345_I2C::GetAcceleration(ADXL345_I2C::Axes axis)
{
	int16_t rawAccel = 0;
	//if(m_i2c)
	//{
		Read(kDataRegister + (uint8_t)axis, sizeof(rawAccel), (uint8_t *)&rawAccel);
	//}
	return rawAccel * kGsPerLSB;
}

/**
 * Get the acceleration of all axes in Gs.
 *
 * @return An object containing the acceleration measured on each axis of the ADXL345 in Gs.
 */
ADXL345_I2C::AllAxes ADXL345_I2C::GetAccelerations()
{
	AllAxes data = AllAxes();
	int16_t rawData[3];
	//if (m_i2c)
	//{
		Read(kDataRegister, sizeof(rawData), (uint8_t*)rawData);

		data.XAxis = rawData[0] * kGsPerLSB;
		data.YAxis = rawData[1] * kGsPerLSB;
		data.ZAxis = rawData[2] * kGsPerLSB;
	//}
	return data;
}


text:
package com.mgmtp.perfload.core.client.config.scope;

import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.fail;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.testng.annotations.Test;

import com.google.common.base.Throwables;
import com.google.inject.Key;
import com.google.inject.Provider;

/**
 * @author rnaegele
 */
public class ExecutionScopeTest {

	@Test
	public void testEnterExitWithSingleThread() {
		Set<Object> objects = new HashSet<>();
		ExecutionScope es = new ExecutionScope();
		Key<Object> key = Key.get(Object.class);
		Provider<Object> provider = new ObjectProvider();

		UUID uuid = UUID.randomUUID();
		es.enterScope(uuid, new HashMap<>());

		for (int i = 0; i < 5; ++i) {
			Object scoped = es.scope(key, provider).get();
			objects.add(scoped);
		}

		assertThat(objects.size()).isEqualTo(1);

		es.exitScope(uuid);
		es.enterScope(uuid, new HashMap<>());

		for (int i = 0; i < 5; ++i) {
			Object scoped = es.scope(key, provider).get();
			objects.add(scoped);
		}

		es.exitScope(uuid);

		assertThat(objects.size()).isEqualTo(2);
	}

	@Test(expectedExceptions = NullPointerException.class)
	public void testNotEntered() {
		ExecutionScope es = new ExecutionScope();
		Key<Object> key = Key.get(Object.class);
		Provider<Object> provider = new ObjectProvider();
		es.scope(key, provider).get();
		fail("Scope should not have been entered.");
	}

	@Test(expectedExceptions = IllegalStateException.class)
	public void testJoinNotEntered() {
		ExecutionScope es = new ExecutionScope();
		es.joinScope(UUID.randomUUID());
		fail("Scope should not have been entered.");
	}

	@Test(expectedExceptions = IllegalStateException.class)
	public void testDisjoinNotEntered() {
		ExecutionScope es = new ExecutionScope();
		es.disjoinScope(UUID.randomUUID());
		fail("Scope should not have been entered.");
	}

	@Test(expectedExceptions = IllegalStateException.class)
	public void testDisjoinNotJoined() {
		ExecutionScope es = new ExecutionScope();
		es.enterScope(UUID.randomUUID(), new HashMap<>());
		es.disjoinScope(UUID.randomUUID());
		fail("Scope should not have been entered.");
	}

	@Test
	public void testEnterExitWithMultipleThreads() throws InterruptedException, ExecutionException {
		int threadCount = 5;

		final Set<Object> objects = new HashSet<>();
		final ExecutionScope es = new ExecutionScope();
		final Key<Object> key = Key.get(Object.class);
		final Provider<Object> provider = new ObjectProvider();
		ExecutorService exec = Executors.newFixedThreadPool(threadCount);

		for (int i = 0; i < threadCount; ++i) {
			exec.submit(() -> {
				UUID uuid = UUID.randomUUID();
				es.enterScope(uuid, new HashMap<>());
				Object scoped = es.scope(key, provider).get();
				objects.add(scoped);
				es.exitScope(uuid);
			}).get();
		}

		assertThat(objects.size()).isEqualTo(threadCount);

		for (int i = 0; i < threadCount; ++i) {
			exec.submit(() -> {
				UUID uuid = UUID.randomUUID();
				es.enterScope(uuid, new HashMap<>());

				Provider<Object> scopedProvider = es.scope(key, provider);
				assertThat(scopedProvider.toString()).isEqualTo("unscoped provider[ExecutionScope]");

				Object scoped = scopedProvider.get();
				objects.add(scoped);
				es.exitScope(uuid);
			}).get();
		}

		assertThat(objects.size()).isEqualTo(2 * threadCount);
	}

	@Test
	public void testJoinDisjoinWithMultipleThreads() throws InterruptedException, ExecutionException {
		int threadCount = 5;

		final Set<Object> objects = new HashSet<>();
		final ExecutionScope es = new ExecutionScope();
		final Key<Object> key = Key.get(Object.class);
		final Provider<Object> provider = new ObjectProvider();
		ExecutorService exec = Executors.newFixedThreadPool(threadCount);

		UUID uuid1 = UUID.randomUUID();
		UUID uuid2 = UUID.randomUUID();
		CountDownLatch latch1 = new CountDownLatch(2);
		CountDownLatch latch2 = new CountDownLatch(10);

		Future<?> future1 = exec.submit(() -> {
			try {
				es.enterScope(uuid1, new HashMap<>());
				Object scoped = es.scope(key, provider).get();
				objects.add(scoped);
				latch1.countDown();
				latch2.await();
				es.exitScope(uuid1);
			} catch (InterruptedException ex) {
				Throwables.propagate(ex);
			}
		});

		Future<?> future2 = exec.submit(() -> {
			try {
				es.enterScope(uuid2, new HashMap<>());
				Object scoped = es.scope(key, provider).get();
				objects.add(scoped);
				latch1.countDown();
				latch2.await();
				es.exitScope(uuid2);
			} catch (InterruptedException ex) {
				Throwables.propagate(ex);
			}
		});

		for (int i = 0; i < threadCount; ++i) {
			exec.submit(() -> {
				es.joinScope(uuid1);
				Object scoped = es.scope(key, provider).get();
				objects.add(scoped);
				es.disjoinScope(uuid1);
				latch2.countDown();
			}).get();
		}

		for (int i = 0; i < threadCount; ++i) {
			exec.submit(() -> {
				es.joinScope(uuid2);
				Object scoped = es.scope(key, provider).get();
				objects.add(scoped);
				es.disjoinScope(uuid2);
				latch2.countDown();
			}).get();
		}

		future1.get();
		future2.get();

		// two objects because we had two different executionIds
		assertThat(objects.size()).isEqualTo(2);
	}

	private static class ObjectProvider implements Provider<Object> {
		@Override
		public Object get() {
			return new Object();
		}

		@Override
		public String toString() {
			return "unscoped provider";
		}
	}
}


text: Added the *MWG.Lists.McAfeeId* output to the ***mwg-get-available-lists*** command.


text:
#ifndef __FINSH_ERROR_H__
#define __FINSH_ERROR_H__

#include <finsh.h>

int finsh_error_init(void);

/* get error number */
u_char finsh_errno(void);

int finsh_error_set(u_char type);
const char* finsh_error_string(u_char type);

#endif


text:
from flask import Blueprint, jsonify

dummy = Blueprint('dummy', __name__)

@dummy.route('/')
def index():
    return jsonify({'Hello': 'World'})


text:
package de.schreibertobias.sprout.chat;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import org.joda.time.DateTime;

import java.io.Serializable;

public class Message implements Serializable {

    @SerializedName("sender")
    @Expose
    private String mSender;

    @SerializedName("content")
    @Expose
    private String mContent;

    @SerializedName("own_message")
    @Expose
    private boolean mOwnMessage;

    @SerializedName("date")
    @Expose
    private DateTime mDate;

    public String getSender() {
        return mSender;
    }

    public void setSender(String sender) {
        mSender = sender;
    }

    public String getContent() {
        return mContent;
    }

    public void setContent(String content) {
        mContent = content;
    }

    public boolean isOwnMessage() {
        return mOwnMessage;
    }

    public void setOwnMessage(boolean ownMessage) {
        mOwnMessage = ownMessage;
    }

    public DateTime getDate() {
        return mDate;
    }

    public void setDate(DateTime date) {
        mDate = date;
    }

    public Message() {
        super();
    }
}


text:
class Options
{
 public:
    std::string output_filename;
    std::string chart_filename;
};

int get_args(int argc, const char *argv[], Options& aOptions);

// ----------------------------------------------------------------------

int main(int argc, const char *argv[])
{
    Options options;
    int exit_code = get_args(argc, argv, options);
    if (exit_code == 0) {
        try {
            auto chart = std::unique_ptr<sdb::Chart>{dynamic_cast<sdb::Chart*>(sdb::read_chart_from_sdb(options.chart_filename))};
            auto viewport = chart->viewport();
            std::cout << viewport << '\n';

            sdb::DrawSerum draw_serum;
            sdb::DrawVaccineAntigen draw_vaccine;
            sdb::DrawReferenceAntigen draw_reference;
            sdb::DrawTestAntigen draw_test;
            std::vector<const sdb::DrawPoint*> draw_points(chart->points().size(), nullptr);
            for (size_t point_no = 0; point_no < chart->points().size(); ++point_no) {
                const auto& p = chart->points()[point_no];
                if (p.attributes.antigen) {
                    if (p.attributes.vaccine) {
                        draw_points[point_no] = &draw_vaccine;
                    }
                    else if (p.attributes.reference) {
                        draw_points[point_no] = &draw_reference;
                    }
                    else {
                        draw_points[point_no] = &draw_test;
                    }
                }
                else {
                    draw_points[point_no] = &draw_serum;
                }
            }

            sdb::DrawPointSettings settings;
            settings.test_antigen_outline_color.from_string("black");
            settings.test_antigen_fill_color.from_string("green");
            settings.reference_antigen_outline_color.from_string("black");
            settings.vaccine_antigen_outline_color.from_string("black");
            settings.serum_outline_color.from_string("black");

            double width = 600;
            auto surface = std::make_unique<acmacs::surface::PdfCairo>(options.output_filename, width, width);
            surface->viewport(viewport);
            aSurface.rectangle_filled(viewport.origin, viewport.size, WHITE, Pixels{0}, WHITE);
            surface->grid(Scaled{1}, "grey80", Pixels{0.5});

            size_t drawn = 0;
            for (size_t level = 0; level < 10 && drawn < draw_points.size(); ++level) {
                for (size_t point_no = 0; point_no < draw_points.size(); ++point_no) {
                    if (draw_points[point_no]->level() == level) {
                        draw_points[point_no]->draw(*surface, chart->points()[point_no], chart->plot_style().style(point_no), settings);
                        ++drawn;
                    }
                }
            }

            aSurface.rectangle(viewport.origin, viewport.size, BLACK, Pixels{2});
        }
        catch (std::exception& err) {
            std::cerr << err.what() << '\n';
            exit_code = 1;
        }
    }
    return exit_code;
}

// ----------------------------------------------------------------------

int get_args(int argc, const char *argv[], Options& aOptions)
{
    using namespace boost::program_options;
    options_description desc("Options");
    desc.add_options()
            ("help", "Print help messages")
            ("chart", value<std::string>(&aOptions.chart_filename), "path to chart for signature page")
            ("output,o", value<std::string>(&aOptions.output_filename)->required(), "output pdf")
            ;
    positional_options_description pos_opt;
    pos_opt.add("chart", 1);
    pos_opt.add("output", 1);

    variables_map vm;
    try {
        store(command_line_parser(argc, argv).options(desc).positional(pos_opt).run(), vm);
        if (vm.count("help")) {
            std::cerr << desc << '\n';
            return 1;
        }
        notify(vm);
        return 0;
    }
    catch(required_option& e) {
        std::cerr << "ERROR: " << e.what() << '\n';
        std::cerr << desc << '\n';
          // std::cerr << "Usage: " << argv[0] << " <tree.json> <output.pdf>" << '\n';
        return 2;
    }
    catch(error& e) {
        std::cerr << "ERROR: " << e.what() << '\n';
        std::cerr << desc << '\n';
        return 3;
    }

} // get_args

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:


text:
module RocketModel

  module DirtyAttribute

    def set(value)
      store_changes
      super if value != get
    end

    def changed?
      @previous_value != get
    end

    def previous_value
      @previous_value
    end

    def apply!
      @previous_value = get
    end

    def restore!
      set @previous_value
      apply!
    end

    def store_changes
      @previous_value ||= get
    end
    private :store_changes

    def set_defaults
      super
      apply!
    end
    private :set_defaults
  end

  # == Rocket Model Dirty
  #
  # Provides a way to track changes in your object
  #
  # Example:
  #
  #   class Person
  #     include RocketModel::AttributeMethods
  #     include RocketModel::Dirty
  #
  #     attribute :name, :String, default: "No name"
  #   end
  #
  #   person = Person.new name: "Steave"
  #   person.changes # => {"name" => ["No name", "Steave"]}
  #
  #   person.name = "Bill"
  #   person.changes # => {"name" => ["No name", "Bill"]}
  #

  module Dirty

    def set_attribute_value(name, value) # :nodoc:
      new_value = super
      if instance_variable_get("@#{name}").changed?
        changed_attributes[name] = new_value
      end
    end

    # Returns list of changed attribute names
    def changed
      changed_attributes.keys
    end

    # Returns +true+ if some attribute changed
    def changed?
      !changed.empty?
    end

    # Returns list of changed attributes with changed values
    def changes
      changed.each_with_object({}) do |name, h|
        h[name] = [previous_value(name), public_send(name)]
      end
    end

    def changes_for_save # :nodoc:
      changed.each_with_object({}) do |name, h|
        h[name] = public_send(name)
      end
    end

    # Return previous value of given attribute
    #   person.previous_value(:name) # =>"No name"
    def previous_value(name)
      v = instance_variable_get("@#{name}")
      v.previous_value
    end

    # Clean changes
    def changes_applied
      changed.each do |name|
        instance_variable_get("@#{name}").apply!
      end
      @changed_attributes = {}
    end

    # Restore previous value and clean changes
    def restore_attributes
      changed.each do |name|
        instance_variable_get("@#{name}").restore!
      end
      @changed_attributes = {}
    end

    def changed_attributes # :nodoc:
      @changed_attributes ||= {}
    end
    private :changed_attributes

    def define_attribute_variable(name, type, options) # :nodoc:
      super.extend DirtyAttribute
    end
    private :define_attribute_variable

  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using DropBoxSync.iOS;
using System.Threading.Tasks;
using System.Threading;

namespace DropboxPaint
{
	// The UIApplicationDelegate for the application. This class is responsible for launching the
	// User Interface of the application, as well as listening (and optionally responding) to
	// application events from iOS.
	[Register ("AppDelegate")]
	public partial class AppDelegate : UIApplicationDelegate
	{
		const string DropboxSyncKey = "YOUR_APP_KEY";
		const string DropboxSyncSecret = "YOUR_APP_SECRET";

		// class-level declarations
		UIWindow window;
		DropboxPaintViewController viewController;

		//
		// This method is invoked when the application has loaded and is ready to run. In this
		// method you should instantiate the window, load the UI into it and then make the window
		// visible.
		//
		// You have 17 seconds to return from this method, or iOS will terminate your application.
		//
		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
			var manager = new DBAccountManager (DropboxSyncKey, DropboxSyncSecret);
			DBAccountManager.SharedManager = manager;

			window = new UIWindow (UIScreen.MainScreen.Bounds);

			viewController = new DropboxPaintViewController ();
			window.RootViewController = viewController;

			Task.Factory.StartNew (() => {
				this.BeginInvokeOnMainThread (() => {
					var account = DBAccountManager.SharedManager.LinkedAccount;
					if (account != null) {
						SetupDropbox ();
					} else
						manager.LinkFromController (window.RootViewController);
				});
			});

			window.MakeKeyAndVisible ();

			return true;
		}

		public override bool OpenUrl (UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
		{
			var account = DBAccountManager.SharedManager.HandleOpenURL (url);
			SetupDropbox ();
			return account != null;
		}

		void SetupDropbox ()
		{
			var t = Task.Factory.StartNew (() => {
				DropboxDatabase.Shared.Init ();
			});
		}
	}
}


text:
This is for Xcode 9, Swift 4.0.

**Please note that _ValueCoding_ is marked as deprecated, as it has been rendered obsolete by Apple introducing the `Codable` protocol. The project has been mothballed, and will no longer be maintained.**

# 2.2.0
This is for Xcode 9, Swift 3.2.

# 2.1.0
This is for Xcode 8.1, Swift 3.0.1

# 2.0.0
This is the Swift 3.0 compatible version.

The key change here is that `CodingType` has been renamed to `CodingProtocol` in accordance with Swift 3.0 naming style.

# 1.5.0
This is a Swift 2.3 compatible version

# 1.4.0
1. [[VCD-19](https://github.com/danthorpe/ValueCoding/pull/19)]: Recreates the project to use a single multi-platform framework target.

# 1.3.0
1. [[VCD-13](https://github.com/danthorpe/ValueCoding/pull/13)]: Switches test coverage reporting to Coveralls. Also adds SwiftLint rules into the project and CI.
2. [[VCD-14](https://github.com/danthorpe/ValueCoding/pull/14)]: Updates to Swift 2.2 syntax. :)

# 1.2.0
1. [[VCD-9, VCD-10](https://github.com/danthorpe/ValueCoding/pull/10)]: Adds support for a single level of nesting inside SequenceType values. For example it is now possible to encode and decode `[[Foo]]` structures where `Foo` conforms to `ValueCoding`.

# 1.1.1
1. [[VCD-7](https://github.com/danthorpe/ValueCoding/pull/7)]: Updates CI stuff.
2. [[VCD-8](https://github.com/danthorpe/ValueCoding/pull/8)]: Updates documentation and README. Thanks [@mrackwitz](https://github.com/danthorpe/ValueCoding/commit/489809da1ba70abf09bc519b784d77a3c47b9f41).

# 1.1.0
1. [[VCD-4](https://github.com/danthorpe/ValueCoding/pull/4)]: Supports tvOS platform, and updates to Xcode 7.1

# 1.0.1
1. [[VCD-1](https://github.com/danthorpe/ValueCoding/pull/1)]: Sets up cross platform project
2. [[VCD-2](https://github.com/danthorpe/ValueCoding/pull/2)]: Adds podspec


text:
using Microsoft.AspNetCore.Routing;

namespace R4Mvc.ModelUnbinders
{
    public class DefaultModelUnbinder : IModelUnbinder
    {
        public void UnbindModel(RouteValueDictionary routeValueDictionary, string routeName, object routeValue)
        {
            routeValueDictionary[routeName] = routeValue;
        }
    }
}


text:
redirect_to: https://anvio.org/help/7.1/artifacts/variability-profile
---


text:
package com.dylan.recom.webservice;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.servlet.ServletContainer;

/**
 * Created by dylan
 */
public class RecoServer {
  private Server webServer = null;
  public void start() {
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    context.setContextPath("/");

    webServer = new Server(9999);
    webServer.setHandler(context);

    ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/*");
    jerseyServlet.setInitOrder(0);

    // Tells the Jersey Servlet which REST service/class to load.
    jerseyServlet.setInitParameter("jersey.config.server.provider.packages",
        "com.dylan.recom.webservice");

    try {
      System.out.println("Web Server started ......");
      webServer.start();
      webServer.join();
    } catch(Exception e) {
      e.printStackTrace();
    } finally {
      webServer.destroy();
    }

  }

  public void stop() throws Exception{
    if(webServer != null) {
      webServer.stop();
    }
  }

  public static void main(String[] args) throws Exception {
    RecoServer recoServer = new RecoServer();
    recoServer.start();
  }
}


text:
/**
	* @module Repositories with all operations allowed
*/

define(function () {

    /**
	 * Repository ctor
	 * @constructor
	*/
    var Repository = (function () {

        var repository = function (entityManagerProvider, entityTypeName, resourceName, fetchStrategy) {

            // Ensure resourceName is registered
            var entityType;
            if (entityTypeName) {
                entityType = getMetastore().getEntityType(entityTypeName);
                entityType.setProperties({ defaultResourceName: resourceName });

                getMetastore().setEntityTypeForResourceName(resourceName, entityTypeName);
            }

            /**
			 * Get Entity by identity
			 * @method
			 * @param {int/string} key - The entity identity
			 * @return {promise}
			*/
            this.withId = function (key) {
                if (!entityTypeName) {
                    throw new Error('Repository must be created with an entity type specified');
                }

                return manager().fetchEntityByKey(entityTypeName, key, true);
            };

            /**
			 * Find Entity by predicate
			 * @method
			 * @param {string} predicate
			 * @param {string} expansionCondition
			 * @return {promise}
			*/
            this.find = function (predicate, expansionCondition) {
                var query;

                if (expansionCondition) {
                    query = breeze.EntityQuery
					    .from(resourceName)
					    .where(predicate)
                        .expand(expansionCondition);
                } else {
                    query = breeze.EntityQuery
                        .from(resourceName)
                        .where(predicate);
                }

                return executeQuery(query);
            };

            /**
			 * Count by predicate
			 * @method
			 * @param {string} predicate
			 * @param {string} expansionCondition
			 * @return {promise}
			*/
            this.count = function (predicate) {
                var query;

                query = breeze.EntityQuery
                    .from(resourceName)
                    .where(predicate)
                    .take(0).inlineCount();

                return entityManagerProvider.manager()
					.executeQuery(query.using(fetchStrategy || breeze.FetchStrategy.FromServer))
					.then(function (data) {
					    return data.inlineCount;
					});
            };

            /**
			 * Find Entity by predicate with projection
			 * @method
			 * @param {string} predicate
			 * @param {string} selectCondition
			 * @return {promise}
			*/
            this.select = function (predicate, selectCondition) {
                var query = breeze.EntityQuery
                    .from(resourceName)
                    .where(predicate)
                    .select(selectCondition);

                return executeQuery(query);
            };

            /**
			 * Find Entity by predicate in cache
			 * @method
			 * @param {string} predicate
			 * @return {object}
			*/
            this.findInCache = function (predicate) {
                var query = breeze.EntityQuery
					.from(resourceName)
					.where(predicate);

                return executeCacheQuery(query);
            };

            /**
			 * Get all entities
			 * @method
			 * @return {promise}
			*/
            this.all = function () {
                var query = breeze.EntityQuery
					.from(resourceName);

                return executeQuery(query);
            };

            /**
			 * Create a new entity and add it to the context
			 * @method
			 * @param {object} values - Initial values
			*/
            this.create = function (values) {
                console.log('Creating entity: ' + entityTypeName);
                var entity = manager().createEntity(entityTypeName, values);
                return entity;
            };

            /**
			 * Set an entity as deleted
			 * @method
			 * @param {object} entity - The entity to delete
			*/
            this.delete = function (entity) {
                ensureEntityType(entity, entityTypeName);
                return entity.entityAspect.setDeleted(entity);
            };

            function executeQuery(query) {
                return entityManagerProvider.manager()
					.executeQuery(query.using(fetchStrategy || breeze.FetchStrategy.FromServer))
					.then(function (data) {
					    return data.results;
					});
            }

            function executeCacheQuery(query) {
                return entityManagerProvider.manager().executeQueryLocally(query);
            }

            function getMetastore() {
                return manager().metadataStore;
            }

            function manager() {
                return entityManagerProvider.manager();
            }

            function ensureEntityType(obj, entityTypeName) {
                if (!obj.entityType || obj.entityType.shortName !== entityTypeName) {
                    throw new Error('Object must be an entity of type ' + entityTypeName);
                }
            }
        };

        return repository;
    })();

    return {
        create: create,
        getCtor: Repository
    };

    /**
	 * Create a new Repository
	 * @method
	 * @param {EntityManagerProvider} entityManagerProvider
	 * @param {string} entityTypeName
	 * @param {string} resourceName
	 * @param {FetchStrategy} fetchStrategy
	 * @return {Repository}
	*/
    function create(entityManagerProvider, entityTypeName, resourceName, fetchStrategy) {
        return new Repository(entityManagerProvider, entityTypeName, resourceName, fetchStrategy);
    }
});


text:
	#include <unistd.h>
	#include <cstdlib>
	#include <cstring>
	#include <netdb.h>
#else
	#include <winsock2.h>
	#include <ws2tcpip.h>
	#include <wspiapi.h>
#endif

#include <memory>
#include <string>
#include <iostream>
#include <sstream>
#include <udt4/udt.h>

#include "socket/NpuSocket.h"
#include "NpuConfig.h"
#include "NpuErrorCode.h"

namespace npu {

	NpuClientActor::NpuClientActor(const NpuConfig& config) : NpuActor(config) {
	}

	NpuClientActor::~NpuClientActor() {
	}

	int NpuClientActor::execute() {
		struct addrinfo hints, *local, *remote;
		memset(&hints, 0, sizeof(struct addrinfo));

		hints.ai_flags = AI_PASSIVE;
		hints.ai_family = AF_INET;
		hints.ai_socktype = SOCK_STREAM;

		std::stringstream localService;
		localService << config::DEFAULT_PORT;
		if (0 != getaddrinfo(NULL, localService.str().c_str(), &hints, &local)) {
			std::cout << "invalid local network address" << std::endl;
			return ERR_INVALID_LOCAL_SOCKET;
		}
		UDTSOCKET udtClientSocket = UDT::socket(local->ai_family, local->ai_socktype, local->ai_protocol);
		// UDT Options
		//UDT::setsockopt(udtClientSocket, 0, UDT_CC, new CCCFactory<CUDPBlast>(), sizeof(CCCFactory<CUDPBlast>));
		//UDT::setsockopt(udtClientSocket, 0, UDT_MSS, new int(9000), sizeof(int));
		//UDT::setsockopt(udtClientSocket, 0, UDT_SNDBUF, new int(10000000), sizeof(int));
		//UDT::setsockopt(udtClientSocket, 0, UDP_SNDBUF, new int(10000000), sizeof(int));
		//UDT::setsockopt(udtClientSocket, 0, UDT_MAXBW, new int64_t(12500000), sizeof(int));
		freeaddrinfo(local);

		// Windows UDP issue
		// For better performance, modify HKLM\System\CurrentControlSet\Services\Afd\Parameters\FastSendDatagramThreshold
		#if OS_MS_WINDOWS
		UDT::setsockopt(udtClientSocket, 0, UDT_MSS, new int(1052), sizeof(int));
		#endif

		std::stringstream remoteService;
		remoteService << config().port();
		if (0 != getaddrinfo(config().remoteHost().c_str(), remoteService.str().c_str(), &hints, &remote)) {
			std::cout << "invalid server address: " << config().remoteHost() << ":" << config().port() << std::endl;
			return ERR_INVALID_REMOTE_SOCKET;
		}
		// Connect to the server, with implicit bind.
		if (UDT::ERROR == UDT::connect(udtClientSocket, remote->ai_addr, remote->ai_addrlen)) {
			freeaddrinfo(remote);
			std::cout << "socket connect failed: " << UDT::getlasterror().getErrorMessage() << std::endl;
			return ERR_CONNECT_FAILED;
		}
		freeaddrinfo(remote);

		std::unique_ptr<NpuSocket> npuSocket(new NpuSocket(udtClientSocket));
		doExecute(*npuSocket);

		// Close the socket.
		if (UDT::getsockstate(udtClientSocket) == CONNECTED) {
			npuSocket->sendCommand(CMD_CLOSE);
		}
		UDT::close(udtClientSocket);
		return SUCCESS;
	}

	const std::string NpuClientActor::toString() const {
		return "ClientActor";
	}
}


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Status Page</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" href="apple-touch-icon.png">
        <link rel="stylesheet" href="/css/normalize.css">
        <link rel="stylesheet" href="/css/page.css">

Projects

        {{ range $key, $config := .Projects}}

{{$config.Name}}

                        Loading Status...

        {{ end }}


text:
require File.expand_path('../../lib/utilitylib.rb', __FILE__)

tests = {
  agent:         agent,
  master:        master,
  ensurable:     false,
  resource_name: 'package',
  agent_only:    true,
}

# Skip -ALL- tests if a top-level platform/os key exludes this platform
skip_unless_supported(tests)

# Native mode third-party rpm's require repo setup
tests[:env] = os_family[/cisco-wrlinux/] ? :native : :centos

tests[:centos] = {
  # GS/OAC-only test. Use dos2unix rpm from the wild.
  # dos2unix is a tiny rpm that is not normally present
  title_pattern:  'dos2unix',
  manifest_props: {
    name:          'dos2unix',
    ensure:        'installed',
    provider:      'yum',
    allow_virtual: 'false',
  },
  resource:       { 'ensure' => '[0-9]+' },
}

tests[:native] = {
  # Native-only test. Use local repo for native testing.
  title_pattern:  'demo-one',
  manifest_props: {
    name:          'demo-one',
    ensure:        'installed',
    provider:      'yum',
    allow_virtual: 'false',
  },
  resource:       { 'ensure' => '[0-9]+' },
}

# class to contain the test_dependencies specific to this test case
class TestPackage < BaseHarness
  def self.dependency_manifest(ctx, _tests, id)
    return unless id == :native
    dep = %(
      # Create local repo files
      file { '/tmp/beaker-repo' :
        ensure => 'directory',
      }
      file { '/tmp/beaker-repo/demo-one-1.0-1.x86_64.rpm' :
        ensure  => present,
        source  => 'puppet:///modules/ciscopuppet/demo-one-1.0-1.x86_64.rpm',
        require => File['/tmp/beaker-repo'],
      }
      exec { 'createrepo':
        command => '/usr/bin/createrepo /tmp/beaker-repo',
        unless  => '/bin/ls /tmp/beaker-repo/repodata 2>/dev/null',
        require => File['/tmp/beaker-repo/demo-one-1.0-1.x86_64.rpm'],
      }

      yumrepo { 'beaker':
         # Create beaker repo config on switch
         baseurl  => 'file:///tmp/beaker-repo',
         descr    => "Beaker test rpms",
         enabled  => 1,
         gpgcheck => 0,
         cost     => 505,
         require  => Exec['createrepo'],
         before   => Package['#{ctx.os_family[/cisco-wrlinux/] ? 'demo-one' : 'dos2unix'}'],
      }
    )
    ctx.logger.info("\n  * dependency_manifest\n#{dep}")
    dep
  end
end

def cleanup(tests, id)
  agent = tests[:agent]
  # Remove the test rpm from the switch
  puppet_resource_cmd_from_params(tests, id)
  cmd = tests[id][:resource_cmd] + ' ensure=purged'
  logger.info("Cleanup: #{cmd}")
  on(agent, cmd, acceptable_error_codes: [0, 2])

  return unless id == :native
  # Remove any local repo cruft
  on(agent, 'rm -f /etc/yum/repos.d/beaker.repo', acceptable_error_codes: [0, 2])
  on(agent, 'rm -rf /tmp/beaker-repo/', acceptable_error_codes: [0, 2])
end

#################################################################
# TEST CASE EXECUTION
#################################################################
test_name "TestCase :: #{tests[:resource_name]}" do
  id = tests[:env]
  teardown { cleanup(tests, id) }
  cleanup(tests, id)

  # ----------------------------------------------------
  logger.info("\n#{'-' * 60}\nSection 1. Install")
  tests[id][:desc] = '1.1 Install RPM'
  test_harness_run(tests, id, harness_class: TestPackage)

  # ----------------------------------------------------
  logger.info("\n#{'-' * 60}\nSection 2. Uninstall")
  tests[id][:desc] = '1.2 Uninstall RPM'
  tests[id][:manifest_props][:ensure] = 'purged'
  tests[id][:resource] = { 'ensure' => 'purged' }
  test_harness_run(tests, id, harness_class: TestPackage)
end
logger.info("TestCase :: #{tests[:resource_name]} :: End")


text:
<?php

namespace Siggy;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class Timer extends Model {
	public $table = 'timers';

	public $incrementing = true;
	public $timestamps = true;

	protected $fillable = [
		'planet',
		'moon',
		'owner',
		'system_id',
		'group_id',
		'start_at',
		'end_at',
		'type',
		'notes'
	];

	protected $hidden = [
		'group_id'
	];

	protected $dates = [
		'start_at',
		'end_at'
	];

	public static function findAllByGroupOrdered(int $groupId): array
	{
		return self::where('group_id',$groupId)
				->orderBy('end_at','desc')
				->get()
				->all();
	}
}


text:
const { assert, skip, test, module: describe, only } = require('qunit');
const { GPU } = require('../../../../../../src');
const { greenCanvas } = require('../../../../../browser-test-utils');

describe('feature: to-string unsigned precision constants HTMLCanvas');

function testArgument(mode, done) {
  const canvasInput1 = greenCanvas(mode, 1, 1);
  const canvasInput2 = greenCanvas(mode, 1, 1);
  const gpu = new GPU({mode});
  const originalKernel = gpu.createKernel(function () {
    const pixel1 = this.constants.canvas1[this.thread.y][this.thread.x];
    const pixel2 = this.constants.canvas2[this.thread.y][this.thread.x];
    return pixel1[1] + pixel2[1];
  }, {
    output: [1],
    precision: 'unsigned',
    constants: { canvas1: canvasInput1, canvas2: canvasInput2 }
  });
  const canvas = originalKernel.canvas;
  const context = originalKernel.context;
  assert.deepEqual(originalKernel()[0], 2);
  const kernelString = originalKernel.toString();
  const canvasInput3 = greenCanvas(mode, 1, 1);
  const canvasInput4 = greenCanvas(mode, 1, 1);
  const newKernel = new Function('return ' + kernelString)()({
    context,
    canvas,
    constants: {
      canvas1: canvasInput3,
      canvas2: canvasInput4
    }
  });
  assert.deepEqual(newKernel()[0], 2);
  gpu.destroy();
}

(GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => {
  testArgument('webgl');
});

(GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => {
  testArgument('webgl2');
});


text:
package rage.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rage.models.Exercise;
import rage.models.User;
import rage.models.UserExercise;
import rage.models.daos.ExerciseDao;
import rage.models.daos.UserExerciseDao;

@Service
@Transactional
@SuppressWarnings("nullness")
public class ExerciseListingService {

    @Autowired ExerciseDao exerciseDao;
    @Autowired UserExerciseDao userExerciseDao;

    /**
     * Find the Exercises of the specified Course (per User) to inform TMC-Core about
     * the state of the Exercises, such as (attempted, completed).
     * @param user The User whose Skills you want to fetch
     * @param courseName The specified Course name that is the parent of the Exercises
     * @return (List of type Exercise) The list of Exercises
     */
    public List<Exercise> addUserSpecificInfoToExercises(User user, String courseName) {
        List<Exercise> exercises = exerciseDao.findExercises(courseName);
        List<UserExercise> userExercises = userExerciseDao.findByUserAndCourseName(user, courseName);
        Map<String, Exercise> map = new HashMap<>();
        for (Exercise exercise : exercises) {
            map.put(exercise.getName(), exercise);
        }
        setExerciseFields(userExercises, map);
        return exercises;
    }

    private void setExerciseFields(List<UserExercise> userExercises, Map<String, Exercise> map) {
        for (UserExercise userExercise : userExercises) {
            map.get(userExercise.getExercise().getName()).setAttempted(userExercise.isAttempted());
            map.get(userExercise.getExercise().getName()).setCompleted(userExercise.isCompleted());
            map.get(userExercise.getExercise().getName()).setAllReviewPointsGiven(userExercise.isAllReviewPointsGiven());
            map.get(userExercise.getExercise().getName()).setReturnable(userExercise.isReturnable());
        }
    }

}


text:
<?php

namespace App\Repositories\Satis;

interface ArchiveInterface
{
    // ...
}


text:
(function($) {
    //'use strict';
    var youtubeGimmick = {
        name: 'youtube',
        load: function() {
            $.md.stage('gimmick').subscribe(function(done) {
                youtubeLinkToIframe();
                done();
            });
        }
    } ;
    $.md.registerGimmick(youtubeGimmick);

    function youtubeLinkToIframe() {
        var $youtube_links = $('a[href*=youtube\\.com]:empty, a[href*=youtu\\.be]:empty');

        $youtube_links.each(function() {
            var $this = $(this);
            var href = $this.attr('href');
            if (href !== undefined) {
                // extract the v parameter from youtube
                var exp = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
                var m = href.match(exp);

                if (m && m[1].length === 11) {
                    // insert the iframe
                    var short_handle = m[1];
                    var frame = $('<iframe class="md-external" frameborder="0" allowfullscreen></iframe>');
                    frame.attr('src', 'http://youtube.com/embed/' + short_handle);
                    // remove the a tag
                    $this.replaceWith(frame);

                }
            }
        });
    }
}(jQuery));


text:
package org.mifos.test.acceptance.util;

import com.thoughtworks.selenium.Selenium;
import org.mifos.test.acceptance.framework.admin.AdminPage;
import org.mifos.test.acceptance.framework.admin.FeesCreatePage;
import org.mifos.test.acceptance.framework.center.MeetingParameters;
import org.mifos.test.acceptance.framework.client.CreateClientEnterMfiDataPage;
import org.mifos.test.acceptance.framework.client.CreateClientEnterPersonalDataPage;
import org.mifos.test.acceptance.framework.customer.CustomerChangeStatusPage;
import org.mifos.test.acceptance.framework.office.OfficeParameters;
import org.mifos.test.acceptance.framework.testhelpers.NavigationHelper;
import org.mifos.test.acceptance.framework.testhelpers.OfficeHelper;
import org.mifos.test.acceptance.framework.testhelpers.UserHelper;
import org.mifos.test.acceptance.framework.user.CreateUserParameters;

import java.sql.SQLException;

public class TestDataSetup {

    private final ApplicationDatabaseOperation applicationDatabaseOperation;
    private final Selenium selenium;

    public TestDataSetup(Selenium selenium, ApplicationDatabaseOperation applicationDatabaseOperation) {
        this.selenium = selenium;
        this.applicationDatabaseOperation = applicationDatabaseOperation;
    }

    public void createBranch(int officeType, String officeName, String shortName) throws SQLException {
        if (applicationDatabaseOperation.doesBranchOfficeExist(officeName,officeType, shortName)) {
            return;
        }
        OfficeHelper officeHelper = new OfficeHelper(selenium);
        OfficeParameters officeParameters = new OfficeParameters();
        officeParameters.setOfficeType(officeType);
        officeParameters.setOfficeName(officeName);
        officeParameters.setShortName(shortName);
        officeParameters.setParentOffice("Head Office(Mifos HO )");
        officeHelper.createOffice(officeParameters);
    }

    public void createUser(String userLoginName, String userName, String officeName) throws SQLException {
        String firstName = userName.split(" ")[0];
        String lastName = userName.split(" ")[1];
        if (applicationDatabaseOperation.doesSystemUserExist(userLoginName,userName,officeName)) {
            return;
        }
        CreateUserParameters userParameters = new AdminPage(selenium).getAdminUserParameters();
        userParameters.setUserName(userLoginName);
        userParameters.setFirstName(firstName);
        userParameters.setLastName(lastName);
        new UserHelper(selenium).createUser(userParameters, officeName);
    }

    public void createClient(String clientName, String officeName, String loanOfficerName) throws SQLException {
        CreateClientEnterPersonalDataPage.SubmitFormParameters clientPersonalInfoParameters = defineClient(clientName);
        if (applicationDatabaseOperation.doesClientExist(clientName, officeName)) {
            return;
        }
        new NavigationHelper(selenium).navigateToHomePage().
                navigateToClientsAndAccountsUsingHeaderTab().
                navigateToCreateNewClientPage().
                navigateToCreateClientWithoutGroupPage().
                chooseOffice(officeName).
                create(clientPersonalInfoParameters).
                submitAndGotoCreateClientEnterMfiDataPage().
                submitAndGotoCreateClientPreviewDataPage(defineMfiData(loanOfficerName)).
                submit().navigateToClientViewDetailsPage().
                navigateToCustomerChangeStatusPage().
                submitAndGotoCustomerChangeStatusPreviewDataPage(setApprovalStatus()).
                submitAndGotoClientViewDetailsPage().
                navigateToEditMeetingSchedule().
                editClientMeeting(setMeetingScheduleParameters());
    }

    public void createFee(FeesCreatePage.SubmitFormParameters feeParameters) throws SQLException {
        if (applicationDatabaseOperation.doesFeeExist(feeParameters.getFeeName())) {
            return;
        }
        new NavigationHelper(selenium).
                navigateToAdminPage().
                navigateToFeesCreate().
                fillFeesParameters(feeParameters).
                submitPageAndGotoPreviewFeesCreatePage().
                submit();
    }

    private CustomerChangeStatusPage.SubmitFormParameters setApprovalStatus() {
        CustomerChangeStatusPage.SubmitFormParameters approvalStatusParameters = new CustomerChangeStatusPage.SubmitFormParameters();
        approvalStatusParameters.setNotes("For Test");
        approvalStatusParameters.setStatus(CustomerChangeStatusPage.SubmitFormParameters.APPROVED);
        return approvalStatusParameters;
    }

    private CreateClientEnterMfiDataPage.SubmitFormParameters defineMfiData(String userName) {
        CreateClientEnterMfiDataPage.SubmitFormParameters mfiDataParameters = new CreateClientEnterMfiDataPage.SubmitFormParameters();
        mfiDataParameters.setMeeting(setMeetingScheduleParameters());
        mfiDataParameters.setLoanOfficerId(userName);
        return mfiDataParameters;
    }

    private MeetingParameters setMeetingScheduleParameters() {
        MeetingParameters meetingParameters = new MeetingParameters();
        meetingParameters.setMeetingPlace("test_location");
        meetingParameters.setWeekFrequency("1");
        meetingParameters.setWeekDay(MeetingParameters.TUESDAY);
        return meetingParameters;
    }

    private CreateClientEnterPersonalDataPage.SubmitFormParameters defineClient(String clientName) {
        CreateClientEnterPersonalDataPage.SubmitFormParameters clientPersonalInfoParameters = new CreateClientEnterPersonalDataPage.SubmitFormParameters();
        clientPersonalInfoParameters.setSalutation(CreateClientEnterPersonalDataPage.SubmitFormParameters.MRS);
        clientPersonalInfoParameters.setFirstName(clientName.split(" ")[0]);
        clientPersonalInfoParameters.setLastName(clientName.split(" ")[1]);
        clientPersonalInfoParameters.setDateOfBirthDD("22");
        clientPersonalInfoParameters.setDateOfBirthMM("05");
        clientPersonalInfoParameters.setDateOfBirthYYYY("1987");
        clientPersonalInfoParameters.setGender(CreateClientEnterPersonalDataPage.SubmitFormParameters.FEMALE);
        clientPersonalInfoParameters.setPovertyStatus(CreateClientEnterPersonalDataPage.SubmitFormParameters.POOR);
        clientPersonalInfoParameters.setSpouseNameType(CreateClientEnterPersonalDataPage.SubmitFormParameters.FATHER);
        clientPersonalInfoParameters.setSpouseFirstName("father");
        clientPersonalInfoParameters.setSpouseLastName("lastname" + StringUtil.getRandomString(8));
        return clientPersonalInfoParameters;
    }

    public void addDecliningPrincipalBalance() throws SQLException {
        if (!applicationDatabaseOperation.doesDecliningPrincipalBalanceExist()) {
            applicationDatabaseOperation.insertDecliningPrincipalBalanceInterestType();
        }
        //To change body of created methods use File | Settings | File Templates.
    }
}


text:
package org.aerogear.digger.client.model;

import com.offbytwo.jenkins.helper.BuildConsoleStreamListener;

/**
 * Class to control the behavior of build logs streaming.
 */
public class LogStreamingOptions {

    /**
     * Polling interval. Default to 5 seconds.
     */
    private int pollingInterval = 5;

    /**
     * Polling timeout. Default to 1 hour.
     */
    private int pollingTimeout = 60*60;

    /**
     * Listener of streaming events.
     */
    private BuildConsoleStreamListener streamListener;

    /**
     * Constructor. Create with a listener
     * @param streamListener the listener to receive log data.
     */
    public LogStreamingOptions(BuildConsoleStreamListener streamListener) {
        this.streamListener = streamListener;
    }

    /**
     * Constructor. Create with a listener, polling interval and polling timeout values.
     * @param streamListener the listener to receive log data.
     * @param pollingInterval in seconds
     * @param pollingTimeout in seconds
     */
    public LogStreamingOptions(BuildConsoleStreamListener streamListener, int pollingInterval, int pollingTimeout) {
        this.streamListener = streamListener;
        this.pollingInterval = pollingInterval;
        this.pollingTimeout = pollingTimeout;
    }

    public int getPollingInterval() {
        return pollingInterval;
    }

    public void setPollingInterval(int pollingInterval) {
        this.pollingInterval = pollingInterval;
    }

    public int getPollingTimeout() {
        return pollingTimeout;
    }

    public void setPollingTimeout(int pollingTimeout) {
        this.pollingTimeout = pollingTimeout;
    }

    public BuildConsoleStreamListener getStreamListener() {
        return streamListener;
    }

    public void setStreamListener(BuildConsoleStreamListener streamListener) {
        this.streamListener = streamListener;
    }
}


text:
package cz.req.ax;

public interface BeanEventListener<T> {

    void beanEvent(T bean);

}


text:
package org.drools.template.parser;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import org.drools.RuleBase;
import org.drools.RuleBaseFactory;
import org.drools.StatefulSession;
import org.drools.compiler.PackageBuilder;
import org.drools.rule.Package;
import org.drools.template.model.Condition;
import org.drools.template.model.Consequence;
import org.drools.template.model.DRLOutput;
import org.drools.template.model.Global;
import org.drools.template.model.Import;
import org.drools.template.model.Rule;

/**
 *
 *
 * Create a rule base for the set of rule templates in the
 * TemplateContainer. These rules are used internally by the
 * engine to generate the actual decision table rules based on
 * which columns have been filled in.
 *
 * Basically, if a rule template requires columns A and B then
 * the template rule base will generate a rule with columns A and B
 * as the LHS and a RHS which triggers the rule to be generated.
 * ie.
 * rule "template1"
 *   when
 *     r : Row()
 *     column1 : Column(name == "column1")
 *     Cell(row == r, column == column1)
 *     column2 : Column(name == "column2")
 *     Cell(row == r, column == column2, value == "xyz")
 *   then
 *     generator.generate( "template1", r);
 *   end
 */
public class DefaultTemplateRuleBase implements TemplateRuleBase {
    private RuleBase ruleBase;

    public DefaultTemplateRuleBase(final TemplateContainer tc) {
        ruleBase = readRule(getDTRules(tc.getTemplates()));
    }

    /* (non-Javadoc)
     * @see org.drools.decisiontable.parser.TemplateRuleBase#newWorkingMemory()
     */
    public StatefulSession newStatefulSession() {
        return ruleBase.newStatefulSession();
    }
    /**
     *
     * @param templates
     * @return
     */
    private String getDTRules(Map<String, RuleTemplate> templates) {
        org.drools.template.model.Package p = new org.drools.template.model.Package(
                DefaultTemplateRuleBase.class.getPackage().getName());
        addImports(p);
        addGlobals(p);
        int i = 1;
        for ( RuleTemplate template : templates.values() ) {
            createTemplateRule(p, i++, template);
        }
        DRLOutput out = new DRLOutput();
        p.renderDRL(out);
        return out.getDRL();

    }

    private void createTemplateRule(org.drools.template.model.Package p, int index, RuleTemplate template) {
        Rule rule = new Rule(template.getName(), null, index);
        Condition condition = new Condition();
        condition.setSnippet("r : Row()");
        rule.addCondition(condition);
        createColumnConditions(template, rule);
        rule.addConsequence(createConsequence(template));
        p.addRule(rule);
    }

    private void createColumnConditions(RuleTemplate template, Rule rule) {
        for ( TemplateColumn column : template.getColumns() ) {
            column.addCondition(rule);
        }
    }

    private void addGlobals(org.drools.template.model.Package p) {
        Global global = new Global();
        global.setClassName(DefaultGenerator.class.getName());
        global.setIdentifier("generator");
        p.addVariable(global);
    }

    private void addImports(org.drools.template.model.Package p) {
        Import drlImport1 = new Import();
        drlImport1.setClassName(Map.class.getName());
        Import drlImport2 = new Import();
        drlImport2.setClassName(HashMap.class.getName());
        p.addImport(drlImport1);
        p.addImport(drlImport2);
    }

    private Consequence createConsequence(RuleTemplate template) {
        StringBuffer action = new StringBuffer();
        action.append("generator.generate( \"");
        action.append(template.getName()).append("\", r);");
        final Consequence consequence = new Consequence();
        consequence.setSnippet(action.toString());
        return consequence;
    }

    private RuleBase readRule(String drl) {
        try {
//            System.out.println(drl);
            // read in the source
            Reader source = new StringReader(drl);
            PackageBuilder builder = new PackageBuilder();
            builder.addPackageFromDrl(source);
            Package pkg = builder.getPackage();

            // add the package to a rulebase (deploy the rule package).
            RuleBase ruleBase = RuleBaseFactory.newRuleBase();
            ruleBase.addPackage(pkg);
            return ruleBase;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}


text:
import sys

from command import Command
from git_command import GitCommand
from git_refs import GitRefs, HEAD, R_HEADS, R_TAGS, R_PUB, R_M
from error import GitError

class Rebase(Command):
  common = True
  helpSummary = "Rebase local branches on upstream branch"
  helpUsage = """
%prog {[<project>...] | -i <project>...}
"""
  helpDescription = """
'%prog' uses git rebase to move local changes in the current topic branch to
the HEAD of the upstream history, useful when you have made commits in a topic
branch but need to incorporate new upstream changes "underneath" them.
"""

  def _Options(self, p):
    p.add_option('-i', '--interactive',
                dest="interactive", action="store_true",
                help="interactive rebase (single project only)")

    p.add_option('-f', '--force-rebase',
                 dest='force_rebase', action='store_true',
                 help='Pass --force-rebase to git rebase')
    p.add_option('--no-ff',
                 dest='no_ff', action='store_true',
                 help='Pass --no-ff to git rebase')
    p.add_option('-q', '--quiet',
                 dest='quiet', action='store_true',
                 help='Pass --quiet to git rebase')
    p.add_option('--autosquash',
                 dest='autosquash', action='store_true',
                 help='Pass --autosquash to git rebase')
    p.add_option('--whitespace',
                 dest='whitespace', action='store', metavar='WS',
                 help='Pass --whitespace to git rebase')

  def Execute(self, opt, args):
    all = self.GetProjects(args)
    one_project = len(all) == 1

    if opt.interactive and not one_project:
      print >>sys.stderr, 'error: interactive rebase not supported with multiple projects'
      return -1

    for project in all:
      cb = project.CurrentBranch
      if not cb:
        if one_project:
          print >>sys.stderr, "error: project %s has a detatched HEAD" % project.relpath
          return -1
        # ignore branches with detatched HEADs
        continue

      upbranch = project.GetBranch(cb)
      if not upbranch.LocalMerge:
        if one_project:
          print >>sys.stderr, "error: project %s does not track any remote branches" % project.relpath
          return -1
        # ignore branches without remotes
        continue

      args = ["rebase"]

      if opt.whitespace:
        args.append('--whitespace=%s' % opt.whitespace)

      if opt.quiet:
        args.append('--quiet')

      if opt.force_rebase:
        args.append('--force-rebase')

      if opt.no_ff:
        args.append('--no-ff')

      if opt.autosquash:
        args.append('--autosquash')

      if opt.interactive:
        args.append("-i")

      args.append(upbranch.LocalMerge)

      print >>sys.stderr, '# %s: rebasing %s -> %s' % \
        (project.relpath, cb, upbranch.LocalMerge)

      if GitCommand(project, args).Wait() != 0:
        return -1


text:
Package.describe({
    summary: "shopping cart",
    name: "ksondere:42-cent-cart",
    summary: "A simple and pluggable shopping cart that uses 42-cent npm for payment gateway options",
  	version: "0.0.1",
    git: "https://github.com/ksondere/42-cent-cart.git"
});

Package.on_use(function (api) {
	api.versionsFrom("METEOR@0.9.0");
	Npm.depends({"42-cent": "1.1.0", "authorize-net": "1.0.4"});

	api.use([
	    'tracker@1.0.3',
	    'templating',
	    'session',
	    'amplify'
		]
	  , 'client');

	api.use([
		'iron:router@1.0.7', 'mongo@1.0.8', 'underscore', 'accounts-base', 'random', 'meteorhacks:npm@1.3.0', 'meteorhacks:async@1.0.0', 'materialize:materialize@0.96.1'
		], ['server','client']);

    api.addFiles(['lib/server/payments.js'], ['server']);

    api.addFiles(['lib/both/environment.js','lib/both/routes.js','lib/both/collections.js', 'lib/both/payment_gateways.js'],
		['client','server']);
    api.addFiles(['lib/client/cart.html','lib/client/cart.js', 'lib/client/products.html'], 'client');
    api.addFiles(['lib/server/publications.js'], 'server');

    api.export('Cart', ['client','server']);
	api.export('Products', ['client', 'server']);
});