text:
require 'rails_helper'
require 'test_graph_helper'

# Note: We do not specify the format of the export. All that matters is that
# whatever is exported, can be imported.
describe 'NeoClone class' do
  context 'locked?' do
    before(:each) do
      @fake_tracker = double
      allow(@fake_tracker).to receive(:log)
      allow(@fake_tracker).to receive(:ftime).and_return('')
    end

    it 'returns false by default' do
      expect(NeoClone.new(@fake_tracker).locked?).to eq(false)
    end

    it 'returns true after lock!' do
      NeoClone.new(@fake_tracker).lock!
      expect(NeoClone.new(@fake_tracker).locked?).to eq(true)
    end

    it 'returns false after lock! followed by unlock!' do
      NeoClone.new(@fake_tracker).lock!
      NeoClone.new(@fake_tracker).unlock!
      expect(NeoClone.new(@fake_tracker).locked?).to eq(false)
    end
  end

  context 'export/import' do
    before(:each) do
      @fake_tracker = double
      allow(@fake_tracker).to receive(:log)
      allow(@fake_tracker).to receive(:ftime).and_return('')
    end

    it 'successfully clones an existing graph into a blank one' do
      t1 = create(:test_model_node)
      t2 = create(:test_model_node)
      t3 = create(:test_model_target_node)
      t4 = create(:test_model_target_node)
      t1.target = t3
      t1.save
      TestModelCustomRel.create(from_node: t2, to_node: t4, rel_property: 'foo')
      t1_uuid = t1.uuid
      t2_uuid = t2.uuid
      t3_uuid = t3.uuid
      t4_uuid = t3.uuid

      export = NeoClone.new(@fake_tracker).export

      TestModelNode.all.each { |t| t.destroy }
      TestModelTargetNode.all.each { |t| t.destroy }

      # uncomment to debug the Cypher
      # puts "\n\n#{export.join("\n")}\n"

      NeoClone.new(@fake_tracker).import(export)
      t1 = TestModelNode.find_by(uuid: t1_uuid)
      t2 = TestModelNode.find_by(uuid: t2_uuid)
      t3 = TestModelTargetNode.find_by(uuid: t3_uuid)
      expect(t1).to exist
      expect(t2).to exist
      expect(t3).to exist
      expect(t1.target).to eq(t3)
      expect(t2.custom_rel_targets).to eq([t4])
      expect(t2.custom_rel_targets.rels[0].rel_property).to eq('foo')
    end

    it 'erases existing nodes' do
      t1_uuid = create(:test_model_node).uuid
      export = NeoClone.new(@fake_tracker).export
      t2_uuid = create(:test_model_node).uuid
      NeoClone.new(@fake_tracker).import(export)
      expect(TestModelNode.find_by(uuid: t2_uuid)).to be_nil
    end

    it 'locks itself, then unlocks, while importing' do
      create(:test_model_node)
      export = NeoClone.new(@fake_tracker).export
      importer = NeoClone.new(@fake_tracker)
      allow(importer).to receive(:lock!).and_return(true)
      expect(importer).to receive(:lock!).ordered
      expect(importer).to receive(:unlock!).ordered
      importer.import(export)
    end

    it 'copies 100 nodes and 300 relationships' do
      test_nodes = []
      50.times do
        test_nodes.push(create(:test_model_node))
      end
      target_nodes = []
      50.times do
        target_nodes.push(create(:test_model_target_node))
      end
      test_nodes.each_with_index do |test_node, i|
        test_node.target = target_nodes[i]
        test_node.different_targets = [target_nodes[(i + 17) % 50],
                                       target_nodes[(i + 39) % 50],
                                       target_nodes[(i + 4) % 50],
                                       target_nodes[(i + 12) % 50]]
        test_node.save
      end
      export = NeoClone.new(@fake_tracker).export
      NeoClone.new(@fake_tracker).import(export)
      expect(TestModelNode.all.count).to eq(50)
      expect(TestModelTargetNode.all.count).to eq(50)
      TestModelNode.all.each do |node|
        expect(node.target).to_not be_nil
        expect(node.different_targets.count).to eq(4)
      end
    end

    # You will typically see the next two tests take about 5 seconds to run.
    # Almost all of that time is the initial series of creates and updates to
    # set up the test graph. The actual export/import process is much faster.
    it 'exports 100 nodes and 300 relationships in less than 0.175s' do
      test_nodes = []
      50.times do
        test_nodes.push(create(:test_model_node))
      end
      target_nodes = []
      50.times do
        target_nodes.push(create(:test_model_target_node))
      end
      test_nodes.each_with_index do |test_node, i|
        test_node.target = target_nodes[i]
        test_node.different_targets = [target_nodes[(i + 17) % 50],
                                       target_nodes[(i + 39) % 50],
                                       target_nodes[(i + 4) % 50],
                                       target_nodes[(i + 12) % 50]]
        test_node.save
      end
      start = Time.now
      export = NeoClone.new(@fake_tracker).export
      expect(Time.now - start).to be < 0.175
    end

    it 'imports 100 nodes and 300 relationships in less than 2.5s' do
      start = Time.now
      test_nodes = []
      50.times do
        test_nodes.push(create(:test_model_node))
      end
      target_nodes = []
      50.times do
        target_nodes.push(create(:test_model_target_node))
      end
      test_nodes.each_with_index do |test_node, i|
        test_node.target = target_nodes[i]
        test_node.different_targets = [target_nodes[(i + 17) % 50],
                                       target_nodes[(i + 39) % 50],
                                       target_nodes[(i + 4) % 50],
                                       target_nodes[(i + 12) % 50]]
        test_node.save
      end
      export = NeoClone.new(@fake_tracker).export
      start = Time.now
      NeoClone.new(@fake_tracker).import(export)
      #puts "Import time: #{Time.now - start} sec"
      expect(Time.now - start).to be < 2.5
    end
  end
end


text:
package main

// Tests of 'implements' query applied to methods, -output=json.
// See go.tools/oracle/oracle_test.go for explanation.
// See implements-methods.golden for expected query results.

import _ "lib"

func main() {
}

type F interface {
	f() // @implements F.f "f"
}

type FG interface {
	f()       // @implements FG.f "f"
	g() []int // @implements FG.g "g"
}

type C int
type D struct{}

func (c *C) f() {} // @implements *C.f "f"
func (d D) f()  {} // @implements D.f "f"

func (d *D) g() []int { return nil } // @implements *D.g "g"

type sorter []int

func (sorter) Len() int           { return 0 } // @implements Len "Len"
func (sorter) Less(i, j int) bool { return false }
func (sorter) Swap(i, j int)      {}

type I interface {
	Method(*int) *int // @implements I.Method "Method"
}

redpajama_set_name: RedPajamaGithub


text:
import unittest
from ctypes import *
import _ctypes_test

class Callbacks(unittest.TestCase):
    functype = CFUNCTYPE

##    def tearDown(self):
##        import gc
##        gc.collect()

    def callback(self, *args):
        self.got_args = args
        return args[-1]

    def check_type(self, typ, arg):
        PROTO = self.functype.im_func(typ, typ)
        result = PROTO(self.callback)(arg)
        if typ == c_float:
            self.assertAlmostEqual(result, arg, places=5)
        else:
            self.assertEqual(self.got_args, (arg,))
            self.assertEqual(result, arg)

        PROTO = self.functype.im_func(typ, c_byte, typ)
        result = PROTO(self.callback)(-3, arg)
        if typ == c_float:
            self.assertAlmostEqual(result, arg, places=5)
        else:
            self.assertEqual(self.got_args, (-3, arg))
            self.assertEqual(result, arg)

    ################

    def test_byte(self):
        self.check_type(c_byte, 42)
        self.check_type(c_byte, -42)

    def test_ubyte(self):
        self.check_type(c_ubyte, 42)

    def test_short(self):
        self.check_type(c_short, 42)
        self.check_type(c_short, -42)

    def test_ushort(self):
        self.check_type(c_ushort, 42)

    def test_int(self):
        self.check_type(c_int, 42)
        self.check_type(c_int, -42)

    def test_uint(self):
        self.check_type(c_uint, 42)

    def test_long(self):
        self.check_type(c_long, 42)
        self.check_type(c_long, -42)

    def test_ulong(self):
        self.check_type(c_ulong, 42)

    def test_longlong(self):
        # test some 64-bit values, positive and negative
        self.check_type(c_longlong, 5948291757245277467)
        self.check_type(c_longlong, -5229388909784190580)
        self.check_type(c_longlong, 42)
        self.check_type(c_longlong, -42)

    def test_ulonglong(self):
        # test some 64-bit values, with and without msb set.
        self.check_type(c_ulonglong, 10955412242170339782)
        self.check_type(c_ulonglong, 3665885499841167458)
        self.check_type(c_ulonglong, 42)

    def test_float(self):
        # only almost equal: double -> float -> double
        import math
        self.check_type(c_float, math.e)
        self.check_type(c_float, -math.e)

    def test_double(self):
        self.check_type(c_double, 3.14)
        self.check_type(c_double, -3.14)

    def test_longdouble(self):
        self.check_type(c_longdouble, 3.14)
        self.check_type(c_longdouble, -3.14)

    def test_char(self):
        self.check_type(c_char, "x")
        self.check_type(c_char, "a")

    # disabled: would now (correctly) raise a RuntimeWarning about
    # a memory leak.  A callback function cannot return a non-integral
    # C type without causing a memory leak.
##    def test_char_p(self):
##        self.check_type(c_char_p, "abc")
##        self.check_type(c_char_p, "def")

    def test_pyobject(self):
        o = ()
        from sys import getrefcount as grc
        for o in (), [], object():
            initial = grc(o)
            # This call leaks a reference to 'o'...
            self.check_type(py_object, o)
            before = grc(o)
            # ...but this call doesn't leak any more.  Where is the refcount?
            self.check_type(py_object, o)
            after = grc(o)
            self.assertEqual((after, o), (before, o))

    def test_unsupported_restype_1(self):
        # Only "fundamental" result types are supported for callback
        # functions, the type must have a non-NULL stgdict->setfunc.
        # POINTER(c_double), for example, is not supported.

        prototype = self.functype.im_func(POINTER(c_double))
        # The type is checked when the prototype is called
        self.assertRaises(TypeError, prototype, lambda: None)

    def test_unsupported_restype_2(self):
        prototype = self.functype.im_func(object)
        self.assertRaises(TypeError, prototype, lambda: None)

    def test_issue_7959(self):
        proto = self.functype.im_func(None)

        class X(object):
            def func(self): pass
            def __init__(self):
                self.v = proto(self.func)

        import gc
        for i in range(32):
            X()
        gc.collect()
        live = [x for x in gc.get_objects()
                if isinstance(x, X)]
        self.assertEqual(len(live), 0)

try:
    WINFUNCTYPE
except NameError:
    pass
else:
    class StdcallCallbacks(Callbacks):
        functype = WINFUNCTYPE

################################################################

