text:
import os
import sys
import shutil
import unittest
import IECore

class TestRelativePreset( unittest.TestCase ) :

	def testDiffData( self ):

		emptyPreset = IECore.RelativePreset()
		a = emptyPreset.getDiffData()
		self.assertTrue( isinstance( a, IECore.CompoundObject ) )
		self.assertEqual( len(a), 0 )
		emptyPreset.setDiffData( IECore.CompoundObject() )
		self.assertRaises( Exception, lambda : emptyPreset.setDiffData( IECore.CompoundData() ) )

	def testSparseSimpleChanges( self ) :

		def createTestObj():
			testObj = IECore.Parameterised( "testParameterised1" )
			testObj.parameters().addParameters(
				[
					IECore.BoolParameter( "a", "", True ),
					IECore.FloatParameter( "b", "", 1.0 ),
				]
			)
			return testObj

		def createTestObj2():
			testObj2 = IECore.Parameterised( "testParameterised2" )
			testObj2.parameters().addParameters(
				[
					IECore.BoolParameter( "a", "", True ),
					IECore.FloatParameter( "c", "", 0.0	),
				]
			)
			return testObj2

		testObjA = createTestObj()
		testObjB = createTestObj()
		testObjB["a"] = False
		r = IECore.RelativePreset( testObjB.parameters(), testObjA.parameters() )

		testObj2 = createTestObj2()

		self.failUnless( r.applicableTo( testObjA, testObjA.parameters() ) )
		self.failUnless( r.applicableTo( testObj2, testObj2.parameters() ) )

		r( testObjB, testObjB.parameters() )

		self.assertEqual( testObjB.parameters()["a"].getTypedValue(), False )
		self.assertEqual( testObjB.parameters()["b"].getTypedValue(), 1.0 )

		r( testObj2, testObj2.parameters() )

		self.assertEqual( testObj2.parameters()["a"].getTypedValue(), False )
		self.assertEqual( testObj2.parameters()["c"].getTypedValue(), 0.0 )

		r = IECore.RelativePreset( testObjB.parameters() )
		testObjB["a"] = True
		testObjB["b"] = 2.0
		r( testObjB, testObjB.parameters() )
		self.assertEqual( testObjB.parameters()["a"].getTypedValue(), False )
		self.assertEqual( testObjB.parameters()["b"].getTypedValue(), 1.0 )

	def testClasses( self ) :

		def createTestObj():
			testObj = IECore.Parameterised( "testParameterised1" )
			testObj.parameters().addParameters(
				[
					IECore.BoolParameter( "a", "", True ),
					IECore.ClassParameter( "b", "", "IECORE_OP_PATHS" ),
				]
			)
			return testObj

		def createTestObj2():
			testObj2 = IECore.Parameterised( "testParameterised2" )
			testObj2.parameters().addParameters(
				[
					IECore.ClassParameter( "b", "",	"IECORE_OP_PATHS" ),
				]
			)
			return testObj2

		testObjA = createTestObj()
		testObjB = createTestObj()
		testObj2 = createTestObj2()

		testObjB["b"].setClass( "maths/multiply", 2 )

		classes1 = testObjB.parameters()["b"].getClass( True )
		classes2 = testObj2.parameters()["b"].getClass( True )
		self.assertNotEqual( classes1[1:], classes2[1:] )

		r = IECore.RelativePreset( testObjB.parameters(), testObjA.parameters() )

		self.failUnless( r.applicableTo( testObjB, testObjB.parameters() ) )
		self.failUnless( r.applicableTo( testObj2, testObj2.parameters() ) )

		r( testObj2, testObj2.parameters() )

		classes1 = testObjB.parameters()["b"].getClass( True )
		classes2 = testObj2.parameters()["b"].getClass( True )

		self.assertEqual( classes1[1:], classes2[1:] )

		r = IECore.RelativePreset( testObjB.parameters() )
		testObjB["a"] = False
		testObjB["b"].setClass("", 0)
		r( testObjB, testObjB.parameters() )
		classes1 = testObjB.parameters()["b"].getClass( True )
		self.assertEqual( classes1[1:], classes2[1:] )
		self.assertEqual( testObjB["a"].getTypedValue(), True )

		testObjA["b"].setClass( "maths/multiply", 1 )
		classes1 = testObjB.parameters()["b"].getClass( True )
		classes2 = testObjA.parameters()["b"].getClass( True )
		self.assertNotEqual( classes1[1:], classes2[1:] )
		r = IECore.RelativePreset( testObjB.parameters(), testObjA.parameters() )
		r( testObj2, testObj2.parameters() )
		classes1 = testObjB.parameters()["b"].getClass( True )
		classes2 = testObj2.parameters()["b"].getClass( True )
		self.assertEqual( classes1[1:], classes2[1:] )

	def testCompareFilter( self ) :

		def createTestObj():
			testObj = IECore.Parameterised( "testParameterised1" )
			testObj.parameters().addParameters(
				[
					IECore.ClassParameter( "a", "", "IECORE_OP_PATHS" ),
					IECore.ClassParameter( "b", "", "IECORE_OP_PATHS" ),
				]
			)
			return testObj

		def filterCmp( p1, p2 ):
			# only keep track of changes on parameter 'a'
			return bool(p1.name in ['a', ''])

		testObjA = createTestObj()
		testObjB = createTestObj()

		testObjA["a"].setClass( "maths/multiply", 2 )
		testObjA["b"].setClass( "maths/multiply", 2 )
		testObjB["a"].setClass( "maths/multiply", 2 )
		testObjB["b"].setClass( "maths/multiply", 2 )
		testObjB["a"]["a"].setTypedValue( 10 )
		testObjB["a"]["b"].setTypedValue( 20 )
		testObjB["b"]["a"].setTypedValue( 30 )
		testObjB["b"]["b"].setTypedValue( 40 )

		r = IECore.RelativePreset( testObjB.parameters(), testObjA.parameters(), compareFilter = filterCmp )

		r( testObjA, testObjA.parameters() )

		self.assertEqual( testObjA["a"]["a"].getTypedValue(), 10 )
		self.assertEqual( testObjA["a"]["b"].getTypedValue(), 2 )
		self.assertEqual( testObjA["b"]["a"].getTypedValue(), 1 )
		self.assertEqual( testObjA["b"]["b"].getTypedValue(), 2 )

	def testClassVectors( self ) :

		def createTestObj() :
			testObj = IECore.Parameterised( "testParameterised1" )
			testObj.parameters().addParameters(
				[
					IECore.BoolParameter( "a", "", True ),
					IECore.ClassVectorParameter( "b", "", "IECORE_OP_PATHS" ),
				]
			)
			return testObj

		testObjA = createTestObj()
		testObjB = createTestObj()

		testObjB.parameters()["b"].setClasses(
			[
				( "mult", "maths/multiply", 2 ),
				( "coIO", "compoundObjectInOut", 1 ),
			]
		)

		def createTestObj2():
			testObj2 = IECore.Parameterised( "testParameterised2" )
			testObj2.parameters().addParameters(
				[
					IECore.ClassVectorParameter( "b", "", "IECORE_OP_PATHS" ),
				]
			)
			return testObj2

		testObj2 = createTestObj2()

		classes1 = [ c[1:] for c in testObjB.parameters()["b"].getClasses( True ) ]
		classes2 = [ c[1:] for c in testObj2.parameters()["b"].getClasses( True ) ]

		self.assertNotEqual( classes1, classes2 )
		self.assertEqual( len(classes1), 2 )

		r1 = IECore.RelativePreset( testObjB.parameters() )
		r2 = IECore.RelativePreset( testObjB.parameters(), testObjA.parameters() )

		self.failUnless( r1.applicableTo( testObjB, testObjB.parameters() ) )
		self.failUnless( r1.applicableTo( testObj2, testObj2.parameters() ) )
		self.failUnless( r2.applicableTo( testObj2, testObj2.parameters() ) )

		r2( testObj2, testObj2.parameters() )

		classes2 = [ c[1:] for c in testObj2.parameters()["b"].getClasses( True ) ]
		self.assertEqual( classes1, classes2 )

		# now we reorder ops...
		testObjC = createTestObj()
		classes1.reverse()
		testObjC["b"].setClasses( classes1 )
		r = IECore.RelativePreset( testObjC.parameters(), testObjB.parameters() )

		r( testObj2, testObj2.parameters() )
		classes2 = [ c[1:] for c in testObj2.parameters()["b"].getClasses( True ) ]
		self.assertEqual( classes1, classes2 )

		# now we remove an op
		testObj2["b"].removeClass( "mult" )
		classes2 = [ c[1] for c in testObj2.parameters()["b"].getClasses( True ) ]
		self.assertEqual( classes2, [ "coIO" ] )
		r = IECore.RelativePreset( testObj2.parameters(), testObjB.parameters() )
		r( testObjB, testObjB.parameters() )
		classes1 = [ c[1] for c in testObjB.parameters()["b"].getClasses( True ) ]
		self.assertEqual( classes1, [ "coIO" ] )

		# now we add it back
		testObj2["b"].setClass( "mult", "maths/multiply", 2 )
		testObj2["b"].setClass( "another", "maths/multiply", 2 )
		r = IECore.RelativePreset( testObj2.parameters(), testObjB.parameters() )
		r( testObjB, testObjB.parameters() )
		classes1 = [ c[1:] for c in testObjB.parameters()["b"].getClasses( True ) ]
		classes2 = [ c[1:] for c in testObj2.parameters()["b"].getClasses( True ) ]
		self.assertEqual( len(classes2), 3 )
		self.assertEqual( classes1, classes2 )

		# now we replace one of them
		testObj2["b"].setClass( "another", "compoundObjectInOut", 1 )
		r = IECore.RelativePreset( testObj2.parameters(), testObjB.parameters() )
		r( testObjB, testObjB.parameters() )
		classes1 = [ c[1:] for c in testObjB.parameters()["b"].getClasses( True ) ]
		classes2 = [ c[1:] for c in testObj2.parameters()["b"].getClasses( True ) ]
		self.assertEqual( len(classes2), 3 )
		self.assertEqual( classes1, classes2 )

	def testDeepClassVectors( self ) :

		def createParameterised():
			testObj = IECore.Parameterised( "testParameterised1" )
			testObj.parameters().addParameters(
				[
					IECore.BoolParameter( "a", "", True ),
					IECore.ClassVectorParameter( "b", "", "IECORE_OP_PATHS" ),
					IECore.BoolParameter( "c", "", False ),
				]
			)
			testObj.parameters()["b"].setClasses(
				[
					( "p0", "maths/multiply", 2 ),
					( "p1", "compoundObjectInOut", 1 ),
					( "p2", "classVectorParameterTest", 1),
					( "p3", "maths/multiply", 1 ),
					( "p4", "classParameterTest", 1),
				]
			)
			testObj["b"]["p2"]["cv"].setClasses(
				[
					( "p0", "maths/multiply", 2 ),
					( "p1", "compoundObjectInOut", 1 )
				]
			)
			testObj["b"]["p4"]["cp"].setClass( "maths/multiply", 2 )
			return testObj

		testObjA = createParameterised()

		testObjB = createParameterised()

		# test no differences
		r = IECore.RelativePreset( testObjB.parameters(), testObjA.parameters() )
		# the diff should be empty!
		self.assertEqual( r._RelativePreset__data, IECore.CompoundObject() )
		# applying empty diff should not break
		r( testObjB, testObjB.parameters() )
		self.assertEqual( testObjA.parameters().getValue(), testObjB.parameters().getValue() )

		# now we modify the object a lot!!
		testObjB["a"] = False
		testObjB["c"] = True
		testObjB["b"].removeClass( "p1" )
		testObjB["b"].removeClass( "p3" )
		testObjB["b"]["p0"]["a"] = False
		testObjB["b"]["p4"]["cp"]["a"] = 10
		testObjB["b"]["p2"]["cv"]["p0"]["a"] = 20
		testObjB["b"]["p2"]["cv"].setClass("p1", "maths/multiply", 2 )	# replace one op
		testObjB["b"]["p2"]["cv"].setClass("p3", "floatParameter", 1 )	# add one op
		# reoder "b" elements
		order = map( lambda c: c[1:], testObjB["b"].getClasses(True) )
		order.reverse()
		testObjB["b"].setClasses(order)

		# now we apply the changes on an object identical to the original one represented in the basic preset.
		testObj2 = createParameterised()
		r = IECore.RelativePreset( testObjB.parameters(), testObjA.parameters() )
		relPreset = r	# copy this preset, as it's going to be used later on again...
		r( testObj2, testObj2.parameters() )
		self.assertEqual( testObj2.parameters().getValue(), testObjB.parameters().getValue() )
		classes1 = [ c[1:] for c in testObjB.parameters()["b"].getClasses( True ) ]
		classes2 = [ c[1:] for c in testObj2.parameters()["b"].getClasses( True ) ]
		self.assertEqual( len(classes2), 3 )
		self.assertEqual( classes1, classes2 )
		classes1 = [ c[1:] for c in testObjB.parameters()["b"]["p2"]["cv"].getClasses( True ) ]
		classes2 = [ c[1:] for c in testObj2.parameters()["b"]["p2"]["cv"].getClasses( True ) ]
		self.assertEqual( testObjB.parameters()["b"]["p2"]["cv"].keys(), [ 'p0', 'p1', 'p3' ] )
		self.assertEqual( len(classes2), 3 )
		self.assertEqual( classes1, classes2 )

		# we test the other way around
		testObj2 = createParameterised()
		r = IECore.RelativePreset( testObj2.parameters(), testObjB.parameters() )
		r( testObjB, testObjB.parameters() )
		self.assertEqual( testObj2.parameters().getValue(), testObjB.parameters().getValue() )
		classes1 = [ c[1:] for c in testObjB.parameters()["b"].getClasses( True ) ]
		classes2 = [ c[1:] for c in testObj2.parameters()["b"].getClasses( True ) ]
		self.assertEqual( len(classes2), 5 )
		self.assertEqual( classes1, classes2 )
		classes1 = [ c[1:] for c in testObjB.parameters()["b"]["p2"]["cv"].getClasses( True ) ]
		classes2 = [ c[1:] for c in testObj2.parameters()["b"]["p2"]["cv"].getClasses( True ) ]
		self.assertEqual( len(classes2), 2 )
		self.assertEqual( classes1, classes2 )

		# now it gets tricky... we try to apply the changes on a different object...
		testObj2 = createParameterised()
		testObj2.parameters().removeParameter("a")		# remove "a"
		testObj2.parameters().removeParameter("c")		# replace "c" by something else
		testObj2.parameters().addParameter(
			IECore.IntParameter( "c", "", 10 )
		)
		testObj2.parameters().addParameter(				# add new parameter "d"
			IECore.IntParameter( "d", "", 10 )
		)
		testObj2["b"].removeClass("p1")				# we remove "p1" - the same parameter that the preset will try to remove later... it should ignore it
		testObj2["b"].setClass("p3", "compoundObjectInOut", 1 )	# we replace "p3" - the same parameter that the preset will try to remove later... it should not remove because it's a different class.
		testObj2["b"]["p4"]["cp"]["a"] = 30			# we want this value to be replaced by 10 which was the relative change on that parameter
		testObj2["b"]["p2"]["cv"].setClass("p1", "maths/multiply", 1 )	# replace an op that the preset will try to replace too...  but will not because the original class is different
		testObj2["b"]["p2"]["cv"].setClass("p3", "compoundObjectInOut", 1 )	# add one op that the preset will try to add too... name clashes!

		relPreset( testObj2, testObj2.parameters() )

		self.assertEqual( testObj2["c"].getTypedValue(), 10 )	# guarantee that the replaced parameter "c" was not affected by the Preset
		self.assert_( "p3" in testObj2["b"].keys() )			# ok, "p3" was not removed!
		self.assertEqual( testObj2["b"]["p4"]["cp"]["a"].getTypedValue(), 10 )	# ok, the preset changes were applied here
		self.assertEqual( testObj2["b"]["p2"]["cv"].getClass( "p1", True )[2], 1 )	# ok, the Preset did not change this one because it was looking for a compoundObjectInOut class name...
		self.assertEqual( testObj2["b"]["p2"]["cv"].getClass( "p3", True )[1], "compoundObjectInOut" )	# ok, the Preset did not remove the current "p3" parameter...
		self.assertEqual( testObj2["b"]["p2"]["cv"].getClass( "p2", True )[1], "maths/multiply" )	# ok, the Preset added a new parameter "p2" with the "p1" Preset...
		self.assertEqual( testObj2["b"]["p2"]["cv"].getClass( "p4", True )[1], "floatParameter" )	# ok, the Preset added a new parameter "p4" with the "p3" Preset...
		self.assertEqual( testObj2["b"]["p2"]["cv"].keys(), [ 'p0', 'p2', 'p4', 'p1', 'p3' ] )

	def __checkOrder( self, localChangesParam, applyToParam, expectedOrder ):
		r = IECore.RelativePreset( localChangesParam, baseVec() )
		testObj = IECore.Parameterised( "test" )
		testObj.parameters().addParameters(
			[
						applyToParam
			]
		)
		r( testObj, applyToParam )
		resultOrder = map( lambda c: c[1], applyToParam.getClasses( True ) )
		self.assertEqual( resultOrder, expectedOrder )

	def testBaseInsertions( self ):
		# easy tests applying to base vector
		self.__checkOrder( topInsert(), baseVec(), [ 'p5', 'p1', 'p2', 'p3', 'p4' ] )
		self.__checkOrder( doubleTopInsert(), baseVec(), [ 'p5', 'p6', 'p1', 'p2', 'p3', 'p4' ] )
		self.__checkOrder( bottomInsert(), baseVec(), [ 'p1', 'p2', 'p3', 'p4', 'p5' ] )
		self.__checkOrder( centerInsert(), baseVec(), [ 'p1', 'p2', 'p5', 'p3', 'p4' ] )
		self.__checkOrder( doubleCenterInsert(), baseVec(), [ 'p1', 'p2', 'p5', 'p6', 'p3', 'p4' ] )
		self.__checkOrder( twoInserts(), baseVec(), [ 'p1', 'p2', 'p5', 'p3', 'p6', 'p4' ] )

	def testEmptyVectorInsertions(self):
		# tests applying to empty classes vector
		self.__checkOrder( topInsert(), emptyVec(), [ 'p5' ] )
		self.__checkOrder( doubleTopInsert(), emptyVec(), [ 'p5', 'p6' ] )
		self.__checkOrder( bottomInsert(), emptyVec(), [ 'p5' ] )
		self.__checkOrder( centerInsert(), emptyVec(), [ 'p5' ] )
		self.__checkOrder( doubleCenterInsert(), emptyVec(), [ 'p5', 'p6' ] )
		self.__checkOrder( twoInserts(), emptyVec(), [ 'p5', 'p6' ] )

	def testRemovedP2Insertions( self ):
		# tests applying to "removed P2" vector
		self.__checkOrder( topInsert(), removedP2Vec(), [ 'p5', 'p1', 'p3', 'p4' ] )
		self.__checkOrder( doubleTopInsert(), removedP2Vec(), [ 'p5', 'p6', 'p1', 'p3', 'p4' ] )
		self.__checkOrder( bottomInsert(), removedP2Vec(), [ 'p1', 'p3', 'p4', 'p5' ] )
		self.__checkOrder( centerInsert(), removedP2Vec(), [ 'p1', 'p5', 'p3', 'p4' ] )
		self.__checkOrder( doubleCenterInsert(), removedP2Vec(), [ 'p1', 'p5', 'p6', 'p3', 'p4' ] )
		self.__checkOrder( twoInserts(), removedP2Vec(), [ 'p1', 'p5', 'p3', 'p6', 'p4' ] )

	def testRemovedP3Insertions( self ):
		# tests applying to "removed P3" vector
		self.__checkOrder( topInsert(), removedP3Vec(), [ 'p5', 'p1', 'p2', 'p4' ] )
		self.__checkOrder( doubleTopInsert(), removedP3Vec(), [ 'p5', 'p6', 'p1', 'p2', 'p4' ] )
		self.__checkOrder( bottomInsert(), removedP3Vec(), [ 'p1', 'p2', 'p4', 'p5' ] )
		self.__checkOrder( centerInsert(), removedP3Vec(), [ 'p1', 'p2', 'p5', 'p4' ] )
		self.__checkOrder( doubleCenterInsert(), removedP3Vec(), [ 'p1', 'p2', 'p5', 'p6', 'p4' ] )
		self.__checkOrder( twoInserts(), removedP3Vec(), [ 'p1', 'p2', 'p5', 'p6', 'p4' ] )

	def testReversedBaseInsertions(self):
		# tests applying to reversed base vector
		self.__checkOrder( topInsert(), reversedBaseVec(), [ 'p5', 'p4', 'p3', 'p2', 'p1' ] )
		self.__checkOrder( doubleTopInsert(), reversedBaseVec(), [ 'p5', 'p6', 'p4', 'p3', 'p2', 'p1' ] )
		self.__checkOrder( bottomInsert(), reversedBaseVec(), [ 'p4', 'p5', 'p3', 'p2', 'p1' ] )
		self.__checkOrder( centerInsert(), reversedBaseVec(), [ 'p4', 'p3', 'p2', 'p5', 'p1' ] )
		self.__checkOrder( doubleCenterInsert(), reversedBaseVec(), [ 'p4', 'p3', 'p2', 'p5', 'p6', 'p1' ] )
		self.__checkOrder( twoInserts(), reversedBaseVec(), [ 'p4', 'p3', 'p6', 'p2', 'p5', 'p1' ] )

	def testDifferentInsertions(self):
		# tests applying to different classes but same names vector
		self.__checkOrder( topInsert(), differentClassesVec(), [ 'p5', 'p2', 'p1', 'p3' ] )
		self.__checkOrder( doubleTopInsert(), differentClassesVec(), [ 'p5', 'p6', 'p2', 'p1', 'p3' ] )
		self.__checkOrder( bottomInsert(), differentClassesVec(), [ 'p5', 'p2', 'p1', 'p3' ] )
		self.__checkOrder( centerInsert(), differentClassesVec(), [ 'p5', 'p2', 'p1', 'p3' ] )
		self.__checkOrder( doubleCenterInsert(), differentClassesVec(), [ 'p5', 'p6', 'p2', 'p1', 'p3' ] )
		self.__checkOrder( twoInserts(), differentClassesVec(), [ 'p5', 'p6', 'p2', 'p1', 'p3' ] )

	def testNameClashingInsertions(self):
		# tests applying to unrelated but with name clashing vector
		self.__checkOrder( topInsert(), nameclashingVec(), [ 'p0', 'p5', 'p6', 'p7' ] )
		self.__checkOrder( doubleTopInsert(), nameclashingVec(), [ 'p0', 'p1', 'p5', 'p6', 'p7' ] )
		self.__checkOrder( bottomInsert(), nameclashingVec(), [ 'p0', 'p5', 'p6', 'p7' ] )
		self.__checkOrder( centerInsert(), nameclashingVec(), [ 'p0', 'p5', 'p6', 'p7' ] )
		self.__checkOrder( doubleCenterInsert(), nameclashingVec(), [ 'p0', 'p1', 'p5', 'p6', 'p7' ] )
		self.__checkOrder( twoInserts(), nameclashingVec(), [ 'p0', 'p1', 'p5', 'p6', 'p7' ] )

	def testUnrelatedInsertions(self):
		# tests applying to unrelated vector
		self.__checkOrder( topInsert(), unrelatedVec(), [ 'p5', 'p10', 'p11', 'p12' ] )
		self.__checkOrder( doubleTopInsert(), unrelatedVec(), [ 'p5', 'p6', 'p10', 'p11', 'p12' ] )
		self.__checkOrder( bottomInsert(), unrelatedVec(), [ 'p5', 'p10', 'p11', 'p12' ] )
		self.__checkOrder( centerInsert(), unrelatedVec(), [ 'p5', 'p10', 'p11', 'p12' ] )
		self.__checkOrder( doubleCenterInsert(), unrelatedVec(), [ 'p5', 'p6', 'p10', 'p11', 'p12' ] )
		self.__checkOrder( twoInserts(), unrelatedVec(), [ 'p5', 'p6', 'p10', 'p11', 'p12' ] )

	def testLocalizedReordering(self):
		# simple localized reorder in place
		self.__checkOrder( switchP2andP4(), baseVec(), [ 'p1', 'p4', 'p3', 'p2' ] )

		# test reordering with unknown items in between.
		extendedBaseVec = createVec( [ ('p0','floatParameter'), ('p1','floatParameter'), ('p5','floatParameter'), ('p2','maths/multiply'), ('p6','floatParameter'), ('p3', 'compoundObjectInOut'), ('p7','floatParameter'), ('p4', 'floatParameter'), ('p8','floatParameter') ] )
		self.__checkOrder( switchP2andP4(), extendedBaseVec, [ 'p0', 'p1', 'p5', 'p4', 'p3', 'p7', 'p2', 'p6', 'p8' ] )

		# now we prove that changes in the order of originally unmodified parameters are not affected when we apply the preset
		invExtendedBaseVec = createVec( [ ('p8','floatParameter'), ('p2','maths/multiply'), ('p6','floatParameter'), ('p3', 'compoundObjectInOut'), ('p7','floatParameter'), ('p4', 'floatParameter'), ('p0','floatParameter'), ('p5','floatParameter'), ('p1','floatParameter') ] )
		self.__checkOrder( switchP2andP4(), invExtendedBaseVec, [ 'p8', 'p4', 'p3', 'p7', 'p2', 'p6', 'p0', 'p5', 'p1' ] )

