text:
package push

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// BindTag invokes the push.BindTag API synchronously
func (client *Client) BindTag(request *BindTagRequest) (response *BindTagResponse, err error) {
	response = CreateBindTagResponse()
	err = client.DoAction(request, response)
	return
}

// BindTagWithChan invokes the push.BindTag API asynchronously
func (client *Client) BindTagWithChan(request *BindTagRequest) (<-chan *BindTagResponse, <-chan error) {
	responseChan := make(chan *BindTagResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.BindTag(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// BindTagWithCallback invokes the push.BindTag API asynchronously
func (client *Client) BindTagWithCallback(request *BindTagRequest, callback func(response *BindTagResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *BindTagResponse
		var err error
		defer close(result)
		response, err = client.BindTag(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// BindTagRequest is the request struct for api BindTag
type BindTagRequest struct {
	*requests.RpcRequest
	KeyType   string           `position:"Query" name:"KeyType"`
	TagName   string           `position:"Query" name:"TagName"`
	ClientKey string           `position:"Query" name:"ClientKey"`
	AppKey    requests.Integer `position:"Query" name:"AppKey"`
}

// BindTagResponse is the response struct for api BindTag
type BindTagResponse struct {
	*responses.BaseResponse
	RequestId string `json:"RequestId" xml:"RequestId"`
}

// CreateBindTagRequest creates a request to invoke BindTag API
func CreateBindTagRequest() (request *BindTagRequest) {
	request = &BindTagRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Push", "2016-08-01", "BindTag", "", "")
	request.Method = requests.POST
	return
}

// CreateBindTagResponse creates a response to parse from BindTag response
func CreateBindTagResponse() (response *BindTagResponse) {
	response = &BindTagResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
* Name      : Jane Doe
* Twitter   : [@janedoe][]
* Github    : [janedoe][]
* Website   : [jane.doe.com][]

##Abstract

[Presentation description goes here. Try to keep it under say, 500 words, but more than 140 characters]

##Speaker Bio

![jandoe](https://raw.github.com/cascadiajs/2013.cascadiajs.com/master/images/janedoe.png)

I'm a magical sloth that likes to crawl and climb through the forest and sit in the stream and I write code sometimes.

[@janedoe]:http://twitter.com/janedoe
[janedoe]:http://github.com/janedoe
[jane.doe.com]:http://jane.doe.com

redpajama_set_name: RedPajamaGithub


text:
package integration_test

import (
	"github.com/cloudfoundry/bosh-agent/settings"

	"github.com/cloudfoundry/bosh-agent/agentclient/applyspec"
	"github.com/cloudfoundry/bosh-agent/integration"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Instance Info", func() {
	var (
		fileSettings settings.Settings
	)

	BeforeEach(func() {
		err := testEnvironment.CleanupDataDir()
		Expect(err).ToNot(HaveOccurred())

		err = testEnvironment.CleanupLogFile()
		Expect(err).ToNot(HaveOccurred())

		err = testEnvironment.UpdateAgentConfig("file-settings-agent.json")
		Expect(err).ToNot(HaveOccurred())

		fileSettings = settings.Settings{
			Blobstore: settings.Blobstore{
				Type: "local",
				Options: map[string]interface{}{
					"blobstore_path": "/var/vcap/data",
				},
			},
			Disks: settings.Disks{
				Ephemeral: "/dev/sdh",
			},
		}

		err = testEnvironment.AttachDevice("/dev/sdh", 128, 2)
		Expect(err).ToNot(HaveOccurred())

		err = testEnvironment.CreateFilesettings(fileSettings)
		Expect(err).ToNot(HaveOccurred())
	})

	AfterEach(func() {
		err := testEnvironment.DetachDevice("/dev/sdh")
		Expect(err).ToNot(HaveOccurred())
	})

	Context("on ubuntu", func() {

		JustBeforeEach(func() {
			err := testEnvironment.StartAgentTunnel()
			Expect(err).NotTo(HaveOccurred())
		})

		It("apply spec saves instance info to file and is readable by anyone", func() {
			applySpec := applyspec.ApplySpec{ConfigurationHash: "fake-desired-config-hash", NodeID: "node-id01-123f-r2344", AvailabilityZone: "ex-az", Deployment: "deployment-name", Name: "instance-name"}
			err := testEnvironment.AgentClient.Apply(applySpec)
			Expect(err).NotTo(HaveOccurred())

			verifyFilePermissions("/var/vcap/instance/id", testEnvironment)
			verifyFileContent("/var/vcap/instance/id", applySpec.NodeID, testEnvironment)

			verifyFilePermissions("/var/vcap/instance/az", testEnvironment)
			verifyFileContent("/var/vcap/instance/az", applySpec.AvailabilityZone, testEnvironment)

			verifyFilePermissions("/var/vcap/instance/name", testEnvironment)
			verifyFileContent("/var/vcap/instance/name", applySpec.Name, testEnvironment)

			verifyFilePermissions("/var/vcap/instance/deployment", testEnvironment)
			verifyFileContent("/var/vcap/instance/deployment", applySpec.Deployment, testEnvironment)

			verifyDirectoryExecutable("/var/vcap/instance", testEnvironment)
		})
	})
})

func verifyFileContent(filePath string, expectedContent string, testEnvironment *integration.TestEnvironment) {
	deployment, err := testEnvironment.RunCommand("cat " + filePath)
	Expect(err).NotTo(HaveOccurred())
	Expect(deployment).To(Equal(expectedContent))
}

func verifyFilePermissions(filePath string, testEnvironment *integration.TestEnvironment) {
	fileListing, err := testEnvironment.RunCommand("ls -l " + filePath)
	Expect(err).NotTo(HaveOccurred())

	Expect(fileListing[1]).To(Equal(uint8('r')))
	Expect(fileListing[2]).To(Equal(uint8('w')))
	Expect(fileListing[4]).To(Equal(uint8('r')))
	Expect(fileListing[7]).To(Equal(uint8('r')))
}

func verifyDirectoryExecutable(filePath string, testEnvironment *integration.TestEnvironment) {
	fileListing, err := testEnvironment.RunCommand("ls -l -d " + filePath)
	Expect(err).NotTo(HaveOccurred())

	Expect(fileListing[3]).To(Equal(uint8('x')))
	Expect(fileListing[6]).To(Equal(uint8('x')))
	Expect(fileListing[9]).To(Equal(uint8('x')))
}


text:
/**
 * @author Kai Salmen / www.kaisalmen.de
 */

'use strict';

if (KSX.demos.projectionspace === undefined) KSX.demos.projectionspace = {};

KSX.demos.projectionspace.Main = (function () {

    var MAIN_CLEAR_COLOR = 0x101010;
    var RTT_CLEAR_COLOR = 0x0B0B0B;
    var RTT_CAM_HEIGHT = -2.5;
    var RTT_CAM_ORBIT = 16;
    var RTT_POS_DIVIDER = 50;
    var RTT_ROTATION_SPEED = 0.01;

    Home.prototype = Object.create(KSX.core.ThreeJsApp.prototype, {
        constructor: {
            configurable: true,
            enumerable: true,
            value: Home,
            writable: true
        }
    });

    function Home( elementToBindTo, elementNameVideo, elementNameVideoBuffer, mobileDevice ) {
        KSX.core.ThreeJsApp.call(this);

        this.configure({
            name: 'Home',
            htmlCanvas: elementToBindTo,
            renderers: {
                regular: {
                    canvas: elementToBindTo,
                    antialias: true
                }
            },
            useScenePerspective: true,
            useCube: true
        });
        this.platformVerification = new KSX.core.PlatformVerification();
        this.mobileDevice = mobileDevice;

        this.video = elementNameVideo;
        this.videoBuffer = elementNameVideoBuffer;
		this.videoBufferContext = this.videoBuffer.getContext( '2d' );
        this.videoTexture = null;

        this.controls = null;
        this.textureTools = new KSX.tools.TextureTools();
        this.rtt = null;

        this.textStorage = new KSX.tools.text.Text();
        this.textureCube = null;

        this.projectionSpace = new KSX.instancing.ProjectionSpace({
            low: { index: 0, name: 'Low', x: 240, y: 100, defaultHeightFactor: 15, mesh: null },
            medium: { index: 1, name: 'Medium', x: 720, y: 302, defaultHeightFactor: 20, mesh: null },
            high: { index: 2, name: 'High', x: 1280, y: 536, defaultHeightFactor: 25, mesh: null },
            extreme: { index: 3, name: 'Extreme', x: 1920, y: 804, defaultHeightFactor: 30, mesh: null },
            insane: { index: 4, name: 'Insane', x: 3840, y: 1608, defaultHeightFactor: 35, mesh: null }
        }, 0);

        var scope = this;
        this.uiModel = {
            videoTextureEnabled: false,
            animate: true,
            projectionSpace: scope.projectionSpace,
            callbacks: {
                resetViewAndParameters: function () { scope.resetViewAndParameters() },
                resizeProjectionSpace: function ( index, force ) {
                    scope.resizeProjectionSpace( index, force );
                },
                checkVideo: function () { scope.checkVideo() }
            }
        };
        this.homeUi = new KSX.demos.projectionspace.Ui( this.mobileDevice, this.uiModel );

        this.cameraDefaults = {
            posCamera: new THREE.Vector3( 0.0, -1.15 * this.projectionSpace.getHeight(), 0.85 * this.projectionSpace.getWidth() ),
            far: 100000
        };
    }

    Home.prototype.initPreGL = function() {
        var scope = this;

        scope.homeUi.initPreGL();

        var callbackOnTextSuccess = function () {
            var promises = [];
            var cubeBasePath = KSX.globals.basedir + '/resource/textures/meadow';
            promises.push( scope.textureTools.loadTextureCube( cubeBasePath ) );

            Promise.all(promises).then(
                function (results) {
                    scope.textureCube = results[0];
                    scope.preloadDone = true;
                }
            ).catch(
                function (error) {
                    console.log('The following error occurred: ', error);
                }
            );
        };

        var callbackOnShaderSuccess = function () {
            var listOfFonts = [];
            listOfFonts['droid_sans_mono_regular'] = 'resource/fonts/droid_sans_mono_regular.typeface.json';

            scope.textStorage.loadListOfFonts(KSX.globals.basedir, listOfFonts, callbackOnTextSuccess);
        };

        scope.projectionSpace.loadAsyncResources( callbackOnShaderSuccess );
    };

    Home.prototype.initGL = function () {
        if ( !this.platformVerification.verifyVertexShaderTextureAccess( this.renderer, true ) ) {
            this.initOk = false;
            return;
        }
        if ( !this.platformVerification.verifyHwInstancingSupport( this.renderer, true ) ) {
            this.initOk = false;
            return;
        }

        this.renderer.setClearColor(MAIN_CLEAR_COLOR);
        this.renderer.autoClear = false;

        // init video texture and params
        this.videoBuffer.width = 1920;
        this.videoBuffer.height = 804;
        this.videoBufferContext.fillStyle = "#000000";
        this.videoBufferContext.fillRect( 0, 0, 1920, 804 );

        this.videoTexture = new THREE.Texture( this.videoBuffer );
        this.videoTexture.minFilter = THREE.LinearFilter;
        this.videoTexture.magFilter = THREE.LinearFilter;
        this.videoTexture.format = THREE.RGBFormat;

        this.rtt = initRtt( this.projectionSpace.getWidth(), this.projectionSpace.getHeight(), this.textStorage, this.textureCube );
        this.projectionSpace.initGL();
        this.projectionSpace.shader.textures['rtt'] = this.rtt.texture.texture;
        this.projectionSpace.shader.textures['video'] = this.videoTexture;

        this.resizeProjectionSpace( this.mobileDevice ? 0 : 1, true );
        this.scenePerspective.scene.add( this.projectionSpace.pivot );
        this.checkVideo();

        this.homeUi.announceFeedback( this.projectionSpace.printStats() );

        // init camera and bind to controls
        this.scenePerspective.setCameraDefaults( this.cameraDefaults );
        this.controls = new THREE.TrackballControls( this.scenePerspective.camera );
    };

    var initRtt = function ( width, height, textStorage, textureCube ) {
        var canvasRtt = new KSX.core.Canvas( {
            offsetWidth: width,
            offsetHeight: height
        } );

        var rtt = new KSX.core.ThreeJsApp.ScenePerspective( canvasRtt );
        rtt.useCube = true;
        rtt.count = 0;
        // manual init required
        rtt.initGL();

        var defaults = {
            posCamera: new THREE.Vector3( 0, RTT_CAM_HEIGHT, RTT_CAM_ORBIT )
        };
        rtt.setCameraDefaults( defaults );

        rtt.lights = {
            ambientLight: new THREE.AmbientLight( 0x696856 ),
            directionalLight1: new THREE.DirectionalLight( 0xE0E0E0 ),
            directionalLight2: new THREE.DirectionalLight( 0x0000AA )
        };
        rtt.lights.directionalLight1.position.set(  10, 10, 10 );
        rtt.lights.directionalLight2.position.set( -10, 5, 5 );

        rtt.scene.add( rtt.lights.ambientLight );
        rtt.scene.add( rtt.lights.directionalLight1 );
        rtt.scene.add( rtt.lights.directionalLight2 );

        // Skybox shader
        var skyboxShader = THREE.ShaderLib[ "cube" ];
        skyboxShader.uniforms[ "tCube" ].value = textureCube;

        rtt.materials = {
            sphereRed: new THREE.MeshStandardMaterial({
                color: 0xFF0000,
                envMap: textureCube,
                envMapIntensity: 0.33,
                roughness: 0.4,
                metalness: 0.66
            }),
            sphereYellow: new THREE.MeshStandardMaterial({
                color: 0xFFFF00,
                envMap: textureCube,
                envMapIntensity: 0.5,
                roughness: 0.1,
                metalness: 0.9
            }),
            boxCenter: new THREE.MeshStandardMaterial({
                color: 0x00FF00,
                envMap: textureCube,
                envMapIntensity: 0.66
            }),
            text: new THREE.MeshStandardMaterial({
                envMap: textureCube,
                envMapIntensity: 0.75,
                metalness: 1.0
            }),
            envCube: new THREE.ShaderMaterial({
                fragmentShader: skyboxShader.fragmentShader,
                vertexShader: skyboxShader.vertexShader,
                uniforms: skyboxShader.uniforms,
                depthWrite: false,
                side: THREE.BackSide
            })
        };

        var textUnitWelcome = textStorage.addText( 'Welcome', 'droid_sans_mono_regular', 'Welcome back to', rtt.materials.text, 1.5, 10, 1, 0.1 );
        var textUnitDomain = textStorage.addText( 'Domain', 'droid_sans_mono_regular', 'www.kaisalmen.de', rtt.materials.text, 1.5, 10, 1, 0.1 );
        textUnitWelcome.mesh.position.set( -10, 4, 0 );
        textUnitDomain.mesh.position.set( -10, -5, 0 );

        rtt.meshes = {
            sphereRed: new THREE.Mesh( new THREE.SphereBufferGeometry( 2, 32, 32 ), rtt.materials.sphereRed ),
            sphereYellow: new THREE.Mesh( new THREE.SphereBufferGeometry( 1, 64, 64 ), rtt.materials.sphereYellow ),
            boxCenter: new THREE.Mesh( new THREE.BoxBufferGeometry( 2, 2, 2 ), rtt.materials.boxCenter ),
            envCube: new THREE.Mesh( new THREE.BoxGeometry( 10000, 10000, 10000 ), rtt.materials.envCube ),
            textWelcome: textUnitWelcome.mesh,
            textDomain: textUnitDomain.mesh,
            textPivot: new THREE.Object3D(),
            sphereYellowPivot: new THREE.Object3D(),
            lightPivot: new THREE.Object3D(),
        };

        rtt.scene.add( rtt.meshes.sphereRed );
        rtt.scene.add( rtt.meshes.boxCenter );
        rtt.meshes.sphereYellow.position.set( -12, 0, 0 );
        rtt.meshes.sphereYellowPivot.add( rtt.meshes.sphereYellow );
        rtt.scene.add( rtt.meshes.sphereYellowPivot );
        rtt.meshes.sphereYellowPivot.rotateZ( Math.PI / 9 );
        rtt.sceneCube.add( rtt.meshes.envCube );

        rtt.meshes.textPivot.add( rtt.meshes.textWelcome );
        rtt.meshes.textPivot.add( rtt.meshes.textDomain );
        rtt.meshes.lightPivot.add( rtt.lights.directionalLight1 );
        rtt.meshes.lightPivot.add( rtt.lights.directionalLight2 );

        rtt.scene.add( rtt.meshes.textPivot );
        rtt.scene.add( rtt.meshes.lightPivot );

        rtt.texture = new THREE.WebGLRenderTarget(
            rtt.canvas.getWidth(),
            rtt.canvas.getHeight(),
            {
                minFilter: THREE.LinearFilter,
                magFilter: THREE.NearestFilter,
                format: THREE.RGBFormat
            }
        );

        return rtt;
    };

    Home.prototype.initPostGL = function () {
        var scope = this;
        scope.homeUi.buildUi();

        if ( scope.mobileDevice ) {

            alert( 'Performance of mobile GPUs is likely not adequate for this site!' );

        }
		this.removeLoading();
        return true;
    };

    Home.prototype.resizeDisplayGL = function () {
        this.controls.handleResize();
    };

    Home.prototype.renderPre = function () {
        this.controls.update();

        if (this.uiModel.videoTextureEnabled && this.video.readyState === this.video.HAVE_ENOUGH_DATA) {
            this.videoBufferContext.drawImage(this.video, 0, 0);
            this.videoTexture.needsUpdate = true;
        }

        this.renderer.setClearColor(RTT_CLEAR_COLOR);
        if ( this.uiModel.animate ) {
            var spherePosFactor = 5.0;

            this.rtt.meshes.sphereRed.position.set(
                spherePosFactor * Math.sin( this.rtt.count / RTT_POS_DIVIDER ),
                0,
                spherePosFactor * Math.cos( this.rtt.count / RTT_POS_DIVIDER )
            );
            this.rtt.meshes.lightPivot.rotateY( RTT_ROTATION_SPEED );
            this.rtt.meshes.boxCenter.rotateX( -RTT_ROTATION_SPEED );
            this.rtt.meshes.boxCenter.rotateY( -RTT_ROTATION_SPEED );

            this.rtt.meshes.sphereYellowPivot.rotateY( - 2 * RTT_ROTATION_SPEED );

            this.rtt.camera.position.set(
                -RTT_CAM_ORBIT * Math.sin( this.rtt.count / 100 ),
                RTT_CAM_HEIGHT,
                RTT_CAM_ORBIT * Math.cos( this.rtt.count / 100 )
            );

            this.rtt.count++;
            this.rtt.updateCamera();
        }

        this.rtt.cameraCube.rotation.copy( this.rtt.camera.rotation );
        this.renderer.render( this.rtt.sceneCube, this.rtt.cameraCube, this.rtt.texture, true );
        this.renderer.render( this.rtt.scene, this.rtt.camera, this.rtt.texture, false );
        this.renderer.setClearColor(MAIN_CLEAR_COLOR);
    };

    Home.prototype.renderPost = function () {
        this.homeUi.render();
    };

    Home.prototype.checkVideo = function () {
        if ( this.uiModel.videoTextureEnabled ) {
            this.projectionSpace.flipTexture( 'video' );

            if ( this.uiModel.animate ) {
                this.video.play();
            }
            else {
                this.video.pause();
            }
        }
        else {
            this.projectionSpace.flipTexture( 'rtt' );

            if ( !this.video.paused ) {
                this.video.pause();
            }
        }
    };

    Home.prototype.resizeProjectionSpace = function ( index, force ) {
        var success = true;
        if ( index === this.projectionSpace.index ) {
            success = false;
        }
        if ( force ) {
            this.projectionSpace.resetProjectionSpace( index );
            success = true;
        }

        if ( success ) {
            this.projectionSpace.switchDimensionMesh( index );

            this.rtt.canvas.resetWidth( this.projectionSpace.getWidth(), this.projectionSpace.getHeight() );
            this.rtt.texture.setSize( this.projectionSpace.getWidth(), this.projectionSpace.getHeight() );

            this.homeUi.announceFeedback( this.projectionSpace.printStats() );

            this.cameraDefaults.posCamera = new THREE.Vector3( 0.0, -1.15 * this.projectionSpace.getHeight(), 0.85 * this.projectionSpace.getWidth() );
            this.scenePerspective.setCameraDefaults( this.cameraDefaults );
        }

        return success;
    };

    Home.prototype.resetViewAndParameters = function () {
        this.resizeProjectionSpace( this.mobileDevice ? 0 : 1, true );

        this.controls.reset();
        this.controls.target = this.scenePerspective.cameraTarget;

        this.uiModel.animate = true;
        this.uiModel.videoTextureEnabled = false;
        this.checkVideo();
    };

    return Home;
})();


text:
import FileRoute from 'davros/routes/file';

export default class FilesRoute extends FileRoute {}


text:
package br.com.social.DAO.contato.telefone;

import org.springframework.stereotype.Component;

import br.com.social.DAO.GenericDAO;
import br.com.social.model.contato.Telefone;

@Component
public class TelefoneDAO extends GenericDAO<Long, Telefone> implements ITelefoneDAO {
	public TelefoneDAO() {
		// TODO Auto-generated constructor stub
		super(Telefone.class);
	}
}


text:
package com.ibm.bi.dml.test.integration.functions.append;

import org.junit.Test;

import com.ibm.bi.dml.api.DMLException;
import com.ibm.bi.dml.api.DMLScript;
import com.ibm.bi.dml.api.DMLScript.RUNTIME_PLATFORM;
import com.ibm.bi.dml.lops.LopProperties.ExecType;
import com.ibm.bi.dml.test.integration.AutomatedTestBase;
import com.ibm.bi.dml.test.integration.TestConfiguration;
import com.ibm.bi.dml.test.utils.TestUtils;

public class StringAppendTest extends AutomatedTestBase
{

	private final static String TEST_NAME1 = "basic_string_append";
	private final static String TEST_NAME2 = "loop_string_append";

	private final static String TEST_DIR = "functions/append/";

	@Override
	public void setUp() {
		TestUtils.clearAssertionInformation();
		addTestConfiguration(TEST_NAME1, new TestConfiguration(TEST_DIR, TEST_NAME1, new String[] {"S"}));
		addTestConfiguration(TEST_NAME2, new TestConfiguration(TEST_DIR, TEST_NAME2, new String[] {"S"}));
	}

	@Test
	public void testBasicStringAppendCP() {
		runStringAppendTest(TEST_NAME1, -1, false, ExecType.CP);
	}

	@Test
	public void testLoopStringAppendCP() {
		runStringAppendTest(TEST_NAME2, 100, false, ExecType.CP);
	}

	@Test
	public void testLoopStringAppendErrorCP() {
		runStringAppendTest(TEST_NAME2, 10000, true, ExecType.CP);
	}

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

	@Test
	public void testBasicStringAppendSP() {
		runStringAppendTest(TEST_NAME1, -1, false, ExecType.SPARK);
	}

	@Test
	public void testLoopStringAppendSP() {
		runStringAppendTest(TEST_NAME2, 100, false, ExecType.SPARK);
	}

	@Test
	public void testLoopStringAppendErrorSP() {
		runStringAppendTest(TEST_NAME2, 10000, true, ExecType.SPARK);
	}

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

	//note: there should be no difference to running in MR because scalar operation

	@Test
	public void testBasicStringAppendMR() {
		runStringAppendTest(TEST_NAME1, -1, false, ExecType.CP);
	}

	@Test
	public void testLoopStringAppendMR() {
		runStringAppendTest(TEST_NAME2, 100, false, ExecType.CP);
	}

	@Test
	public void testLoopStringAppendErrorMR() {
		runStringAppendTest(TEST_NAME2, 10000, true, ExecType.CP);
	}

	/**
	 *
	 * @param platform
	 * @param rows
	 * @param cols1
	 * @param cols2
	 * @param cols3
	 */
	public void runStringAppendTest(String TEST_NAME, int iters, boolean exceptionExpected, ExecType et)
	{
		RUNTIME_PLATFORM oldPlatform = rtplatform;

	    if(et == ExecType.SPARK) {
	    	rtplatform = RUNTIME_PLATFORM.SPARK;
	    }
	    else {
			rtplatform = (et==ExecType.MR) ? RUNTIME_PLATFORM.HADOOP : RUNTIME_PLATFORM.HYBRID;
	    }
		boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;
		if( rtplatform == RUNTIME_PLATFORM.SPARK )
			DMLScript.USE_LOCAL_SPARK_CONFIG = true;

		try
		{
			TestConfiguration config = getTestConfiguration(TEST_NAME);
			loadTestConfiguration(config);

			String RI_HOME = SCRIPT_DIR + TEST_DIR;
			fullDMLScriptName = RI_HOME + TEST_NAME + ".dml";
			programArgs = new String[]{"-args",  Integer.toString(iters),
					                             RI_HOME + OUTPUT_DIR + "C" };

			runTest(true, exceptionExpected, DMLException.class, 0);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			throw new RuntimeException(ex);
		}
		finally
		{
			rtplatform = oldPlatform;
			DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;
		}

	}
}


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
Fl. France 5:61. 1899

#### Original name
null

### Remarks
null


text:
<?php

declare(strict_types=1);

namespace Nelmio\Alice\FixtureBuilder\Denormalizer\Fixture\SpecificationBagDenormalizer;

use Nelmio\Alice\Definition\SpecificationBag;
use Nelmio\Alice\Definition\SpecificationBagFactory;
use Nelmio\Alice\FixtureBuilder\Denormalizer\Fixture\SpecificationsDenormalizerInterface;
use Nelmio\Alice\FixtureBuilder\Denormalizer\FlagParserInterface;
use Nelmio\Alice\FixtureInterface;
use Nelmio\Alice\NotCallableTrait;

class DummySpecificationBagDenormalizer implements SpecificationsDenormalizerInterface
{
    use NotCallableTrait;

    /**
     * @inheritdoc
     */
    public function denormalize(
        FixtureInterface $fixture,
        FlagParserInterface $parser,
        array $unparsedSpecs
    ): SpecificationBag
    {
        return SpecificationBagFactory::create();
    }
}


text:
package io.cattle.platform.servicediscovery.dao.impl;

import static io.cattle.platform.core.model.tables.HostTable.HOST;
import static io.cattle.platform.core.model.tables.InstanceHostMapTable.INSTANCE_HOST_MAP;
import static io.cattle.platform.core.model.tables.InstanceTable.INSTANCE;
import static io.cattle.platform.core.model.tables.ServiceExposeMapTable.SERVICE_EXPOSE_MAP;
import static io.cattle.platform.core.model.tables.ServiceTable.SERVICE;
import io.cattle.platform.core.constants.CommonStatesConstants;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.dao.GenericMapDao;
import io.cattle.platform.core.model.Host;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.model.Service;
import io.cattle.platform.core.model.ServiceExposeMap;
import io.cattle.platform.core.model.tables.records.HostRecord;
import io.cattle.platform.core.model.tables.records.InstanceRecord;
import io.cattle.platform.core.model.tables.records.ServiceExposeMapRecord;
import io.cattle.platform.core.model.tables.records.ServiceRecord;
import io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.process.ObjectProcessManager;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.servicediscovery.api.constants.ServiceDiscoveryConstants;
import io.cattle.platform.servicediscovery.api.dao.ServiceExposeMapDao;
import io.cattle.platform.servicediscovery.service.ServiceDiscoveryService;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.lang3.tuple.Pair;

public class ServiceExposeMapDaoImpl extends AbstractJooqDao implements ServiceExposeMapDao {

    @Inject
    ObjectManager objectManager;

    @Inject
    ObjectProcessManager objectProcessManager;

    @Inject
    ServiceDiscoveryService sdService;

    @Inject
    GenericMapDao mapDao;

    @Override
    public Pair<Instance, ServiceExposeMap> createServiceInstance(Map<String, Object> properties, Service service,
            String instanceName) {
        final Instance instance = objectManager.create(Instance.class, properties);
        ServiceExposeMap exposeMap = createServiceInstanceMap(service, instance);
        return Pair.of(instance, exposeMap);
    }

    @Override
    @SuppressWarnings("unchecked")
    public ServiceExposeMap createServiceInstanceMap(Service service, final Instance instance) {
        Map<String, String> instanceLabels = DataAccessor.fields(instance)
                .withKey(InstanceConstants.FIELD_LABELS).withDefault(Collections.EMPTY_MAP).as(Map.class);
        String dnsPrefix = instanceLabels
                .get(ServiceDiscoveryConstants.LABEL_SERVICE_LAUNCH_CONFIG);
        if (ServiceDiscoveryConstants.PRIMARY_LAUNCH_CONFIG_NAME.equalsIgnoreCase(dnsPrefix)) {
            dnsPrefix = null;
        }

        return objectManager.create(ServiceExposeMap.class, SERVICE_EXPOSE_MAP.INSTANCE_ID, instance.getId(),
                SERVICE_EXPOSE_MAP.SERVICE_ID, service.getId(), SERVICE_EXPOSE_MAP.ACCOUNT_ID,
                service.getAccountId(), SERVICE_EXPOSE_MAP.DNS_PREFIX, dnsPrefix);
    }

    @Override
    public List<? extends Instance> listServiceInstances(long serviceId) {
        return create()
                .select(INSTANCE.fields())
                .from(INSTANCE)
                .join(SERVICE_EXPOSE_MAP)
                .on(SERVICE_EXPOSE_MAP.INSTANCE_ID.eq(INSTANCE.ID)
                        .and(SERVICE_EXPOSE_MAP.SERVICE_ID.eq(serviceId))
                        .and(SERVICE_EXPOSE_MAP.STATE.in(CommonStatesConstants.ACTIVATING,
                                CommonStatesConstants.ACTIVE, CommonStatesConstants.REQUESTED))
                        .and(INSTANCE.STATE.notIn(CommonStatesConstants.PURGING, CommonStatesConstants.PURGED,
                                CommonStatesConstants.REMOVED, CommonStatesConstants.REMOVING)))
                .fetchInto(InstanceRecord.class);
    }

    @Override
    public List<? extends ServiceExposeMap> getNonRemovedServiceInstanceMap(long serviceId) {
        return create()
                .select(SERVICE_EXPOSE_MAP.fields())
                .from(SERVICE_EXPOSE_MAP)
                .join(INSTANCE)
                .on(SERVICE_EXPOSE_MAP.INSTANCE_ID.eq(INSTANCE.ID)
                        .and(SERVICE_EXPOSE_MAP.SERVICE_ID.eq(serviceId))
                        .and(SERVICE_EXPOSE_MAP.REMOVED.isNull())
                        .and(SERVICE_EXPOSE_MAP.STATE.notIn(CommonStatesConstants.REMOVED,
                                CommonStatesConstants.REMOVING))
                        .and(INSTANCE.STATE.notIn(CommonStatesConstants.PURGING,
                                CommonStatesConstants.PURGED, CommonStatesConstants.REMOVED,
                                CommonStatesConstants.REMOVING)))
                .fetchInto(ServiceExposeMapRecord.class);
    }

    @Override
    public ServiceExposeMap findInstanceExposeMap(Instance instance) {
        if (instance == null) {
            return null;
        }
        List<? extends ServiceExposeMap> instanceServiceMap = mapDao.findNonRemoved(ServiceExposeMap.class,
                Instance.class,
                instance.getId());
        if (instanceServiceMap.isEmpty()) {
            // not a service instance
            return null;
        }
        return instanceServiceMap.get(0);
    }

    @Override
    public ServiceExposeMap createIpToServiceMap(Service service, String ipAddress) {
        ServiceExposeMap map = getServiceIpExposeMap(service, ipAddress);
        if (map == null) {
            map = objectManager.create(ServiceExposeMap.class, SERVICE_EXPOSE_MAP.SERVICE_ID, service.getId(),
                    SERVICE_EXPOSE_MAP.IP_ADDRESS, ipAddress, SERVICE_EXPOSE_MAP.ACCOUNT_ID,
                    service.getAccountId());
        }
        return map;
    }

    @Override
    public ServiceExposeMap getServiceIpExposeMap(Service service, String ipAddress) {
        return objectManager.findAny(ServiceExposeMap.class,
                SERVICE_EXPOSE_MAP.SERVICE_ID, service.getId(),
                SERVICE_EXPOSE_MAP.IP_ADDRESS, ipAddress,
                SERVICE_EXPOSE_MAP.REMOVED, null);
    }

    @Override
    public List<? extends Service> getActiveServices(long accountId) {
        return create()
                .select(SERVICE.fields())
                .from(SERVICE)
                .where(SERVICE.ACCOUNT_ID.eq(accountId))
                .and(SERVICE.REMOVED.isNull())
                .and(SERVICE.STATE.in(CommonStatesConstants.ACTIVE, CommonStatesConstants.ACTIVATING, CommonStatesConstants.UPDATING_ACTIVE))
                .fetchInto(ServiceRecord.class);
    }

    @Override
    public List<? extends ServiceExposeMap> getNonRemovedServiceIpMaps(long serviceId) {
        return create()
                .select(SERVICE_EXPOSE_MAP.fields())
                .from(SERVICE_EXPOSE_MAP)
                .where(SERVICE_EXPOSE_MAP.SERVICE_ID.eq(serviceId))
                .and(SERVICE_EXPOSE_MAP.REMOVED.isNull()
                        .and(SERVICE_EXPOSE_MAP.STATE.notIn(CommonStatesConstants.REMOVED,
                                CommonStatesConstants.REMOVING))
                        .and(SERVICE_EXPOSE_MAP.IP_ADDRESS.isNotNull()))
                .fetchInto(ServiceExposeMapRecord.class);
    }

    @Override
    public Host getHostForInstance(long instanceId) {
        List<? extends Host> results = create()
                .select(HOST.fields())
                .from(HOST)
                .join(INSTANCE_HOST_MAP)
                .on(HOST.ID.eq(INSTANCE_HOST_MAP.HOST_ID))
                .where(INSTANCE_HOST_MAP.INSTANCE_ID.eq(instanceId))
                .fetchInto(HostRecord.class);
        if (results.size() > 0) {
            return results.get(0);
        }
        return null;
    }

    @Override
    public boolean isPrimaryServiceInstance(ServiceExposeMap map) {
        return map.getDnsPrefix() == null;
    }

    @Override
    public boolean isActiveMap(ServiceExposeMap serviceExposeMap) {
        List<String> validStates = Arrays.asList(CommonStatesConstants.ACTIVATING,
                CommonStatesConstants.ACTIVE, CommonStatesConstants.UPDATING_ACTIVE, CommonStatesConstants.REQUESTED);
        return (validStates.contains(serviceExposeMap.getState()));

    }

    @Override
    public ServiceExposeMap getServiceHostnameExposeMap(Service service, String hostName) {
        return objectManager.findAny(ServiceExposeMap.class,
                SERVICE_EXPOSE_MAP.SERVICE_ID, service.getId(),
                SERVICE_EXPOSE_MAP.HOST_NAME, hostName,
                SERVICE_EXPOSE_MAP.REMOVED, null);
    }

    @Override
    public ServiceExposeMap createHostnameToServiceMap(Service service, String hostName) {
        ServiceExposeMap map = getServiceHostnameExposeMap(service, hostName);
        if (map == null) {
            map = objectManager.create(ServiceExposeMap.class, SERVICE_EXPOSE_MAP.SERVICE_ID, service.getId(),
                    SERVICE_EXPOSE_MAP.HOST_NAME, hostName, SERVICE_EXPOSE_MAP.ACCOUNT_ID,
                    service.getAccountId());
        }
        return map;
    }

    @Override
    public List<? extends ServiceExposeMap> getNonRemovedServiceHostnameMaps(long serviceId) {
        return create()
                .select(SERVICE_EXPOSE_MAP.fields())
                .from(SERVICE_EXPOSE_MAP)
                .where(SERVICE_EXPOSE_MAP.SERVICE_ID.eq(serviceId))
                .and(SERVICE_EXPOSE_MAP.REMOVED.isNull()
                        .and(SERVICE_EXPOSE_MAP.STATE.notIn(CommonStatesConstants.REMOVED,
                                CommonStatesConstants.REMOVING))
                        .and(SERVICE_EXPOSE_MAP.HOST_NAME.isNotNull()))
                .fetchInto(ServiceExposeMapRecord.class);
    }
}


text:
package io.takari.bpm.model;

public enum ExpressionType {

    NONE,
    SIMPLE,
    DELEGATE
}


text:
package kcp

import (
	"crypto/rand"
	"encoding/binary"
	"hash/crc32"
	"io"
	"net"
	"sync"
	"sync/atomic"
	"time"

	"github.com/pkg/errors"
	"golang.org/x/net/ipv4"
)

type errTimeout struct {
	error
}

func (errTimeout) Timeout() bool   { return true }
func (errTimeout) Temporary() bool { return true }
func (errTimeout) Error() string   { return "i/o timeout" }

const (
	defaultWndSize           = 128 // default window size, in packet
	nonceSize                = 16  // magic number
	crcSize                  = 4   // 4bytes packet checksum
	cryptHeaderSize          = nonceSize + crcSize
	mtuLimit                 = 2048
	rxQueueLimit             = 8192
	rxFECMulti               = 3 // FEC keeps rxFECMulti* (dataShard+parityShard) ordered packets in memory
	defaultKeepAliveInterval = 10
)

const (
	errBrokenPipe       = "broken pipe"
	errInvalidOperation = "invalid operation"
)

var (
	xmitBuf sync.Pool
	sid     uint32
)

func init() {
	xmitBuf.New = func() interface{} {
		return make([]byte, mtuLimit)
	}
}

type (
	// UDPSession defines a KCP session implemented by UDP
	UDPSession struct {
		sid uint32
		kcp *KCP      // the core ARQ
		l   *Listener // point to server listener if it's a server socket

		// forward error correction
		fec              *FEC
		fecDataShards    [][]byte
		fecHeaderOffset  int
		fecPayloadOffset int

		fecCnt     int // count datashard
		fecMaxSize int // record maximum data length in datashard

		conn              net.PacketConn // the underlying packet socket
		block             BlockCrypt
		remote            net.Addr
		rd                time.Time // read deadline
		wd                time.Time // write deadline
		sockbuff          []byte    // kcp receiving is based on packet, I turn it into stream
		die               chan struct{}
		chReadEvent       chan struct{}
		chWriteEvent      chan struct{}
		headerSize        int
		ackNoDelay        bool
		isClosed          bool
		keepAliveInterval int32
		mu                sync.Mutex
		updateInterval    int32
	}

	setReadBuffer interface {
		SetReadBuffer(bytes int) error
	}

	setWriteBuffer interface {
		SetWriteBuffer(bytes int) error
	}

	emitPacket struct {
		conn    net.PacketConn
		to      net.Addr
		data    []byte
		recycle bool
	}
)

// newUDPSession create a new udp session for client or server
func newUDPSession(conv uint32, dataShards, parityShards int, l *Listener, conn net.PacketConn, remote net.Addr, block BlockCrypt) *UDPSession {
	sess := new(UDPSession)
	sess.sid = atomic.AddUint32(&sid, 1)
	sess.die = make(chan struct{})
	sess.chReadEvent = make(chan struct{}, 1)
	sess.chWriteEvent = make(chan struct{}, 1)
	sess.remote = remote
	sess.conn = conn
	sess.keepAliveInterval = defaultKeepAliveInterval
	sess.l = l
	sess.block = block

	// FEC initialization
	sess.fec = newFEC(rxFECMulti*(dataShards+parityShards), dataShards, parityShards)
	if sess.fec != nil {
		if sess.block != nil {
			sess.fecHeaderOffset = cryptHeaderSize
		}
		sess.fecPayloadOffset = sess.fecHeaderOffset + fecHeaderSize

		// fec data shards
		sess.fecDataShards = make([][]byte, sess.fec.shardSize)
		for k := range sess.fecDataShards {
			sess.fecDataShards[k] = make([]byte, mtuLimit)
		}
	}

	// calculate header size
	if sess.block != nil {
		sess.headerSize += cryptHeaderSize
	}
	if sess.fec != nil {
		sess.headerSize += fecHeaderSizePlus2
	}

	sess.kcp = NewKCP(conv, func(buf []byte, size int) {
		if size >= IKCP_OVERHEAD {
			sess.output(buf[:size])
		}
	})
	sess.kcp.WndSize(defaultWndSize, defaultWndSize)
	sess.kcp.SetMtu(IKCP_MTU_DEF - sess.headerSize)
	sess.kcp.setFEC(dataShards, parityShards)

	updater.addSession(sess)
	if sess.l == nil { // it's a client connection
		go sess.readLoop()
		atomic.AddUint64(&DefaultSnmp.ActiveOpens, 1)
	} else {
		atomic.AddUint64(&DefaultSnmp.PassiveOpens, 1)
	}
	currestab := atomic.AddUint64(&DefaultSnmp.CurrEstab, 1)
	maxconn := atomic.LoadUint64(&DefaultSnmp.MaxConn)
	if currestab > maxconn {
		atomic.CompareAndSwapUint64(&DefaultSnmp.MaxConn, maxconn, currestab)
	}

	return sess
}

// Read implements the Conn Read method.
func (s *UDPSession) Read(b []byte) (n int, err error) {
	for {
		s.mu.Lock()
		if len(s.sockbuff) > 0 { // copy from buffer
			n = copy(b, s.sockbuff)
			s.sockbuff = s.sockbuff[n:]
			s.mu.Unlock()
			return n, nil
		}

		if s.isClosed {
			s.mu.Unlock()
			return 0, errors.New(errBrokenPipe)
		}

		if !s.rd.IsZero() {
			if time.Now().After(s.rd) { // timeout
				s.mu.Unlock()
				return 0, errTimeout{}
			}
		}

		if n := s.kcp.PeekSize(); n > 0 { // data arrived
			if len(b) >= n {
				s.kcp.Recv(b)
			} else {
				buf := make([]byte, n)
				s.kcp.Recv(buf)
				n = copy(b, buf)
				s.sockbuff = buf[n:] // store remaining bytes into sockbuff for next read
			}
			s.mu.Unlock()
			atomic.AddUint64(&DefaultSnmp.BytesReceived, uint64(n))
			return n, nil
		}

		var timeout *time.Timer
		var c <-chan time.Time
		if !s.rd.IsZero() {
			delay := s.rd.Sub(time.Now())
			timeout = time.NewTimer(delay)
			c = timeout.C
		}
		s.mu.Unlock()

		// wait for read event or timeout
		select {
		case <-s.chReadEvent:
		case <-c:
		case <-s.die:
		}

		if timeout != nil {
			timeout.Stop()
		}
	}
}

// Write implements the Conn Write method.
func (s *UDPSession) Write(b []byte) (n int, err error) {
	for {
		s.mu.Lock()
		if s.isClosed {
			s.mu.Unlock()
			return 0, errors.New(errBrokenPipe)
		}

		if !s.wd.IsZero() {
			if time.Now().After(s.wd) { // timeout
				s.mu.Unlock()
				return 0, errTimeout{}
			}
		}

		if s.kcp.WaitSnd() < int(s.kcp.Cwnd()) {
			n = len(b)
			for {
				if len(b) <= int(s.kcp.mss) {
					s.kcp.Send(b)
					break
				} else {
					s.kcp.Send(b[:s.kcp.mss])
					b = b[s.kcp.mss:]
				}
			}

			s.kcp.flush(false)
			s.mu.Unlock()
			atomic.AddUint64(&DefaultSnmp.BytesSent, uint64(n))
			return n, nil
		}

		var timeout *time.Timer
		var c <-chan time.Time
		if !s.wd.IsZero() {
			delay := s.wd.Sub(time.Now())
			timeout = time.NewTimer(delay)
			c = timeout.C
		}
		s.mu.Unlock()

		// wait for write event or timeout
		select {
		case <-s.chWriteEvent:
		case <-c:
		case <-s.die:
		}

		if timeout != nil {
			timeout.Stop()
		}
	}
}

// Close closes the connection.
func (s *UDPSession) Close() error {
	updater.removeSession(s)

	s.mu.Lock()
	defer s.mu.Unlock()
	if s.isClosed {
		return errors.New(errBrokenPipe)
	}
	close(s.die)
	s.isClosed = true
	atomic.AddUint64(&DefaultSnmp.CurrEstab, ^uint64(0))
	if s.l == nil { // client socket close
		return s.conn.Close()
	}

	return nil
}

// LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
func (s *UDPSession) LocalAddr() net.Addr { return s.conn.LocalAddr() }

// RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
func (s *UDPSession) RemoteAddr() net.Addr { return s.remote }

// SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
func (s *UDPSession) SetDeadline(t time.Time) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.rd = t
	s.wd = t
	return nil
}

// SetReadDeadline implements the Conn SetReadDeadline method.
func (s *UDPSession) SetReadDeadline(t time.Time) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.rd = t
	return nil
}

// SetWriteDeadline implements the Conn SetWriteDeadline method.
func (s *UDPSession) SetWriteDeadline(t time.Time) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.wd = t
	return nil
}

// SetWindowSize set maximum window size
func (s *UDPSession) SetWindowSize(sndwnd, rcvwnd int) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.kcp.WndSize(sndwnd, rcvwnd)
}

// SetMtu sets the maximum transmission unit
func (s *UDPSession) SetMtu(mtu int) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.kcp.SetMtu(mtu - s.headerSize)
}

// SetStreamMode toggles the stream mode on/off
func (s *UDPSession) SetStreamMode(enable bool) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if enable {
		s.kcp.stream = 1
	} else {
		s.kcp.stream = 0
	}
}

// SetACKNoDelay changes ack flush option, set true to flush ack immediately,
func (s *UDPSession) SetACKNoDelay(nodelay bool) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.ackNoDelay = nodelay
}