class SampleCallbacksTestCase(unittest.TestCase):

    def test_integrate(self):
        # Derived from some then non-working code, posted by David Foster
        dll = CDLL(_ctypes_test.__file__)

        # The function prototype called by 'integrate': double func(double);
        CALLBACK = CFUNCTYPE(c_double, c_double)

        # The integrate function itself, exposed from the _ctypes_test dll
        integrate = dll.integrate
        integrate.argtypes = (c_double, c_double, CALLBACK, c_long)
        integrate.restype = c_double

        def func(x):
            return x**2

        result = integrate(0.0, 1.0, CALLBACK(func), 10)
        diff = abs(result - 1./3.)

        self.assertLess(diff, 0.01, "%s not less than 0.01" % diff)

    def test_issue_8959_a(self):
        from ctypes.util import find_library
        libc_path = find_library("c")
        if not libc_path:
            return # cannot test
        libc = CDLL(libc_path)

        @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
        def cmp_func(a, b):
            return a[0] - b[0]

        array = (c_int * 5)(5, 1, 99, 7, 33)

        libc.qsort(array, len(array), sizeof(c_int), cmp_func)
        self.assertEqual(array[:], [1, 5, 7, 33, 99])

    try:
        WINFUNCTYPE
    except NameError:
        pass
    else:
        def test_issue_8959_b(self):
            from ctypes.wintypes import BOOL, HWND, LPARAM
            global windowCount
            windowCount = 0

            @WINFUNCTYPE(BOOL, HWND, LPARAM)
            def EnumWindowsCallbackFunc(hwnd, lParam):
                global windowCount
                windowCount += 1
                return True #Allow windows to keep enumerating

            windll.user32.EnumWindows(EnumWindowsCallbackFunc, 0)

    def test_callback_register_int(self):
        # Issue #8275: buggy handling of callback args under Win64
        # NOTE: should be run on release builds as well
        dll = CDLL(_ctypes_test.__file__)
        CALLBACK = CFUNCTYPE(c_int, c_int, c_int, c_int, c_int, c_int)
        # All this function does is call the callback with its args squared
        func = dll._testfunc_cbk_reg_int
        func.argtypes = (c_int, c_int, c_int, c_int, c_int, CALLBACK)
        func.restype = c_int

        def callback(a, b, c, d, e):
            return a + b + c + d + e

        result = func(2, 3, 4, 5, 6, CALLBACK(callback))
        self.assertEqual(result, callback(2*2, 3*3, 4*4, 5*5, 6*6))

    def test_callback_register_double(self):
        # Issue #8275: buggy handling of callback args under Win64
        # NOTE: should be run on release builds as well
        dll = CDLL(_ctypes_test.__file__)
        CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
                             c_double, c_double)
        # All this function does is call the callback with its args squared
        func = dll._testfunc_cbk_reg_double
        func.argtypes = (c_double, c_double, c_double,
                         c_double, c_double, CALLBACK)
        func.restype = c_double

        def callback(a, b, c, d, e):
            return a + b + c + d + e

        result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
        self.assertEqual(result,
                         callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))

################################################################

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


text:
#include "PiecewiseConstantReward.h"
#include "ValueFunction.h"

namespace hmdp_base
{

PiecewiseConstantReward::PiecewiseConstantReward (const int &sdim)
  : ContinuousReward (0, sdim)
{
  m_bspType = PiecewiseConstantRewardT;
}

PiecewiseConstantReward::PiecewiseConstantReward (const int &sdim, const int &d, const double &pos)
  : ContinuousReward (0, sdim, d, pos)
{
  m_bspType = PiecewiseConstantRewardT;
}

PiecewiseConstantReward::PiecewiseConstantReward (const int &dimension, const int &sdim)
  : ContinuousReward (dimension, sdim)
{
  m_bspType = PiecewiseConstantRewardT;
}

PiecewiseConstantReward::PiecewiseConstantReward (const int &dimension, const int &sdim,
						  const int &d, const double &pos)
  : ContinuousReward (dimension, sdim, d, pos)
{
  m_bspType = PiecewiseConstantRewardT;
}

PiecewiseConstantReward::PiecewiseConstantReward (const int &dimension, const int &sdim, double **lowPos,
						  double **highPos, double *low, double *high,
						  const double *value)
  : ContinuousReward (dimension, sdim)
{
  m_bspType = PiecewiseConstantRewardT;

  /* create a bsp tree from the transition tiling:
     create a tree for each tile, and intersect them. */
  PiecewiseConstantReward *bsp_n = this;
  PiecewiseConstantReward *bsp_c = this;
  BspTreeOperations::setIntersectionType (BTI_INIT); /* leaf intersection type */

  for (int tiles=0; tiles<m_tilingDimension; tiles++)
    {
      for (int i=0; i<m_nDim; i++)
	{
	  /* higher bound */
	  bsp_n->setDimension (i);

	  /* check if higher bound belongs to the domain. */
	  if (highPos[tiles][i] > high[i])
	    {
	      std::cerr << "[Warning]: PiecewiseConstantReward constructor: upper bound is outside the domain in tile: "
			<< tiles << ".\n";
	      highPos[tiles][i] = high[i];
	    }

	  bsp_n->setPosition (highPos[tiles][i]);

	  /* check if lower bound belongs to the domain. */
	  if (lowPos[tiles][i] < low[i])
	    {
	      std::cerr << "[Warning]: PiecewiseConstantReward constructor: lower bound is outside the domain in tile: "
			<< tiles << ".\n";
	      lowPos[tiles][i] = low[i];
	    }

	  bsp_n->setLowerTree (new PiecewiseConstantReward (m_tilingDimension, m_nDim, i, lowPos[tiles][i]));
	  bsp_n->setGreaterTree (new PiecewiseConstantReward (m_tilingDimension, m_nDim));
	  bsp_n = static_cast<PiecewiseConstantReward*> (bsp_n->getLowerTree ());

	  /* lower bound */
	  bsp_n->setLowerTree (new PiecewiseConstantReward (m_tilingDimension, m_nDim));
	  bsp_n->setGreaterTree (new PiecewiseConstantReward (m_tilingDimension, m_nDim));
	  bsp_n = static_cast<PiecewiseConstantReward*> (bsp_n->getGreaterTree ());

	  if (i == m_nDim - 1)  /* we now can fill the leaf (corresponds to a single tile) */
	    {
	      //std::cout << "adding vector of value: " << value[tiles] << std::endl;
	      AlphaVector *av = new AlphaVector (value[tiles]);
	      bsp_n->addAVector (av);
	    }
	}
      if (tiles > 0)
	{
	  BspTree *intersectedTree = BspTreeOperations::intersectTrees (this, bsp_c, low, high);
	  BspTree::deleteBspTree (bsp_c); bsp_c = 0;
	  if (m_lt) BspTree::deleteBspTree (m_lt);
	  if (m_ge) BspTree::deleteBspTree (m_ge);
	  m_lt = m_ge = 0;

	  /* copy because subtrees because we can't replace C++ prevents from replacing 'this' */
	  if (intersectedTree->getLowerTree ())
	    setLowerTree (new PiecewiseConstantReward (*static_cast<PiecewiseConstantReward*> (intersectedTree->getLowerTree ())));
	  if (intersectedTree->getGreaterTree ())
	    setGreaterTree (new PiecewiseConstantReward (*static_cast<PiecewiseConstantReward*> (intersectedTree->getGreaterTree ())));
	  BspTree::deleteBspTree (intersectedTree);
	}
      if (tiles < m_tilingDimension - 1)
	{
	  bsp_c = new PiecewiseConstantReward (m_tilingDimension, m_nDim);
	  bsp_n = bsp_c;
	}
    } /* end for tiles */
}

PiecewiseConstantReward::PiecewiseConstantReward(const int &sdim, const double *low,
						 const double *high, const double &val)
  : ContinuousReward (sdim)
{
  m_bspType = PiecewiseConstantRewardT;
  PiecewiseConstantReward *cr_n = this;

  for (int i=0; i<m_nDim; i++)
    {
      /* upper bound */
      cr_n->setDimension (i);
      cr_n->setPosition (high[i]);
      cr_n->setLowerTree (new PiecewiseConstantReward (m_nDim, i, low[i]));
      cr_n->setGreaterTree (new PiecewiseConstantReward (m_nDim));
      cr_n = static_cast<PiecewiseConstantReward*> (cr_n->getLowerTree ());

      /* lower bound */
      cr_n->setLowerTree (new PiecewiseConstantReward (m_nDim));
      cr_n->setGreaterTree (new PiecewiseConstantReward (m_nDim));
      cr_n = static_cast<PiecewiseConstantReward*> (cr_n->getGreaterTree ());
    }

  /* set vf initial value to zero */
  AlphaVector *av = new AlphaVector (val);
  cr_n->addAVector (av);
}

PiecewiseConstantReward::PiecewiseConstantReward (const PiecewiseConstantReward &cr)
  : ContinuousReward (cr.getTilingDimension (), cr.getSpaceDimension (), cr.getDimension (), cr.getPosition ())
{
  m_bspType = PiecewiseConstantRewardT;
  m_maxValue = cr.getSubTreeMaxValue ();

  /* copy alpha vectors */
  if (cr.getAlphaVectors ())
    {
      m_alphaVectors = new std::vector<AlphaVector*> ();
      for (unsigned int i=0; i<cr.getAlphaVectorsSize (); i++)
	m_alphaVectors->push_back (new AlphaVector (*cr.getAlphaVectorNth (i)));
    }

  if (cr.getAchievedGoals ())
    {
      m_achievedGoals = new std::vector<int> (*cr.getAchievedGoals ());
    }

  if (! cr.isLeaf ())
    {
      PiecewiseConstantReward *blt = static_cast<PiecewiseConstantReward*> (cr.getLowerTree ());
      m_lt = new PiecewiseConstantReward (*blt);
      PiecewiseConstantReward *bge = static_cast<PiecewiseConstantReward*> (cr.getGreaterTree ());
      m_ge = new PiecewiseConstantReward (*bge);
    }
  else m_lt = m_ge = 0;
}

PiecewiseConstantReward::PiecewiseConstantReward (const int &dimension, const BspTree &bt)
  : ContinuousReward (dimension, bt.getSpaceDimension (), bt.getDimension (), bt.getPosition ())
{
  m_bspType = PiecewiseConstantRewardT;

  if (! bt.isLeaf ())
    {
      m_lt = new PiecewiseConstantReward (0, *bt.getLowerTree ());
      m_ge = new PiecewiseConstantReward (0, *bt.getGreaterTree ());
    }
  else m_lt = m_ge = 0;

}

PiecewiseConstantReward::PiecewiseConstantReward(const ValueFunction &vf)
  : ContinuousReward(vf.getSpaceDimension (),vf.getDimension (),vf.getPosition ())
{
  m_bspType = PiecewiseConstantRewardT;

  /* copy alpha vectors. */
  if (vf.getAlphaVectors ())
    {
      m_alphaVectors = new std::vector<AlphaVector*> (1);
      (*m_alphaVectors)[0] = new AlphaVector (*vf.getAlphaVectorNth (0));
    }

  if (vf.getAchievedGoals ())
    {
      m_achievedGoals = new std::vector<int>(*vf.getAchievedGoals ());
    }

  if (! vf.isLeaf())
    {
      ValueFunction *vflt = static_cast<ValueFunction*>(vf.getLowerTree());
      m_lt = new PiecewiseConstantReward(*vflt);
      ValueFunction *vfge = static_cast<ValueFunction*>(vf.getGreaterTree());
      m_ge = new PiecewiseConstantReward(*vfge);
    }
}

PiecewiseConstantReward::~PiecewiseConstantReward ()
{}

void PiecewiseConstantReward::leafDataIntersectMax (const BspTree &bt, const BspTree &btr,
							   double *low, double *high)
{
  const PiecewiseConstantReward &pcra = static_cast<const PiecewiseConstantReward&> (bt);
  const PiecewiseConstantReward &pcrb = static_cast<const PiecewiseConstantReward&> (btr);

  if (! m_alphaVectors)
    m_alphaVectors = new std::vector<AlphaVector*> (1);
  else delete (*m_alphaVectors)[0];

  if (pcra.getAlphaVectors () && pcrb.getAlphaVectors ())
    {
      AlphaVector::maxConstantAlphaVector (*pcra.getAlphaVectors (),
					   *pcrb.getAlphaVectors (), 0, 0, m_alphaVectors);
    }
  else if (pcra.getAlphaVectors ())
    (*m_alphaVectors)[0] = new AlphaVector (*pcra.getAlphaVectorNth (0));
  else if (pcrb.getAlphaVectors ())
    (*m_alphaVectors)[0] = new AlphaVector (*pcrb.getAlphaVectorNth (0));
  else { delete m_alphaVectors; m_alphaVectors = 0; }

  /* goals */
  if (m_achievedGoals)
    {
      delete m_achievedGoals;
      m_achievedGoals = 0;
    }
  if ((pcra.getAchievedGoals () && pcrb.getAchievedGoals ())
      && (pcra.getConstantValue () == pcrb.getConstantValue ())
      && (pcra.getAchievedGoals ()->size () == pcrb.getAchievedGoals ()->size ()))
    {
      m_achievedGoals = new std::vector<int> (*pcrb.getAchievedGoals ());
    }
  else
    {
      if (pcra.getAchievedGoals ()
	  && pcra.getConstantValue () == getConstantValue ())
	m_achievedGoals = new std::vector<int> (*pcra.getAchievedGoals ());
      else if (pcrb.getAchievedGoals ()
	       && pcrb.getConstantValue () == getConstantValue ())
	m_achievedGoals = new std::vector<int> (*pcrb.getAchievedGoals ());
    }
}

void PiecewiseConstantReward::leafDataIntersectPlus (const BspTree &bt, const BspTree &btr,
                                                           double *low, double *high)
{
  const PiecewiseConstantReward &pcra = static_cast<const PiecewiseConstantReward&> (bt);
  const PiecewiseConstantReward &pcrb = static_cast<const PiecewiseConstantReward&> (btr);

  if (! m_alphaVectors)
    m_alphaVectors = new std::vector<AlphaVector*> (1);
  else delete (*m_alphaVectors)[0];

  if (pcra.getAlphaVectors () && pcrb.getAlphaVectors ())
    AlphaVector::simpleSumAlphaVectors (*pcra.getAlphaVectors (), *pcrb.getAlphaVectors (), m_alphaVectors);
  else if (pcra.getAlphaVectors ())
    (*m_alphaVectors)[0] = new AlphaVector (*pcra.getAlphaVectorNth (0));
  else if (pcrb.getAlphaVectors ())
    (*m_alphaVectors)[0] = new AlphaVector (*pcrb.getAlphaVectorNth (0));
  else { delete m_alphaVectors; m_alphaVectors = 0; }

  /* unionize goal sets */
  unionGoalSets (pcra, pcrb);
}

void PiecewiseConstantReward::leafDataIntersectMinus (const BspTree &bt, const BspTree &btr,
                                                           double *low, double *high)
{
  const PiecewiseConstantReward &pcra = static_cast<const PiecewiseConstantReward&> (bt);
  const PiecewiseConstantReward &pcrb = static_cast<const PiecewiseConstantReward&> (btr);

  if (! m_alphaVectors)
    m_alphaVectors = new std::vector<AlphaVector*> ();
  if (pcra.getAlphaVectors () && pcrb.getAlphaVectors ())
    AlphaVector::simpleSubtractAlphaVectors (*pcra.getAlphaVectors (), *pcrb.getAlphaVectors (), m_alphaVectors);
  else if (pcra.getAlphaVectors ())
    {
      AlphaVector *av = new AlphaVector (*pcra.getAlphaVectorNth (0));
      av->multiplyByScalar (-1.0);
      m_alphaVectors->push_back (av);
    }
  else if (pcrb.getAlphaVectors ())
    {
      AlphaVector *av = new AlphaVector (*pcrb.getAlphaVectorNth (0));
      av->multiplyByScalar (-1.0);
      m_alphaVectors->push_back (av);
    }
  else { delete m_alphaVectors; m_alphaVectors = 0; }

  /* unionize goal sets */
  unionGoalSets (pcra, pcrb);
}

void PiecewiseConstantReward::mergeContiguousLeaves (ContinuousReward *root, ContinuousReward *lt,
						     ContinuousReward *ge)
{
  PiecewiseConstantReward *pcrlt = static_cast<PiecewiseConstantReward*> (lt);
  PiecewiseConstantReward *pcrge = static_cast<PiecewiseConstantReward*> (ge);

  /* get constants */
  double c1 = pcrlt->getConstantValue ();
  double c2 = pcrge->getConstantValue ();

  if ((BspTreeOperations::m_piecesMergingByValue
       && Alg::REqual (c1, c2, Alg::m_doubleEpsilon))     /* merge by value only. */
      || (BspTreeOperations::m_piecesMergingEquality
	  && Alg::REqual (c1, c2, Alg::m_doubleEpsilon)
	  && (pcrlt->getAchievedGoals () && pcrge->getAchievedGoals ())
	  && (Alg::eqVectorInt (*pcrlt->getAchievedGoals (),
				*pcrge->getAchievedGoals ()))))
    {
      /* transfer data to root and delete leaves. */
      root->transferData (*pcrlt);
      delete lt; lt = 0;
      delete ge; ge = 0;
      root->setLowerTree (0);
      root->setGreaterTree (0);
    }
}

/* stuff for asymetric operators. Warning: this applies to the constant case only (for now). */
double PiecewiseConstantReward::updateSubTreeMaxValue ()
{
  if (isLeaf ())
    {
      if (m_alphaVectors)
	{
	  m_maxValue = getConstantValue ();
	  return m_maxValue;
	}
      else return 0.0; /* beware. */
    }
  else
    {
      PiecewiseConstantReward *crlt
	= static_cast<PiecewiseConstantReward*> (getLowerTree ());
      double low_max = crlt->updateSubTreeMaxValue ();
      PiecewiseConstantReward *crge
	= static_cast<PiecewiseConstantReward*> (getGreaterTree ());
      double high_max = crge->updateSubTreeMaxValue ();
      m_maxValue = std::max (low_max, high_max);
      return m_maxValue;
    }
}

/* plot of a leaf uses a vrml box */
void PiecewiseConstantReward::plot2DVrml2Leaf (const double &space, std::ofstream &output_vrml,
					       double *low, double *high,
					       const double &scale0, const double &scale1,
					       const double &max_value)
{
  if (! m_alphaVectors)
    return;

  double width0 = (high[0]-low[0])/scale0, width1 = (high[1]-low[1])/scale1;
  double pos0 = (high[0]+low[0])/(2.0 * scale0), pos1 = (high[1]+low[1])/(2.0 * scale1);
  output_vrml << "\t\tTransform {\n\t\t\ttranslation "
	      << pos0 << ' ' << -getConstantValue () / 2.0  << ' ' << pos1 << ' '
	      << "\n\t\t\tchildren [\n\t\t\t\tShape {\n\t\t\t\t\tappearance Appearance {material Material {} }\n\t\t\t\t\tgeometry Box {size "
	      << width0-space << ' ' << getConstantValue () << ' ' << width1-space << "}\n\t\t\t}\n\t\t]\n\t}\n";
}

} /* end of namespace */