def createVec( classes ) :
	testObj = IECore.ClassVectorParameter( "vec", "", "IECORE_OP_PATHS" )
	for (pName,cName) in classes :
		testObj.setClass( pName, cName, 1 )
	return testObj

# creating some shared data for the following tests....
def baseVec():
	return createVec( [ ('p1','floatParameter'), ('p2','maths/multiply'), ('p3', 'compoundObjectInOut'), ('p4', 'floatParameter') ] )

def switchP2andP4():
	return createVec( [ ('p1','floatParameter'), ('p4', 'floatParameter'), ('p3', 'compoundObjectInOut'), ('p2','maths/multiply') ] )

def topInsert():
	return createVec( [ ('p5','maths/multiply'), ('p1','floatParameter'), ('p2','maths/multiply'), ('p3', 'compoundObjectInOut'), ('p4', 'floatParameter') ] )

def doubleTopInsert():
	return createVec( [ ('p5','maths/multiply'), ('p6','maths/multiply'), ('p1','floatParameter'), ('p2','maths/multiply'), ('p3', 'compoundObjectInOut'), ('p4', 'floatParameter') ] )

def bottomInsert():
	return createVec( [ ('p1','floatParameter'), ('p2','maths/multiply'), ('p3', 'compoundObjectInOut'), ('p4', 'floatParameter'), ('p5','maths/multiply') ] )