// SetNoDelay calls nodelay() of kcp
func (s *UDPSession) SetNoDelay(nodelay, interval, resend, nc int) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.kcp.NoDelay(nodelay, interval, resend, nc)
	atomic.StoreInt32(&s.updateInterval, int32(interval))
}

// SetDSCP sets the 6bit DSCP field of IP header, no effect if it's accepted from Listener
func (s *UDPSession) SetDSCP(dscp int) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.l == nil {
		if nc, ok := s.conn.(*ConnectedUDPConn); ok {
			return ipv4.NewConn(nc.Conn).SetTOS(dscp << 2)
		} else if nc, ok := s.conn.(net.Conn); ok {
			return ipv4.NewConn(nc).SetTOS(dscp << 2)
		}
	}
	return errors.New(errInvalidOperation)
}

// SetReadBuffer sets the socket read buffer, no effect if it's accepted from Listener
func (s *UDPSession) SetReadBuffer(bytes int) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.l == nil {
		if nc, ok := s.conn.(setReadBuffer); ok {
			return nc.SetReadBuffer(bytes)
		}
	}
	return errors.New(errInvalidOperation)
}

// SetWriteBuffer sets the socket write buffer, no effect if it's accepted from Listener
func (s *UDPSession) SetWriteBuffer(bytes int) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.l == nil {
		if nc, ok := s.conn.(setWriteBuffer); ok {
			return nc.SetWriteBuffer(bytes)
		}
	}
	return errors.New(errInvalidOperation)
}