text:
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import {assert, assertInstanceof} from 'chrome://resources/js/assert.js';
import {EventTracker} from 'chrome://resources/js/event_tracker.js';

/**
 * @fileoverview Touch Handler. Class that handles all touch events and
 * uses them to interpret higher level gestures and behaviors. TouchEvent is a
 * built in mobile safari type:
 * http://developer.apple.com/safari/library/documentation/UserExperience/Reference/TouchEventClassReference/TouchEvent/TouchEvent.html.
 * This class is intended to work with all webkit browsers, tested on Chrome and
 * iOS.
 *
 * The following types of gestures are currently supported.  See the definition
 * of TouchHandler.EventType for details.
 *
 * Single Touch:
 *      This provides simple single-touch events.  Any secondary touch is
 *      ignored.
 *
 * Drag:
 *      A single touch followed by some movement. This behavior will handle all
 *      of the required events and report the properties of the drag to you
 *      while the touch is happening and at the end of the drag sequence. This
 *      behavior will NOT perform the actual dragging (redrawing the element)
 *      for you, this responsibility is left to the client code.
 *
 * Long press:
 *     When your element is touched and held without any drag occuring, the
 *     LONG_PRESS event will fire.
 */

/**
 * A TouchHandler attaches to an Element, listents for low-level touch (or
 * mouse) events and dispatching higher-level events on the element.
 * @param {!Element} element The element to listen on and fire events
 * for.
 * @constructor
 */
export function TouchHandler(element) {
  /**
   * @type {!Element}
   * @private
   */
  this.element_ = element;

  /**
   * The absolute sum of all touch y deltas.
   * @type {number}
   * @private
   */
  this.totalMoveY_ = 0;

  /**
   * The absolute sum of all touch x deltas.
   * @type {number}
   * @private
   */
  this.totalMoveX_ = 0;

  /**
   * An array of tuples where the first item is the horizontal component of a
   * recent relevant touch and the second item is the touch's time stamp. Old
   * touches are removed based on the max tracking time and when direction
   * changes.
   * @type {!Array<number>}
   * @private
   */
  this.recentTouchesX_ = [];

  /**
   * An array of tuples where the first item is the vertical component of a
   * recent relevant touch and the second item is the touch's time stamp. Old
   * touches are removed based on the max tracking time and when direction
   * changes.
   * @type {!Array<number>}
   * @private
   */
  this.recentTouchesY_ = [];

  /**
   * Used to keep track of all events we subscribe to so we can easily clean
   * up
   * @type {EventTracker}
   * @private
   */
  this.events_ = new EventTracker();
}

/**
 * DOM Events that may be fired by the TouchHandler at the element
 * @enum {string}
 */
TouchHandler.EventType = {
  // Fired whenever the element is touched as the only touch to the device.
  // enableDrag defaults to false, set to true to permit dragging.
  TOUCH_START: 'touchHandler:touch_start',

  // Fired when an element is held for a period of time.  Prevents dragging
  // from occuring (even if enableDrag was set to true).
  LONG_PRESS: 'touchHandler:long_press',

  // If enableDrag was set to true at TOUCH_START, DRAG_START will fire when
  // the touch first moves sufficient distance.  enableDrag is set to true but
  // can be reset to false to cancel the drag.
  DRAG_START: 'touchHandler:drag_start',

  // If enableDrag was true after DRAG_START, DRAG_MOVE will fire whenever the
  // touch is moved.
  DRAG_MOVE: 'touchHandler:drag_move',

  // Fired just before TOUCH_END when a drag is released.  Correlates 1:1 with
  // a DRAG_START.
  DRAG_END: 'touchHandler:drag_end',

  // Fired whenever a touch that is being tracked has been released.
  // Correlates 1:1 with a TOUCH_START.
  TOUCH_END: 'touchHandler:touch_end',

  // Fired whenever the element is tapped in a short time and no dragging is
  // detected.
  TAP: 'touchHandler:tap',
};

/**
 * The type of event sent by TouchHandler
 * @constructor
 * @extends {Event}
 * @param {!TouchHandler.EventType} type The type of event.
 * @param {boolean} bubbles Whether or not the event should bubble.
 * @param {number} clientX The X location of the touch.
 * @param {number} clientY The Y location of the touch.
 * @param {!Element} touchedElement The element at the current location of the
 *        touch.
 */
TouchHandler.Event = function(type, bubbles, clientX, clientY, touchedElement) {
  const event = document.createEvent('Event');
  event.initEvent(type, bubbles, true);
  event.__proto__ = TouchHandler.Event.prototype;

  /**
   * The X location of the touch affected
   * @type {number}
   */
  event.clientX = clientX;

  /**
   * The Y location of the touch affected
   * @type {number}
   */
  event.clientY = clientY;

  /**
   * The element at the current location of the touch.
   * @type {!Element}
   */
  event.touchedElement = touchedElement;

  return event;
};