def centerInsert():
	return createVec( [ ('p1','floatParameter'), ('p2','maths/multiply'), ('p5','maths/multiply'), ('p3', 'compoundObjectInOut'), ('p4', 'floatParameter') ] )

def doubleCenterInsert():
	return createVec( [ ('p1','floatParameter'), ('p2','maths/multiply'), ('p5','maths/multiply'), ('p6','maths/multiply'), ('p3', 'compoundObjectInOut'), ('p4', 'floatParameter') ] )

def twoInserts():
	return createVec( [ ('p1','floatParameter'), ('p2','maths/multiply'), ('p5','maths/multiply'), ('p3', 'compoundObjectInOut'), ('p6','maths/multiply'), ('p4', 'floatParameter') ] )

def removedP2Vec():
	return createVec( [ ('p1','floatParameter'), ('p3', 'compoundObjectInOut'), ('p4', 'floatParameter') ] )

def removedP3Vec():
	return createVec( [ ('p1','floatParameter'), ('p2','maths/multiply'), ('p4', 'floatParameter') ] )

def reversedBaseVec():
	return createVec( [ ('p4', 'floatParameter'), ('p3', 'compoundObjectInOut'), ('p2','maths/multiply'), ('p1','floatParameter') ] )

def emptyVec():
	return createVec( [] )

def differentClassesVec():
	return createVec( [ ('p2','floatParameter'), ('p1','maths/multiply'), ('p3', 'floatParameter') ] )

def nameclashingVec():
	return createVec( [ ('p5','maths/multiply'), ('p6','floatParameter'), ('p7', 'floatParameter')  ] )

def unrelatedVec():
	return createVec( [ ('p10','maths/multiply'), ('p11','floatParameter'), ('p12', 'floatParameter')  ] )

if __name__ == "__main__":
	unittest.main()


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.cosmos.implementation;

import com.azure.cosmos.BridgeInternal;
import com.azure.cosmos.CosmosException;
import com.azure.cosmos.implementation.directconnectivity.HttpUtils;
import com.azure.cosmos.implementation.http.HttpHeaders;

import java.net.URI;
import java.util.Map;

/**
 * The type Retry with exception.
 */
public class RetryWithException extends CosmosException {

    /**
     * Instantiates a new Retry with exception.
     *
     * @param cosmosError the cosmos error
     * @param lsn the lsn
     * @param partitionKeyRangeId the partition key range id
     * @param responseHeaders the response headers
     */
    public RetryWithException(CosmosError cosmosError, long lsn, String partitionKeyRangeId,
                              Map<String, String> responseHeaders) {
        super(HttpConstants.StatusCodes.RETRY_WITH, cosmosError, responseHeaders);
        BridgeInternal.setLSN(this, lsn);
        BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId);
    }

    RetryWithException(String message, URI requestUri) {
        this(message, null, null, requestUri);
    }

    RetryWithException(String message,
                       Exception innerException,
                       URI requestUri) {
        this(message, innerException, null, requestUri);
    }

    /**
     * Instantiates a new Retry with exception.
     *
     * @param message the message
     * @param headers the headers
     * @param requestUri the request uri
     */
    public RetryWithException(String message, HttpHeaders headers, URI requestUri) {
        super(message,
            null,
            HttpUtils.asMap(headers),
            HttpConstants.StatusCodes.RETRY_WITH,
            requestUri != null ? requestUri.toString() : null);
    }

    RetryWithException(String message, HttpHeaders headers, String requestUriString) {
        super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.RETRY_WITH, requestUriString);
    }

    RetryWithException(String message,
                       Exception innerException,
                       HttpHeaders headers,
                       URI requestUri) {
        super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.RETRY_WITH,
            requestUri != null ? requestUri.toString() : null);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.tapchatapp.android.client.message;

public final class BannedMessage extends BufferEventMessage {
    public static final String TYPE = "banned";
}


text:
package com.ibm.liberty.starter.service.persistence.api;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("api")
public class TechnologyAPI extends Application {

}


text:
'use strict';

var arrayCavaleiros = [];

function carregarDadosNaPagina() {
    $.ajax({ url: urlCavaleiroGet, type: 'GET' })
    .then(
        function onSuccess(res) {
            console.log(res.data);
            res.data.forEach(function (cava) {

                carregarCavaleiro(cava);

                arrayCavaleiros.push(cava.Id);
            });
        },
        function onError(res) {
            console.error(':(');
            console.error(res);

            var criarSpanComErro = function (msg) {
                return $('<span>').text(msg).addClass('erro');
            };

            $('#feedback')
            .append(criarSpanComErro(res.status))
            .append($('<br>'))
            .append(criarSpanComErro(res.statusText));
        }
    )
    .always(function (res) {
        console.log('acabouuuuuuuu');
    });
};
carregarDadosNaPagina();

function registrarEventoDoBotao() {
    $('#btnCriar').click(function () {

        $.ajax({
            url: urlCavaleiroPost,
            type: 'POST',
            data: {
                Nome: 'Xiru ' + new Date().getTime(),
                AlturaCm: 187,
                pesoLb: 220.423432,
                Signo: 7,
                TipoSanguineo: 1,
                DataNascimento: new Date(),
                Golpes: ['Cólera do Dragão', 'Cólera dos 100 dragões'],
                LocalNascimento: {
                    Texto: 'Beijing'
                },
                LocalTreinamento: {
                    Texto: '5 picos de rosan'
                },
                Imagens: [{
                    Url: 'http://images.uncyc.org/pt/3/37/Shiryumestrepokemon.jpg',
                    IsThumb: true
                }, {
                    Url: 'http://images.uncyc.org/pt/thumb/5/52/Shyryugyarados.jpg/160px-Shyryugyarados.jpg',
                    IsThumb: false
                }]
            }
        });

    });

    $('#btnNovoCavaleiro').click(function (e) {

        var formData = new FormData($('#frmNovoCavaleiro')[0]);

        var novasImagens = [];
        $('#novasImagens li').each(function (i) {
            novasImagens.push({
                url: $(this).find('input[name=urlImagem]').val(),
                isThumb: $(this).find('input[name=isThumb]').is(':checked')
            });
        });

        var novosGolpes = [];
        $('#novosGolpes li').each(function (i) {
            novosGolpes.push($(this).find('input[name=golpe]').val());
        });

        $.ajax({
            url: urlCavaleiroPost,
            type: 'POST',
            data: {
                Nome: formData.get('nome'),
                AlturaCm: parseFloat(formData.get('alturaMetros')) * 100,
                PesoLb: parseFloat(formData.get('pesoKg')) * 2.20462262,
                Signo: formData.get('signo'),
                TipoSanguineo: formData.get('tipoSanguineo'),
                DataNascimento: formData.get('dataNascimento'),
                Golpes: novosGolpes,
                LocalNascimento: {
                    Texto: formData.get('localNascimento')
                },
                LocalTreinamento: {
                    Texto: formData.get('localTreinamento')
                },
                Imagens: novasImagens
            }
        });

        $frmNovoCavaleiro[0].reset();
        e.preventDefault();
    });
};
registrarEventoDoBotao();

function obterThumb(cavaleiro) {
    // Pegando a primeira imagem que é thumbnail
    return cavaleiro.Imagens.filter(function (i) {
        return i.IsThumb==true;
    })[0];
};

function carregarCavaleiro(cavaleiro) {

    console.log(cavaleiro.Imagens);

    var imagem = obterThumb(cavaleiro) || { Url: 'https://i.ytimg.com/vi/trKzSiBOqt4/hqdefault.jpg' };

    $('#cavaleiros').append(
                    $('<li>').append($('<img>').attr('src', imagem.Url).addClass('imgCava')).append(cavaleiro.Nome)
                     .append($('<button>').text('Editar'))

                     .append($('<button>', { text: 'Excluir', click: function () { excluirCavaleiro(cavaleiro); } }))
                );
}