// SetKeepAlive changes per-connection NAT keepalive interval; 0 to disable, default to 10s
func (s *UDPSession) SetKeepAlive(interval int) {
	atomic.StoreInt32(&s.keepAliveInterval, int32(interval))
}

// output pipeline entry
// steps for output data processing:
// 1. FEC
// 2. CRC32
// 3. Encryption
// 4. emit to emitTask
// 5. emitTask WriteTo kernel
func (s *UDPSession) output(buf []byte) {
	var ecc [][]byte

	// extend buf's header space
	ext := xmitBuf.Get().([]byte)[:s.headerSize+len(buf)]
	copy(ext[s.headerSize:], buf)

	// FEC stage
	if s.fec != nil {
		s.fec.markData(ext[s.fecHeaderOffset:])
		binary.LittleEndian.PutUint16(ext[s.fecPayloadOffset:], uint16(len(ext[s.fecPayloadOffset:])))

		// copy data to fec datashards
		sz := len(ext)
		s.fecDataShards[s.fecCnt] = s.fecDataShards[s.fecCnt][:sz]
		copy(s.fecDataShards[s.fecCnt], ext)
		s.fecCnt++

		// record max datashard length
		if sz > s.fecMaxSize {
			s.fecMaxSize = sz
		}

		//  calculate Reed-Solomon Erasure Code
		if s.fecCnt == s.fec.dataShards {
			// bzero each datashard's tail
			for i := 0; i < s.fec.dataShards; i++ {
				shard := s.fecDataShards[i]
				slen := len(shard)
				xorBytes(shard[slen:s.fecMaxSize], shard[slen:s.fecMaxSize], shard[slen:s.fecMaxSize])
			}

			// calculation of RS
			ecc = s.fec.calcECC(s.fecDataShards, s.fecPayloadOffset, s.fecMaxSize)
			for k := range ecc {
				s.fec.markFEC(ecc[k][s.fecHeaderOffset:])
				ecc[k] = ecc[k][:s.fecMaxSize]
			}

			// reset counters to zero
			s.fecCnt = 0
			s.fecMaxSize = 0
		}
	}

	// encryption stage
	if s.block != nil {
		io.ReadFull(rand.Reader, ext[:nonceSize])
		checksum := crc32.ChecksumIEEE(ext[cryptHeaderSize:])
		binary.LittleEndian.PutUint32(ext[nonceSize:], checksum)
		s.block.Encrypt(ext, ext)

		if ecc != nil {
			for k := range ecc {
				io.ReadFull(rand.Reader, ecc[k][:nonceSize])
				checksum := crc32.ChecksumIEEE(ecc[k][cryptHeaderSize:])
				binary.LittleEndian.PutUint32(ecc[k][nonceSize:], checksum)
				s.block.Encrypt(ecc[k], ecc[k])
			}
		}
	}

	// emit stage
	defaultEmitter.emit(emitPacket{s.conn, s.remote, ext, true})
	if ecc != nil {
		for k := range ecc {
			defaultEmitter.emit(emitPacket{s.conn, s.remote, ecc[k], false})
		}
	}
}