TouchHandler.Event.prototype = {
  __proto__: Event.prototype,

  /**
   * For TOUCH_START and DRAG START events, set to true to enable dragging or
   * false to disable dragging.
   * @type {boolean|undefined}
   */
  enableDrag: undefined,

  /**
   * For DRAG events, provides the horizontal component of the
   * drag delta. Drag delta is defined as the delta of the start touch
   * position and the current drag position.
   * @type {number|undefined}
   */
  dragDeltaX: undefined,

  /**
   * For DRAG events, provides the vertical component of the
   * drag delta.
   * @type {number|undefined}
   */
  dragDeltaY: undefined,
};

/**
 * Maximum movement of touch required to be considered a tap.
 * @type {number}
 * @private
 */
TouchHandler.MAX_TRACKING_FOR_TAP_ = 8;

/**
 * The maximum number of ms to track a touch event. After an event is older
 * than this value, it will be ignored in velocity calculations.
 * @type {number}
 * @private
 */
TouchHandler.MAX_TRACKING_TIME_ = 250;

/**
 * The maximum number of touches to track.
 * @type {number}
 * @private
 */
TouchHandler.MAX_TRACKING_TOUCHES_ = 5;

/**
 * The maximum velocity to return, in pixels per millisecond, that is used
 * to guard against errors in calculating end velocity of a drag. This is a
 * very fast drag velocity.
 * @type {number}
 * @private
 */
TouchHandler.MAXIMUM_VELOCITY_ = 5;

/**
 * The velocity to return, in pixel per millisecond, when the time stamps on
 * the events are erroneous. The browser can return bad time stamps if the
 * thread is blocked for the duration of the drag. This is a low velocity to
 * prevent the content from moving quickly after a slow drag. It is less
 * jarring if the content moves slowly after a fast drag.
 * @type {number}
 * @private
 */
TouchHandler.VELOCITY_FOR_INCORRECT_EVENTS_ = 1;

/**
 * The time, in milliseconds, that a touch must be held to be considered
 * 'long'.
 * @type {number}
 * @private
 */
TouchHandler.TIME_FOR_LONG_PRESS_ = 500;