function excluirCavaleiro(cava) {

    $.ajax({ url: '/Cavaleiro/Delete', type: 'DELETE', data: { id: cava.Id } })
        .fail(function (res) { console.error(res); })
        .done(function(res) { console.log(res) });
};

function notificarNovosCavaleiros(numero) {
    Notification.requestPermission().then(function (result) {
        console.log(result);
        if (result === 'granted') {
            var plural = (numero === 1 ? '' : 's');
            var options = {
                body: numero + ' novo'+ plural +' cavaleiro' + plural + ' adicionado' + plural,
                icon: 'http://vignette1.wikia.nocookie.net/vsbattles/images/4/41/Seiya_Render_1.png/revision/latest?cb=20160227173402'
            }
            new Notification('', options);
        }
    });
};

$(document).ready(
            function () {
                setInterval(function () {
                    $.ajax({ url: urlCavaleiroGet, type: 'GET' })
                    .done(function (res) {
                        var cont = 0;
                        res.data.forEach(function (e) {
                            if($.inArray(e.Id,arrayCavaleiros) === -1)
                            {
                                carregarCavaleiro(e);

                                arrayCavaleiros.push(e.Id);
                                cont++;
                            }
                        });
                        if (cont != 0)notificarNovosCavaleiros(cont);
                    })
                }, 5000);
            });

$('#btnAdicionarGolpe').click(function () {
    var $novoTxt = $('<input>').attr('name', 'golpe').attr('type', 'text').attr('placeholder', 'Ex: Pó de diamante');
    $('#novosGolpes').append( $('<li>').append($novoTxt) );
});

$('#btnAdicionarImg').click(function () {
var $novoTxt = $('<input>').attr('name', 'urlImagem').attr('type', 'text').attr('placeholder', 'Ex: bit.ly/shiryu.png');
var $novoCheckbox =
  $('<label>').append(
    $('<input>')
    .attr('type', 'checkbox')
    .attr('name', 'isThumb')
    .attr('checked', 'checked')
  ).append('É thumbnail?');
$('#novasImagens').append( $('<li>').append($novoTxt).append($novoCheckbox));
});