// kcp update, returns interval for next calling
func (s *UDPSession) update() time.Duration {
	s.mu.Lock()
	s.kcp.flush(false)
	if s.kcp.WaitSnd() < int(s.kcp.Cwnd()) {
		s.notifyWriteEvent()
	}
	s.mu.Unlock()
	return time.Duration(atomic.LoadInt32(&s.updateInterval)) * time.Millisecond
}

// GetConv gets conversation id of a session
func (s *UDPSession) GetConv() uint32 {
	return s.kcp.conv
}

func (s *UDPSession) notifyReadEvent() {
	select {
	case s.chReadEvent <- struct{}{}:
	default:
	}
}

func (s *UDPSession) notifyWriteEvent() {
	select {
	case s.chWriteEvent <- struct{}{}:
	default:
	}
}

func (s *UDPSession) kcpInput(data []byte) {
	var kcpInErrors, fecErrs, fecRecovered, fecSegs uint64

	if s.fec != nil {
		f := s.fec.decode(data)
		s.mu.Lock()
		if f.flag == typeData {
			if ret := s.kcp.Input(data[fecHeaderSizePlus2:], true, s.ackNoDelay); ret != 0 {
				kcpInErrors++
			}
		}

		if f.flag == typeData || f.flag == typeFEC {
			if f.flag == typeFEC {
				fecSegs++
			}

			if recovers := s.fec.input(f); recovers != nil {
				for _, r := range recovers {
					if len(r) >= 2 { // must be larger than 2bytes
						sz := binary.LittleEndian.Uint16(r)
						if int(sz) <= len(r) && sz >= 2 {
							if ret := s.kcp.Input(r[2:sz], false, s.ackNoDelay); ret == 0 {
								fecRecovered++
							} else {
								kcpInErrors++
							}
						} else {
							fecErrs++
						}
					} else {
						fecErrs++
					}
				}
			}
		}

		// notify reader
		if n := s.kcp.PeekSize(); n > 0 {
			s.notifyReadEvent()
		}
		s.mu.Unlock()
	} else {
		s.mu.Lock()
		if ret := s.kcp.Input(data, true, s.ackNoDelay); ret != 0 {
			kcpInErrors++
		}
		// notify reader
		if n := s.kcp.PeekSize(); n > 0 {
			s.notifyReadEvent()
		}
		s.mu.Unlock()
	}

	atomic.AddUint64(&DefaultSnmp.InSegs, 1)
	atomic.AddUint64(&DefaultSnmp.InBytes, uint64(len(data)))
	if fecSegs > 0 {
		atomic.AddUint64(&DefaultSnmp.FECSegs, fecSegs)
	}
	if kcpInErrors > 0 {
		atomic.AddUint64(&DefaultSnmp.KCPInErrors, kcpInErrors)
	}
	if fecErrs > 0 {
		atomic.AddUint64(&DefaultSnmp.FECErrs, fecErrs)
	}
	if fecRecovered > 0 {
		atomic.AddUint64(&DefaultSnmp.FECRecovered, fecRecovered)
	}
}