TouchHandler.prototype = {
  /**
   * If defined, the identifer of the single touch that is active.  Note that
   * 0 is a valid touch identifier - it should not be treated equivalently to
   * undefined.
   * @type {number|undefined}
   * @private
   */
  activeTouch_: undefined,

  /**
   * @type {boolean|undefined}
   * @private
   */
  tracking_: undefined,

  /**
   * @type {number|undefined}
   * @private
   */
  startTouchX_: undefined,

  /**
   * @type {number|undefined}
   * @private
   */
  startTouchY_: undefined,

  /**
   * @type {number|undefined}
   * @private
   */
  endTouchX_: undefined,

  /**
   * @type {number|undefined}
   * @private
   */
  endTouchY_: undefined,

  /**
   * Time of the touchstart event.
   * @type {number|undefined}
   * @private
   */
  startTime_: undefined,

  /**
   * The time of the touchend event.
   * @type {number|undefined}
   * @private
   */
  endTime_: undefined,

  /**
   * @type {number|undefined}
   * @private
   */
  lastTouchX_: undefined,

  /**
   * @type {number|undefined}
   * @private
   */
  lastTouchY_: undefined,

  /**
   * @type {number|undefined}
   * @private
   */
  lastMoveX_: undefined,

  /**
   * @type {number|undefined}
   * @private
   */
  lastMoveY_: undefined,

  /**
   * @type {number|undefined}
   * @private
   */
  longPressTimeout_: undefined,

  /**
   * If defined and true, the next click event should be swallowed
   * @type {boolean|undefined}
   * @private
   */
  swallowNextClick_: undefined,

  /**
   * @type {boolean}
   * @private
   */
  draggingEnabled_: false,

  /**
   * Start listenting for events.
   * @param {boolean=} opt_capture True if the TouchHandler should listen to
   *      during the capture phase.
   * @param {boolean=} opt_mouse True if the TouchHandler should generate
   *      events for mouse input (in addition to touch input).
   */
  enable(opt_capture, opt_mouse) {
    const capture = !!opt_capture;

    // Just listen to start events for now. When a touch is occuring we'll
    // want to be subscribed to move and end events on the document, but we
    // don't want to incur the cost of lots of no-op handlers on the document.
    this.events_.add(
        this.element_, 'touchstart', this.onStart_.bind(this), capture);
    if (opt_mouse) {
      this.events_.add(
          this.element_, 'mousedown',
          this.mouseToTouchCallback_(this.onStart_.bind(this)), capture);
    }

    // If the element is long-pressed, we may need to swallow a click
    this.events_.add(this.element_, 'click', this.onClick_.bind(this), true);
  },

  /**
   * Stop listening to all events.
   */
  disable() {
    this.stopTouching_();
    this.events_.removeAll();
  },

  /**
   * Wraps a callback with translations of mouse events to touch events.
   * NOTE: These types really should be function(Event) but then we couldn't
   * use this with bind (which operates on any type of function).  Doesn't
   * JSDoc support some sort of polymorphic types?
   * @param {Function} callback The event callback.
   * @return {Function} The wrapping callback.
   * @private
   */
  mouseToTouchCallback_(callback) {
    return function(e) {
      // Note that there may be synthesizes mouse events caused by touch
      // events (a mouseDown after a touch-click).  We leave it up to the
      // client to worry about this if it matters to them (typically a short
      // mouseDown/mouseUp without a click is no big problem and it's not
      // obvious how we identify such synthesized events in a general way).
      const touch = {
        // any fixed value will do for the identifier - there will only
        // ever be a single active 'touch' when using the mouse.
        identifier: 0,
        clientX: e.clientX,
        clientY: e.clientY,
        target: e.target,
      };
      e.touches = [];
      e.targetTouches = [];
      e.changedTouches = [touch];
      if (e.type !== 'mouseup') {
        e.touches[0] = touch;
        e.targetTouches[0] = touch;
      }
      callback(e);
    };
  },

  /**
   * Begin tracking the touchable element, it is eligible for dragging.
   * @private
   */
  beginTracking_() {
    this.tracking_ = true;
  },

  /**
   * Stop tracking the touchable element, it is no longer dragging.
   * @private
   */
  endTracking_() {
    this.tracking_ = false;
    this.dragging_ = false;
    this.totalMoveY_ = 0;
    this.totalMoveX_ = 0;
  },

  /**
   * Reset the touchable element as if we never saw the touchStart
   * Doesn't dispatch any end events - be careful of existing listeners.
   */
  cancelTouch() {
    this.stopTouching_();
    this.endTracking_();
    // If clients needed to be aware of this, we could fire a cancel event
    // here.
  },

  /**
   * Record that touching has stopped
   * @private
   */
  stopTouching_() {
    // Mark as no longer being touched
    this.activeTouch_ = undefined;

    // If we're waiting for a long press, stop
    window.clearTimeout(this.longPressTimeout_);

    // Stop listening for move/end events until there's another touch.
    // We don't want to leave handlers piled up on the document.
    // Note that there's no harm in removing handlers that weren't added, so
    // rather than track whether we're using mouse or touch we do both.
    this.events_.remove(document, 'touchmove');
    this.events_.remove(document, 'touchend');
    this.events_.remove(document, 'touchcancel');
    this.events_.remove(document, 'mousemove');
    this.events_.remove(document, 'mouseup');
  },

  /**
   * Touch start handler.
   * @param {!TouchEvent} e The touchstart event.
   * @private
   */
  onStart_(e) {
    // Only process single touches.  If there is already a touch happening, or
    // two simultaneous touches then just ignore them.
    if (e.touches.length > 1) {
      // Note that we could cancel an active touch here.  That would make
      // simultaneous touch behave similar to near-simultaneous. However, if
      // the user is dragging something, an accidental second touch could be
      // quite disruptive if it cancelled their drag.  Better to just ignore
      // it.
      return;
    }

    // It's still possible there could be an active "touch" if the user is
    // simultaneously using a mouse and a touch input.
    if (this.activeTouch_ !== undefined) {
      return;
    }

    const touch = e.targetTouches[0];
    this.activeTouch_ = touch.identifier;

    // We've just started touching so shouldn't swallow any upcoming click
    if (this.swallowNextClick_) {
      this.swallowNextClick_ = false;
    }

    this.disableTap_ = false;

    // Sign up for end/cancel notifications for this touch.
    // Note that we do this on the document so that even if the user drags
    // their finger off the element, we'll still know what they're doing.
    if (e.type === 'mousedown') {
      this.events_.add(
          document, 'mouseup',
          this.mouseToTouchCallback_(this.onEnd_.bind(this)), false);
    } else {
      this.events_.add(document, 'touchend', this.onEnd_.bind(this), false);
      this.events_.add(document, 'touchcancel', this.onEnd_.bind(this), false);
    }

    // This timeout is cleared on touchEnd and onDrag
    // If we invoke the function then we have a real long press
    window.clearTimeout(this.longPressTimeout_);
    this.longPressTimeout_ = window.setTimeout(
        this.onLongPress_.bind(this), TouchHandler.TIME_FOR_LONG_PRESS_);

    // Dispatch the TOUCH_START event
    this.draggingEnabled_ =
        !!this.dispatchEvent_(TouchHandler.EventType.TOUCH_START, touch);

    // We want dragging notifications
    if (e.type === 'mousedown') {
      this.events_.add(
          document, 'mousemove',
          this.mouseToTouchCallback_(this.onMove_.bind(this)), false);
    } else {
      this.events_.add(document, 'touchmove', this.onMove_.bind(this), false);
    }

    this.startTouchX_ = this.lastTouchX_ = touch.clientX;
    this.startTouchY_ = this.lastTouchY_ = touch.clientY;
    this.startTime_ = e.timeStamp;

    this.recentTouchesX_ = [];
    this.recentTouchesY_ = [];
    this.recentTouchesX_.push(touch.clientX, e.timeStamp);
    this.recentTouchesY_.push(touch.clientY, e.timeStamp);

    this.beginTracking_();
  },

  /**
   * Given a list of Touches, find the one matching our activeTouch
   * identifier. Note that Chrome currently always uses 0 as the identifier.
   * In that case we'll end up always choosing the first element in the list.
   * @param {TouchList} touches The list of Touch objects to search.
   * @return {!Touch|undefined} The touch matching our active ID if any.
   * @private
   */
  findActiveTouch_(touches) {
    assert(this.activeTouch_ !== undefined, 'Expecting an active touch');
    // A TouchList isn't actually an array, so we shouldn't use
    // Array.prototype.filter/some, etc.
    for (let i = 0; i < touches.length; i++) {
      if (touches[i].identifier === this.activeTouch_) {
        return touches[i];
      }
    }
    return undefined;
  },

  /**
   * Touch move handler.
   * @param {!TouchEvent} e The touchmove event.
   * @private
   */
  onMove_(e) {
    if (!this.tracking_) {
      return;
    }

    // Our active touch should always be in the list of touches still active
    assert(this.findActiveTouch_(e.touches), 'Missing touchEnd');

    const that = this;
    const touch = this.findActiveTouch_(e.changedTouches);
    if (!touch) {
      return;
    }

    const clientX = touch.clientX;
    const clientY = touch.clientY;

    const moveX = this.lastTouchX_ - clientX;
    const moveY = this.lastTouchY_ - clientY;
    this.totalMoveX_ += Math.abs(moveX);
    this.totalMoveY_ += Math.abs(moveY);
    this.lastTouchX_ = clientX;
    this.lastTouchY_ = clientY;

    const couldBeTap = this.totalMoveY_ <= TouchHandler.MAX_TRACKING_FOR_TAP_ ||
        this.totalMoveX_ <= TouchHandler.MAX_TRACKING_FOR_TAP_;

    if (!couldBeTap) {
      this.disableTap_ = true;
    }

    if (this.draggingEnabled_ && !this.dragging_ && !couldBeTap) {
      // If we're waiting for a long press, stop
      window.clearTimeout(this.longPressTimeout_);

      // Dispatch the DRAG_START event and record whether dragging should be
      // allowed or not.  Note that this relies on the current value of
      // startTouchX/Y - handlers may use the initial drag delta to determine
      // if dragging should be permitted.
      this.dragging_ =
          this.dispatchEvent_(TouchHandler.EventType.DRAG_START, touch);

      if (this.dragging_) {
        // Update the start position here so that drag deltas have better
        // values but don't touch the recent positions so that velocity
        // calculations can still use touchstart position in the time and
        // distance delta.
        this.startTouchX_ = clientX;
        this.startTouchY_ = clientY;
        this.startTime_ = e.timeStamp;
      } else {
        this.endTracking_();
      }
    }

    if (this.dragging_) {
      this.dispatchEvent_(TouchHandler.EventType.DRAG_MOVE, touch);

      this.removeTouchesInWrongDirection_(
          this.recentTouchesX_, this.lastMoveX_, moveX);
      this.removeTouchesInWrongDirection_(
          this.recentTouchesY_, this.lastMoveY_, moveY);
      this.removeOldTouches_(this.recentTouchesX_, e.timeStamp);
      this.removeOldTouches_(this.recentTouchesY_, e.timeStamp);
      this.recentTouchesX_.push(clientX, e.timeStamp);
      this.recentTouchesY_.push(clientY, e.timeStamp);
    }

    this.lastMoveX_ = moveX;
    this.lastMoveY_ = moveY;
  },

  /**
   * Filters the provided recent touches array to remove all touches except
   * the last if the move direction has changed.
   * @param {!Array<number>} recentTouches An array of tuples where the first
   *     item is the x or y component of the recent touch and the second item
   *     is the touch time stamp.
   * @param {number|undefined} lastMove The x or y component of the previous
   *     move.
   * @param {number} recentMove The x or y component of the most recent move.
   * @private
   */
  removeTouchesInWrongDirection_(recentTouches, lastMove, recentMove) {
    if (lastMove && recentMove && recentTouches.length > 2 &&
        (lastMove > 0 ^ recentMove > 0)) {
      recentTouches.splice(0, recentTouches.length - 2);
    }
  },

  /**
   * Filters the provided recent touches array to remove all touches older
   * than the max tracking time or the 5th most recent touch.
   * @param {!Array<number>} recentTouches An array of tuples where the first
   *     item is the x or y component of the recent touch and the second item
   *     is the touch time stamp.
   * @param {number} recentTime The time of the most recent event.
   * @private
   */
  removeOldTouches_(recentTouches, recentTime) {
    while (recentTouches.length &&
               recentTime - recentTouches[1] >
                   TouchHandler.MAX_TRACKING_TIME_ ||
           recentTouches.length > TouchHandler.MAX_TRACKING_TOUCHES_ * 2) {
      recentTouches.splice(0, 2);
    }
  },

  /**
   * Touch end handler.
   * @param {!TouchEvent} e The touchend event.
   * @private
   */
  onEnd_(e) {
    const that = this;
    assert(this.activeTouch_ !== undefined, 'Expect to already be touching');

    // If the touch we're tracking isn't changing here, ignore this touch end.
    const touch = this.findActiveTouch_(e.changedTouches);
    if (!touch) {
      // In most cases, our active touch will be in the 'touches' collection,
      // but we can't assert that because occasionally two touchend events can
      // occur at almost the same time with both having empty 'touches' lists.
      // I.e., 'touches' seems like it can be a bit more up to date than the
      // current event.
      return;
    }

    // This is touchEnd for the touch we're monitoring
    assert(!this.findActiveTouch_(e.touches), 'Touch ended also still active');

    // Indicate that touching has finished
    this.stopTouching_();

    if (this.tracking_) {
      const clientX = touch.clientX;
      const clientY = touch.clientY;

      if (this.dragging_) {
        this.endTime_ = e.timeStamp;
        this.endTouchX_ = clientX;
        this.endTouchY_ = clientY;

        this.removeOldTouches_(this.recentTouchesX_, e.timeStamp);
        this.removeOldTouches_(this.recentTouchesY_, e.timeStamp);

        this.dispatchEvent_(TouchHandler.EventType.DRAG_END, touch);

        // Note that in some situations we can get a click event here as well.
        // For now this isn't a problem, but we may want to consider having
        // some logic that hides clicks that appear to be caused by a touchEnd
        // used for dragging.
      }

      this.endTracking_();
    }
    this.draggingEnabled_ = false;

    // Note that we dispatch the touchEnd event last so that events at
    // different levels of semantics nest nicely (similar to how DOM
    // drag-and-drop events are nested inside of the mouse events that trigger
    // them).
    this.dispatchEvent_(TouchHandler.EventType.TOUCH_END, touch);
    if (!this.disableTap_) {
      this.dispatchEvent_(TouchHandler.EventType.TAP, touch);
    }
  },

  /**
   * Get end velocity of the drag. This method is specific to drag behavior,
   * so if touch behavior and drag behavior is split then this should go with
   * drag behavior. End velocity is defined as deltaXY / deltaTime where
   * deltaXY is the difference between endPosition and the oldest recent
   * position, and deltaTime is the difference between endTime and the oldest
   * recent time stamp.
   * @return {Object} The x and y velocity.
   */
  getEndVelocity() {
    // Note that we could move velocity to just be an end-event parameter.
    let velocityX = this.recentTouchesX_.length ?
        (this.endTouchX_ - this.recentTouchesX_[0]) /
            (this.endTime_ - this.recentTouchesX_[1]) :
        0;
    let velocityY = this.recentTouchesY_.length ?
        (this.endTouchY_ - this.recentTouchesY_[0]) /
            (this.endTime_ - this.recentTouchesY_[1]) :
        0;

    velocityX = this.correctVelocity_(velocityX);
    velocityY = this.correctVelocity_(velocityY);

    return {x: velocityX, y: velocityY};
  },

  /**
   * Correct erroneous velocities by capping the velocity if we think it's too
   * high, or setting it to a default velocity if know that the event data is
   * bad.
   * @param {number} velocity The x or y velocity component.
   * @return {number} The corrected velocity.
   * @private
   */
  correctVelocity_(velocity) {
    let absVelocity = Math.abs(velocity);

    // We add to recent touches for each touchstart and touchmove. If we have
    // fewer than 3 touches (6 entries), we assume that the thread was blocked
    // for the duration of the drag and we received events in quick succession
    // with the wrong time stamps.
    if (absVelocity > TouchHandler.MAXIMUM_VELOCITY_) {
      absVelocity = this.recentTouchesY_.length < 3 ?
          TouchHandler.VELOCITY_FOR_INCORRECT_EVENTS_ :
          TouchHandler.MAXIMUM_VELOCITY_;
    }
    return absVelocity * (velocity < 0 ? -1 : 1);
  },

  /**
   * Handler when an element has been pressed for a long time
   * @private
   */
  onLongPress_() {
    // Swallow any click that occurs on this element without an intervening
    // touch start event.  This simple click-busting technique should be
    // sufficient here since a real click should have a touchstart first.
    this.swallowNextClick_ = true;
    this.disableTap_ = true;

    // Dispatch to the LONG_PRESS
    assert(typeof this.startTouchX_ === 'number');
    assert(typeof this.startTouchY_ === 'number');
    this.dispatchEventXY_(
        TouchHandler.EventType.LONG_PRESS, this.element_,
        /** @type {number} */ (this.startTouchX_),
        /** @type {number} */ (this.startTouchY_));
  },

  /**
   * Click handler - used to swallow clicks after a long-press
   * @param {!Event} e The click event.
   * @private
   */
  onClick_(e) {
    if (this.swallowNextClick_) {
      e.preventDefault();
      e.stopPropagation();
      this.swallowNextClick_ = false;
    }
  },

  /**
   * Dispatch a TouchHandler event to the element
   * @param {!TouchHandler.EventType} eventType The event to dispatch.
   * @param {Touch} touch The touch triggering this event.
   * @return {boolean|undefined} The value of enableDrag after dispatching
   *         the event.
   * @private
   */
  dispatchEvent_(eventType, touch) {
    // Determine which element was touched.  For mouse events, this is always
    // the event/touch target.  But for touch events, the target is always the
    // target of the touchstart (and it's unlikely we can change this
    // since the common implementation of touch dragging relies on it). Since
    // touch is our primary scenario (which we want to emulate with mouse),
    // we'll treat both cases the same and not depend on the target.
    /** @type {Element} */
    let touchedElement;
    if (eventType === TouchHandler.EventType.TOUCH_START) {
      touchedElement = assertInstanceof(touch.target, Element);
    } else {
      touchedElement = assert(this.element_.ownerDocument.elementFromPoint(
          touch.clientX, touch.clientY));
    }

    return this.dispatchEventXY_(
        eventType, touchedElement, touch.clientX, touch.clientY);
  },

  /**
   * Dispatch a TouchHandler event to the element
   * @param {!TouchHandler.EventType} eventType The event to dispatch.
   * @param {!Element} touchedElement
   * @param {number} clientX The X location for the event.
   * @param {number} clientY The Y location for the event.
   * @return {boolean|undefined} The value of enableDrag after dispatching
   *         the event.
   * @private
   */
  dispatchEventXY_(eventType, touchedElement, clientX, clientY) {
    const isDrag =
        (eventType === TouchHandler.EventType.DRAG_START ||
         eventType === TouchHandler.EventType.DRAG_MOVE ||
         eventType === TouchHandler.EventType.DRAG_END);

    // Drag events don't bubble - we're really just dragging the element,
    // not affecting its parent at all.
    const bubbles = !isDrag;

    const event = new TouchHandler.Event(
        eventType, bubbles, clientX, clientY, touchedElement);

    // Set enableDrag when it can be overridden
    if (eventType === TouchHandler.EventType.TOUCH_START) {
      event.enableDrag = false;
    } else if (eventType === TouchHandler.EventType.DRAG_START) {
      event.enableDrag = true;
    }

    if (isDrag) {
      event.dragDeltaX = clientX - this.startTouchX_;
      event.dragDeltaY = clientY - this.startTouchY_;
    }

    this.element_.dispatchEvent(event);
    return event.enableDrag;
  },
};


text:
namespace kaldi {

void SendPartialResult(const std::vector<int32> &words,
                       const fst::SymbolTable *word_syms, const bool line_break,
                       const int32 serv_sock, const sockaddr_in &client_addr) {
  KALDI_ASSERT(word_syms != NULL);
  std::stringstream sstream;
  for (size_t i = 0; i < words.size(); i++) {
    std::string word = word_syms->Find(words[i]);
    if (word == "")
      KALDI_ERR << "Word-id " << words[i] << " not in symbol table.";
    sstream << word << ' ';
  }
  if (line_break) sstream << "\n\n";

  ssize_t sent = sendto(serv_sock, sstream.str().c_str(), sstream.str().size(),
                        0, reinterpret_cast<const sockaddr *>(&client_addr),
                        sizeof(client_addr));
  if (sent == -1)
    KALDI_WARN << "sendto() call failed when tried to send recognition results";
}

}  // namespace kaldi