text:
![Tasks API](https://www.google.com/images/icons/product/tasks-32.png)

# Unoffical Tasks API v1 Samples for .NET

## API Description

Lets you manage your tasks and task lists.

[Offical Documentation](https://developers.google.com/google-apps/tasks/firstapp)

## Sample Description

These samples show how to access the [Tasks API v1](https://developers.google.com/google-apps/tasks/firstapp) with the Offical [Google .Net client library](https://github.com/google/google-api-dotnet-client)

Tutorials to go along with some of these samples can be found on [www.daimto.com](http://www.daimto.com/)

## Developer Documentation

* [Google API client Library for .NET - Get Started](https://developers.google.com/api-client-library/dotnet/get_started)

* [Supported APIs](https://developers.google.com/api-client-library/dotnet/apis/)

### Installation

NuGet package:

Location: [NuGet Google.Apis.tasks.v1](https://www.nuget.org/packages/Google.Apis.tasks.v1)
Install Command: PM>  Install-Package Google.Apis.tasks.v1

```
PM> Install-Package Google.Apis.tasks.v1
```

### Usage

OAuth2
```
var keyFileLocation = @"C:\Users\Daimto\Documents\DaimtoTestEverythingCredentials\Diamto Test Everything Project-29e50502c19b.json";
var user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
var scopes = new String[] { Google.Apis.tasks.v1.tasksService.Scope.tasksReadonly };
var service = GoogleSamplecSharpSample.tasksv1.Auth.Oauth2Example.GettasksService(keyFileLocation, user, scopes);
```

Public API Key

```
var apiKey = "XXXX";
var servicePublicKey = GoogleSamplecSharpSample.tasksv1.Auth.ApiKeyExample.GetService(apiKey);
```

Service Account
```
var serviceAccountKeyFileLocation = @"C:\Users\Daimto\Documents\DaimtoTestEverythingCredentials\Diamto Test Everything Project-29e50502c19b.json";
var serviceAccountEmail = "googledrivemirrornas@daimto-tutorials-101.iam.gserviceaccount.com";
var scopes = new String[] { Google.Apis.tasks.v1.tasksService.Scope.Calendar };
var serviceAccountService = GoogleSamplecSharpSample.tasksv1.Auth.ServiceAccountExample.AuthenticateServiceAccount(serviceAccountKeyFileLocation, serviceAccountEmail, scopes);
```


text:
package expression

import (
	"github.com/pingcap/tidb/parser/mysql"
	"github.com/pingcap/tidb/parser/terror"
	"github.com/pingcap/tidb/types"
	"github.com/pingcap/tidb/util/chunk"
)

func (b *builtinAddDatetimeAndDurationSig) vecEvalTime(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	if err := b.args[0].VecEvalTime(b.ctx, input, result); err != nil {
		return err
	}
	buf0 := result

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalDuration(b.ctx, input, buf1); err != nil {
		return err
	}

	result.MergeNulls(buf1)

	arg0s := buf0.Times()

	arg1s := buf1.GoDurations()

	resultSlice := result.Times()

	for i := 0; i < n; i++ {

		if result.IsNull(i) {
			continue
		}

		// get arg0 & arg1

		arg0 := arg0s[i]

		arg1 := arg1s[i]

		// calculate

		output, err := arg0.Add(b.ctx.GetSessionVars().StmtCtx, types.Duration{Duration: arg1, Fsp: -1})

		if err != nil {
			return err
		}

		// commit result

		resultSlice[i] = output

	}
	return nil
}

func (b *builtinAddDatetimeAndDurationSig) vectorized() bool {
	return true
}

func (b *builtinAddDatetimeAndStringSig) vecEvalTime(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	if err := b.args[0].VecEvalTime(b.ctx, input, result); err != nil {
		return err
	}
	buf0 := result

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalString(b.ctx, input, buf1); err != nil {
		return err
	}

	result.MergeNulls(buf1)

	arg0s := buf0.Times()

	resultSlice := result.Times()

	for i := 0; i < n; i++ {

		if result.IsNull(i) {
			continue
		}

		// get arg0 & arg1

		arg0 := arg0s[i]

		arg1 := buf1.GetString(i)

		// calculate

		if !isDuration(arg1) {
			result.SetNull(i, true) // fixed: true
			continue
		}
		sc := b.ctx.GetSessionVars().StmtCtx
		arg1Duration, _, err := types.ParseDuration(sc, arg1, types.GetFsp(arg1))
		if err != nil {
			if terror.ErrorEqual(err, types.ErrTruncatedWrongVal) {
				sc.AppendWarning(err)
				result.SetNull(i, true) // fixed: true
				continue
			}
			return err
		}

		output, err := arg0.Add(sc, arg1Duration)

		if err != nil {
			return err
		}

		// commit result

		resultSlice[i] = output

	}
	return nil
}

func (b *builtinAddDatetimeAndStringSig) vectorized() bool {
	return true
}

func (b *builtinAddDurationAndDurationSig) vecEvalDuration(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	if err := b.args[0].VecEvalDuration(b.ctx, input, result); err != nil {
		return err
	}
	buf0 := result

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalDuration(b.ctx, input, buf1); err != nil {
		return err
	}

	result.MergeNulls(buf1)

	arg0s := buf0.GoDurations()

	arg1s := buf1.GoDurations()

	resultSlice := result.GoDurations()

	for i := 0; i < n; i++ {

		if result.IsNull(i) {
			continue
		}

		// get arg0 & arg1

		arg0 := arg0s[i]

		arg1 := arg1s[i]

		// calculate

		output, err := types.AddDuration(arg0, arg1)
		if err != nil {
			return err
		}

		// commit result

		resultSlice[i] = output

	}
	return nil
}

func (b *builtinAddDurationAndDurationSig) vectorized() bool {
	return true
}

func (b *builtinAddDurationAndStringSig) vecEvalDuration(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	if err := b.args[0].VecEvalDuration(b.ctx, input, result); err != nil {
		return err
	}
	buf0 := result

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalString(b.ctx, input, buf1); err != nil {
		return err
	}

	result.MergeNulls(buf1)

	arg0s := buf0.GoDurations()

	resultSlice := result.GoDurations()

	for i := 0; i < n; i++ {

		if result.IsNull(i) {
			continue
		}

		// get arg0 & arg1

		arg0 := arg0s[i]

		arg1 := buf1.GetString(i)

		// calculate

		if !isDuration(arg1) {
			result.SetNull(i, true) // fixed: true
			continue
		}
		sc := b.ctx.GetSessionVars().StmtCtx
		arg1Duration, _, err := types.ParseDuration(sc, arg1, types.GetFsp(arg1))
		if err != nil {
			if terror.ErrorEqual(err, types.ErrTruncatedWrongVal) {
				sc.AppendWarning(err)
				result.SetNull(i, true) // fixed: true
				continue
			}
			return err
		}

		output, err := types.AddDuration(arg0, arg1Duration.Duration)
		if err != nil {
			return err
		}

		// commit result

		resultSlice[i] = output

	}
	return nil
}

func (b *builtinAddDurationAndStringSig) vectorized() bool {
	return true
}

func (b *builtinAddStringAndDurationSig) vecEvalString(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	buf0, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf0)
	if err := b.args[0].VecEvalString(b.ctx, input, buf0); err != nil {
		return err
	}

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalDuration(b.ctx, input, buf1); err != nil {
		return err
	}

	result.ReserveString(n)

	arg1s := buf1.GoDurations()

	for i := 0; i < n; i++ {

		if buf0.IsNull(i) || buf1.IsNull(i) {
			result.AppendNull()
			continue
		}

		// get arg0 & arg1

		arg0 := buf0.GetString(i)

		arg1 := arg1s[i]

		// calculate

		sc := b.ctx.GetSessionVars().StmtCtx
		fsp1 := b.args[1].GetType().GetDecimal()
		arg1Duration := types.Duration{Duration: arg1, Fsp: fsp1}
		var output string
		var isNull bool
		if isDuration(arg0) {

			output, err = strDurationAddDuration(sc, arg0, arg1Duration)

			if err != nil {
				if terror.ErrorEqual(err, types.ErrTruncatedWrongVal) {
					sc.AppendWarning(err)
					result.AppendNull() // fixed: false
					continue
				}
				return err
			}
		} else {

			output, isNull, err = strDatetimeAddDuration(sc, arg0, arg1Duration)

			if err != nil {
				return err
			}
			if isNull {
				sc.AppendWarning(err)
				result.AppendNull() // fixed: false
				continue
			}
		}

		// commit result

		result.AppendString(output)

	}
	return nil
}

func (b *builtinAddStringAndDurationSig) vectorized() bool {
	return true
}

func (b *builtinAddStringAndStringSig) vecEvalString(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	buf0, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf0)
	if err := b.args[0].VecEvalString(b.ctx, input, buf0); err != nil {
		return err
	}

	arg1Type := b.args[1].GetType()
	if mysql.HasBinaryFlag(arg1Type.GetFlag()) {
		result.ReserveString(n)
		for i := 0; i < n; i++ {
			result.AppendNull()
		}
		return nil
	}

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalString(b.ctx, input, buf1); err != nil {
		return err
	}

	result.ReserveString(n)

	for i := 0; i < n; i++ {

		if buf0.IsNull(i) || buf1.IsNull(i) {
			result.AppendNull()
			continue
		}

		// get arg0 & arg1

		arg0 := buf0.GetString(i)

		arg1 := buf1.GetString(i)

		// calculate

		sc := b.ctx.GetSessionVars().StmtCtx
		arg1Duration, _, err := types.ParseDuration(sc, arg1, getFsp4TimeAddSub(arg1))
		if err != nil {
			if terror.ErrorEqual(err, types.ErrTruncatedWrongVal) {
				sc.AppendWarning(err)
				result.AppendNull() // fixed: false
				continue
			}
			return err
		}

		var output string
		var isNull bool
		if isDuration(arg0) {

			output, err = strDurationAddDuration(sc, arg0, arg1Duration)

			if err != nil {
				if terror.ErrorEqual(err, types.ErrTruncatedWrongVal) {
					sc.AppendWarning(err)
					result.AppendNull() // fixed: false
					continue
				}
				return err
			}
		} else {

			output, isNull, err = strDatetimeAddDuration(sc, arg0, arg1Duration)

			if err != nil {
				return err
			}
			if isNull {
				sc.AppendWarning(err)
				result.AppendNull() // fixed: false
				continue
			}
		}

		// commit result

		result.AppendString(output)

	}
	return nil
}

func (b *builtinAddStringAndStringSig) vectorized() bool {
	return true
}

func (b *builtinAddDateAndDurationSig) vecEvalString(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	buf0, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf0)
	if err := b.args[0].VecEvalDuration(b.ctx, input, buf0); err != nil {
		return err
	}

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalDuration(b.ctx, input, buf1); err != nil {
		return err
	}

	result.ReserveString(n)

	arg0s := buf0.GoDurations()

	arg1s := buf1.GoDurations()

	for i := 0; i < n; i++ {

		if buf0.IsNull(i) || buf1.IsNull(i) {
			result.AppendNull()
			continue
		}

		// get arg0 & arg1

		arg0 := arg0s[i]

		arg1 := arg1s[i]

		// calculate

		fsp0 := b.args[0].GetType().GetDecimal()
		fsp1 := b.args[1].GetType().GetDecimal()
		arg1Duration := types.Duration{Duration: arg1, Fsp: fsp1}

		sum, err := types.Duration{Duration: arg0, Fsp: fsp0}.Add(arg1Duration)

		if err != nil {
			return err
		}
		output := sum.String()

		// commit result

		result.AppendString(output)

	}
	return nil
}

func (b *builtinAddDateAndDurationSig) vectorized() bool {
	return true
}

func (b *builtinAddDateAndStringSig) vecEvalString(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	buf0, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf0)
	if err := b.args[0].VecEvalDuration(b.ctx, input, buf0); err != nil {
		return err
	}

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalString(b.ctx, input, buf1); err != nil {
		return err
	}

	result.ReserveString(n)

	arg0s := buf0.GoDurations()

	for i := 0; i < n; i++ {

		if buf0.IsNull(i) || buf1.IsNull(i) {
			result.AppendNull()
			continue
		}

		// get arg0 & arg1

		arg0 := arg0s[i]

		arg1 := buf1.GetString(i)

		// calculate

		if !isDuration(arg1) {
			result.AppendNull() // fixed: false
			continue
		}
		sc := b.ctx.GetSessionVars().StmtCtx
		arg1Duration, _, err := types.ParseDuration(sc, arg1, getFsp4TimeAddSub(arg1))
		if err != nil {
			if terror.ErrorEqual(err, types.ErrTruncatedWrongVal) {
				sc.AppendWarning(err)
				result.AppendNull() // fixed: false
				continue
			}
			return err
		}

		fsp0 := b.args[0].GetType().GetDecimal()

		sum, err := types.Duration{Duration: arg0, Fsp: fsp0}.Add(arg1Duration)

		if err != nil {
			return err
		}
		output := sum.String()

		// commit result

		result.AppendString(output)

	}
	return nil
}

func (b *builtinAddDateAndStringSig) vectorized() bool {
	return true
}

func (b *builtinAddTimeDateTimeNullSig) vecEvalTime(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	result.ResizeTime(n, true)

	return nil
}

func (b *builtinAddTimeDateTimeNullSig) vectorized() bool {
	return true
}

func (b *builtinAddTimeStringNullSig) vecEvalString(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	result.ReserveString(n)
	for i := 0; i < n; i++ {
		result.AppendNull()
	}

	return nil
}

func (b *builtinAddTimeStringNullSig) vectorized() bool {
	return true
}

func (b *builtinAddTimeDurationNullSig) vecEvalDuration(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	result.ResizeGoDuration(n, true)

	return nil
}

func (b *builtinAddTimeDurationNullSig) vectorized() bool {
	return true
}

func (b *builtinSubDatetimeAndDurationSig) vecEvalTime(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	if err := b.args[0].VecEvalTime(b.ctx, input, result); err != nil {
		return err
	}
	buf0 := result

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalDuration(b.ctx, input, buf1); err != nil {
		return err
	}

	result.MergeNulls(buf1)

	arg0s := buf0.Times()

	arg1s := buf1.GoDurations()

	resultSlice := result.Times()

	for i := 0; i < n; i++ {

		if result.IsNull(i) {
			continue
		}

		// get arg0 & arg1

		arg0 := arg0s[i]

		arg1 := arg1s[i]

		// calculate

		sc := b.ctx.GetSessionVars().StmtCtx
		arg1Duration := types.Duration{Duration: arg1, Fsp: -1}
		output, err := arg0.Add(sc, arg1Duration.Neg())

		if err != nil {
			return err
		}

		// commit result

		resultSlice[i] = output

	}
	return nil
}

func (b *builtinSubDatetimeAndDurationSig) vectorized() bool {
	return true
}

func (b *builtinSubDatetimeAndStringSig) vecEvalTime(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	if err := b.args[0].VecEvalTime(b.ctx, input, result); err != nil {
		return err
	}
	buf0 := result

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalString(b.ctx, input, buf1); err != nil {
		return err
	}

	result.MergeNulls(buf1)

	arg0s := buf0.Times()

	resultSlice := result.Times()

	for i := 0; i < n; i++ {

		if result.IsNull(i) {
			continue
		}

		// get arg0 & arg1

		arg0 := arg0s[i]

		arg1 := buf1.GetString(i)

		// calculate

		if !isDuration(arg1) {
			result.SetNull(i, true) // fixed: true
			continue
		}
		sc := b.ctx.GetSessionVars().StmtCtx
		arg1Duration, _, err := types.ParseDuration(sc, arg1, types.GetFsp(arg1))
		if err != nil {
			if terror.ErrorEqual(err, types.ErrTruncatedWrongVal) {
				sc.AppendWarning(err)
				result.SetNull(i, true) // fixed: true
				continue
			}
			return err
		}
		output, err := arg0.Add(sc, arg1Duration.Neg())

		if err != nil {
			return err
		}

		// commit result

		resultSlice[i] = output

	}
	return nil
}

func (b *builtinSubDatetimeAndStringSig) vectorized() bool {
	return true
}

func (b *builtinSubDurationAndDurationSig) vecEvalDuration(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	if err := b.args[0].VecEvalDuration(b.ctx, input, result); err != nil {
		return err
	}
	buf0 := result

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalDuration(b.ctx, input, buf1); err != nil {
		return err
	}

	result.MergeNulls(buf1)

	arg0s := buf0.GoDurations()

	arg1s := buf1.GoDurations()

	resultSlice := result.GoDurations()

	for i := 0; i < n; i++ {

		if result.IsNull(i) {
			continue
		}

		// get arg0 & arg1

		arg0 := arg0s[i]

		arg1 := arg1s[i]

		// calculate

		output, err := types.SubDuration(arg0, arg1)
		if err != nil {
			return err
		}

		// commit result

		resultSlice[i] = output

	}
	return nil
}

func (b *builtinSubDurationAndDurationSig) vectorized() bool {
	return true
}

func (b *builtinSubDurationAndStringSig) vecEvalDuration(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	if err := b.args[0].VecEvalDuration(b.ctx, input, result); err != nil {
		return err
	}
	buf0 := result

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalString(b.ctx, input, buf1); err != nil {
		return err
	}

	result.MergeNulls(buf1)

	arg0s := buf0.GoDurations()

	resultSlice := result.GoDurations()

	for i := 0; i < n; i++ {

		if result.IsNull(i) {
			continue
		}

		// get arg0 & arg1

		arg0 := arg0s[i]

		arg1 := buf1.GetString(i)

		// calculate

		if !isDuration(arg1) {
			result.SetNull(i, true) // fixed: true
			continue
		}
		sc := b.ctx.GetSessionVars().StmtCtx
		arg1Duration, _, err := types.ParseDuration(sc, arg1, types.GetFsp(arg1))
		if err != nil {
			if terror.ErrorEqual(err, types.ErrTruncatedWrongVal) {
				sc.AppendWarning(err)
				result.SetNull(i, true) // fixed: true
				continue
			}
			return err
		}

		output, err := types.SubDuration(arg0, arg1Duration.Duration)
		if err != nil {
			return err
		}

		// commit result

		resultSlice[i] = output

	}
	return nil
}

func (b *builtinSubDurationAndStringSig) vectorized() bool {
	return true
}

func (b *builtinSubStringAndDurationSig) vecEvalString(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	buf0, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf0)
	if err := b.args[0].VecEvalString(b.ctx, input, buf0); err != nil {
		return err
	}

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalDuration(b.ctx, input, buf1); err != nil {
		return err
	}

	result.ReserveString(n)

	arg1s := buf1.GoDurations()

	for i := 0; i < n; i++ {

		if buf0.IsNull(i) || buf1.IsNull(i) {
			result.AppendNull()
			continue
		}

		// get arg0 & arg1

		arg0 := buf0.GetString(i)

		arg1 := arg1s[i]

		// calculate

		sc := b.ctx.GetSessionVars().StmtCtx
		fsp1 := b.args[1].GetType().GetDecimal()
		arg1Duration := types.Duration{Duration: arg1, Fsp: fsp1}
		var output string
		var isNull bool
		if isDuration(arg0) {

			output, err = strDurationSubDuration(sc, arg0, arg1Duration)

			if err != nil {
				if terror.ErrorEqual(err, types.ErrTruncatedWrongVal) {
					sc.AppendWarning(err)
					result.AppendNull() // fixed: false
					continue
				}
				return err
			}
		} else {

			output, isNull, err = strDatetimeSubDuration(sc, arg0, arg1Duration)

			if err != nil {
				return err
			}
			if isNull {
				sc.AppendWarning(err)
				result.AppendNull() // fixed: false
				continue
			}
		}

		// commit result

		result.AppendString(output)

	}
	return nil
}

func (b *builtinSubStringAndDurationSig) vectorized() bool {
	return true
}

func (b *builtinSubStringAndStringSig) vecEvalString(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	buf0, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf0)
	if err := b.args[0].VecEvalString(b.ctx, input, buf0); err != nil {
		return err
	}

	arg1Type := b.args[1].GetType()
	if mysql.HasBinaryFlag(arg1Type.GetFlag()) {
		result.ReserveString(n)
		for i := 0; i < n; i++ {
			result.AppendNull()
		}
		return nil
	}

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalString(b.ctx, input, buf1); err != nil {
		return err
	}

	result.ReserveString(n)

	for i := 0; i < n; i++ {

		if buf0.IsNull(i) || buf1.IsNull(i) {
			result.AppendNull()
			continue
		}

		// get arg0 & arg1

		arg0 := buf0.GetString(i)

		arg1 := buf1.GetString(i)

		// calculate

		sc := b.ctx.GetSessionVars().StmtCtx
		arg1Duration, _, err := types.ParseDuration(sc, arg1, getFsp4TimeAddSub(arg1))
		if err != nil {
			if terror.ErrorEqual(err, types.ErrTruncatedWrongVal) {
				sc.AppendWarning(err)
				result.AppendNull() // fixed: false
				continue
			}
			return err
		}

		var output string
		var isNull bool
		if isDuration(arg0) {

			output, err = strDurationSubDuration(sc, arg0, arg1Duration)

			if err != nil {
				if terror.ErrorEqual(err, types.ErrTruncatedWrongVal) {
					sc.AppendWarning(err)
					result.AppendNull() // fixed: false
					continue
				}
				return err
			}
		} else {

			output, isNull, err = strDatetimeSubDuration(sc, arg0, arg1Duration)

			if err != nil {
				return err
			}
			if isNull {
				sc.AppendWarning(err)
				result.AppendNull() // fixed: false
				continue
			}
		}

		// commit result

		result.AppendString(output)

	}
	return nil
}

func (b *builtinSubStringAndStringSig) vectorized() bool {
	return true
}

func (b *builtinSubDateAndDurationSig) vecEvalString(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	buf0, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf0)
	if err := b.args[0].VecEvalDuration(b.ctx, input, buf0); err != nil {
		return err
	}

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalDuration(b.ctx, input, buf1); err != nil {
		return err
	}

	result.ReserveString(n)

	arg0s := buf0.GoDurations()

	arg1s := buf1.GoDurations()

	for i := 0; i < n; i++ {

		if buf0.IsNull(i) || buf1.IsNull(i) {
			result.AppendNull()
			continue
		}

		// get arg0 & arg1

		arg0 := arg0s[i]

		arg1 := arg1s[i]

		// calculate

		fsp0 := b.args[0].GetType().GetDecimal()
		fsp1 := b.args[1].GetType().GetDecimal()
		arg1Duration := types.Duration{Duration: arg1, Fsp: fsp1}

		sum, err := types.Duration{Duration: arg0, Fsp: fsp0}.Sub(arg1Duration)

		if err != nil {
			return err
		}
		output := sum.String()

		// commit result

		result.AppendString(output)

	}
	return nil
}