func (s *UDPSession) receiver(ch chan []byte) {
	for {
		data := xmitBuf.Get().([]byte)[:mtuLimit]
		if n, _, err := s.conn.ReadFrom(data); err == nil && n >= s.headerSize+IKCP_OVERHEAD {
			select {
			case ch <- data[:n]:
			case <-s.die:
			}
		} else if err != nil {
			return
		} else {
			atomic.AddUint64(&DefaultSnmp.InErrs, 1)
		}
	}
}

// read loop for client session
func (s *UDPSession) readLoop() {
	chPacket := make(chan []byte, rxQueueLimit)
	go s.receiver(chPacket)

	for {
		select {
		case data := <-chPacket:
			raw := data
			dataValid := false
			if s.block != nil {
				s.block.Decrypt(data, data)
				data = data[nonceSize:]
				checksum := crc32.ChecksumIEEE(data[crcSize:])
				if checksum == binary.LittleEndian.Uint32(data) {
					data = data[crcSize:]
					dataValid = true
				} else {
					atomic.AddUint64(&DefaultSnmp.InCsumErrors, 1)
				}
			} else if s.block == nil {
				dataValid = true
			}

			if dataValid {
				s.kcpInput(data)
			}
			xmitBuf.Put(raw)
		case <-s.die:
			return
		}
	}
}

type (
	// Listener defines a server listening for connections
	Listener struct {
		block                    BlockCrypt
		dataShards, parityShards int
		fec                      *FEC // for fec init test
		conn                     net.PacketConn
		sessions                 map[string]*UDPSession
		chAccepts                chan *UDPSession
		chDeadlinks              chan net.Addr
		headerSize               int
		die                      chan struct{}
		rxbuf                    sync.Pool
		rd                       atomic.Value
		wd                       atomic.Value
	}

	packet struct {
		from net.Addr
		data []byte
	}
)

// monitor incoming data for all connections of server
func (l *Listener) monitor() {
	chPacket := make(chan packet, rxQueueLimit)
	go l.receiver(chPacket)
	for {
		select {
		case p := <-chPacket:
			raw := p.data
			data := p.data
			from := p.from
			dataValid := false
			if l.block != nil {
				l.block.Decrypt(data, data)
				data = data[nonceSize:]
				checksum := crc32.ChecksumIEEE(data[crcSize:])
				if checksum == binary.LittleEndian.Uint32(data) {
					data = data[crcSize:]
					dataValid = true
				} else {
					atomic.AddUint64(&DefaultSnmp.InCsumErrors, 1)
				}
			} else if l.block == nil {
				dataValid = true
			}

			if dataValid {
				addr := from.String()
				s, ok := l.sessions[addr]
				if !ok { // new session
					var conv uint32
					convValid := false
					if l.fec != nil {
						isfec := binary.LittleEndian.Uint16(data[4:])
						if isfec == typeData {
							conv = binary.LittleEndian.Uint32(data[fecHeaderSizePlus2:])
							convValid = true
						}
					} else {
						conv = binary.LittleEndian.Uint32(data)
						convValid = true
					}

					if convValid {
						s := newUDPSession(conv, l.dataShards, l.parityShards, l, l.conn, from, l.block)
						s.kcpInput(data)
						l.sessions[addr] = s
						l.chAccepts <- s
					}
				} else {
					s.kcpInput(data)
				}
			}

			l.rxbuf.Put(raw)
		case deadlink := <-l.chDeadlinks:
			delete(l.sessions, deadlink.String())
		case <-l.die:
			return
		}
	}
}

func (l *Listener) receiver(ch chan packet) {
	for {
		data := l.rxbuf.Get().([]byte)[:mtuLimit]
		if n, from, err := l.conn.ReadFrom(data); err == nil && n >= l.headerSize+IKCP_OVERHEAD {
			ch <- packet{from, data[:n]}
		} else if err != nil {
			return
		} else {
			atomic.AddUint64(&DefaultSnmp.InErrs, 1)
		}
	}
}

// SetReadBuffer sets the socket read buffer for the Listener
func (l *Listener) SetReadBuffer(bytes int) error {
	if nc, ok := l.conn.(setReadBuffer); ok {
		return nc.SetReadBuffer(bytes)
	}
	return errors.New(errInvalidOperation)
}

// SetWriteBuffer sets the socket write buffer for the Listener
func (l *Listener) SetWriteBuffer(bytes int) error {
	if nc, ok := l.conn.(setWriteBuffer); ok {
		return nc.SetWriteBuffer(bytes)
	}
	return errors.New(errInvalidOperation)
}

// SetDSCP sets the 6bit DSCP field of IP header
func (l *Listener) SetDSCP(dscp int) error {
	if nc, ok := l.conn.(net.Conn); ok {
		return ipv4.NewConn(nc).SetTOS(dscp << 2)
	}
	return errors.New(errInvalidOperation)
}

// Accept implements the Accept method in the Listener interface; it waits for the next call and returns a generic Conn.
func (l *Listener) Accept() (net.Conn, error) {
	return l.AcceptKCP()
}

// AcceptKCP accepts a KCP connection
func (l *Listener) AcceptKCP() (*UDPSession, error) {
	var timeout <-chan time.Time
	if tdeadline, ok := l.rd.Load().(time.Time); ok && !tdeadline.IsZero() {
		timeout = time.After(tdeadline.Sub(time.Now()))
	}

	select {
	case <-timeout:
		return nil, &errTimeout{}
	case c := <-l.chAccepts:
		return c, nil
	case <-l.die:
		return nil, errors.New(errBrokenPipe)
	}
}

// SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
func (l *Listener) SetDeadline(t time.Time) error {
	l.SetReadDeadline(t)
	l.SetWriteDeadline(t)
	return nil
}

// SetReadDeadline implements the Conn SetReadDeadline method.
func (l *Listener) SetReadDeadline(t time.Time) error {
	l.rd.Store(t)
	return nil
}

// SetWriteDeadline implements the Conn SetWriteDeadline method.
func (l *Listener) SetWriteDeadline(t time.Time) error {
	l.wd.Store(t)
	return nil
}

// Close stops listening on the UDP address. Already Accepted connections are not closed.
func (l *Listener) Close() error {
	close(l.die)
	return l.conn.Close()
}