int main(int argc, char *argv[]) {
  try {
    using namespace kaldi;
    using namespace fst;

    typedef kaldi::int32 int32;

    // Up to delta-delta derivative features are calculated (unless LDA is used)
    const int32 kDeltaOrder = 2;

    const char *usage =
        "Decode speech, using feature batches received over a network "
        "connection\n\n"
        "Utterance segmentation is done on-the-fly.\n"
        "Feature splicing/LDA transform is used, if the optional(last) "
        "argument "
        "is given.\n"
        "Otherwise delta/delta-delta(2-nd order) features are produced.\n\n"
        "Usage: online-server-gmm-decode-faster [options] model-in"
        "fst-in word-symbol-table silence-phones udp-port [lda-matrix-in]\n\n"
        "Example: online-server-gmm-decode-faster --rt-min=0.3 --rt-max=0.5 "
        "--max-active=4000 --beam=12.0 --acoustic-scale=0.0769 "
        "model HCLG.fst words.txt '1:2:3:4:5' 1234 lda-matrix";
    ParseOptions po(usage);
    BaseFloat acoustic_scale = 0.1;
    int32 cmn_window = 600,
          min_cmn_window =
              100;  // adds 1 second latency, only at utterance start.
    int32 right_context = 4, left_context = 4;

    kaldi::DeltaFeaturesOptions delta_opts;
    delta_opts.Register(&po);
    OnlineFasterDecoderOpts decoder_opts;
    OnlineFeatureMatrixOptions feature_reading_opts;
    decoder_opts.Register(&po, true);
    feature_reading_opts.Register(&po);

    po.Register("left-context", &left_context,
                "Number of frames of left context");
    po.Register("right-context", &right_context,
                "Number of frames of right context");
    po.Register("acoustic-scale", &acoustic_scale,
                "Scaling factor for acoustic likelihoods");
    po.Register(
        "cmn-window", &cmn_window,
        "Number of feat. vectors used in the running average CMN calculation");
    po.Register("min-cmn-window", &min_cmn_window,
                "Minumum CMN window used at start of decoding (adds "
                "latency only at start)");

    po.Read(argc, argv);
    if (po.NumArgs() != 5 && po.NumArgs() != 6) {
      po.PrintUsage();
      return 1;
    }

    std::string model_rxfilename = po.GetArg(1), fst_rxfilename = po.GetArg(2),
                word_syms_filename = po.GetArg(3),
                silence_phones_str = po.GetArg(4),
                lda_mat_rspecifier = po.GetOptArg(6);
    int32 udp_port = atoi(po.GetArg(5).c_str());

    Matrix<BaseFloat> lda_transform;
    if (lda_mat_rspecifier != "") {
      bool binary_in;
      Input ki(lda_mat_rspecifier, &binary_in);
      lda_transform.Read(ki.Stream(), binary_in);
    }

    std::vector<int32> silence_phones;
    if (!SplitStringToIntegers(silence_phones_str, ":", false, &silence_phones))
      KALDI_ERR << "Invalid silence-phones string " << silence_phones_str;
    if (silence_phones.empty()) KALDI_ERR << "No silence phones given!";

    TransitionModel trans_model;
    AmDiagGmm am_gmm;
    {
      bool binary;
      Input ki(model_rxfilename, &binary);
      trans_model.Read(ki.Stream(), binary);
      am_gmm.Read(ki.Stream(), binary);
    }

    fst::SymbolTable *word_syms = NULL;
    if (!(word_syms = fst::SymbolTable::ReadText(word_syms_filename)))
      KALDI_ERR << "Could not read symbol table from file "
                << word_syms_filename;

    fst::Fst<fst::StdArc> *decode_fst = ReadDecodeGraph(fst_rxfilename);

    // We are not properly registering/exposing MFCC and frame extraction
    // options,
    // because there are parts of the online decoding code, where some of these
    // options are hardwired(ToDo: we should fix this at some point)
    MfccOptions mfcc_opts;
    mfcc_opts.use_energy = false;

    OnlineFasterDecoder decoder(*decode_fst, decoder_opts, silence_phones,
                                trans_model);
    VectorFst<LatticeArc> out_fst;
    int32 feature_dim = mfcc_opts.num_ceps;  // default to 13 right now.
    OnlineUdpInput udp_input(udp_port, feature_dim);
    OnlineCmnInput cmn_input(&udp_input, cmn_window, min_cmn_window);
    OnlineFeatInputItf *feat_transform = 0;

    if (lda_mat_rspecifier != "") {
      feat_transform = new OnlineLdaInput(&cmn_input, lda_transform,
                                          left_context, right_context);
    } else {
      DeltaFeaturesOptions opts;
      opts.order = kDeltaOrder;
      feat_transform = new OnlineDeltaInput(opts, &cmn_input);
    }

    // feature_reading_opts contains number of retries, batch size.
    OnlineFeatureMatrix feature_matrix(feature_reading_opts, feat_transform);

    OnlineDecodableDiagGmmScaled decodable(am_gmm, trans_model, acoustic_scale,
                                           &feature_matrix);

    std::cerr << std::endl
              << "Listening on UDP port " << udp_port << " ... " << std::endl;
    bool partial_res = false;
    while (1) {
      OnlineFasterDecoder::DecodeState dstate = decoder.Decode(&decodable);
      std::vector<int32> word_ids;
      if (dstate & (decoder.kEndFeats | decoder.kEndUtt)) {
        decoder.FinishTraceBack(&out_fst);
        fst::GetLinearSymbolSequence(out_fst, static_cast<vector<int32> *>(0),
                                     &word_ids,
                                     static_cast<LatticeArc::Weight *>(0));
        SendPartialResult(word_ids, word_syms, partial_res || word_ids.size(),
                          udp_input.descriptor(), udp_input.client_addr());
        partial_res = false;
      } else {
        if (decoder.PartialTraceback(&out_fst)) {
          fst::GetLinearSymbolSequence(out_fst, static_cast<vector<int32> *>(0),
                                       &word_ids,
                                       static_cast<LatticeArc::Weight *>(0));
          SendPartialResult(word_ids, word_syms, false, udp_input.descriptor(),
                            udp_input.client_addr());
          if (!partial_res) partial_res = (word_ids.size() > 0);
        }
      }
    }

    if (feat_transform) delete feat_transform;
    if (word_syms) delete word_syms;
    if (decode_fst) delete decode_fst;
    return 0;
  } catch (const std::exception &e) {
    std::cerr << e.what();
    return -1;
  }
}  // main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.awesometickets"/>

    <mvc:annotation-driven/>
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/resource/*"/>
            <bean id="cacheInterceptor" class="com.awesometickets.web.interceptor.CacheInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>/config.properties</value>
        </property>
        <property name="fileEncoding" value="utf-8" />
    </bean>

    <bean id="cookieSerializer" class="org.springframework.session.web.http.DefaultCookieSerializer">
        <property name="cookieName" value="${cookie.name}" />
        <property name="cookiePath" value="${cookie.path}" />
        <property name="useSecureCookie" value="${cookie.secure}" />
        <property name="useHttpOnlyCookie" value="${cookie.httpOnly}" />
        <property name="cookieMaxAge" value="${cookie.maxAge}" />
    </bean>

    <bean id="sessionRepositoryFilter"
          class="org.springframework.session.web.http.SessionRepositoryFilter">
        <constructor-arg ref="sessionRepository"/>
        <property name="httpSessionStrategy">
            <bean class="org.springframework.session.web.http.CookieHttpSessionStrategy">
                <property name="cookieSerializer" ref="cookieSerializer" />
            </bean>
        </property>
    </bean>

    <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>

    <bean id="jedisConnectionFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.host}"/>
        <property name="port" value="${redis.port}"/>
    </bean>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory"/>
        <property name="defaultSerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
    </bean>

    <bean id="exceptionResolver" class="com.awesometickets.config.ExceptionHandler"/>

    <!-- Import the config of jpa and hibernate -->
    <import resource="business-config.xml"/>

</beans>


text:
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;

namespace GRA.Controllers.ViewModel.MissionControl.Drawing
{
    public class CriterionDetailViewModel
    {
        public GRA.Domain.Model.DrawingCriterion Criterion { get; set; }
        public SelectList SystemList { get; set; }
        public SelectList BranchList { get; set; }
        public SelectList ProgramList { get; set; }
        [DisplayName("Require participant to have read a book")]
        public string ProgramPlaceholder { get; set; }

        public int EligibleCount { get; set; }
    }
}


text:
#include <stdio.h>
#include <vector>
#include <CL/cl.h>
#include <iostream>
#include <fstream>
#include <string>
#include <tchar.h>
#include <cstdio>
#include <Windows.h>

//OpenCV
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "opencv2/imgproc/imgproc.hpp"

using namespace std;
using  std::string;
using namespace cv;

//#pragma comment(lib,"OpenCL.lib")

//read image and get arguements
void img_init(string &str, Mat &img_buf, unsigned int &img_rows, unsigned int &img_cols, unsigned int &img_channels)
{
	img_buf = imread(str);
//	GaussianBlur(img_buf, img_buf, Size(7, 7), 0, 0, BORDER_DEFAULT);
	cvtColor(img_buf, img_buf, CV_BGR2GRAY);
//	imwrite("test_gray.jpg",img_buf);
	img_rows = img_buf.rows;
	img_cols = img_buf.cols;
	img_channels = img_buf.channels();
}

//create program
cl_program load_program(cl_context context, const char* filename)
{
	std::ifstream in(filename, std::ios_base::binary);
	if(!in.good())
	{
		return 0;

	}

	// get file length

	in.seekg(0, std::ios_base::end);
    size_t length = in.tellg();
    in.seekg(0, std::ios_base::beg);

    // read program source

	std::vector<char> data(length + 1);
	in.read(&data[0], length);
	data[length] = 0;

    // create and build program

	const char* source = &data[0];
	cl_program program = clCreateProgramWithSource(context, 1, &source, 0, 0);
	if(program == 0)
	{
		return 0;
	}
	if(clBuildProgram(program, 0, 0, 0, 0, 0) != CL_SUCCESS)
	{
		return 0;
	}
	return program;
}

int _tmain(int argc, _TCHAR* argv[])
{

	//begin time counte
	LARGE_INTEGER t1,t2,tc;
	QueryPerformanceFrequency(&tc);
    QueryPerformanceCounter(&t1);

	//Read image
	string str_in_img = "test.jpg";
	Mat in_img;
	unsigned int in_img_rows, in_img_cols, in_img_channels;
	img_init(str_in_img, in_img, in_img_rows, in_img_cols, in_img_channels);
	/*
	//seperate 3 channels
	vector<Mat>in_img_sec;
	split(in_img,in_img_sec);
	*/
	cout << "in_img_rows = " << in_img_rows <<endl;
	cout << "in_img_cols = " << in_img_cols <<endl;
	cout << "in_img_channels = " << in_img_channels <<endl;
	cout << "isContinue = " << in_img.isContinuous() << endl;
	/*
	cout << "in_secimg_rows = " << in_img_sec[0].rows <<endl;
	cout << "in_secimg_cols = " << in_img_sec[0].cols <<endl;
	cout << "in_secimg_channels = " << in_img_sec[0].channels() <<endl;
	cout << "Sec_In_isContinue = " << in_img_sec[0].isContinuous() << endl;
	*/
// 	merge(in_img_sec, img_all);

	cl_int err;
    cl_uint num;

	//get platform IDs
    err = clGetPlatformIDs(0, 0, &num);
    if(err != CL_SUCCESS)
	{
		std::cerr << "Unable to get platforms\n";
        return 0;
    }
    std::vector<cl_platform_id> platforms(num);
    err = clGetPlatformIDs(num, &platforms[0], &num);
    if(err != CL_SUCCESS)
	{
		std::cerr << "Unable to get platform ID\n";
        return 0;
	}

	//make context
	cl_context_properties prop[] = { CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(platforms[0]), 0 };
	cl_context context = clCreateContextFromType(prop, CL_DEVICE_TYPE_DEFAULT, NULL, NULL, NULL);
	if(context == 0)
	{
		std::cerr << "Can't create OpenCL context\n";
		return 0;
	}

	//get devices
	size_t cb;
	clGetContextInfo(context, CL_CONTEXT_DEVICES, 0, NULL, &cb);
	std::vector<cl_device_id> devices(cb / sizeof(cl_device_id));
	clGetContextInfo(context, CL_CONTEXT_DEVICES, cb, &devices[0], 0);

	clGetDeviceInfo(devices[0], CL_DEVICE_NAME, 0, NULL, &cb);
	std::string devname;
	devname.resize(cb);
	clGetDeviceInfo(devices[0], CL_DEVICE_NAME, cb, &devname[0], 0);
	std::cout << "Device: " << devname.c_str() << "\n";

	cl_command_queue queue = clCreateCommandQueue(context, devices[0], 0, 0);
	if(queue == 0)
	{
		std::cerr << "Can't create command queue\n";
		clReleaseContext(context);
		return 0;
	}

	//create buffers
	unsigned int DATA_SIZE = in_img_rows * in_img_cols * in_img_channels;