func (b *builtinSubDateAndDurationSig) vectorized() bool {
	return true
}

func (b *builtinSubDateAndStringSig) vecEvalString(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	buf0, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf0)
	if err := b.args[0].VecEvalDuration(b.ctx, input, buf0); err != nil {
		return err
	}

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)
	if err := b.args[1].VecEvalString(b.ctx, input, buf1); err != nil {
		return err
	}

	result.ReserveString(n)

	arg0s := buf0.GoDurations()

	for i := 0; i < n; i++ {

		if buf0.IsNull(i) || buf1.IsNull(i) {
			result.AppendNull()
			continue
		}

		// get arg0 & arg1

		arg0 := arg0s[i]

		arg1 := buf1.GetString(i)

		// calculate

		if !isDuration(arg1) {
			result.AppendNull() // fixed: false
			continue
		}
		sc := b.ctx.GetSessionVars().StmtCtx
		arg1Duration, _, err := types.ParseDuration(sc, arg1, getFsp4TimeAddSub(arg1))
		if err != nil {
			if terror.ErrorEqual(err, types.ErrTruncatedWrongVal) {
				sc.AppendWarning(err)
				result.AppendNull() // fixed: false
				continue
			}
			return err
		}

		fsp0 := b.args[0].GetType().GetDecimal()

		sum, err := types.Duration{Duration: arg0, Fsp: fsp0}.Sub(arg1Duration)

		if err != nil {
			return err
		}
		output := sum.String()

		// commit result

		result.AppendString(output)

	}
	return nil
}

func (b *builtinSubDateAndStringSig) vectorized() bool {
	return true
}

func (b *builtinSubTimeDateTimeNullSig) vecEvalTime(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	result.ResizeTime(n, true)

	return nil
}

func (b *builtinSubTimeDateTimeNullSig) vectorized() bool {
	return true
}

func (b *builtinSubTimeStringNullSig) vecEvalString(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	result.ReserveString(n)
	for i := 0; i < n; i++ {
		result.AppendNull()
	}

	return nil
}

func (b *builtinSubTimeStringNullSig) vectorized() bool {
	return true
}

func (b *builtinSubTimeDurationNullSig) vecEvalDuration(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()

	result.ResizeGoDuration(n, true)

	return nil
}

func (b *builtinSubTimeDurationNullSig) vectorized() bool {
	return true
}

func (b *builtinNullTimeDiffSig) vecEvalDuration(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()
	result.ResizeGoDuration(n, true)
	return nil
}

func (b *builtinNullTimeDiffSig) vectorized() bool {
	return true
}

func (b *builtinTimeStringTimeDiffSig) vecEvalDuration(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()
	result.ResizeGoDuration(n, false)
	r64s := result.GoDurations()
	buf0, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf0)

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)

	if err := b.args[0].VecEvalTime(b.ctx, input, buf0); err != nil {
		return err
	}
	if err := b.args[1].VecEvalString(b.ctx, input, buf1); err != nil {
		return err
	}

	result.MergeNulls(buf0, buf1)
	arg0 := buf0.Times()
	stmtCtx := b.ctx.GetSessionVars().StmtCtx
	for i := 0; i < n; i++ {
		if result.IsNull(i) {
			continue
		}
		lhsTime := arg0[i]
		_, rhsTime, rhsIsDuration, err := convertStringToDuration(stmtCtx, buf1.GetString(i), b.tp.GetDecimal())
		if err != nil {
			return err
		}
		if rhsIsDuration {
			result.SetNull(i, true)
			continue
		}
		d, isNull, err := calculateTimeDiff(stmtCtx, lhsTime, rhsTime)
		if err != nil {
			return err
		}
		if isNull {
			result.SetNull(i, true)
			continue
		}
		r64s[i] = d.Duration
	}
	return nil
}

func (b *builtinTimeStringTimeDiffSig) vectorized() bool {
	return true
}

func (b *builtinDurationStringTimeDiffSig) vecEvalDuration(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()
	result.ResizeGoDuration(n, false)
	r64s := result.GoDurations()
	buf0 := result
	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)

	if err := b.args[0].VecEvalDuration(b.ctx, input, buf0); err != nil {
		return err
	}
	if err := b.args[1].VecEvalString(b.ctx, input, buf1); err != nil {
		return err
	}

	result.MergeNulls(buf1)
	arg0 := buf0.GoDurations()
	var (
		lhs types.Duration
		rhs types.Duration
	)
	stmtCtx := b.ctx.GetSessionVars().StmtCtx
	for i := 0; i < n; i++ {
		if result.IsNull(i) {
			continue
		}
		lhs.Duration = arg0[i]
		rhsDur, _, rhsIsDuration, err := convertStringToDuration(stmtCtx, buf1.GetString(i), b.tp.GetDecimal())
		if err != nil {
			return err
		}
		if !rhsIsDuration {
			result.SetNull(i, true)
			continue
		}
		rhs = rhsDur
		d, isNull, err := calculateDurationTimeDiff(b.ctx, lhs, rhs)
		if err != nil {
			return err
		}
		if isNull {
			result.SetNull(i, true)
			continue
		}
		r64s[i] = d.Duration
	}
	return nil
}

func (b *builtinDurationStringTimeDiffSig) vectorized() bool {
	return true
}

func (b *builtinDurationDurationTimeDiffSig) vecEvalDuration(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()
	result.ResizeGoDuration(n, false)
	r64s := result.GoDurations()
	buf0 := result
	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)

	if err := b.args[0].VecEvalDuration(b.ctx, input, buf0); err != nil {
		return err
	}
	if err := b.args[1].VecEvalDuration(b.ctx, input, buf1); err != nil {
		return err
	}

	result.MergeNulls(buf1)
	arg0 := buf0.GoDurations()
	arg1 := buf1.GoDurations()
	var (
		lhs types.Duration
		rhs types.Duration
	)
	for i := 0; i < n; i++ {
		if result.IsNull(i) {
			continue
		}
		lhs.Duration = arg0[i]
		rhs.Duration = arg1[i]
		d, isNull, err := calculateDurationTimeDiff(b.ctx, lhs, rhs)
		if err != nil {
			return err
		}
		if isNull {
			result.SetNull(i, true)
			continue
		}
		r64s[i] = d.Duration
	}
	return nil
}

func (b *builtinDurationDurationTimeDiffSig) vectorized() bool {
	return true
}

func (b *builtinStringTimeTimeDiffSig) vecEvalDuration(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()
	result.ResizeGoDuration(n, false)
	r64s := result.GoDurations()
	buf0, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf0)

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)

	if err := b.args[0].VecEvalString(b.ctx, input, buf0); err != nil {
		return err
	}
	if err := b.args[1].VecEvalTime(b.ctx, input, buf1); err != nil {
		return err
	}

	result.MergeNulls(buf0, buf1)
	arg1 := buf1.Times()
	stmtCtx := b.ctx.GetSessionVars().StmtCtx
	for i := 0; i < n; i++ {
		if result.IsNull(i) {
			continue
		}
		_, lhsTime, lhsIsDuration, err := convertStringToDuration(stmtCtx, buf0.GetString(i), b.tp.GetDecimal())
		if err != nil {
			return err
		}
		if lhsIsDuration {
			result.SetNull(i, true)
			continue
		}
		rhsTime := arg1[i]
		d, isNull, err := calculateTimeDiff(stmtCtx, lhsTime, rhsTime)
		if err != nil {
			return err
		}
		if isNull {
			result.SetNull(i, true)
			continue
		}
		r64s[i] = d.Duration
	}
	return nil
}

func (b *builtinStringTimeTimeDiffSig) vectorized() bool {
	return true
}

func (b *builtinStringDurationTimeDiffSig) vecEvalDuration(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()
	result.ResizeGoDuration(n, false)
	r64s := result.GoDurations()
	buf1 := result
	buf0, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf0)

	if err := b.args[0].VecEvalString(b.ctx, input, buf0); err != nil {
		return err
	}
	if err := b.args[1].VecEvalDuration(b.ctx, input, buf1); err != nil {
		return err
	}

	result.MergeNulls(buf0)
	arg1 := buf1.GoDurations()
	var (
		lhs types.Duration
		rhs types.Duration
	)
	stmtCtx := b.ctx.GetSessionVars().StmtCtx
	for i := 0; i < n; i++ {
		if result.IsNull(i) {
			continue
		}
		lhsDur, _, lhsIsDuration, err := convertStringToDuration(stmtCtx, buf0.GetString(i), b.tp.GetDecimal())
		if err != nil {
			return err
		}
		if !lhsIsDuration {
			result.SetNull(i, true)
			continue
		}
		lhs = lhsDur
		rhs.Duration = arg1[i]
		d, isNull, err := calculateDurationTimeDiff(b.ctx, lhs, rhs)
		if err != nil {
			return err
		}
		if isNull {
			result.SetNull(i, true)
			continue
		}
		r64s[i] = d.Duration
	}
	return nil
}

func (b *builtinStringDurationTimeDiffSig) vectorized() bool {
	return true
}