// Addr returns the listener's network address, The Addr returned is shared by all invocations of Addr, so do not modify it.
func (l *Listener) Addr() net.Addr {
	return l.conn.LocalAddr()
}

// Listen listens for incoming KCP packets addressed to the local address laddr on the network "udp",
func Listen(laddr string) (net.Listener, error) {
	return ListenWithOptions(laddr, nil, 0, 0)
}

// ListenWithOptions listens for incoming KCP packets addressed to the local address laddr on the network "udp" with packet encryption,
// dataShards, parityShards defines Reed-Solomon Erasure Coding parameters
func ListenWithOptions(laddr string, block BlockCrypt, dataShards, parityShards int) (*Listener, error) {
	udpaddr, err := net.ResolveUDPAddr("udp", laddr)
	if err != nil {
		return nil, errors.Wrap(err, "net.ResolveUDPAddr")
	}
	conn, err := net.ListenUDP("udp", udpaddr)
	if err != nil {
		return nil, errors.Wrap(err, "net.ListenUDP")
	}

	return ServeConn(block, dataShards, parityShards, conn)
}

// ServeConn serves KCP protocol for a single packet connection.
func ServeConn(block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*Listener, error) {
	l := new(Listener)
	l.conn = conn
	l.sessions = make(map[string]*UDPSession)
	l.chAccepts = make(chan *UDPSession, 1024)
	l.chDeadlinks = make(chan net.Addr, 1024)
	l.die = make(chan struct{})
	l.dataShards = dataShards
	l.parityShards = parityShards
	l.block = block
	l.fec = newFEC(rxFECMulti*(dataShards+parityShards), dataShards, parityShards)
	l.rxbuf.New = func() interface{} {
		return make([]byte, mtuLimit)
	}

	// calculate header size
	if l.block != nil {
		l.headerSize += cryptHeaderSize
	}
	if l.fec != nil {
		l.headerSize += fecHeaderSizePlus2
	}

	go l.monitor()
	return l, nil
}

// Dial connects to the remote address "raddr" on the network "udp"
func Dial(raddr string) (net.Conn, error) {
	return DialWithOptions(raddr, nil, 0, 0)
}

// DialWithOptions connects to the remote address "raddr" on the network "udp" with packet encryption
func DialWithOptions(raddr string, block BlockCrypt, dataShards, parityShards int) (*UDPSession, error) {
	udpaddr, err := net.ResolveUDPAddr("udp", raddr)
	if err != nil {
		return nil, errors.Wrap(err, "net.ResolveUDPAddr")
	}

	udpconn, err := net.DialUDP("udp", nil, udpaddr)
	if err != nil {
		return nil, errors.Wrap(err, "net.DialUDP")
	}

	return NewConn(raddr, block, dataShards, parityShards, &ConnectedUDPConn{udpconn, udpconn})
}

// NewConn establishes a session and talks KCP protocol over a packet connection.
func NewConn(raddr string, block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*UDPSession, error) {
	udpaddr, err := net.ResolveUDPAddr("udp", raddr)
	if err != nil {
		return nil, errors.Wrap(err, "net.ResolveUDPAddr")
	}

	var convid uint32
	binary.Read(rand.Reader, binary.LittleEndian, &convid)
	return newUDPSession(convid, dataShards, parityShards, nil, conn, udpaddr, block), nil
}

func currentMs() uint32 {
	return uint32(time.Now().UnixNano() / int64(time.Millisecond))
}

// ConnectedUDPConn is a wrapper for net.UDPConn which converts WriteTo syscalls
// to Write syscalls that are 4 times faster on some OS'es. This should only be
// used for connections that were produced by a net.Dial* call.
type ConnectedUDPConn struct {
	*net.UDPConn
	Conn net.Conn // underlying connection if any
}

// WriteTo redirects all writes to the Write syscall, which is 4 times faster.
func (c *ConnectedUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) {
	return c.Write(b)
}


text:
// this code is borrowed from RxOfficial(rx.codeplex.com) and modified

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace UniRx.InternalUtil
{
    internal class PriorityQueue<T> where T : IComparable<T>
    {
        private static long _count = long.MinValue;

        private IndexedItem[] _items;
        private int _size;

        public PriorityQueue()
            : this(16)
        {
        }

        public PriorityQueue(int capacity)
        {
            _items = new IndexedItem[capacity];
            _size = 0;
        }

        private bool IsHigherPriority(int left, int right)
        {
            return _items[left].CompareTo(_items[right]) < 0;
        }

        private void Percolate(int index)
        {
            if (index >= _size || index < 0)
                return;
            int parent = (index - 1) / 2;
            if (parent < 0 || parent == index)
                return;

            if (IsHigherPriority(index, parent))
            {
                IndexedItem temp = _items[index];
                _items[index] = _items[parent];
                _items[parent] = temp;
                Percolate(parent);
            }
        }

        private void Heapify()
        {
            Heapify(0);
        }

        private void Heapify(int index)
        {
            if (index >= _size || index < 0)
                return;

            int left = 2 * index + 1;
            int right = 2 * index + 2;
            int first = index;

            if (left < _size && IsHigherPriority(left, first))
                first = left;
            if (right < _size && IsHigherPriority(right, first))
                first = right;
            if (first != index)
            {
                IndexedItem temp = _items[index];
                _items[index] = _items[first];
                _items[first] = temp;
                Heapify(first);
            }
        }

        public int Count { get { return _size; } }

        public T Peek()
        {
            if (_size == 0)
                throw new InvalidOperationException("HEAP is Empty");

            return _items[0].Value;
        }

        private void RemoveAt(int index)
        {
            _items[index] = _items[--_size];
            _items[_size] = default(IndexedItem);
            Heapify();
            if (_size < _items.Length / 4)
            {
                IndexedItem[] temp = _items;
                _items = new IndexedItem[_items.Length / 2];
                Array.Copy(temp, 0, _items, 0, _size);
            }
        }

        public T Dequeue()
        {
            T result = Peek();
            RemoveAt(0);
            return result;
        }

        public void Enqueue(T item)
        {
            if (_size >= _items.Length)
            {
                IndexedItem[] temp = _items;
                _items = new IndexedItem[_items.Length * 2];
                Array.Copy(temp, _items, temp.Length);
            }

            int index = _size++;
            _items[index] = new IndexedItem { Value = item, Id = Interlocked.Increment(ref _count) };
            Percolate(index);
        }

        public bool Remove(T item)
        {
            for (int i = 0; i < _size; ++i)
            {
                if (EqualityComparer<T>.Default.Equals(_items[i].Value, item))
                {
                    RemoveAt(i);
                    return true;
                }
            }

            return false;
        }

        struct IndexedItem : IComparable<IndexedItem>
        {
            public T Value;
            public long Id;

            public int CompareTo(IndexedItem other)
            {
                int c = Value.CompareTo(other.Value);
                if (c == 0)
                    c = Id.CompareTo(other.Id);
                return c;
            }
        }
    }
}


text:
using UnityEngine;
using System.Collections;

public class GrandFlowerPlanetBloomed : PollenPlanet {

	public WiltedPlanet[] linkedPlanets;
	// Use this for initialization
	public override void Start () {
        planetType = "grandPollenBloomed";
		makesPollen = true;
	}

	// Update is called once per frame
	void Update () {

	}