//	unsigned int SEC_DATA_SIZE = in_img_sec[0].rows * in_img_sec[0].cols * in_img_sec[0].channels();

	cl_mem cl_img_in = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(uchar) * DATA_SIZE, NULL, NULL);
	cl_mem cl_img_out = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(uchar) * DATA_SIZE, NULL, NULL);

/*
	cl_mem cl_img_in_b = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(uchar) * SEC_DATA_SIZE, NULL, NULL);
	cl_mem cl_secimg_in_g = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(uchar) * SEC_DATA_SIZE, NULL, NULL);
	cl_mem cl_secimg_in_r = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(uchar) * SEC_DATA_SIZE, NULL, NULL);
	cl_mem cl_secimg_out_b = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(uchar) * SEC_DATA_SIZE, NULL, NULL);
	cl_mem cl_secimg_out_g = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(uchar) * SEC_DATA_SIZE, NULL, NULL);
	cl_mem cl_secimg_out_r = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(uchar) * SEC_DATA_SIZE, NULL, NULL);
*/
	if(cl_img_in == 0 || cl_img_out == 0 )
	{
		std::cerr << "Can't create OpenCL buffer\n";
		clReleaseMemObject(cl_img_in);
		clReleaseMemObject(cl_img_out);
		clReleaseCommandQueue(queue);
		clReleaseContext(context);
		return 0;
	}

	//make prograam
	cl_program program = load_program(context, "..\\Gaussian_Filter.cl");
	if(program == 0)
	{
		std::cerr << "Can't load or build program\n";
		clReleaseMemObject(cl_img_in);
		clReleaseMemObject(cl_img_out);
		clReleaseCommandQueue(queue);
		clReleaseContext(context);
		return 0;
	}

	//create kernel
	cl_kernel Gaussian = clCreateKernel(program, "Gaussian", 0);
	if(Gaussian == 0)
	{
		std::cerr << "Can't load kernel\n";
		clReleaseProgram(program);
		clReleaseMemObject(cl_img_in);
		clReleaseMemObject(cl_img_out);
		clReleaseCommandQueue(queue);
		clReleaseContext(context);
		return 0;
	}

	//set kernel arguements
	clSetKernelArg(Gaussian, 0, sizeof(cl_mem), &cl_img_in);
	clSetKernelArg(Gaussian, 1, sizeof(cl_mem), &cl_img_out);
	clSetKernelArg(Gaussian, 2, sizeof(unsigned int), &DATA_SIZE);
//	clSetKernelArg(graying, 3, sizeof(unsigned int), &in_img_cols);
//	clSetKernelArg(graying, 4, sizeof(unsigned int), &in_img_channels);

	//wirte image data to buffer
	uchar* pixel_in = in_img.data;
	err = clEnqueueWriteBuffer(queue, cl_img_in, CL_FALSE, 0, DATA_SIZE, pixel_in, 0, NULL, NULL);
	clFinish(queue);
/*
	uchar* pixel_in_b = in_img_sec[0].data;
	uchar* pixel_in_g = in_img_sec[1].data;
	uchar* pixel_in_r = in_img_sec[2].data;
	err = clEnqueueWriteBuffer(queue, cl_secimg_in_b, CL_FALSE, 0, SEC_DATA_SIZE, pixel_in_b, 0, NULL, NULL);
	clFinish(queue);
	err = clEnqueueWriteBuffer(queue, cl_secimg_in_g, CL_FALSE, 0, SEC_DATA_SIZE, pixel_in_g, 0, NULL, NULL);
	clFinish(queue);
	err = clEnqueueWriteBuffer(queue, cl_secimg_in_r, CL_FALSE, 0, SEC_DATA_SIZE, pixel_in_r, 0, NULL, NULL);
	clFinish(queue);
*/
	//set NDRange
	size_t work_size = 1;
	cl_event event;
	err = clEnqueueNDRangeKernel(queue, Gaussian, 1, 0, &work_size, 0, 0, 0, &event);
	clFinish(queue);

/*
	vector<Mat>out_img_sec(3);//(in_img_rows, in_img_cols, CV_8UC3);//must define the arguements when define the Mat
	for (int ii = 0; ii < 3; ii++)
	{
		out_img_sec[ii].create(in_img_rows, in_img_cols, CV_8UC1);
	}
	cout << "Sec_Out_isContinue = " << out_img_sec[0].isContinuous() << endl;
*/
	Mat out_img(in_img_rows, in_img_cols, CV_8UC1);
	uchar* pixel_out = out_img.data;
	if(err == CL_SUCCESS)
	{
		err = clEnqueueReadBuffer(queue, cl_img_out, CL_FALSE, 0, DATA_SIZE, pixel_out, 0, 0, 0);
		clFinish(queue);
	}
/*
	uchar* pixel_out_b = out_img[0].data;
	uchar* pixel_out_g = out_img_sec[1].data;
	uchar* pixel_out_r = out_img_sec[2].data;

	if(err == CL_SUCCESS)
	{
		err = clEnqueueReadBuffer(queue, cl_secimg_out_b, CL_FALSE, 0, SEC_DATA_SIZE, pixel_out_b, 0, 0, 0);
		clFinish(queue);
		err = clEnqueueReadBuffer(queue, cl_secimg_out_g, CL_FALSE, 0, SEC_DATA_SIZE, pixel_out_g, 0, 0, 0);
		clFinish(queue);
		err = clEnqueueReadBuffer(queue, cl_secimg_out_r, CL_FALSE, 0, SEC_DATA_SIZE, pixel_out_r, 0, 0, 0);
		clFinish(queue);
	}
	clFinish(queue);
*/
//	cout << "" << out_img_sec[0] << endl;

	//time counts over
	QueryPerformanceCounter(&t2);
    printf("OpenCL program Use Time:%f\n",(t2.QuadPart - t1.QuadPart)*1.0/tc.QuadPart);

	//release cl things
	clReleaseKernel(Gaussian);
	clReleaseProgram(program);
	clReleaseMemObject(cl_img_in);
	clReleaseMemObject(cl_img_out);
	clReleaseCommandQueue(queue);
    clReleaseContext(context);

	//begin time count
	LARGE_INTEGER t3,t4;
	QueryPerformanceFrequency(&tc);
    QueryPerformanceCounter(&t3);

	//opencv comparison
	Mat dst_gray,dst;
	GaussianBlur(in_img, dst, Size(5, 5), 0, 0, BORDER_DEFAULT);

	//time count over
	QueryPerformanceCounter(&t4);
    printf("OpenCV program  Use Time:%f\n",(t4.QuadPart - t3.QuadPart)*1.0/tc.QuadPart);

	//show result
	namedWindow("test_in");
	imshow("test_in",in_img);
	namedWindow("test_in_dst");
	imshow("test_in_dst",dst);

	namedWindow("test_out");
	imshow("test_out",out_img);

	waitKey(0);
	return 0;

}


text:
require File.expand_path('../application', __FILE__)

# Initialize the rails application
Kikisdelivery::Application.initialize!


text:
(function(){
  var React, NotifyMixin, div, Button;
  React = require('react');
  NotifyMixin = require('../NotifyMixin');
  div = React.DOM.div;
  Button = React.createClass({
    displayName: 'CUBE.UI.Button',
    mixins: [NotifyMixin],
    render: function(){
      var className, style, click, ref$, this$ = this;
      className = "button " + this.props.className;
      style = this.props.style;
      click = this.props.onClick;
      return div((ref$ = this.props, ref$.className = className, ref$.style = style, ref$.onClick = function(){
        return click.apply(this$, arguments);
      }, ref$), div({}, this.props.children));
    }
  });
  module.exports = Button;
}).call(this);


text:
@protocol SINavigationMenuDelegate <NSObject>

- (void)didSelectItemAtIndex:(NSUInteger)index;

@end

@interface SINavigationMenuView : UIView <SIMenuDelegate>

@property (nonatomic, weak) id <SINavigationMenuDelegate> delegate;
@property (nonatomic, strong) NSArray *items;

- (id)initWithFrame:(CGRect)frame title:(NSString *)title;
- (void)displayMenuInView:(UIView *)view;

@end


text:
var tabId_re = /tabId=([0-9]+)/;
var match = tabId_re.exec(window.location.hash);
if (match) {
  var hist = chrome.extension.getBackgroundPage().History[match[1]];
  var table = document.createElement("table");
  for (var i=0; i < hist.length; i++) {
    var r = table.insertRow(-1);

    var date = "";
    if (i == hist.length - 1 ||
        (hist[i][0].toLocaleDateString() != hist[i+1][0].toLocaleDateString())) {
      date = hist[i][0].toLocaleDateString();
    }
    r.insertCell(-1).textContent = date;

    r.insertCell(-1).textContent = hist[i][0].toLocaleTimeString();

    var end_time;
    if (i == 0) {
      end_time = new Date();
    } else {
      end_time = hist[i-1][0];
    }
    r.insertCell(-1).textContent = FormatDuration(end_time - hist[i][0]);

    var a = document.createElement("a");
    a.textContent = hist[i][1];
    a.setAttribute("href", hist[i][1]);
    a.setAttribute("target", "_blank");
    r.insertCell(-1).appendChild(a);
  }
  document.body.appendChild(table);
}


text:
/**
 * Pipedrive API v1
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * The version of the OpenAPI document: 1.0.0
 *
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 *
 */

import ApiClient from '../ApiClient';
import DeleteRoleAllOfData from './DeleteRoleAllOfData';

/**
 * The DeleteRoleAllOf model module.
 * @module model/DeleteRoleAllOf
 * @version 1.0.0
 */
class DeleteRoleAllOf {
    /**
     * Constructs a new DeleteRoleAllOf.
     * @alias module:model/DeleteRoleAllOf
     */
    constructor() {

        DeleteRoleAllOf.initialize(this);
    }

    /**
     * Initializes the fields of this object.
     * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
     * Only for internal use.
     */
    static initialize(obj) {
    }

    /**
     * Constructs a DeleteRoleAllOf from a plain JavaScript object, optionally creating a new instance.
     * Copies all relevant properties from data to obj if supplied or a new instance if not.
     * @param {Object} data The plain JavaScript object bearing properties of interest.
     * @param {module:model/DeleteRoleAllOf} obj Optional instance to populate.
     * @return {module:model/DeleteRoleAllOf} The populated DeleteRoleAllOf instance.
     */
    static constructFromObject(data, obj) {
        if (data) {
            obj = obj || new DeleteRoleAllOf();

            if (data.hasOwnProperty('data')) {
                obj['data'] = DeleteRoleAllOfData.constructFromObject(data['data']);

                delete data['data'];
            }

            if (Object.keys(data).length > 0) {
                Object.assign(obj, data);
            }

        }
        return obj;
    }

}

/**
 * @member {module:model/DeleteRoleAllOfData} data
 */
DeleteRoleAllOf.prototype['data'] = undefined;

export default DeleteRoleAllOf;