func (b *builtinStringStringTimeDiffSig) vecEvalDuration(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()
	result.ResizeGoDuration(n, false)
	r64s := result.GoDurations()
	buf0, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf0)

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)

	if err := b.args[0].VecEvalString(b.ctx, input, buf0); err != nil {
		return err
	}
	if err := b.args[1].VecEvalString(b.ctx, input, buf1); err != nil {
		return err
	}

	result.MergeNulls(buf0, buf1)
	stmtCtx := b.ctx.GetSessionVars().StmtCtx
	for i := 0; i < n; i++ {
		if result.IsNull(i) {
			continue
		}
		lhsDur, lhsTime, lhsIsDuration, err := convertStringToDuration(stmtCtx, buf0.GetString(i), b.tp.GetDecimal())
		if err != nil {
			return err
		}
		rhsDur, rhsTime, rhsIsDuration, err := convertStringToDuration(stmtCtx, buf1.GetString(i), b.tp.GetDecimal())
		if err != nil {
			return err
		}
		if lhsIsDuration != rhsIsDuration {
			result.SetNull(i, true)
			continue
		}
		var (
			d      types.Duration
			isNull bool
		)
		if lhsIsDuration {
			d, isNull, err = calculateDurationTimeDiff(b.ctx, lhsDur, rhsDur)
		} else {
			d, isNull, err = calculateTimeDiff(stmtCtx, lhsTime, rhsTime)
		}
		if err != nil {
			return err
		}
		if isNull {
			result.SetNull(i, true)
			continue
		}
		r64s[i] = d.Duration
	}
	return nil
}

func (b *builtinStringStringTimeDiffSig) vectorized() bool {
	return true
}

func (b *builtinTimeTimeTimeDiffSig) vecEvalDuration(input *chunk.Chunk, result *chunk.Column) error {
	n := input.NumRows()
	result.ResizeGoDuration(n, false)
	r64s := result.GoDurations()
	buf0, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf0)

	buf1, err := b.bufAllocator.get()
	if err != nil {
		return err
	}
	defer b.bufAllocator.put(buf1)

	if err := b.args[0].VecEvalTime(b.ctx, input, buf0); err != nil {
		return err
	}
	if err := b.args[1].VecEvalTime(b.ctx, input, buf1); err != nil {
		return err
	}

	result.MergeNulls(buf0, buf1)
	arg0 := buf0.Times()
	arg1 := buf1.Times()
	stmtCtx := b.ctx.GetSessionVars().StmtCtx
	for i := 0; i < n; i++ {
		if result.IsNull(i) {
			continue
		}
		lhsTime := arg0[i]
		rhsTime := arg1[i]
		d, isNull, err := calculateTimeDiff(stmtCtx, lhsTime, rhsTime)
		if err != nil {
			return err
		}
		if isNull {
			result.SetNull(i, true)
			continue
		}
		r64s[i] = d.Duration
	}
	return nil
}

func (b *builtinTimeTimeTimeDiffSig) vectorized() bool {
	return true
}