	public override void updateLinkedPlanets()
	{
		foreach (WiltedPlanet planet in linkedPlanets)
		{
			planet.transformWilted();
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/rl_base_titlebar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent">

        <ImageView
            android:id="@+id/iv_base_titlebar_bg"
            android:layout_width="match_parent"
            android:layout_height="310dp"
            android:scaleType="fitXY" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/tb_base_title"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorTransparent"
            app:contentInsetStart="0.0dp"
            app:layout_collapseMode="pin"
            app:layout_scrollFlags="enterAlways|scroll"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:theme="@style/ToolbarStyle">

        </android.support.v7.widget.Toolbar>

    </RelativeLayout>
</layout>


text:
package com.gentics.mesh.assertj.impl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import com.gentics.mesh.assertj.AbstractMeshElementEventModelAssert;
import com.gentics.mesh.core.rest.event.tagfamily.TagFamilyMeshEventModel;

public class TagFamilyMeshEventModelAssert extends AbstractMeshElementEventModelAssert<TagFamilyMeshEventModelAssert, TagFamilyMeshEventModel> {

	public TagFamilyMeshEventModelAssert(TagFamilyMeshEventModel actual) {
		super(actual, TagFamilyMeshEventModelAssert.class);
	}

	public TagFamilyMeshEventModelAssert hasProject(String projectName, String projectUuid) {
		assertNotNull("The project reference was missing in the tag family event.", actual.getProject());
		assertEquals("The project name was missing in the tag family event.", projectName, actual.getProject().getName());
		assertEquals("The project uuid was missing in the tag family event.", projectUuid, actual.getProject().getUuid());
		return this;
	}

}


text:
package telemetry_test

import (
	"fmt"
	"testing"

	"github.com/pingcap/tidb/sessionctx/variable"
	"github.com/pingcap/tidb/telemetry"
	"github.com/pingcap/tidb/testkit"
	"github.com/stretchr/testify/require"
)

func TestTxnUsageInfo(t *testing.T) {
	t.Parallel()

	store, clean := testkit.CreateMockStore(t)
	defer clean()

	t.Run("Used", func(t *testing.T) {
		tk := testkit.NewTestKit(t, store)
		tk.MustExec(fmt.Sprintf("set global %s = 0", variable.TiDBEnableAsyncCommit))
		tk.MustExec(fmt.Sprintf("set global %s = 0", variable.TiDBEnable1PC))

		txnUsage := telemetry.GetTxnUsageInfo(tk.Session())
		require.False(t, txnUsage.AsyncCommitUsed)
		require.False(t, txnUsage.OnePCUsed)

		tk.MustExec(fmt.Sprintf("set global %s = 1", variable.TiDBEnableAsyncCommit))
		tk.MustExec(fmt.Sprintf("set global %s = 1", variable.TiDBEnable1PC))

		txnUsage = telemetry.GetTxnUsageInfo(tk.Session())
		require.True(t, txnUsage.AsyncCommitUsed)
		require.True(t, txnUsage.OnePCUsed)
	})

	t.Run("Count", func(t *testing.T) {
		tk := testkit.NewTestKit(t, store)
		tk.MustExec("use test")
		tk.MustExec("drop table if exists txn_usage_info")
		tk.MustExec("create table txn_usage_info (a int)")
		tk.MustExec(fmt.Sprintf("set %s = 1", variable.TiDBEnableAsyncCommit))
		tk.MustExec(fmt.Sprintf("set %s = 1", variable.TiDBEnable1PC))
		tk.MustExec("insert into txn_usage_info values (1)")
		tk.MustExec(fmt.Sprintf("set %s = 0", variable.TiDBEnable1PC))
		tk.MustExec("insert into txn_usage_info values (2)")
		tk.MustExec(fmt.Sprintf("set %s = 0", variable.TiDBEnableAsyncCommit))
		tk.MustExec("insert into txn_usage_info values (3)")

		txnUsage := telemetry.GetTxnUsageInfo(tk.Session())
		require.True(t, txnUsage.AsyncCommitUsed)
		require.True(t, txnUsage.OnePCUsed)
		require.Greater(t, txnUsage.TxnCommitCounter.AsyncCommit, int64(0))
		require.Greater(t, txnUsage.TxnCommitCounter.OnePC, int64(0))
		require.Greater(t, txnUsage.TxnCommitCounter.TwoPC, int64(0))
	})
}

func TestTemporaryTable(t *testing.T) {
	t.Parallel()

	store, clean := testkit.CreateMockStore(t)
	defer clean()

	tk := testkit.NewTestKit(t, store)
	tk.MustExec("use test")

	usage, err := telemetry.GetFeatureUsage(tk.Session())
	require.NoError(t, err)
	require.False(t, usage.TemporaryTable)

	tk.MustExec("create global temporary table t (id int) on commit delete rows")
	usage, err = telemetry.GetFeatureUsage(tk.Session())
	require.NoError(t, err)
	require.True(t, usage.TemporaryTable)
}


text:
/**
* @author Alexander Y. Kleymenov
* @version $Revision$
*/

package org.apache.harmony.security.x509;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import org.apache.harmony.security.asn1.ASN1BitString;
import org.apache.harmony.security.asn1.ASN1Sequence;
import org.apache.harmony.security.asn1.ASN1Type;
import org.apache.harmony.security.asn1.BerInputStream;
import org.apache.harmony.security.asn1.BitString;
import org.apache.harmony.security.utils.AlgNameMapper;

/**
 * The class encapsulates the ASN.1 DER encoding/decoding work
 * with the following structure which is a part of X.509 certificate
 * (as specified in RFC 3280 -
 *  Internet X.509 Public Key Infrastructure.
 *  Certificate and Certificate Revocation List (CRL) Profile.
 *  http://www.ietf.org/rfc/rfc3280.txt):
 *
 * <pre>
 *  SubjectPublicKeyInfo  ::=  SEQUENCE  {
 *      algorithm            AlgorithmIdentifier,
 *      subjectPublicKey     BIT STRING
 *  }
 * </pre>
 */
public class SubjectPublicKeyInfo {

    // the value of algorithmID field of the structure
    private AlgorithmIdentifier algorithmID;
    // the value of subjectPublicKey field of the structure
    private byte[] subjectPublicKey;
    // the public key corresponding to this SubjectPublicKeyInfo
    private PublicKey publicKey;
    // the value of unusedBits field of the structure
    private int unusedBits;
    // the ASN.1 encoded form of SubjectPublicKeyInfo
    private byte[] encoding;

    /**
     * TODO
     * @param   algID:  AlgorithmIdentifier
     * @param   subjectPublicKey:   byte[]
     */
    public SubjectPublicKeyInfo(AlgorithmIdentifier algID,
                                byte[] subjectPublicKey) {
        this(algID, subjectPublicKey, 0);
    }

    /**
     * TODO
     * @param   algID:  AlgorithmIdentifier
     * @param   subjectPublicKey:   byte[]
     * @param   unused: int
     */
    public SubjectPublicKeyInfo(AlgorithmIdentifier algID,
                                byte[] subjectPublicKey, int unused) {
        this(algID, subjectPublicKey, 0, null);
    }

    //
    // TODO
    // @param   algID:  AlgorithmIdentifier
    // @param   subjectPublicKey:   byte[]
    // @param   unused: int
    // @param   encoding:   byte[]
    //
    private SubjectPublicKeyInfo(AlgorithmIdentifier algID,
                                 byte[] subjectPublicKey, int unused,
                                 byte[] encoding) {
        this.algorithmID = algID;
        this.subjectPublicKey = subjectPublicKey;
        this.unusedBits = unused;
        this.encoding = encoding;
    }

    /**
     * Returns the value of algorithmIdentifier field of the structure.
     * @return  algorithmIdentifier
     */
    public AlgorithmIdentifier getAlgorithmIdentifier() {
        return algorithmID;
    }

    /**
     * Returns the value of subjectPublicKey field of the structure.
     * @return  subjectPublicKey
     */
    public byte[] getSubjectPublicKey() {
        return subjectPublicKey;
    }

    /**
     * Returns the value of unusedBits field of the structure.
     * @return  unusedBits
     */
    public int getUnusedBits() {
        return unusedBits;
    }

    /**
     * Returns ASN.1 encoded form of this X.509 SubjectPublicKeyInfo value.
     * @return a byte array containing ASN.1 encode form.
     */
    public byte[] getEncoded() {
        if (encoding == null) {
            encoding = ASN1.encode(this);
        }
        return encoding;
    }

    /**
     * Returns The PublicKey corresponding to this SubjectPublicKeyInfo
     * instance.
     * @return public key corresponding to this SubjectPublicKeyInfo.
     */
    public PublicKey getPublicKey() {
        if (publicKey == null) {
            String alg_oid = algorithmID.getAlgorithm();
            try {
                String alg =
                    AlgNameMapper.map2AlgName(alg_oid);

                if (alg == null) {
                    alg = alg_oid;
                }
                publicKey = KeyFactory.getInstance(alg)
                    .generatePublic(new X509EncodedKeySpec(getEncoded()));
            } catch (InvalidKeySpecException e) {
            } catch (NoSuchAlgorithmException e) {
            }
            if (publicKey == null) {
                publicKey = new X509PublicKey(alg_oid, getEncoded(),
                        subjectPublicKey);
            }
        }
        return publicKey;
    }

    public static final ASN1Sequence ASN1 = new ASN1Sequence(new ASN1Type[] {
            AlgorithmIdentifier.ASN1, ASN1BitString.getInstance() }) {

        protected Object getDecodedObject(BerInputStream in) {
            Object[] values = (Object[]) in.content;
            return new SubjectPublicKeyInfo(
                    (AlgorithmIdentifier) values[0],
                    ((BitString) values[1]).bytes,
                    ((BitString) values[1]).unusedBits,
                    in.getEncoded());
        }

        protected void getValues(Object object, Object[] values) {

            SubjectPublicKeyInfo spki = (SubjectPublicKeyInfo) object;

            values[0] = spki.algorithmID;
            values[1] = new BitString(spki.subjectPublicKey, spki.unusedBits);
        }
    };
}


text:
#ifndef POISSONSOLVER_HH
#define POISSONSOLVER_HH

#define HAVE_MPI

#include <vector>

#ifdef HAVE_MPI
#    include "mpi.h"
#    include "Epetra_MpiComm.h"
#else
#    include "Epetra_SerialComm.h"
#endif

#include "Epetra_Map.h"
#include "Epetra_Vector.h"
#include "Epetra_CrsMatrix.h"
#include "Teuchos_RCP.hpp"
#include "Teuchos_ParameterList.hpp"

#include "ml_MultiLevelPreconditioner.h"
#include "ml_MultiLevelOperator.h"
#include "ml_epetra_utils.h"

#include "defs.hh"
#include "PartBunch.hh"
#include "Bend.hh"
#include "BoundaryCell.hh"
#include "Commands/BinaryVTKFile.hh"
#include "Commands/ASCIIVTKFile.hh"

/** \brief computes the electrostatic field due to a charge density
 *         inside the domain. Used at the beginning of a simulation
 *         where only the particles distribution in phase space is
 *         known. Implemented as described in
 *         A fast parallel Poisson solver on irregular domains applied to beam dynamics simulations
 *         by A. Adelmann,P. Arbenz and Y. Ineichen.
 */
class PoissonSolver
{
public:
    PoissonSolver(PartBunch & bunch,
                  const Bend & bend,
                  const std::vector<BoundaryCell>& bc,
                  const Mesh_t & mesh,
                  const FieldLayout<DIM> & fl,
                  const BCType & periodicX = PEC,
                  const BCType & periodicY = PEC);
    ~PoissonSolver()
    { ;}

    /// actual computation
    void computeField(VField_Edge_t & EFD,
                      VField_Cell_t & HFD,
                      VField_Edge_t & JFD,
                      const double & dt,
                      const double & tol = 1e-8,
                      const int & maxIterations = 100);
private:
    void SetupMLList(Teuchos::ParameterList & MLList) const;

    Epetra_Map* getGlobalElements();

    /// building the stencil
    void StencilGeometry(Teuchos::RCP<Epetra_Vector> & RHS,
                         Teuchos::RCP<Epetra_CrsMatrix> & A);

    void linearStencil(std::vector<int> & Indices,
                       std::vector<double> & Values,
                       double & rhs,
                       size_t & NumEntries,
                       const Field<bool, DIM, Mesh_t, Vert> & isInside,
                       const size_t & gid);

    void cutoffStencil(std::vector<int> & Indices,
                       std::vector<double> & Values,
                       double & rhs,
                       size_t & NumEntries,
                       const Field<bool, DIM, Mesh_t, Cell> & isInside,
                       const size_t & gid);

    void initializeLHS(Teuchos::RCP<Epetra_Vector> & LHS) const;

    void shiftLHS(SField_t & rho,
                  Teuchos::RCP<Epetra_Vector> & LHS,
                  double tau = 1.0) const;

    void subtract(const SField_t & rho,
                  Teuchos::RCP<Epetra_Vector> & LHS) const;

    void add(const SField_t & rho,
             Teuchos::RCP<Epetra_Vector> & LHS) const;

    void initialGuessLHS(Teuchos::RCP<Epetra_Vector> & LHS) const;

    void fillRHS(const SField_t & rho,
                 Teuchos::RCP<Epetra_Vector> & RHS);

    void fillFields(const Teuchos::RCP<Epetra_Vector> & RHS,
                    VField_Edge_t & EFD,
                    VField_Cell_t & HFD,
                    const int & component = -1);

    void plotPotential(BinaryVtkFile & vtkFile,
                       const Teuchos::RCP<Epetra_Vector> & LHS,
                       const VField_Edge_t & EFD,
                       const int & component);

    bool isInside(const int & idx, const int & idy);

    void distance_bunch_to_boundary(std::vector<double> & dist,
                                    const double & x,
                                    const double & y);

    void print(const std::string & filename,
               Teuchos::RCP<Epetra_Vector> & RHS,
               Teuchos::RCP<Epetra_CrsMatrix> & A) const;

    void printRhoOverLine(const Teuchos::RCP<Epetra_Vector> & LHS,
                          const int & line_nr,
                          std::ostream & out);

    void printEyOverLine(const VField_Edge_t & EFD,
                         const int & line_nr,
                         std::ostream & out);

    void printHzOverLine(const VField_Cell_t & HFD,
                         const int & line_nr,
                         std::ostream & out);

    double _gamma;

    NDIndex<DIM> _lDom;
    NDIndex<DIM> _gDom;
    size_t _Nx;
    size_t _Ny;
    std::vector<double> _hr;
    BCType _bctX;
    BCType _bctY;

    PartBunch & _bunch;

    const Bend & _bend;
    const std::vector<BoundaryCell> & _boundaryCells;
    const Mesh_t & _mesh;
    const FieldLayout<DIM> & _FL;

    Timings::TimerRef _solveTimer;
    Timings::TimerRef _setupTimer;

};

inline
void PoissonSolver::SetupMLList(Teuchos::ParameterList & MLList) const {
    ML_Epetra::SetDefaults("SA", MLList);
    MLList.set("max levels", 8);
    MLList.set("increasing or decreasing", "increasing");

    // we use a V-cycle
    MLList.set("prec type", "MGV");

    // uncoupled aggregation is used (every processor aggregates
    // only local data)
    MLList.set("aggregation: type", "Uncoupled");

    // smoother related parameters
    MLList.set("smoother: type","Chebyshev");
    MLList.set("smoother: sweeps", 3);
    MLList.set("smoother: pre or post", "both");

    // on the coarsest level we solve with  Tim Davis' implementation of
    // Gilbert-Peierl's left-looking sparse partial pivoting algorithm,
    // with Eisenstat & Liu's symmetric pruning. Gilbert's version appears
    // as \c [L,U,P]=lu(A) in MATLAB. It doesn't exploit dense matrix
    // kernels, but it is the only sparse LU factorization algorithm known to be
    // asymptotically optimal, in the sense that it takes time proportional to the
    // number of floating-point operations.
    MLList.set("coarse: type", "Amesos-KLU");

    //FIXME: CHEBY COARSE LEVEL SOLVER
    // SEE PAPER FOR EVALUATION KLU vs. Chebyshev
    //MLList.set("coarse: sweeps", 10);
    //MLList.set("coarse: type", "Chebyshev");

    // turn on all output
//     if(verbose_m)
//         MLList.set("ML output", 101);
//     else
        MLList.set("ML output", 10);

    // try to optimize mem for xt3
    //MLList.set("low memory usage", true);

    // heuristic for max coarse size depending on number of processors
    int coarsest_size = std::max(Ippl::getNodes() * 10, 1024);
    MLList.set("coarse: max size", coarsest_size);
}

inline
Epetra_Map* PoissonSolver::getGlobalElements()
{
#ifdef HAVE_MPI
    Epetra_MpiComm Comm(MPI_COMM_WORLD);
#else
    Epetra_SerialComm Comm;
#endif

    int NumMyElements = (_lDom[0].last() - _lDom[0].first() + 1) *
                        (_lDom[1].last() - _lDom[1].first() + 1);

    unsigned int lid = 0;
    std::vector<int> MyGlobalElements(NumMyElements);
    for (int j = _lDom[1].first(); j <= _lDom[1].last(); ++ j) {
        for (int i = _lDom[0].first(); i <= _lDom[0].last(); ++ i) {
            MyGlobalElements[lid ++] = i + j * _Nx;
        }
    }

    return new Epetra_Map(_Nx * _Ny, NumMyElements, &MyGlobalElements[0], 0, Comm);
}

#endif


text:
package com.example.monoblos.myapplication00;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.facebook.FacebookSdk;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;

public class AddAnnActivity extends AppCompatActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    private NavigationDrawerFragment mNavigationDrawerFragment;
    private String id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_ann);

        setNegative();
        setImage();
        setBtn();
        setId();
    }