text:
<!doctype html>

    <meta charset="utf-8">

    <title>amp-story rtl visual diff</title>
    <meta name="viewport"
          content="width=device-width,minimum-scale=1,initial-scale=1">
    <link rel="canonical" href="./template-vertical.html">

    <amp-story standalone publisher="AMP Team" title="Visual Diff Test"
        publisher-logo-src="/examples/visual-tests/photos/120.png"
        poster-portrait-src="/examples/visual-tests/picsum.photos/image981_900x1600.jpg"
        poster-landscape-src="/examples/visual-tests/picsum.photos/image981_1600x900.jpg"
        poster-square-src="/examples/visual-tests/picsum.photos/image981_1600x1600.jpg">

      <amp-story-page id="cover">
        <amp-story-grid-layer template="fill">
          <amp-img layout="fill" src="/examples/visual-tests/picsum.photos/image980_1600x900.jpg">
          </amp-img>
        </amp-story-grid-layer>
        <amp-story-grid-layer template="vertical">

مرحبا بالعالم

الصفحة الأولى

        </amp-story-grid-layer>
      </amp-story-page>

      <amp-story-page id="page-2">
        <amp-story-grid-layer template="fill">
          <amp-img layout="fill" src="/examples/visual-tests/picsum.photos/image981_1600x900.jpg">
          </amp-img>
        </amp-story-grid-layer>
        <amp-story-grid-layer template="vertical">

مرحبا بالعالم

الصفحة الثانية

        </amp-story-grid-layer>
      </amp-story-page>

      <amp-story-page id="page-3">
        <amp-story-grid-layer template="fill">
          <amp-img layout="fill" src="/examples/visual-tests/picsum.photos/image982_1600x900.jpg">
          </amp-img>
        </amp-story-grid-layer>
        <amp-story-grid-layer template="vertical">

مرحبا بالعالم

الصفحة الثالثة

        </amp-story-grid-layer>
      </amp-story-page>

      <amp-story-page id="page-4">
        <amp-story-grid-layer template="fill">
          <amp-img layout="fill" src="/examples/visual-tests/picsum.photos/image983_1600x900.jpg">
          </amp-img>
        </amp-story-grid-layer>
        <amp-story-grid-layer template="vertical">

مرحبا بالعالم

الصفحة الرابعة

        </amp-story-grid-layer>
      </amp-story-page>

    </amp-story>


text:
extern "C"
{

#define VST_EXPORT   __attribute__ ((visibility ("default")))

    extern VST_EXPORT AEffect * VSTPluginMain(audioMasterCallback audioMaster);

    AEffect * main_plugin (audioMasterCallback audioMaster) asm ("main");

#define main main_plugin

    VST_EXPORT AEffect * main(audioMasterCallback audioMaster)
    {
        return VSTPluginMain(audioMaster);
    }
}


text:
Freak is a general purpose frequency analysis toolkit for English. It provides a set of helper methods for calculating
absolute and relative frequency for the English alphabet.

## Installation

Add this line to your application's Gemfile:

    gem 'freak'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install freak

## Usage

require "freak"

results = Freak::Frequency.frequency("your string here")

relative_frequency = Freak::Frequency.relative_frequency(results)

csv = Freak::Frequency.csv(results)

## Contributing

1. Fork it ( https://github.com/[my-github-username]/freak/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
<?xml version="1.0"?>
<Document>

	<Sentence>
		<value>Lactic acid is mainly produced in muscle cells and red blood cells.</value>
		<pattern_crowdsource> [[Lactic acid|C0064582]] is mainly produced in [[muscle cells|C0596981]] and red blood cells.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Lactic acid</surface-form>
				<RDF-ID>C0064582</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>muscle cells</surface-form>
				<RDF-ID>C0596981</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0596981 LOCATION_OF C0064582</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Times when your body's oxygen level might drop include:   - During intense exercise  - When you have an infection or disease    A test can be done to measure the amount of lactic acid in the blood.</value>
		<pattern_crowdsource> Times when your body's oxygen level might drop include:   - During intense exercise  - When you have an infection or disease    A test can be done to measure the amount of [[lactic acid|C0064582]] in the [[blood|C0005767]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Times</surface-form>
				<RDF-ID>C0040223</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>oxygen</surface-form>
				<RDF-ID>C0030054</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>exercise</surface-form>
				<RDF-ID>C0015259</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>infection</surface-form>
				<RDF-ID>C0009450</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>disease</surface-form>
				<RDF-ID>C0012634</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>test</surface-form>
				<RDF-ID>C0039593</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>amount</surface-form>
				<RDF-ID>C1265611</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>lactic acid</surface-form>
				<RDF-ID>C0064582</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>blood</surface-form>
				<RDF-ID>C0005767</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0005767 LOCATION_OF C0064582</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Most of the time blood is drawn from a vein located on the inside of the elbow or the back of the hand.</value>
		<pattern_crowdsource> Most of the time blood is drawn from a [[vein|C0042449]] located on the inside of the [[elbow|C0013769]] or the back of the hand.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Most</surface-form>
				<RDF-ID>C0205393</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>time</surface-form>
				<RDF-ID>C0040223</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>blood</surface-form>
				<RDF-ID>C0005767</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>vein</surface-form>
				<RDF-ID>C0042449</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>elbow</surface-form>
				<RDF-ID>C0013769</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>hand</surface-form>
				<RDF-ID>C0018563</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0013769 LOCATION_OF C0042449</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Conditions that can increase lactic acid levels include:  - Heart failure  - Liver disease  - Lung disease  - Not enough blood containing oxygen getting to a certain area of the body  - Severe infection that affects the entire body (sepsis)  - Very low levels of oxygen in the blood (hypoxia)</value>
		<pattern_crowdsource> Conditions that can increase lactic acid levels include:  - Heart failure  - Liver disease  - Lung disease  - Not enough blood containing oxygen getting to a certain area of the body  - Severe infection that affects the entire body (sepsis)  - Very low levels of [[oxygen|C0030054]] in the [[blood|C0005767]] (hypoxia)		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>lactic acid</surface-form>
				<RDF-ID>C0064582</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>levels</surface-form>
				<RDF-ID>C0441889</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>failure  - Liver</surface-form>
				<RDF-ID>C0085605</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Heart failure  - Liver disease  - Lung</surface-form>
				<RDF-ID>C0034072</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Not</surface-form>
				<RDF-ID>C1518422</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>blood</surface-form>
				<RDF-ID>C0005767</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>containing</surface-form>
				<RDF-ID>C0332256</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>oxygen</surface-form>
				<RDF-ID>C0030054</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>certain</surface-form>
				<RDF-ID>C0205423</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>area</surface-form>
				<RDF-ID>C0205146</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Severe</surface-form>
				<RDF-ID>C0205082</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>infection</surface-form>
				<RDF-ID>C0009450</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>entire</surface-form>
				<RDF-ID>C0439751</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>sepsis</surface-form>
				<RDF-ID>C0036690</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Very low</surface-form>
				<RDF-ID>C0442811</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>levels</surface-form>
				<RDF-ID>C0441889</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>oxygen</surface-form>
				<RDF-ID>C0030054</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>blood</surface-form>
				<RDF-ID>C0005767</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>hypoxia</surface-form>
				<RDF-ID>C0242184</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0005767 LOCATION_OF C0030054</triple>
		</triples>
	</Sentence>

</Document>


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Contact_page_test_controller extends Base_Controller {

    public function __construct() {

        parent::__construct();

        $this->config->load('contact_page', FALSE, TRUE);

        $this->registry->set('nav', 'contact-page-test');
    }

    public function index() {

        $this->template->build('contact_page_test');
    }

}


text:
package com.pcfs.model;

import java.util.List;

public class Catalog {

    List<Service> services;

    public Catalog(List<Service> services) {
        Service service = new Service.ServiceBuilder()
                .setId("id")
                .setName("name")
                .build();
        this.services = services;
    }

    public List<Service> getServices() {
        return services;
    }
}


text:
#pragma once

namespace SlimDX
{
	namespace XAudio2
	{
		[System::Runtime::InteropServices::StructLayout( System::Runtime::InteropServices::LayoutKind::Sequential )]
		public value class VoiceState : System::IEquatable<VoiceState>
		{
		public:
			property System::IntPtr Context;
			property int BuffersQueued;
			property System::Int64 SamplesPlayed;

			/// <summary>
			/// Tests for equality between two objects.
			/// </summary>
			/// <param name="left">The first value to compare.</param>
			/// <param name="right">The second value to compare.</param>
			/// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns>
			static bool operator == ( VoiceState left, VoiceState right );

			/// <summary>
			/// Tests for inequality between two objects.
			/// </summary>
			/// <param name="left">The first value to compare.</param>
			/// <param name="right">The second value to compare.</param>
			/// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns>
			static bool operator != ( VoiceState left, VoiceState right );

			/// <summary>
			/// Returns the hash code for this instance.
			/// </summary>
			/// <returns>A 32-bit signed integer hash code.</returns>
			virtual int GetHashCode() override;

			/// <summary>
			/// Returns a value that indicates whether the current instance is equal to a specified object.
			/// </summary>
			/// <param name="obj">Object to make the comparison with.</param>
			/// <returns><c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns>
			virtual bool Equals( System::Object^ obj ) override;

			/// <summary>
			/// Returns a value that indicates whether the current instance is equal to the specified object.
			/// </summary>
			/// <param name="other">Object to make the comparison with.</param>
			/// <returns><c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns>
			virtual bool Equals( VoiceState other );

			/// <summary>
			/// Determines whether the specified object instances are considered equal.
			/// </summary>
			/// <param name="value1">The first value to compare.</param>
			/// <param name="value2">The second value to compare.</param>
			/// <returns><c>true</c> if <paramref name="value1"/> is the same instance as <paramref name="value2"/> or
			/// if both are <c>null</c> references or if <c>value1.Equals(value2)</c> returns <c>true</c>; otherwise, <c>false</c>.</returns>
			static bool Equals( VoiceState% value1, VoiceState% value2 );
		};
	}
}


text:
using UnityEngine;
using System.Collections;

public class MoveTargetState : BattleState
{
	protected override void OnMove (object sender, InfoEventArgs<Point> e)
	{
		SelectTile(e.info + pos);
	}
}


text:
#if LESSTHAN_NET40

using System.Diagnostics.Contracts;

namespace System.Threading.Tasks
{
    internal sealed class ContinuationTaskFromResultTask<TAntecedentResult> : Task, IContinuationTask
    {
        private Task<TAntecedentResult>? _antecedent;

        public ContinuationTaskFromResultTask(Task<TAntecedentResult> antecedent, Delegate action, object? state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions)
            : base(action, state, InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, TaskScheduler.Default)
        {
            Contract.Requires(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object>, "Invalid delegate type in ContinuationTaskFromResultTask");
            _antecedent = antecedent;
            CapturedContext = ExecutionContext.Capture();
        }

        public Task? Antecedent => _antecedent;

        /// <summary>
        ///     Evaluates the value selector of the Task which is passed in as an object and stores the result.
        /// </summary>
        internal override void InnerInvoke()
        {
            // Get and null out the antecedent.  This is crucial to avoid a memory
            // leak with long chains of continuations.
            var antecedent = _antecedent;
            Contract.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromResultTask.");
            _antecedent = null;

            // Invoke the delegate
            Contract.Assert(Action != null);
            switch (Action)
            {
                case Action<Task<TAntecedentResult>> action:
                    action(antecedent!);
                    return;

                case Action<Task<TAntecedentResult>, object?> actionWithState:
                    actionWithState(antecedent!, State);
                    return;

                default:
                    Contract.Assert(condition: false, "Invalid Action in ContinuationTaskFromResultTask");
                    break;
            }
        }
    }
}

#endif