text:
[![Latest Stable Version](https://poser.pugx.org/facile-it/doctrine-mysql-come-back/v/stable.svg)](https://packagist.org/packages/facile-it/doctrine-mysql-come-back)
[![Latest Unstable Version](https://poser.pugx.org/facile-it/doctrine-mysql-come-back/v/unstable.svg)](https://packagist.org/packages/facile-it/doctrine-mysql-come-back)
[![Total Downloads](https://poser.pugx.org/facile-it/doctrine-mysql-come-back/downloads.svg)](https://packagist.org/packages/facile-it/doctrine-mysql-come-back)

[![Build status](https://github.com/facile-it/doctrine-mysql-come-back/workflows/Continuous%20Integration/badge.svg)]( https://github.com/facile-it/doctrine-mysql-come-back/actions?query=workflow%3A%22Continuous+Integration%22+branch%3Amaster)
[![Test coverage](https://codecov.io/gh/facile-it/doctrine-mysql-come-back/branch/master/graph/badge.svg?token=vFz9cWGQ3r)](https://codecov.io/gh/facile-it/doctrine-mysql-come-back)

[![License](https://poser.pugx.org/facile-it/doctrine-mysql-come-back/license.svg)](https://packagist.org/packages/facile-it/doctrine-mysql-come-back)
# DoctrineMySQLComeBack

Auto reconnect on Doctrine MySql has gone away exceptions on `doctrine/dbal`.

# Installation

If you're using DBAL 3
```console
$ composer require facile-it/doctrine-mysql-come-back ^2.0
```

If you're using DBAL `^2.3`
```console
$ composer require facile-it/doctrine-mysql-come-back ^1.0
```

# Configuration

In order to use DoctrineMySQLComeBack you have to set the `wrapperClass` connection parameter.
You can choose how many times Doctrine should be able to reconnect, setting `x_reconnect_attempts` driver option. Its value should be an int.

If you're using DBAL v2, you also need to set the `driverClass` parameter too; please refer to the [previous version of this readme](https://github.com/facile-it/doctrine-mysql-come-back/blob/1.10.1/README.md#configuration) for that.

An example of configuration at connection instantiation time:

```php
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\DriverManager;

$config = new Configuration();

//..

$connectionParams = array(
    'dbname' => 'mydb',
    'user' => 'user',
    'password' => 'secret',
    'host' => 'localhost',
    // [doctrine-mysql-come-back] settings
    'wrapperClass' => 'Facile\DoctrineMySQLComeBack\Doctrine\DBAL\Connection',
    'driverClass' => 'Facile\DoctrineMySQLComeBack\Doctrine\DBAL\Driver\PDO\MySQL\Driver',
    'driverOptions' => array(
        'x_reconnect_attempts' => 3
    )
);

$conn = DriverManager::getConnection($connectionParams, $config);

//..
```

An example of yaml configuration on Symfony projects:

```yaml
doctrine:
    dbal:
        connections:
            default:
                # DATABASE_URL would be of "mysql://db_user:db_password@127.0.0.1:3306/db_name"
                url: '%env(resolve:DATABASE_URL)%'
                wrapper_class: 'Facile\DoctrineMySQLComeBack\Doctrine\DBAL\Connection'
                options:
                    x_reconnect_attempts: 3
```

An example of configuration on Laminas Framework 2projects:

```php
return [
    'doctrine' => [
        'connection' => [
            'orm_default' => [
                'wrapperClass' => \Facile\DoctrineMySQLComeBack\Doctrine\DBAL\Connection::class,
                'params' => [
                    'host' => 'localhost',
                    'port' => '3307',
                    'user' => '##user##',
                    'password' => '##password##',
                    'dbname' => '##database##',
                    'charset' => 'UTF8',
                    'driverOptions' => [
                        'x_reconnect_attempts' => 9,
                    ]
                ],
            ],
        ],
    ],
];
```

You can use wrapper class `Facile\DoctrineMySQLComeBack\Doctrine\DBAL\Connections\MasterSlaveConnection` if you are using master / slave Doctrine configuration.

# Usage

Since DBAL v3, `Connection::refresh` does not exist anymore, so you don't need to do anything else to leverage the reconnection, it will be automagically done.

From `v1.6` of this library automagically reconnection is enabled also during `$em->getConnection()->beginTransaction()` calls,
and this works also during simple `$em->flush()`, if out of a previous transaction.

# Thanks
Thanks to Dieter Peeters and his proposal on [DBAL-275](https://github.com/doctrine/dbal/issues/1454).
Check it out if you are using doctrine/dbal <2.3.


text:
package org.deploymentobjects.core.domain.model.execution;

import org.deploymentobjects.core.domain.model.environment.Environment;
import org.deploymentobjects.core.domain.model.environment.EnvironmentRepository;
import org.deploymentobjects.core.domain.shared.EventPublisher;
import org.deploymentobjects.core.domain.shared.DomainEvent.EventType;

public class PersistStep extends Executable {

	private EnvironmentRepository repository;
	private EventPublisher publisher;
	private Environment environment;

	public PersistStep(EnvironmentRepository repository,
			EventPublisher publisher, Environment environment) {
		this.repository = repository;
		this.publisher = publisher;
		this.environment = environment;
	}

	public enum PersistEvent implements EventType {
		PERSIST_COMPLETED
	}

	@Override
	public ExitCode execute() {
		repository.save(environment);
		StepExecutionEvent event = new StepExecutionEvent(
				PersistEvent.PERSIST_COMPLETED, this);
		publisher.publish(event);
		return ExitCode.SUCCESS;

	}
	public String toString(){
		return "persist!!";
	}

}


text:
<?php
if(!empty($_GET['user']) ) {
	$user_search = get_row($q="select avatar, user_text, last_login, gname, p_respect, g_name from usr inner join players on p_usr_id = usr_id left join gangs on p_gang_id = g_id where gname ='".mysql_real_escape_string(trim($_GET['user']))."'");
	if(!empty($user_search)){
		$user_search->last_login = date("d m Y",$user_search->last_login - 3600);
	}
} else $msg = 'błędne dane';
?>


text:
Your browser's Javascript functionality is turned off. Please turn it on so that you can experience the full capabilities of this site.

My Account

Home

                              /

My Account

Create Account

                              <form action="https://shop.diesel.com/signup?dwcont=C651836531" method="post" id="RegistrationForm">
                                 <fieldset>
                                    <input type="text" style="display: none" />
                                    <input type="password" style="display: none" />

                                       Email*

                                       <input  class="input-text email required" autocomplete="off" id="dwfrm_profile_customer_email" type="text" name="dwfrm_profile_customer_email" value=""  maxlength="50"/>

                                       Confirm Email*

                                       <input  class="input-text email required" autocomplete="off" id="dwfrm_profile_customer_emailconfirm" type="text" name="dwfrm_profile_customer_emailconfirm" value=""  maxlength="50"/>

                                       Password*

                                       <input  autocomplete="off" class="input-text-pw required" id="dwfrm_profile_login_password" type="password" name="dwfrm_profile_login_password" value=""  maxlength="20"/>

                                          8 - 20 characters

                                       Confirm Password*

                                       <input  autocomplete="off" class="input-text-pw required" id="dwfrm_profile_login_passwordconfirm" type="password" name="dwfrm_profile_login_passwordconfirm" value=""  maxlength="20"/>

                                       First Name*

                                       <input  class="input-text required" autocomplete="off" id="dwfrm_profile_customer_firstname" type="text" name="dwfrm_profile_customer_firstname" value=""  maxlength="50"/>

                                       Last Name*

                                       <input  class="input-text required" autocomplete="off" id="dwfrm_profile_customer_lastname" type="text" name="dwfrm_profile_customer_lastname" value=""  maxlength="50"/>

                                       Date of Birth*

                                       <input  class="input-text datepicker account-dob" autocomplete="off" id="dwfrm_profile_customer_birthday" type="text" name="dwfrm_profile_customer_birthday" value=""  maxlength="10"/>

                                          Gender

                                          <select class="input-select  gender-dropdown" id="dwfrm_profile_customer_customergender" name="dwfrm_profile_customer_customergender" >
                                             <option class="select-option" label="Male" value="1">Male</option>
                                             <option class="select-option" label="Female" value="2">Female</option>
                                          </select>

                                       Zip Code*

                                          <input  class="input-text zip-code postalCode account-zip" autocomplete="off" id="dwfrm_profile_customer_zip" type="text" name="dwfrm_profile_customer_zip" value=""  maxlength="10"/>

                                 </fieldset>

                                       <input class="input-checkbox" type="checkbox" name="dwfrm_profile_customer_privacypolicy" id="dwfrm_profile_customer_privacypolicy" value="true"  data-checkbox="main"/>

                                    I have read and understood the  Privacy Notice about the processing of my personal data by Diesel USA and DIESEL S.p.A., and I agree to its collection for marketing purposes (newsletters, news and promotions) and profiling.
If you would like to choose a partial consent option, please click here.

                                       <input class="input-checkbox" type="checkbox" checked="checked" name="dwfrm_profile_customer_acceptnewsletters" id="dwfrm_profile_customer_acceptnewsletters" value="true"  data-checkbox="subscription"/>
                                       I agree to the processing of my personal data to send me news and general promotions from Diesel USA and DIESEL S.p.A. through newsletters.

                                       <input class="input-checkbox" type="checkbox" checked="checked" name="dwfrm_profile_customer_addtoemaillist" id="dwfrm_profile_customer_addtoemaillist" value="true"  data-checkbox="subscription"/>
                                       I agree to the processing of my personal data for profiling in order to send me personalised communications and promotions from Diesel USA and DIESEL S.p.A.

                                    <button type="submit" value="Apply" name="dwfrm_profile_confirm">
                                    Apply
                                    </button>

                                 <input type="hidden" name="dwfrm_profile_securekey" value="617179477"/>
                              </form>

Secondary Navigation

                                          Shop Confidently

Privacy Policy

Secure Shopping

Need Help?

If you have any question or need help with your account,
you may Contact Us to assist you.

Customer Service

customerservice@shop.diesel.com

                                    877-344-8342

                                    8:00 AM ET to 12:00 AM ET, 7-days a week.


text:
namespace UnitTestProject1.Domain
{
    public class TestClass
    {
        public TestClass(int value)
        {

        }
    }
}


text:
package org.hyperimage.client.ws;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java-Klasse für adminGetUserByUserName complex type.
 *
 *
Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
 *
 *

 * <complexType name="adminGetUserByUserName">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="userName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "adminGetUserByUserName", propOrder = {
    "userName"
})
public class AdminGetUserByUserName {

    protected String userName;

    /**
     * Ruft den Wert der userName-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getUserName() {
        return userName;
    }

    /**
     * Legt den Wert der userName-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setUserName(String value) {
        this.userName = value;
    }

}


text:
'use strict';

module.exports = [{
  method: 'GET',
  path: '/api/gist/{id}',
  config: {
    handler: require('../controllers/gist'),
    description: 'API to get gists from github and return the data',
    notes: 'This is a clever note',
    tags: ['api', 'gist']
  }
}];


text:
namespace Microsoft.Web.Mvc.Test {
    using System.Collections.Generic;
    using System.Globalization;
    using System.Web.Mvc;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Microsoft.Web.Mvc;
    using Moq;

    [TestClass]
    public class ExpressionInputExtensionsTest {
        [TestMethod]
        public void TextboxForWithExpressionRendersInputTagUsingExpression() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary(new Product { ProductName = "ASP.NET MVC" });
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);

            // Act
            string result = htmlHelper.TextBoxFor(p => p.ProductName);

            // Assert
            Assert.AreEqual("<input id=\"ProductName\" name=\"ProductName\" type=\"text\" value=\"ASP.NET MVC\" />", result);
        }

        [TestMethod]
        public void TextboxForWithExpressionRendersInputTagUsingExpressionUsingValueFromModelState() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary(new Product { ProductName = "ASP.NET MVC" });
            viewData.ModelState.SetModelValue("ProductName", new ValueProviderResult("Something Else", "Something Else", CultureInfo.InvariantCulture));
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);

            // Act
            string result = htmlHelper.TextBoxFor(p => p.ProductName);

            // Assert
            Assert.AreEqual("<input id=\"ProductName\" name=\"ProductName\" type=\"text\" value=\"Something Else\" />", result);
        }

        [TestMethod]
        public void TextboxForWithExpressionRendersInputTagUsingExpressionUsingValueFromViewState() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary();
            Product productInViewData = new Product { ProductName = "Something Else" };
            viewData["ProductName"] = "Not Something Else";
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);

            // Act
            string result = htmlHelper.TextBoxFor(p => p.ProductName);

            // Assert
            Assert.AreEqual("<input id=\"ProductName\" name=\"ProductName\" type=\"text\" value=\"Not Something Else\" />", result);
        }

        [TestMethod]
        public void TextboxForWithExpressionRendersInputTagUsingExpressionWithIntProperty() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary(new Product { Id = 123 });
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);

            // Act
            string result = htmlHelper.TextBoxFor(p => p.Id);

            // Assert
            Assert.AreEqual("<input id=\"Id\" name=\"Id\" type=\"text\" value=\"123\" />", result);
        }

        [TestMethod]
        public void TextboxForWithExpressionContainingMethodCallRendersInputTagUsingExpressionProperty() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary(new Product { Id = 123 });
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);

            // Act
            string result = htmlHelper.TextBoxFor(p => p.Id.ToString());

            // Assert
            Assert.AreEqual("<input id=\"Id\" name=\"Id\" type=\"text\" value=\"123\" />", result);
        }

        [TestMethod]
        public void TextboxForWithAttributesAndExpressionRendersAttributes() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary(new Product { ProductName = "ASP.NET MVC" });
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);

            // Act
            string result = htmlHelper.TextBoxFor(p => p.ProductName, new { width = 123, maxlength = 99 });

            // Assert
            Assert.AreEqual("<input id=\"ProductName\" maxlength=\"99\" name=\"ProductName\" type=\"text\" value=\"ASP.NET MVC\" width=\"123\" />", result);
        }

        [TestMethod]
        public void HiddenForWithExpressionRendersInputTagUsingExpression() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary(new Product { ProductName = "ASP.NET MVC" });
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);

            // Act
            string result = htmlHelper.HiddenFor(p => p.ProductName);

            // Assert
            Assert.AreEqual("<input id=\"ProductName\" name=\"ProductName\" type=\"hidden\" value=\"ASP.NET MVC\" />", result);
        }

        [TestMethod]
        public void HiddenForWithExpressionRendersInputTagUsingExpressionUsingValueFromModelState() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary(new Product { ProductName = "ASP.NET MVC" });
            viewData.ModelState.SetModelValue("ProductName", new ValueProviderResult("Something Else", "Something Else", CultureInfo.InvariantCulture));
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);

            // Act
            string result = htmlHelper.HiddenFor(p => p.ProductName);

            // Assert
            Assert.AreEqual("<input id=\"ProductName\" name=\"ProductName\" type=\"hidden\" value=\"Something Else\" />", result);
        }

        [TestMethod]
        public void HiddenForWithAttributesAndExpressionRendersAttributes() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary(new Product { ProductName = "ASP.NET MVC" });
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);

            // Act
            string result = htmlHelper.HiddenFor(p => p.ProductName, new { @class = "test-css-class" });

            // Assert
            Assert.AreEqual("<input class=\"test-css-class\" id=\"ProductName\" name=\"ProductName\" type=\"hidden\" value=\"ASP.NET MVC\" />", result);
        }

        [TestMethod]
        public void DropDownListSelectListItemWithSelectedTrueSelectedAttribute() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary(new Product { ProductName = null });
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);
            IList<SelectListItem> selectList = new List<SelectListItem>();
            selectList.Add(new SelectListItem { Text = "option 1", Value = "option_1", Selected=true });
            selectList.Add(new SelectListItem { Text = "option 2", Value = "option_2", Selected=false });

            // Act
            string result = htmlHelper.DropDownListFor(p => p.ProductName, selectList);

            // Assert
            Assert.AreEqual(@"<select id=""ProductName"" name=""ProductName""><option selected=""selected"" value=""option_1"">option 1</option>
<option value=""option_2"">option 2</option>
</select>", result);
        }

        [TestMethod]
        public void DropDownListWithOptionLabelAndSelectedIdInModelStateRendersSelectedOption() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary(new Product { CategoryId = 2 });
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);
            IList<SelectListItem> selectList = new List<SelectListItem>();
            selectList.Add(new SelectListItem { Text = "option 1", Value = "1"});
            selectList.Add(new SelectListItem { Text = "option 2", Value = "2"});

            // Act
            string result = htmlHelper.DropDownListFor(p => p.CategoryId, selectList, "Select One");

            // Assert
            Assert.AreEqual(@"<select id=""CategoryId"" name=""CategoryId""><option value="""">Select One</option>
<option value=""1"">option 1</option>
<option selected=""selected"" value=""2"">option 2</option>
</select>", result);
        }

        [TestMethod]
        public void DropDownListForWithAttributesAndExpressionRendersOptionsAndAttributes() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary(new Product { CategoryId = 123 });
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);
            IList<SelectListItem> selectList = new List<SelectListItem>();
            selectList.Add(new SelectListItem { Text = "option 1", Value= "1", Selected= false });
            selectList.Add(new SelectListItem { Text = "option 2", Value = "2", Selected = false });

            // Act
            string result = htmlHelper.DropDownListFor(p => p.CategoryId, selectList, new { @class = "test-css-class" });

            // Assert
            Assert.AreEqual(@"<select class=""test-css-class"" id=""CategoryId"" name=""CategoryId""><option value=""1"">option 1</option>
<option value=""2"">option 2</option>
</select>", result);
        }

        [TestMethod]
        public void ValidationMessageForWithNoErrorReturnsNull() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary(new Product());
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);

            // Act
            string html = htmlHelper.ValidationMessageFor(p => p.ProductName);

            // Assert
            Assert.IsNull(html);
        }

        [TestMethod]
        public void ValidationMessageForDisplaysErrorMessageInModelState() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary(new Product());
            viewData.ModelState.AddModelError("ProductName", "Error Will Robinson!");
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);

            // Act
            string html = htmlHelper.ValidationMessageFor(p => p.ProductName);

            // Assert
            Assert.AreEqual(@"Error Will Robinson!", html);
        }

        [TestMethod]
        public void ValidationMessageForDisplaysSpecifiedErrorMessage() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary(new Product());
            viewData.ModelState.AddModelError("ProductName", "Error");
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);

            // Act
            string html = htmlHelper.ValidationMessageFor(p => p.ProductName, "Error Will Robinson!");

            // Assert
            Assert.AreEqual(@"Error Will Robinson!", html);
        }

        [TestMethod]
        public void ValidationMessageForWithAttributesRendersAttribute() {
            // Arrange
            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            ViewDataDictionary viewData = new ViewDataDictionary(new Product());
            viewData.ModelState.AddModelError("ProductName", "Error");
            Mock<IViewDataContainer> mockIViewDataContainer = new Mock<IViewDataContainer>();
            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper<Product> htmlHelper = new HtmlHelper<Product>(mockViewContext.Object, mockIViewDataContainer.Object);

            // Act
            string html = htmlHelper.ValidationMessageFor(p => p.ProductName, "Error Will Robinson!", new { title = "Error!"});

            // Assert
            Assert.AreEqual(@"Error Will Robinson!", html);
        }

        internal class Product {
            public string ProductName {
                get;
                set;
            }

            public int Id {
                get;
                set;
            }

            public int CategoryId {
                get;
                set;
            }
        }
    }
}


text:
namespace NQuery.Syntax
{
    public sealed class IntersectQuerySyntax : QuerySyntax
    {
        internal IntersectQuerySyntax(SyntaxTree syntaxTree, QuerySyntax leftQuery, SyntaxToken intersectKeyword, QuerySyntax rightQuery)
            : base(syntaxTree)
        {
            LeftQuery = leftQuery;
            IntersectKeyword = intersectKeyword;
            RightQuery = rightQuery;
        }

        public override SyntaxKind Kind
        {
            get { return SyntaxKind.IntersectQuery; }
        }

        public override IEnumerable<SyntaxNodeOrToken> ChildNodesAndTokens()
        {
            yield return LeftQuery;
            yield return IntersectKeyword;
            yield return RightQuery;
        }

        public QuerySyntax LeftQuery { get; }

        public SyntaxToken IntersectKeyword { get; }

        public QuerySyntax RightQuery { get; }
    }
}