    private void setId(){
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            this.id = bundle.getString("id");
        }
    }

    private void sendReq(String req){
        HttpPostConnection httpPostConnection = new HttpPostConnection();
        String s = null;
        String result = "Fail";
        String pass = "http://203.151.92.187:8080/addAnnouncement";

        try {
            httpPostConnection.execute(pass,req);
            s = httpPostConnection.get();
            JSONObject parentObject = new JSONObject(s);
            result = parentObject.getString("status");
        }catch(ExecutionException e){e.printStackTrace();
        }catch(CancellationException e){e.printStackTrace();
        }catch(InterruptedException e){e.printStackTrace();
        }catch(JSONException e){ e.printStackTrace();}
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
    }

    private void setBtn(){
        Button btn = (Button)findViewById(R.id.btnCreate);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean ch = true;
                EditText editTitle = (EditText) findViewById(R.id.addTitle);
                EditText editDes = (EditText) findViewById(R.id.addDes);

                if(editTitle.getText().toString().equals("")) ch = false;
                if(editDes.getText().toString().equals("")) ch = false;

                if(ch) {
                    String inParam = "sessionId=" + URLEncoder.encode(SingletonID.getInstance().getSessionId()) +
                            "&courseId=" + URLEncoder.encode(id) +
                            "&title=" + URLEncoder.encode(editTitle.getText().toString()) +
                            "&description=" + URLEncoder.encode(editDes.getText().toString());

                    sendReq(inParam);
                    finish();
                }
                else Toast.makeText(getApplicationContext(),"ข้อมูลไม่ครบ",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setNegative(){
        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));
    }

    private void setImage(){
        ImageView imageview = (ImageView)findViewById(R.id.imageView);
        imageview.setImageResource(R.drawable.ic_announcement_black_24dp);
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                .commit();
    }

    public void onSectionAttached(int number) {
        switch (number) {
            case 1:
                if(getSupportFragmentManager().getFragments().size()>1) {
                    Intent intent = new Intent(this, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();
                }
                break;
            case 2:
                startActivity(new Intent(this,SearchActivity.class));
                break;
            case 3:
                if(SingletonID.getInstance().getStatus()==0) startActivity(new Intent(this,AnnStdActivity.class));
                else startActivity(new Intent(this,SearchStudentActivity.class));
                break;
            case 4:
                if(SingletonID.getInstance().getStatus()==0){
                    startActivity(new Intent(this, MyCourseActivity.class));
                }
                else startActivity(new Intent(this, CreateSubjectActivity.class));
                break;
            case 5:
                if(SingletonID.getInstance().getStatus()==0){
                    SingletonID.getInstance().clear();
                    FacebookSdk.clearLoggingBehaviors();
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();
                }
                else {//my course teacher
                    startActivity(new Intent(this, MyCourseTeacherActivity.class));
                }
                break;
            case 6:
                if(SingletonID.getInstance().getStatus()==1){
                    SingletonID.getInstance().clear();
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();
                }
                break;
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle("CE SMART TRACKER");
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#003366")));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((AddAnnActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
        }
    }
}


text:
package integrations

import (
	"fmt"
	"net/http"
	"testing"

	"code.gitea.io/gitea/models"
	api "code.gitea.io/gitea/modules/structs"

	"github.com/stretchr/testify/assert"
)

const testHookContent = `#!/bin/bash

echo Hello, World!
`

func TestAPIListGitHooks(t *testing.T) {
	defer prepareTestEnv(t)()

	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository)
	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)

	// user1 is an admin user
	session := loginUser(t, "user1")
	token := getTokenForLoggedInUser(t, session)
	req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s",
		owner.Name, repo.Name, token)
	resp := MakeRequest(t, req, http.StatusOK)
	var apiGitHooks []*api.GitHook
	DecodeJSON(t, resp, &apiGitHooks)
	assert.Len(t, apiGitHooks, 3)
	for _, apiGitHook := range apiGitHooks {
		if apiGitHook.Name == "pre-receive" {
			assert.True(t, apiGitHook.IsActive)
			assert.Equal(t, testHookContent, apiGitHook.Content)
		} else {
			assert.False(t, apiGitHook.IsActive)
			assert.Empty(t, apiGitHook.Content)
		}
	}
}

func TestAPIListGitHooksNoHooks(t *testing.T) {
	defer prepareTestEnv(t)()

	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)

	// user1 is an admin user
	session := loginUser(t, "user1")
	token := getTokenForLoggedInUser(t, session)
	req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s",
		owner.Name, repo.Name, token)
	resp := MakeRequest(t, req, http.StatusOK)
	var apiGitHooks []*api.GitHook
	DecodeJSON(t, resp, &apiGitHooks)
	assert.Len(t, apiGitHooks, 3)
	for _, apiGitHook := range apiGitHooks {
		assert.False(t, apiGitHook.IsActive)
		assert.Empty(t, apiGitHook.Content)
	}
}

func TestAPIListGitHooksNoAccess(t *testing.T) {
	defer prepareTestEnv(t)()

	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)

	session := loginUser(t, owner.Name)
	token := getTokenForLoggedInUser(t, session)
	req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s",
		owner.Name, repo.Name, token)
	MakeRequest(t, req, http.StatusForbidden)
}

func TestAPIGetGitHook(t *testing.T) {
	defer prepareTestEnv(t)()

	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository)
	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)

	// user1 is an admin user
	session := loginUser(t, "user1")
	token := getTokenForLoggedInUser(t, session)
	req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s",
		owner.Name, repo.Name, token)
	resp := MakeRequest(t, req, http.StatusOK)
	var apiGitHook *api.GitHook
	DecodeJSON(t, resp, &apiGitHook)
	assert.True(t, apiGitHook.IsActive)
	assert.Equal(t, testHookContent, apiGitHook.Content)
}

func TestAPIGetGitHookNoAccess(t *testing.T) {
	defer prepareTestEnv(t)()

	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)

	session := loginUser(t, owner.Name)
	token := getTokenForLoggedInUser(t, session)
	req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s",
		owner.Name, repo.Name, token)
	MakeRequest(t, req, http.StatusForbidden)
}

func TestAPIEditGitHook(t *testing.T) {
	defer prepareTestEnv(t)()

	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)

	// user1 is an admin user
	session := loginUser(t, "user1")
	token := getTokenForLoggedInUser(t, session)

	urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s",
		owner.Name, repo.Name, token)
	req := NewRequestWithJSON(t, "PATCH", urlStr, &api.EditGitHookOption{
		Content: testHookContent,
	})
	resp := MakeRequest(t, req, http.StatusOK)
	var apiGitHook *api.GitHook
	DecodeJSON(t, resp, &apiGitHook)
	assert.True(t, apiGitHook.IsActive)
	assert.Equal(t, testHookContent, apiGitHook.Content)

	req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s",
		owner.Name, repo.Name, token)
	resp = MakeRequest(t, req, http.StatusOK)
	var apiGitHook2 *api.GitHook
	DecodeJSON(t, resp, &apiGitHook2)
	assert.True(t, apiGitHook2.IsActive)
	assert.Equal(t, testHookContent, apiGitHook2.Content)
}

func TestAPIEditGitHookNoAccess(t *testing.T) {
	defer prepareTestEnv(t)()

	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)

	session := loginUser(t, owner.Name)
	token := getTokenForLoggedInUser(t, session)
	urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s",
		owner.Name, repo.Name, token)
	req := NewRequestWithJSON(t, "PATCH", urlStr, &api.EditGitHookOption{
		Content: testHookContent,
	})
	MakeRequest(t, req, http.StatusForbidden)
}

func TestAPIDeleteGitHook(t *testing.T) {
	defer prepareTestEnv(t)()

	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository)
	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)

	// user1 is an admin user
	session := loginUser(t, "user1")
	token := getTokenForLoggedInUser(t, session)

	req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s",
		owner.Name, repo.Name, token)
	MakeRequest(t, req, http.StatusNoContent)

	req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s",
		owner.Name, repo.Name, token)
	resp := MakeRequest(t, req, http.StatusOK)
	var apiGitHook2 *api.GitHook
	DecodeJSON(t, resp, &apiGitHook2)
	assert.False(t, apiGitHook2.IsActive)
	assert.Empty(t, apiGitHook2.Content)
}

func TestAPIDeleteGitHookNoAccess(t *testing.T) {
	defer prepareTestEnv(t)()

	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)

	session := loginUser(t, owner.Name)
	token := getTokenForLoggedInUser(t, session)
	req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s",
		owner.Name, repo.Name, token)
	MakeRequest(t, req, http.StatusForbidden)
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>nodeAttributes</key>
	<dict>
		<key>category</key>
		<string>- Kineme GL</string>
		<key>categories</key>
		<array>
			<string>- Kineme GL</string>
		</array>
		<key>copyright</key>
		<string>Copyright 2008 Kosada Incorporated. All rights reserved.</string>
		<key>description</key>
		<string>This patch renders a GL Mesh structure.

Despite being in the public release of GL Tools, this patch is considered a Beta and should not be used in a production environment.

http://kineme.net/</string>
		<key>name</key>
		<string>GL Grid Renderer</string>
	</dict>
	<key>inputAttributes</key>
	<dict>
		<key>inputStructure</key>
		<dict>
			<key>description</key>
			<string>Grid structure to render</string>
			<key>name</key>
			<string>Structure Input</string>
		</dict>
		<key>inputWireFrame</key>
		<dict>
			<key>description</key>
			<string>Controls whether or not to render a white wireframe over the mesh</string>
			<key>name</key>
			<string>Wireframe</string>
			<key>menu</key>
				<array>
					<string>None</string>
					<string>Triangles</string>
					<string>Quads</string>
				</array>
		</dict>
		<key>inputSubdivisionAmount</key>
		<dict>
			<key>description</key>
			<string>Subdivide quads (useful for faking perspective projection)</string>
			<key>name</key>
			<string>Subdivision Level</string>
		</dict>
		<key>inputSelection</key>
		<dict>
			<key>description</key>
			<string>Selected input.  Used with the Highlighter to help visualize grid-modification</string>
			<key>name</key>
			<string>Selected Point</string>
		</dict>
		<key>inputHighlightSelection</key>
		<dict>
			<key>description</key>
			<string>Determines whether or not a highlight point will be drawn over the currently selected point.</string>
			<key>name</key>
			<string>Highlight Selection</string>
		</dict>
		<key>inputImage</key>
		<dict>
			<key>description</key>
			<string>Image to texture the grid with.</string>
			<key>name</key>
			<string>Image</string>
		</dict>
		<key>inputColor</key>
		<dict>
			<key>description</key>
			<string>Grid color</string>
			<key>name</key>
			<string>Color</string>
		</dict>
	</dict>
</dict>
</plist>


text:
export * from './auth';
export * from './restricted';
export * from './app.routes';
export * from './app.component';
export * from './app.module';
export * from './tickets'