text:
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Grouchy.HttpApi.Client.Abstractions.Exceptions;
using Grouchy.HttpApi.Client.Abstractions.Extensions;
using Grouchy.HttpApi.Client.Extensions;
using Grouchy.HttpApi.Client.Tests.Configuration;
using Grouchy.HttpApi.Client.Tests.Stubs;
using NUnit.Framework;
using Shouldly;

namespace Grouchy.HttpApi.Client.Tests.instrumenting_scenarios
{
   // ReSharper disable once InconsistentNaming
   public class get_throws_exception
   {
      private readonly StubHttpClientEventCallback _callback = new StubHttpClientEventCallback();

      private Exception _exceptionThrown;
      private Exception _exception;

      [OneTimeSetUp]
      public async Task  setup_scenario()
      {
         _exceptionThrown = new Exception();
         var baseHttpClient = new StubHttpClient(_exceptionThrown);
         var configuration = new InstrumentingConfiguration {Uri = new Uri("http://exception-host")};
         var httpClient = baseHttpClient.AddInstrumenting(configuration, new []{_callback});

         try
         {
            await httpClient.GetAsync("/ping");
         }
         catch (Exception e)
         {
            _exception = e;
         }
      }

      [Test]
      public void should_log_request_initiated()
      {
         var lastRequest = _callback.RequestsInitiated.Last();
         lastRequest.ShouldNotBeNull();
         lastRequest.EventType.ShouldBe("HttpClientRequestInitiated");
         lastRequest.Uri.ShouldBe("http://exception-host/ping");
         lastRequest.Method.ShouldBe("GET");
      }

      [Test]
      public void should_not_log_response()
      {
         _callback.ResponsesReceived.ShouldBeEmpty();
      }

      [Test]
      public void should_not_log_timeout_received()
      {
         _callback.TimeOuts.ShouldBeEmpty();
      }

      [Test]
      public void should_log_exception_received()
      {
         var lastException = _callback.ExceptionsThrown.Last();
         lastException.ShouldNotBeNull();
         lastException.EventType.ShouldBe("HttpClientExceptionThrown");
         lastException.Uri.ShouldBe("http://exception-host/ping");
         lastException.Method.ShouldBe("GET");
         lastException.Exception.ShouldBeSameAs(_exceptionThrown);
      }

      [Test]
      public void should_throw_http_client_exception()
      {
         _exception.ShouldBeOfType<HttpClientException>();
      }

      [Test]
      public void should_populate_http_client_exception()
      {
         var httpClientException = (HttpClientException)_exception;

         httpClientException.InnerException.ShouldBeSameAs(_exceptionThrown);
         httpClientException.RequestUri.ShouldBe(new Uri("http://exception-host/ping"));
         httpClientException.Method.ShouldBe(HttpMethod.Get);
         httpClientException.Message.ShouldBe("Unexpected exception, GET http://exception-host/ping");
      }
   }
}


text:
import { IParallelEnumerable } from "../../types"
import { nextIteration } from "./_nextIteration"
import { typeDataToArray } from "./_typeDataToArray"

export const partition = async <TSource>(
    source: IParallelEnumerable<TSource>, predicate: (x: TSource) => boolean): Promise<[pass: TSource[], fail: TSource[]]> => {
    const dataFunc = nextIteration(source, (value) => {
        return [predicate(value), value] as [boolean, TSource]
    })

    const values = await typeDataToArray(dataFunc)

    const fail: TSource[] = []
    const pass: TSource[] = []

    for (const [passed, value] of values) {
        if (passed) {
            pass.push(value)
        } else {
            fail.push(value)
        }
    }

    return [pass, fail]
}

redpajama_set_name: RedPajamaGithub


text:
<?php
if (isset($_POST['Constituency']) && isset($_POST['NNP']) && isset($_POST['NDC'])) {
	$constituency = $_POST['Constituency'];
	$NNP = $_POST['NNP'];
	$NDC = $_POST['NDC'];
	$res = updatePoll($constituency, $NNP, $NDC);
}

if (isset($_POST['Constituency']) && isset($_POST['DeleteConstituency'])) {
	$constituencyDel = $_POST['Constituency'];
	$res = deleteConstituency($constituencyDel);
	//echo $res;
}

function getDBConnection(){
	try{ // Uses try and catch to handle any unforeseen errors
		$db = new mysqli("localhost","root","","evsdatabase");
		if ($db == null && $db->connect_errno > 0) return null;
		return $db;
	}catch(Exception $e){ } // We currently do nothing in the catch, but later we can log
	return null;
}

function getVotes() {
	$votes = [];
	$db = getDBConnection();
	$sql = "SELECT * FROM votes";
	if ($db) {
		$results = $db->query($sql);
		while ($results && $row = $results->fetch_array(MYSQLI_ASSOC)) {
			$votes [] = $row;
		}
		$db->close();
	}
	return $votes;
}

function updatePoll($constituency, $NNP,  $NDC) {
	$success = False;
	$db = getDBConnection();
	$sql = "UPDATE votes SET NNPTraditional = $NNP, NDCTraditional = $NDC WHERE Constituency = '$constituency';";
	if ($db) {
		$success = $db->query($sql);
		$db->close();
	}
	return $success;
}

function deleteConstituency($constituency) {
	$success = False;
	$db = getDBConnection();
	$sql = "DELETE FROM `evsdatabase`.`votes` WHERE `votes`.`Constituency` = '$constituency';";
	if ($db) {
		$success = $db->query($sql);
		$db->close();
	}
	if ($success == False) {
		echo "<script type='text/javascript'>alert('Ooops Delete Fail');</script>";
	}
	return $success;
}

function addConstituency($constituency) {
	$success = False;
	$db = getDBConnection();
	$sql = "INSERT INTO votes (Constituency) VALUES ('$constituency');";
	if ($db) {
		$success = $db->query($sql);
		$db->close();
	}
	return $success;
}

function editConstituency($old, $new) {
	$success = False;
	$db = getDBConnection();
	$sql = "UPDATE  `evsdatabase`.`votes` SET  `Constituency` =  '$new' WHERE  `votes`.`Constituency` =  '$old';";
	if ($db) {
		$success = $db->query($sql);
		$db->close();
	}
	return $success;
}

?>


text:
<?php

namespace Aeurus\AdminBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Aeurus\AdminBundle\Entity\ThemeComment;
use Aeurus\AdminBundle\Form\ThemeCommentType;

/**
 * ThemeComment controller.
 *
 * @Route("/themecoment")
 */
class ThemeCommentController extends Controller
{
    /**
     * Lists all ThemeComment entities.
     *
     * @Route("/", name="admin_themecoment")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('AeurusAdminBundle:ThemeComment')->findAll();

        return array(
            'entities' => $entities,
        );
    }

    /**
     * Creates a new ThemeComment entity.
     *
     * @Route("/", name="admin_themecoment_create")
     * @Method("POST")
     * @Template("AeurusAdminBundle:ThemeComment:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity  = new ThemeComment();
        $form = $this->createForm(new ThemeCommentType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_themecoment_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Displays a form to create a new ThemeComment entity.
     *
     * @Route("/new", name="admin_themecoment_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new ThemeComment();
        $form   = $this->createForm(new ThemeCommentType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a ThemeComment entity.
     *
     * @Route("/{id}", name="admin_themecoment_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AeurusAdminBundle:ThemeComment')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find ThemeComment entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing ThemeComment entity.
     *
     * @Route("/{id}/edit", name="admin_themecoment_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AeurusAdminBundle:ThemeComment')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find ThemeComment entity.');
        }

        $editForm = $this->createForm(new ThemeCommentType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing ThemeComment entity.
     *
     * @Route("/{id}", name="admin_themecoment_update")
     * @Method("PUT")
     * @Template("AeurusAdminBundle:ThemeComment:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AeurusAdminBundle:ThemeComment')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find ThemeComment entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new ThemeCommentType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_themecoment_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a ThemeComment entity.
     *
     * @Route("/{id}", name="admin_themecoment_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('AeurusAdminBundle:ThemeComment')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find ThemeComment entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('admin_themecoment'));
    }

    /**
     * Creates a form to delete a ThemeComment entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}


text:
import claripy
import logging

from ..java import JavaSimProcedure
from ...engines.soot.expressions import SimSootExpr_NewArray, SimSootExpr_NullConstant
from ...engines.soot.values import SimSootValue_StringRef, SimSootValue_ThisRef
from .collection import ELEMS, SIZE, INDEX

log = logging.getLogger(name=__name__)

class IteratorHasNext(JavaSimProcedure):

    __provides__ = (
        ('java.util.Iterator', 'hasNext()'),
    )

    def run(self, this_ref):
        log.debug('Called SimProcedure java.util.Iterator.hasNext with args: {}'.format(this_ref))

        if this_ref.symbolic:
            return claripy.BoolS('iterator.hasNext')

        iterator_size = this_ref.load_field(self.state, SIZE, 'int')
        iterator_index = this_ref.load_field(self.state, INDEX, 'int')

        has_next = self.state.solver.eval(iterator_index) < self.state.solver.eval(iterator_size)

        return claripy.BoolV(has_next)

class IteratorNext(JavaSimProcedure):

    __provides__ = (
        ('java.util.Iterator', 'next()'),
    )

    def run(self, this_ref):
        log.debug('Called SimProcedure java.util.Iterator.hasNext with args: {}'.format(this_ref))

        if this_ref.symbolic:
            return SimSootValue_ThisRef.new_object(self.state, 'java.lang.Object', symbolic=True)

        array_ref = this_ref.load_field(self.state, ELEMS, 'java.lang.Object[]')
        iterator_index = this_ref.load_field(self.state, INDEX, 'int')
        # TODO should check boundaries?

        # Update index
        new_iterator_index = claripy.BVV(self.state.solver.eval(iterator_index) + 1, 32)
        this_ref.store_field(self.state, INDEX, 'int', new_iterator_index)

        return self.state.javavm_memory.load_array_element(array_ref, iterator_index)


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Bump.js - Documentation</title>
	<meta name="description" content="Documentation for Bump.js - Documentation">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					Bump.js - Documentation

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

Bump.js - Documentation

Synopsis

Bump.js is a 2D physics engine written in TypeScript.

Motivation

The main purpose of this library is to provide a simple way to handle physics.

Installation

$ npm install @lcluber/bumpjs

Or download it here.

Demo

See a basic example here.

Usage

Learn how to use it here.

API Reference

Read the documentation here.

Tests

No tests to run yet

Contributors

There is still a lot of work to do on this project and I would be glad to get all the help you can provide.
				To contribute you can clone the project on GitHub and see  NOTICE.md for detailed installation walkthrough of the project.

License

MIT License

Copyright (c) 2011 Ludovic CLUBER

Permission is hereby granted, free of charge, to any person obtaining a copy
					of this software and associated documentation files (the "Software"), to deal
					in the Software without restriction, including without limitation the rights
					to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
					copies of the Software, and to permit persons to whom the Software is
				furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
				copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
					IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
					FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
					AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
					LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
					OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
				SOFTWARE.

						Globals

						Internals

						"bump"

						"collision"

						"physics"

						"scene"

						Externals

						"collisions/aabbvsaabb"

						"collisions/circlevsaabb"

						"collisions/circlevscircle"

Legend

Enumeration

Class


text:
<?php

namespace Acme\DemoBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DemoControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/demo/hello/Fabien');

        $this->assertGreaterThan(0, $crawler->filter('html:contains("Hello Fabien")')->count());

        /*
         * Click on a link by first selecting it with the Crawler using either an
         * XPath expression or a CSS selector, then use the Client to click on it.
         * For example, the following code finds all links with the text Greet,
         * then selects the second one, and ultimately clicks on it:
         * */
        $link = $crawler->filter('a:contains("Greet")')->eq(1)->link();

        $crawler = $client->click($link);

        /*
         * Submitting a form is very similar; select a form button, optionally
         * override some form values, and submit the corresponding form:
         * */
        $form = $crawler->selectButton('submit')->form();

        // set some values
        $form['name'] = 'Lucas';
        $form['form_name[subject]'] = 'Hey there!';

        // submit the form
        $crawler = $client->submit($form);

        /*
         * Now that you can easily navigate through an application, use assertions to test that it actually
         * does what you expect it to. Use the Crawler to make assertions on the DOM:
         * */
        // Assert that the response matches a given CSS selector.
        $this->assertGreaterThan(0, $crawler->filter('h1')->count());

        /*Or, test against the Response content directly if you just want to assert that the content contains some text,
         *or if the Response is not an XML/HTML document:
         * */
        $this->assertRegExp(
                '/Hello Fabien/',
                $client->getResponse()->getContent()
        );
    }
}


text:
Create a SQLite database of classes and students for playing around.

``` sh
sqlite3 data/class_enrollments.sqlite.db ".read drop_tables.sql"
sqlite3 data/class_enrollments.sqlite.db ".read create_tables.sql"
python insert_data.py
```

## Things to try

Try some simple and more complicated [queries][2]. Read [how SQLite works][4].

### Explain

Try [EXPLAIN QUERY PLAN][3].

``` sql
sqlite> EXPLAIN QUERY PLAN select * from students where last_name="Smith" and first_name="Chris";
QUERY PLAN
`--SCAN TABLE students
```

[1]: https://sqlite.org/
[2]: queries.sql
[3]: https://sqlite.org/eqp.html
[4]: https://sqlite.org/howitworks.html


text:
/* global describe, it, element, by, expect, browser */
'use strict';

var setup = require('../../common/setup');
var toaster = require('../../common/toaster');
var authentication = require('../../authentication/authentication');
var common = require('../../common/common');
var xedit = require('../../common/xedit');
var topologyTemplates = require('../../topology_templates/topology_templates');

var topologyTemplateName = 'MyTopologyTemplate';
var topologyTemplateNewName = 'MyNewTopologyTemplate';

describe('Topology templates details:', function() {
  it('beforeAll', function() {
    setup.setup();
    common.home();
    authentication.login('architect');
    topologyTemplates.create(topologyTemplateName, 'description');
  });

  it('Architect should be able to rename a topology template', function() {
    topologyTemplates.goToTopologyTemplateDetails(topologyTemplateName);
    xedit.sendKeys('template_' + topologyTemplateName + '_name', topologyTemplateNewName, false);
    expect(element(by.id('template_' + topologyTemplateNewName + '_name')).isPresent()).toBe(true);
  });

  it('Architect should not be able to rename a topology template with an existing name', function() {
    topologyTemplates.create(topologyTemplateName, 'description');
    topologyTemplates.goToTopologyTemplateDetails(topologyTemplateNewName);
    xedit.sendKeys('template_' + topologyTemplateNewName + '_name', topologyTemplateName, false);
    toaster.expectErrors();
    element(by.css('#template_' + topologyTemplateNewName + '_name input')).sendKeys('0');
    toaster.dismissIfPresent();
  });

  it('Architect should be able to edit the topology template description', function() {
    var newDescription = 'New brilliant description';
    topologyTemplates.goToTopologyTemplateDetails(topologyTemplateName);
    xedit.sendKeys('template_' + topologyTemplateName + '_description', newDescription, false);
    expect(element(by.binding('topologyTemplate.description')).getText()).toEqual(newDescription);
  });

  it('Architect should be able to see the topology editor and the version menu element on the detail page', function() {
    topologyTemplates.goToTopologyTemplateDetails(topologyTemplateName);
    topologyTemplates.checkTopologyTemplate(topologyTemplateName);
    expect(element(by.id('app-version-select')).isPresent()).toBe(true);
  });

  it('Component manager should be redirected to error page in case he goes to a topology template url in browser', function() {
    topologyTemplates.goToTopologyTemplateDetails(topologyTemplateName);
    browser.getCurrentUrl().then(function(topologyUrl) {
      authentication.logout();
      authentication.login('componentManager');
      browser.get(topologyUrl);
      browser.waitForAngular();
      browser.getCurrentUrl().then(function(shouldBeRedirectedURL) {
        expect(shouldBeRedirectedURL).toContain('#/restricted');
      });
    });
  });

  it('afterAll', function() { authentication.logout(); });
});


text:
using namespace std;

// main program
int main (int argc, char** argv)
{

	// pretty print option
	// set by command line
	int pretty = 0;

	// process command line arguments
	for (int i = 0; i < argc; ++i)
	{
		// only handle prettyfying option
		if ("-p" == string(argv[i])) pretty ++;
		if ("--pretty" == string(argv[i])) pretty ++;
	}

	// declare variable
	string line;

	// accumulate for test
	string sass = "";

	// read from stdin
	while (cin)
	{
		// read a line
		getline(cin, line);
		// process the line
		sass += line + "\n";
		// break if at end of file
		if (cin.eof()) break;
	};

	// print the resulting scss
	cout << Sass::sass2scss (sass, pretty);

}


text:
package drivers

import (
	"os/exec"

	"golang.org/x/sys/unix"

	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/logger"
)

// lxcCmd represents a running command for an LXC container.
type lxcCmd struct {
	attachedChildPid int
	cmd              *exec.Cmd
}

// PID returns the attached child's process ID.
func (c *lxcCmd) PID() int {
	return c.attachedChildPid
}

// Signal sends a signal to the command.
func (c *lxcCmd) Signal(sig unix.Signal) error {
	err := unix.Kill(c.attachedChildPid, sig)
	if err != nil {
		return err
	}

	logger.Debugf(`Forwarded signal "%d" to PID "%d"`, sig, c.PID())
	return nil
}

// Wait for the command to end and returns its exit code and any error.
func (c *lxcCmd) Wait() (int, error) {
	exitStatus, err := shared.ExitStatus(c.cmd.Wait())

	return exitStatus, err
}

// WindowResize resizes the running command's window.
func (c *lxcCmd) WindowResize(fd, winchWidth, winchHeight int) error {
	err := shared.SetSize(fd, winchWidth, winchHeight)
	if err != nil {
		return err
	}

	logger.Debugf(`Set window size "%dx%d" of PID "%d"`, winchWidth, winchHeight, c.PID())
	return nil
}


text:
var assert = require('assert'),
    autogoal = require('./autogoal.js');
function bfe () {
    autogoal.g.__goals = [
        {
            "name": "a goal name",
            "finished": "Contratulatory text",
            "icon": "king01.png",
            "reward": 100,
            "rewardType": "xp",
            "scheme": "intro",
            "level": 10
        },
        {
            "name": "a goal name two",
            "finished": "Contratulatory text",
            "icon": "king02.png",
            "reward": 100,
            "rewardType": "xp",
            "scheme": "hjk",
            "level": 10
        }
    ];
    autogoal.s.__subgoals = [
        {
            "name": "a subgoal name",
            "hint": "a subgoal hint",
            "reward": 50,
            "action": 'harvest',
            "amount": 1,
            "target": "melon",
            "scheme": "intro",
            "_scheme": "intro",
            "level": 1
        },
        {
            "name": "a subgoal name two",
            "hint": "a subgoal hint",
            "reward": 30,
            "action": 'contract',
            "amount": 2,
            "target": "poor_house",
            "scheme": "intro",
            "_scheme": "intro",
            "level": 2
        },
        {
            "name": "a subgoal name three",
            "hint": "a subgoal hint",
            "reward": 30,
            "action": 'buy',
            "amount": 2,
            "icon": "hell",
            "target": "villager",
            "scheme": "build",
            "_scheme": "build",
            "level": 1
        }
    ];
}
beforeEach( function () {
    bfe();
} );

describe('entities parsing', function () {
    it("loads entities properly", function (be) {
        var entities = autogoal.E.entities();
        expect(typeof entities).toEqual("object");
    });

    it("finds an entity", function(be) {
        expect(typeof autogoal.E.entity('villager')).toEqual("object");
    });
});

describe('single subgoal validator generation', function () {
    it("creates basic validators", function () {
        var validator = autogoal.subgoal_utils.basic_validator('harvest'),
            longKey = "entity.definition.class", validatorValue = "farm";
        expect(validator[longKey]).toEqual(validatorValue);
    });
    it("creates extended validators", function () {
        expect(autogoal.subgoal_utils.validator({
                "action": "harvest",
                "target": "melon"
            })["contract.seedName"]).toEqual( "farming/seed-melon");
    });
    it("creates extended validators for houses", function () {
        expect(autogoal.subgoal_utils.validator({
                "action": "contract",
                "target": "wizard"
            })["entity.key"]).toEqual("buildings/wizards_house");
    });
    it("creates extended validators for whackables", function () {
        expect(autogoal.subgoal_utils.validator({
                "action": "whack",
                "target": "tree-small"
            })["entity.key"]).toEqual("nature/tree-small-b");
    });
    it("creates validators for AND class type constraings", function () {
        expect(autogoal.subgoal_utils.validator({
                "action": "move",
                "target": "*farm"
        })["entity.definition.class"]).toEqual("farm");
    });
});

describe('single subgoal gets rewards', function () {
    it('sets the rewards', function () {
        var reward = autogoal.subgoal_utils.rewards({"reward": 10})[0];
        expect(reward.type).toEqual('gold');
    });
});

describe('single subgoal generator', function () {
    it("maps action strings", function () {
        expect(autogoal.subgoal_utils.map_action("harvest")).toEqual("game:contract/collect");
    });
    it("overrides action based on target", function () {
        expect(autogoal.subgoal_utils.action({"action": "whack", "target": "troll"}).event).toEqual('game:enemy/kill'); //action gets overwritten at the last moment in the subgoal processor
    });
    it("autmagically adds amount IF missing", function () {
        var subgoal = autogoal.subgoal_utils.subgoal({
                "action": "whack", "target": "troll"
            });
        expect(subgoal.amount).toEqual(1);
        subgoal = autogoal.subgoal_utils.subgoal({
                "action": "whack", "target": "troll",
                "amount": 3
            });
        expect(subgoal.amount).toEqual(3);
    });
    it("stitches a subgoal together", function () {
        var subgoal = autogoal.subgoal_utils.subgoal({
                "action": "whack", "target": "troll", "name": "", "hint": ""
            });
        expect(typeof subgoal).toEqual('object');
        expect(subgoal.action).toEqual('game:enemy/kill');
        expect(subgoal.type).toBeDefined();
        expect(subgoal.subgoalText).toBeDefined();
        expect(subgoal.subgoalHint).toBeDefined();
    });
    it("renders the title correctly", function () {

        var subgoal = autogoal.subgoal_utils.subgoal({
                "action": "whack", "target": "troll", "name": "whack troll #x", "hint": "", "icon": "troll-icon"
            });
        expect(subgoal.subgoalText).toEqual("whack troll 1x");

    });
    it("adds an icon to the subgoal", function () {
        var subgoal = autogoal.subgoal_utils.subgoal({
                "action": "buy", "target": "villager", "name": "buy a villager house", "hint": ""
            });
        expect(subgoal.icon).toBeDefined();
        expect(subgoal.icon.indexOf('villager')).not.toEqual(-1);
    });
    it("adds icon only if none was specified", function () {

        var subgoal = autogoal.subgoal_utils.subgoal({
                "action": "buy", "target": "villager", "name": "buy a villager house", "hint": "",
                "icon": 'xxx'
            });
        expect(subgoal.icon).toEqual('xxx');
    });
    it("creates validator even if no target is passed", function () {
        var subgoal = autogoal.subgoal_utils.subgoal({
                "name": "a subgoal name three",
                "hint": "a subgoal hint",
                "reward": 30,
                "action": 'buy',
                "amount": 2,
                "icon": "villager_house",
                "target": "",
                "scheme": "general",
                "_scheme": "general",
                "level": 1
            });
        expect(subgoal).toBeDefined();
        expect(subgoal.action).toEqual('game:entity/buy');
        expect(subgoal.objects).toBeDefined();
        expect(subgoal.objects['entity.definition.class']).toEqual('house');
    });
});

describe('subgoal finder', function () {
    it("has a pool of subgoals", function () {
        var subgoals = autogoal.s.subgoals();
        expect(typeof subgoals).toEqual("object");
        expect(subgoals.length).not.toEqual(0);
    });
    it("finds subgoal by scheme", function () {
        var subgoals = autogoal.s._find({
                "scheme": "intro"
            });
        expect(subgoals).toBeDefined();
        expect(subgoals.length).not.toEqual(0);
        var empty = autogoal.s._find({
                "scheme": "x" + Math.random()
            });
        expect(empty.length).toEqual(0);
    });
    it("finds requested number of subgoals for constraints", function () {
        var setIntroWith1 = autogoal.s.find(1, {"scheme": "intro"}),
            a
            ;
        expect(setIntroWith1.length).toEqual(1);
    });
    it("finds requested number of subgoals for constraints", function () {
        var setIntroWith2 = autogoal.s.find(2, {"scheme": "intro", level: 20}),
            a
            ;
        expect(setIntroWith2.length).toEqual(2);
    });
    it("finds requested number of subgoals for constraints", function () {
        var setIntroWith = autogoal.s.find(3, {"scheme": "intro", level: 20}),
            a
            ;
        expect(setIntroWith.length).toEqual(2);
    });
    it("filters by requested level", function () {
        var set = autogoal.s.find(2, {"scheme": "intro", "level": 1});
        expect(set.length).toEqual(1);
    });
    it("cares for multiple schemes", function () {
        var set = autogoal.s.find(2, {"scheme": "intro-build"});
        expect(set.length).not.toEqual(0);
        var hasIntro = set.some(function (sg) {return sg._scheme === "intro";}),
            hasBuild = set.some(function (sg) {return sg._scheme === "build";});
        expect(hasIntro).toEqual(true);
        expect(hasBuild).toEqual(true);
    });
});

describe('12 is not smaller than 2', function () {

    beforeEach(function () {

        autogoal.g.__goals = [
            {
                "name": "a goal name",
                "finished": "Contratulatory text",
                "icon": "king01.png",
                "reward": 100,
                "rewardType": "xp",
                "scheme": "intro",
                "level": 10
            },
            {
                "name": "a goal name two",
                "finished": "Contratulatory text",
                "icon": "king02.png",
                "reward": 100,
                "rewardType": "xp",
                "scheme": "hjk",
                "level": 10
            }
        ];
        autogoal.s.__subgoals = [
            {
                "name": "a subgoal name",
                "hint": "a subgoal hint",
                "reward": 50,
                "action": 'harvest',
                "amount": 1,
                "target": "melon",
                "scheme": "intro",
                "_scheme": "intro",
                "level": 1
            },
            {
                "name": "a subgoal name two",
                "hint": "a subgoal hint",
                "reward": 30,
                "action": 'contract',
                "amount": 2,
                "target": "poor_house",
                "scheme": "intro",
                "_scheme": "intro",
                "level": "2"
            },
            {
                "name": "a subgoal name three",
                "hint": "a subgoal hint",
                "reward": 30,
                "action": 'buy',
                "amount": 2,
                "icon": "hell",
                "target": "villager",
                "scheme": "intro",
                "_scheme": "intro",
                "level": "12"
            }
        ];
    });

    it("casts strings to numbers when checking for unlock level", function () {
        var set = autogoal.s.find(3, {"scheme": "intro", "level": "2"});
        expect(set.length).toEqual(2);
    });

});

describe("goal builder", function () {
    beforeEach(bfe);
    it("has a pool of goals", function () {
        var goals = autogoal.g.goals();
        expect(typeof goals).toEqual("object");
        expect(goals.length).not.toEqual(0);
    });
    it("stitches the parts to form a goal", function () {
        var goal = autogoal.g.goal(2, autogoal.g.goals()[0]);
        expect(goal.subgoals.length).toEqual(2);
        expect(goal.rewards).toBeDefined();
        expect(goal.storyTitle).toBeDefined();
        expect(goal.finishedText).toBeDefined();
    });
    it("drops goals with no subgoals", function () {
        var goal = autogoal.utils.merge({}, autogoal.g.goals()[1]);
        var orig_scheme = goal.scheme;
        goal.scheme = "xxjj  " + Math.random();
        var subgoals = autogoal.g.subgoals(1, goal);
        expect(subgoals.length).toEqual(0);
        goal.scheme = orig_scheme;
    });

    it("generates subgoals for goal constraints", function () {
        var goal = [].concat(autogoal.g.goals())[0];
        var subgoals = autogoal.g.subgoals(2, goal);
        expect(subgoals.length).toEqual(2);
    });
});


text:
#define COMPONENT_NAME "OMX.TI.DUCATI1.MISC.SAMPLE"	// needs to be specific for every configuration wrapper
#define OMX_SAMPLE_USEBUF OMX_TRUE

/****************************************************************
*  INCLUDE FILES
****************************************************************/
/* ----- system and platform files ----------------------------*/
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

/*-------program files ----------------------------------------*/
#include <OMX_Core.h>
#include <OMX_Component.h>
#include "timm_osal_interfaces.h"

#define OMX_SAMPLE_TILER_TEST

#ifdef OMX_SAMPLE_TILER_TEST

#include "memmgr.h"

#endif

#define OMX_SAMPLE_INPUT_PORT 0
#define OMX_SAMPLE_OUTPUT_PORT 1

#ifdef OMX_SAMPLE_TILER_TEST

#define OMX_SAMPLE_IN_2DYHEIGHT 4
#define OMX_SAMPLE_IN_2DYWIDTH 8
#define OMX_SAMPLE_IN_2DUVHEIGHT 2
#define OMX_SAMPLE_IN_2DUVWIDTH 4
/*
 #define STRIDE_8BIT (16 * 1024)
 #define STRIDE_16BIT (32 * 1024)
*/
#define OMX_SAMPLE_IN_HEIGHT 6
#define OMX_SAMPLE_IN_WIDTH 8

#define STRIDE_LINUX (4 * 1024)

#define OMX_SAMPLE_BUFFER_SIZE 48

void Test_Util_Memcpy_1Dto2D(TIMM_OSAL_PTR pDst2D, TIMM_OSAL_PTR pSrc1D,
    TIMM_OSAL_U32 nSize1D, TIMM_OSAL_U32 nHeight2D, TIMM_OSAL_U32 nWidth2D,
    TIMM_OSAL_U32 nStride2D)
{
	TIMM_OSAL_U8 *pInBuffer;
	TIMM_OSAL_U8 *pOutBuffer;
	TIMM_OSAL_U32 nSizeLeft, i;

	nSizeLeft = nSize1D;
	pInBuffer = (TIMM_OSAL_U8 *) pSrc1D;
	pOutBuffer = (TIMM_OSAL_U8 *) pDst2D;
	//The lower limit is copied. If nSize1D < H*W then 1Dsize is copied else H*W is copied
	for (i = 0; i < nHeight2D; i++)
	{
		if (nSizeLeft >= nWidth2D)
		{
			TIMM_OSAL_Memcpy(pOutBuffer, pInBuffer, nWidth2D);
		} else
		{
			TIMM_OSAL_Memcpy(pOutBuffer, pInBuffer, nSizeLeft);
			break;
		}
		nSizeLeft -= nWidth2D;
		pInBuffer =
		    (TIMM_OSAL_U8 *) ((TIMM_OSAL_U32) pInBuffer + nWidth2D);
		pOutBuffer =
		    (TIMM_OSAL_U8 *) ((TIMM_OSAL_U32) pOutBuffer + nStride2D);
	}
}

#endif

/****************************************************************
*  EXTERNAL REFERENCES NOTE : only use if not found in header file
****************************************************************/
/*--------data declarations -----------------------------------*/
/*--------function prototypes ---------------------------------*/

/****************************************************************
*  PRIVATE DECLARATIONS Defined and used only here
****************************************************************/
/*--------function declarations -------------------------------*/

/*--------data declarations -----------------------------------*/
#define NUM_DOMAINS 0x4
#define OMX_NOPORT 0xfffffffe

//#define INPUT_FILE "../../omx/omx_il_1_x/omx_base/test/patterns/chikita.mp3"
#define INPUT_FILE "sample_input.mp3"
#define NON_TUN_OUTPUT_FILE "nt_output.mp3"

static int gTest = 1;

#define TIMM_OSAL_MallocaBuffer(_size, bContigous, nBlockAlignment) \
        TIMM_OSAL_Malloc (_size, TIMM_OSAL_TRUE, 0, TIMMOSAL_MEM_SEGMENT_EXT)

#define OMX_TEST_BUFFERS_OF_TRAFFIC 20

#define OMX_TEST_BAIL_IF_ERROR(_eError)		\
    if(OMX_ErrorNone != (eError = _eError)){	\
        goto OMX_TEST_BAIL;		\
    }

#define OMX_TEST_SET_ERROR_BAIL(_eCode, _desc)	\
{						\
    eError = _eCode;				\
    printf(_desc);\
    goto OMX_TEST_BAIL;			\
}

#define OMX_TEST_INIT_STRUCT(_s_, _name_)	\
    memset(&(_s_), 0x0, sizeof(_name_));	\
    (_s_).nSize = sizeof(_name_);		\
    (_s_).nVersion.s.nVersionMajor = 0x1;	\
    (_s_).nVersion.s.nVersionMinor = 0x1;	\
    (_s_).nVersion.s.nRevision = 0x0;		\
    (_s_).nVersion.s.nStep = 0x0

#define BUFFER_LIST_CLEAR_ENTRY(_pL, _pB)\
    _pB = _pL->pBufHdr;        \
    _pL->pBufHdr = NULL;    \
    _pL = _pL->pNextBuf;

#define BUFFER_LIST_SET_ENTRY(_pL, _pB)    \
{                \
    BufferList *_pT = _pL;    \
    while(_pT && _pT->pBufHdr){    \
        _pT = _pT->pNextBuf;    \
    }                \
    if(_pT)            \
        _pT->pBufHdr = _pB;    \
}

#define BUFFERLIST_CLEAR_ENTRY(_pL, _pB)\
    _pB = _pL->pBufHdr;        \
    _pL->pBufHdr = NULL;    \
    _pL = _pL->pNextBuf;

typedef struct _BufferList BufferList;

struct _BufferList
{
	OMX_BUFFERHEADERTYPE *pBufHdr;
	OMX_BUFFERHEADERTYPE *pOrigBufHdr;
	BufferList *pNextBuf;
};

typedef struct SampleCompTestCtxt
{
	OMX_HANDLETYPE hComp;
	OMX_STATETYPE eState;
	OMX_U32 nPorts;
	OMX_HANDLETYPE hStateSetEvent;
	OMX_HANDLETYPE hPortDisableEvent;
	OMX_HANDLETYPE hPortEnableEvent;
	OMX_STRING inFilePath;
	OMX_STRING outFilePath;
	FILE *pOutputFile;
	FILE *pInputfile;
	OMX_BOOL bEOS;
	BufferList *pInBufferList;
	BufferList *pOutBufferList;
	OMX_BOOL bClientAllocBuf;
	OMX_U32 nBufDoneCalls;
	OMX_PORT_PARAM_TYPE sPortParam[NUM_DOMAINS];
} SampleCompTestCtxt;

//this test compiles only for ducati SYS
typedef struct TestCtxt
{
	OMX_HANDLETYPE hComp;
	OMX_STATETYPE eState;
	OMX_U32 nPorts;
	OMX_HANDLETYPE hStateSetEvent;
	OMX_HANDLETYPE hPortDisableEvent;
	OMX_HANDLETYPE hPortEnableEvent;
	OMX_STRING inFilePath;
	OMX_STRING outFilePath;
	FILE *pOutputFile;
	FILE *pInputfile;
	OMX_BOOL bEOS;
	BufferList *pInBufferList;
	BufferList *pOutBufferList;
	OMX_BOOL bClientAllocBuf;
	OMX_U32 nBufDoneCalls;
	//OMX_PORT_PARAM_TYPE sPortParam[NUM_DOMAINS];
} TestCtxt;

static OMX_U32 nInBufCount = 0;
static OMX_U32 nOutBufCount = 0;

//Semaphore_Handle EBDSem;
//Semaphore_Params EBDsemParams;

//Semaphore_Handle FBDSem;
//Semaphore_Params FBDsemParams;
/*========================================================*/
/* @ fn OMX_TEST_ErrorToString :: ERROR  to  STRING   */
/*========================================================*/
OMX_STRING OMX_TEST_ErrorToString(OMX_ERRORTYPE eError)
{

	OMX_STRING errorString;

	switch (eError)
	{

	case OMX_ErrorNone:
		errorString = "ErrorNone";
		break;
	case OMX_ErrorInsufficientResources:
		errorString = "ErrorInsufficientResources";
		break;
	case OMX_ErrorUndefined:
		errorString = "ErrorUndefined";
		break;
	case OMX_ErrorInvalidComponentName:
		errorString = "ErrorInvalidComponentName";
		break;
	case OMX_ErrorComponentNotFound:
		errorString = "ErrorComponentNotFound";
		break;
	case OMX_ErrorInvalidComponent:
		errorString = "ErrorInvalidComponent";
		break;
	case OMX_ErrorBadParameter:
		errorString = "ErrorBadParameter";
		break;
	case OMX_ErrorNotImplemented:
		errorString = "ErrorNotImplemented";
		break;
	case OMX_ErrorUnderflow:
		errorString = "ErrorUnderflow";
		break;
	case OMX_ErrorOverflow:
		errorString = "ErrorOverflow";
		break;
	case OMX_ErrorHardware:
		errorString = "ErrorHardware";
		break;
	case OMX_ErrorInvalidState:
		errorString = "ErrorInvalidState";
		break;
	case OMX_ErrorStreamCorrupt:
		errorString = "ErrorStreamCorrupt";
		break;
	case OMX_ErrorPortsNotCompatible:
		errorString = "ErrorPortsNotCompatible";
		break;
	case OMX_ErrorResourcesLost:
		errorString = "ErrorResourcesLost";
		break;
	case OMX_ErrorNoMore:
		errorString = "ErrorNoMore";
		break;
	case OMX_ErrorVersionMismatch:
		errorString = "ErrorVersionMismatch";
		break;
	case OMX_ErrorNotReady:
		errorString = "ErrorNotReady";
		break;
	case OMX_ErrorTimeout:
		errorString = "ErrorTimeout";
		break;
	case OMX_ErrorSameState:
		errorString = "ErrorSameState";
		break;
	case OMX_ErrorResourcesPreempted:
		errorString = "ErrorResourcesPreempted";
		break;
	case OMX_ErrorPortUnresponsiveDuringAllocation:
		errorString = "ErrorPortUnresponsiveDuringAllocation";
		break;
	case OMX_ErrorPortUnresponsiveDuringDeallocation:
		errorString = "ErrorPortUnresponsiveDuringDeallocation";
		break;
	case OMX_ErrorPortUnresponsiveDuringStop:
		errorString = "ErrorPortUnresponsiveDuringStop";
		break;
	case OMX_ErrorIncorrectStateTransition:
		errorString = "ErrorIncorrectStateTransition";
		break;
	case OMX_ErrorIncorrectStateOperation:
		errorString = "ErrorIncorrectStateOperation";
		break;
	case OMX_ErrorUnsupportedSetting:
		errorString = "ErrorUnsupportedSetting";
		break;
	case OMX_ErrorUnsupportedIndex:
		errorString = "ErrorUnsupportedIndex";
		break;
	case OMX_ErrorBadPortIndex:
		errorString = "ErrorBadPortIndex";
		break;
	case OMX_ErrorPortUnpopulated:
		errorString = "ErrorPortUnpopulated";
		break;
	case OMX_ErrorComponentSuspended:
		errorString = "ErrorComponentSuspended";
		break;
	case OMX_ErrorDynamicResourcesUnavailable:
		errorString = "ErrorDynamicResourcesUnavailable";
		break;
	case OMX_ErrorMbErrorsInFrame:
		errorString = "ErrorMbErrorsInFrame";
		break;
	case OMX_ErrorFormatNotDetected:
		errorString = "ErrorFormatNotDetected";
		break;
	case OMX_ErrorContentPipeOpenFailed:
		errorString = "ErrorContentPipeOpenFailed";
		break;
	case OMX_ErrorContentPipeCreationFailed:
		errorString = "ErrorContentPipeCreationFailed";
		break;
	case OMX_ErrorSeperateTablesUsed:
		errorString = "ErrorSeperateTablesUsed";
		break;
	case OMX_ErrorTunnelingUnsupported:
		errorString = "ErrorTunnelingUnsupported";
		break;
	default:
		errorString = "<unknown>";
		break;
	}
	return errorString;
}

/*========================================================*/
/* @ fn OMX_TEST_StateToString :: STATE  to  STRING   */
/*========================================================*/
OMX_STRING OMX_TEST_StateToString(OMX_STATETYPE eState)
{
	OMX_STRING StateString;

	switch (eState)
	{
	case OMX_StateInvalid:
		StateString = "Invalid";
		break;
	case OMX_StateLoaded:
		StateString = "Loaded";
		break;
	case OMX_StateIdle:
		StateString = "Idle";
		break;
	case OMX_StateExecuting:
		StateString = "Executing";
		break;
	case OMX_StatePause:
		StateString = "Pause";
		break;
	case OMX_StateWaitForResources:
		StateString = "WaitForResources ";
		break;
	default:
		StateString = "<unknown>";
		break;
	}

	return StateString;
}

/* Application callback Functions */
/*========================================================*/
/* @ fn SampleTest_EventHandler :: Application callback   */
/*========================================================*/
OMX_ERRORTYPE SampleTest_EventHandler(OMX_IN OMX_HANDLETYPE hComponent,
    OMX_IN OMX_PTR pAppData,
    OMX_IN OMX_EVENTTYPE eEvent,
    OMX_IN OMX_U32 nData1, OMX_IN OMX_U32 nData2, OMX_IN OMX_PTR pEventData)
{
	SampleCompTestCtxt *pContext;

	printf("\n___________ ENTERED CLIENT CALLBACK:%s", __FUNCTION__);

	if (pAppData == NULL)
		return OMX_ErrorNone;

	pContext = (SampleCompTestCtxt *) pAppData;

	switch (eEvent)
	{
	case OMX_EventCmdComplete:
		printf("\n OMX_EventCmdComplete case: \n");
		if (OMX_CommandStateSet == nData1)
		{
			printf(" Component Transitioned to %s state \n",
			    OMX_TEST_StateToString((OMX_STATETYPE) nData2));
			pContext->eState = (OMX_STATETYPE) nData2;
			TIMM_OSAL_SemaphoreRelease(pContext->hStateSetEvent);
		} else if (OMX_CommandFlush == nData1)
		{
			/* Nothing to do over here */
		} else if (OMX_CommandPortDisable == nData1)
		{
			/* Nothing to do over here */
			TIMM_OSAL_SemaphoreRelease(pContext->
			    hPortDisableEvent);
		} else if (OMX_CommandPortEnable == nData1)
		{
			/* Nothing to do over here */
		} else if (OMX_CommandMarkBuffer == nData1)
		{
			/* Nothing to do over here */
		}
		break;

	case OMX_EventError:
		printf("\nOMX EVENT ERROR!!!!!! \n");
		break;

	case OMX_EventMark:
		break;

	case OMX_EventPortSettingsChanged:
		break;

	case OMX_EventBufferFlag:
		break;

	case OMX_EventResourcesAcquired:
		break;

	case OMX_EventComponentResumed:
		break;

	case OMX_EventDynamicResourcesAvailable:
		break;

	case OMX_EventPortFormatDetected:
		break;

	default:
		break;
	}

	goto OMX_TEST_BAIL;
      OMX_TEST_BAIL:
	return OMX_ErrorNone;
}

/*========================================================*/
/* @ fn SampleTest_EmptyBufferDone :: Application callback    */
/*========================================================*/
OMX_ERRORTYPE SampleTest_EmptyBufferDone(OMX_IN OMX_HANDLETYPE hComponent,
    OMX_IN OMX_PTR pAppData, OMX_IN OMX_BUFFERHEADERTYPE * pBuffer)
{
	SampleCompTestCtxt *pContext;

	printf("\n___________ ENTERED CLIENT CALLBACK:%s", __FUNCTION__);

	if (pAppData == NULL)
		return OMX_ErrorNone;

	pContext = (SampleCompTestCtxt *) pAppData;
	pContext->nBufDoneCalls++;

	BUFFER_LIST_SET_ENTRY(pContext->pInBufferList, pBuffer);
	//Semaphore_post(EBDSem);

	goto OMX_TEST_BAIL;
      OMX_TEST_BAIL:
	printf("\nEBD done\n");
	return OMX_ErrorNone;
}

/*========================================================*/
/* @ fn SampleTest_FillBufferDone ::   Application callback  */
/*========================================================*/
OMX_ERRORTYPE SampleTest_FillBufferDone(OMX_IN OMX_HANDLETYPE hComponent,
    OMX_IN OMX_PTR pAppData, OMX_IN OMX_BUFFERHEADERTYPE * pBuffHeader)
{
	SampleCompTestCtxt *pContext;

	printf("\n___________ ENTERED CLIENT CALLBACK:%s", __FUNCTION__);

	if (pAppData == NULL)
		return OMX_ErrorNone;

	pContext = (SampleCompTestCtxt *) pAppData;
	pContext->nBufDoneCalls++;

	if (pContext->pOutputFile && gTest)
	{
		printf(" writing to output file :: buffer cnt : %d\n",
		    nOutBufCount);
		nOutBufCount++;
		fwrite(pBuffHeader->pBuffer, 1, pBuffHeader->nFilledLen,
		    pContext->pOutputFile);
	}

	BUFFER_LIST_SET_ENTRY(pContext->pOutBufferList, pBuffHeader);
	//Semaphore_post(FBDSem);

	goto OMX_TEST_BAIL;
      OMX_TEST_BAIL:
	printf("\nFBD done\n");
	return OMX_ErrorNone;
}

static void SampleTest_ReadInputFile(SampleCompTestCtxt * pContext,
    OMX_PTR pData, OMX_U32 nBytes, FILE * fp)
{
	OMX_U32 nReadSize = 0;

	printf("\nIn read i/p file\n");
	if (pData == NULL)
		printf("\npData is NULL\n");
	else
		printf("\npData = %x\n", pData);
	printf("\nnBytes = %d\n", nBytes);
	if (fp == NULL)
		printf("\nfp is NULL\n");
	else
		printf("\nfp = %x\n", fp);
	nReadSize = fread(pData, 1, nBytes, fp);
	if (nReadSize != nBytes)
	{
		pContext->bEOS = OMX_TRUE;
	}

	printf(" Reading from file :: Buffer cont : %d \n", nInBufCount);
	nInBufCount++;
}

/*========================================================*/
/* @ fn SampleTest_WriteInBuffers ::   Reads a buffer from a file and send to Comp       */
/*========================================================*/
OMX_ERRORTYPE SampleTest_WriteInBuffers(SampleCompTestCtxt * pContext)
{

	OMX_ERRORTYPE eError = OMX_ErrorNone;
	BufferList *pList;
	OMX_BUFFERHEADERTYPE *pBufHeader;
#ifdef OMX_SAMPLE_TILER_TEST
	OMX_U8 *pTmpBuffer = NULL, *pOrigTmpBuffer = NULL;
#endif
	pList = pContext->pInBufferList;
	while (pList && pList->pBufHdr)
	{
		BUFFERLIST_CLEAR_ENTRY(pList, pBufHeader);
		printf("\nAbout to read from input file\n");
#if defined(OMX_SAMPLE_TILER_TEST)

		//OMX_SAMPLE_BUFFER_SIZE is the total amt of data to be sent in the buffer
		pTmpBuffer =
		    TIMM_OSAL_Malloc(OMX_SAMPLE_BUFFER_SIZE, 0, 0, 0);
		if (pTmpBuffer == NULL)
			OMX_TEST_SET_ERROR_BAIL
			    (OMX_ErrorInsufficientResources,
			    "malloc failed \n");
		pOrigTmpBuffer = pTmpBuffer;

		SampleTest_ReadInputFile(pContext, pTmpBuffer,
		    OMX_SAMPLE_BUFFER_SIZE, pContext->pInputfile);

		Test_Util_Memcpy_1Dto2D(pBufHeader->pBuffer, pTmpBuffer,
		    OMX_SAMPLE_BUFFER_SIZE, OMX_SAMPLE_IN_HEIGHT,
		    OMX_SAMPLE_IN_WIDTH, STRIDE_LINUX);
		pBufHeader->nFilledLen = OMX_SAMPLE_BUFFER_SIZE;

		printf("\nBefore ETB pBufHeader->nInputPortIndex = %d\n",
		    pBufHeader->nInputPortIndex);

		TIMM_OSAL_Free(pOrigTmpBuffer);

#else
		SampleTest_ReadInputFile(pContext, pBufHeader->pBuffer,
		    pBufHeader->nAllocLen, pContext->pInputfile);
		pBufHeader->nFilledLen = pBufHeader->nAllocLen;

#endif
		if (pContext->bEOS == OMX_TRUE)
		{
			pBufHeader->nFlags |= OMX_BUFFERFLAG_EOS;
		}

		eError = OMX_EmptyThisBuffer(pContext->hComp, pBufHeader);

		OMX_TEST_BAIL_IF_ERROR(eError);
	}

      OMX_TEST_BAIL:
	return eError;

}

/*========================================================*/
/* @ fn SampleTest_ReadOutBuffers ::   Send out buffers    */
/*========================================================*/

OMX_ERRORTYPE SampleTest_ReadOutBuffers(SampleCompTestCtxt * pContext)
{

	OMX_ERRORTYPE eError = OMX_ErrorNone;
	BufferList *pList;
	OMX_BUFFERHEADERTYPE *pBufHeader;

	pList = pContext->pOutBufferList;
	while (pList && pList->pBufHdr)
	{
		printf("\nAbout to do FTB\n");

		BUFFERLIST_CLEAR_ENTRY(pList, pBufHeader);

		eError = OMX_FillThisBuffer(pContext->hComp, pBufHeader);

		OMX_TEST_BAIL_IF_ERROR(eError);
		if (pBufHeader->nFlags == OMX_BUFFERFLAG_EOS)
		{
			pContext->nBufDoneCalls = OMX_TEST_BUFFERS_OF_TRAFFIC;
		}
	}

      OMX_TEST_BAIL:
	return eError;

}

/*========================================================*/
/* @ fn SampleTest_AllocateBuffers ::   Allocates the Resources on the available ports  */
/*========================================================*/
OMX_ERRORTYPE SampleTest_AllocateBuffers(SampleCompTestCtxt * pContext,
    OMX_PARAM_PORTDEFINITIONTYPE * pPortDef)
{
	OMX_ERRORTYPE eError = OMX_ErrorNone;
	OMX_U8 *pBuffer = NULL;
	BufferList *pBufferList;
	BufferList *pTemp;
	OMX_BUFFERHEADERTYPE *pBufferHdr;
	OMX_U32 i = 100;
	OMX_COMPONENTTYPE *pComp;

#ifdef OMX_SAMPLE_TILER_TEST
	MemAllocBlock *pBlock = NULL;
	OMX_U32 nNumBlocks = 1;

/*For i/p port allocate 2D packed buffer, for o/p port allocate 1D buffer.
Ideally client should get this from GetParams but this is just a sample test so
values are hardcoded*/

	if (pPortDef->nPortIndex == OMX_SAMPLE_INPUT_PORT)
	{
		nNumBlocks = 2;
		pBlock =
		    TIMM_OSAL_Malloc(sizeof(MemAllocBlock) * nNumBlocks, 0, 0,
		    0);
		TIMM_OSAL_Memset(pBlock, 0, sizeof(MemAllocBlock) * nNumBlocks);
		pBlock[0].dim.area.width = OMX_SAMPLE_IN_2DYWIDTH;
		pBlock[0].dim.area.height = OMX_SAMPLE_IN_2DYHEIGHT;
		pBlock[0].pixelFormat = PIXEL_FMT_8BIT;
		pBlock[1].dim.area.width = OMX_SAMPLE_IN_2DUVWIDTH;
		pBlock[1].dim.area.height = OMX_SAMPLE_IN_2DUVHEIGHT;
		pBlock[1].pixelFormat = PIXEL_FMT_16BIT;
	} else
	{
		nNumBlocks = 1;
		pBlock =
		    TIMM_OSAL_Malloc(sizeof(MemAllocBlock) * nNumBlocks, 0, 0,
		    0);
		TIMM_OSAL_Memset(pBlock, 0, sizeof(MemAllocBlock) * nNumBlocks);
		pBlock[0].dim.len = OMX_SAMPLE_BUFFER_SIZE;
		pBlock[0].pixelFormat = PIXEL_FMT_PAGE;
	}
#endif

	for (i = 0; i < pPortDef->nBufferCountActual; i++)
	{
		pBufferList =
		    (BufferList *) TIMM_OSAL_Malloc(sizeof(BufferList),
		    TIMM_OSAL_TRUE, 0, TIMMOSAL_MEM_SEGMENT_INT);
		if (!pBufferList)
		{
			OMX_TEST_SET_ERROR_BAIL
			    (OMX_ErrorInsufficientResources,
			    "malloc failed \n");
		}

		if (pContext->bClientAllocBuf)
		{

#ifdef OMX_SAMPLE_TILER_TEST
/*For i/p port allocate 2D packed buffer, for o/p port allocate 1D buffer.
Ideally client should get this from GetParams but this is just a sample test so
values are hardcoded*/
			pBuffer = MemMgr_Alloc(pBlock, nNumBlocks);
			printf("\nMemMgr allocated buffer = 0x%x\n", pBuffer);
#else
			pBuffer =
			    (OMX_U8 *) TIMM_OSAL_MallocaBuffer(pPortDef->
			    nBufferSize, pPortDef->bBuffersContiguous,
			    pPortDef->nBufferAlignment);

#endif

			if (!pBufferList)
			{
				OMX_TEST_SET_ERROR_BAIL
				    (OMX_ErrorInsufficientResources,
				    "malloc failed \n");
			}

			printf("\nCalling UseBuf on port %d\n",
			    pPortDef->nPortIndex);
			eError =
			    OMX_UseBuffer(pContext->hComp, &pBufferHdr,
			    pPortDef->nPortIndex, 0, pPortDef->nBufferSize,
			    pBuffer);

			OMX_TEST_BAIL_IF_ERROR(eError);

		} else
		{

			pComp = (OMX_COMPONENTTYPE *) pContext->hComp;
			printf("\nCalling allocate buffer\n");
			eError =
			    OMX_AllocateBuffer(pContext->hComp, &pBufferHdr,
			    pPortDef->nPortIndex, 0, pPortDef->nBufferSize);

			OMX_TEST_BAIL_IF_ERROR(eError);
		}
		printf("\npBufferHdr->nOutputPortIndex = %d\n",
		    pBufferHdr->nOutputPortIndex);
		printf("\npBufferHdr->nInputPortIndex = %d\n",
		    pBufferHdr->nInputPortIndex);
		pBufferList->pNextBuf = NULL;
		pBufferList->pBufHdr = pBufferHdr;
		pBufferList->pOrigBufHdr = pBufferHdr;

		if (pPortDef->eDir == OMX_DirInput)
		{
			printf("\npBufferHdr->nOutputPortIndex = %d\n",
			    pBufferHdr->nOutputPortIndex);
			printf("\npBufferHdr->nInputPortIndex = %d\n",
			    pBufferHdr->nInputPortIndex);
			pBufferHdr->nOutputPortIndex = OMX_NOPORT;
			if (pContext->pInBufferList == NULL)
			{
				pContext->pInBufferList = pBufferList;
			} else
			{
				pTemp = pContext->pInBufferList;
				while (pTemp->pNextBuf)
					pTemp = pTemp->pNextBuf;
				pTemp->pNextBuf = pBufferList;
			}
		} else
		{
			pBufferHdr->nInputPortIndex = OMX_NOPORT;
			printf("\npBufferHdr->nOutputPortIndex = %d\n",
			    pBufferHdr->nOutputPortIndex);
			printf("\npBufferHdr->nInputPortIndex = %d\n",
			    pBufferHdr->nInputPortIndex);
			if (pContext->pOutBufferList == NULL)
			{
				pContext->pOutBufferList = pBufferList;
			} else
			{
				pTemp = pContext->pOutBufferList;
				while (pTemp->pNextBuf)
					pTemp = pTemp->pNextBuf;
				pTemp->pNextBuf = pBufferList;
			}
		}
	}

      OMX_TEST_BAIL:
#ifdef OMX_SAMPLE_TILER_TEST
	if (pBlock != NULL)
		TIMM_OSAL_Free(pBlock);
#endif
	if (eError != OMX_ErrorNone)
	{
		if (pBufferList)
		{
			TIMM_OSAL_Free(pBufferList);
		}
	}

	return eError;
}

/*========================================================*/
/* @ fn SampleTest_DeInitBuffers ::   Destroy the resources  */
/*========================================================*/
OMX_ERRORTYPE SampleTest_DeInitBuffers(SampleCompTestCtxt * pContext)
{
	OMX_ERRORTYPE eError = OMX_ErrorNone;
	OMX_U8 *pBuffer;
	BufferList *pBufferList;
	BufferList *pTemp;

	OMX_U32 nRetVal = 0;

	pTemp = pContext->pInBufferList;

	while (pTemp)
	{
		pBufferList = (BufferList *) pTemp;
		pBuffer = (OMX_U8 *) pTemp->pOrigBufHdr->pBuffer;

		printf("\nCalling Free Buffer on port no. %d\n",
		    pTemp->pOrigBufHdr->nInputPortIndex);

		eError =
		    OMX_FreeBuffer(pContext->hComp,
		    pTemp->pOrigBufHdr->nInputPortIndex, pTemp->pOrigBufHdr);
		OMX_TEST_BAIL_IF_ERROR(eError);

                if (pContext->bClientAllocBuf)
                {

#ifdef OMX_SAMPLE_TILER_TEST
                        nRetVal = MemMgr_Free(pBuffer);
                        if (nRetVal)
                        {
                                printf("\nError in MemMgr free\n");
                        }
#else
                        TIMM_OSAL_Free(pBuffer);
#endif
                }

		pTemp = pTemp->pNextBuf;
		if (pBufferList)
			TIMM_OSAL_Free(pBufferList);
	}

	pContext->pInBufferList = NULL;

	pTemp = pContext->pOutBufferList;
	while (pTemp)
	{
		pBufferList = (BufferList *) pTemp;
		pBuffer = (OMX_U8 *) pTemp->pOrigBufHdr->pBuffer;
		printf("\nCalling Free Buffer on port no. %d\n",
		    pTemp->pOrigBufHdr->nOutputPortIndex);

		eError =
		    OMX_FreeBuffer(pContext->hComp,
		    pTemp->pOrigBufHdr->nOutputPortIndex, pTemp->pOrigBufHdr);
		OMX_TEST_BAIL_IF_ERROR(eError);
                if (pContext->bClientAllocBuf)
                {
#ifdef OMX_SAMPLE_TILER_TEST
                        nRetVal = MemMgr_Free(pBuffer);
                        if (nRetVal)
                        {
                                printf("\nError in MemMgr free\n");
                        }
#else
                        TIMM_OSAL_Free(pBuffer);
#endif
                }

		pTemp = pTemp->pNextBuf;
		if (pBufferList)
			TIMM_OSAL_Free(pBufferList);

	}

	pContext->pOutBufferList = NULL;

      OMX_TEST_BAIL:
	return eError;
}

/*========================================================*/
/* @ fn SampleTest_TransitionWait ::   Waits for the transition to be completed ,
 *  incase of loaded to idle Allocates the Resources and while idle to loaded
 *  destroys the resources */
/*========================================================*/
OMX_ERRORTYPE SampleTest_TransitionWait(OMX_STATETYPE eToState,
    SampleCompTestCtxt * pContext)
{
	OMX_ERRORTYPE eError = OMX_ErrorNone;
	OMX_PARAM_PORTDEFINITIONTYPE tPortDef;
	OMX_U32 i, j;

	eError = OMX_SendCommand(pContext->hComp, OMX_CommandStateSet,
	    eToState, NULL);
	OMX_TEST_BAIL_IF_ERROR(eError);

	if ((eToState == OMX_StateIdle) &&
	    (pContext->eState == OMX_StateLoaded))
	{
		for (i = 0; i < NUM_DOMAINS; i++)
		{
			for (j = pContext->sPortParam[i].nStartPortNumber;
			    j < pContext->sPortParam[i].nStartPortNumber
			    + pContext->sPortParam[i].nPorts; j++)
			{

				OMX_TEST_INIT_STRUCT(tPortDef,
				    OMX_PARAM_PORTDEFINITIONTYPE);
				tPortDef.nPortIndex = j;
//printf("\nCalling GetParam before UseBuf on port %d\n",j);
				eError = OMX_GetParameter(pContext->hComp,
				    OMX_IndexParamPortDefinition,
				    (OMX_PTR) & tPortDef);
				OMX_TEST_BAIL_IF_ERROR(eError);

//                    if(tPortDef.bEnabled)//AD
				eError =
				    SampleTest_AllocateBuffers(pContext,
				    &tPortDef);

				OMX_TEST_BAIL_IF_ERROR(eError);
			}
		}
	} else if ((eToState == OMX_StateLoaded) &&
	    (pContext->eState == OMX_StateIdle))
	{

		eError = SampleTest_DeInitBuffers(pContext);
		OMX_TEST_BAIL_IF_ERROR(eError);

	}
	printf("\nWaiting for state set event\n");
	TIMM_OSAL_SemaphoreObtain(pContext->hStateSetEvent,
	    TIMM_OSAL_SUSPEND);
	printf("\nState set event recd.\n");

	if (pContext->eState != eToState)
		OMX_TEST_SET_ERROR_BAIL(OMX_ErrorUndefined,
		    " InComplete Transition \n");

      OMX_TEST_BAIL:
	return eError;
}

/*========================================================*/
/* @ fn OMX_Sample_UT0001 ::  Initializes, move to Idle and then to executing, process
*    buffers and then destroy the component by moving back to idle, loaded, invalid */
/*========================================================*/
void main(void)
{
	OMX_ERRORTYPE eError = OMX_ErrorNone;
	OMX_HANDLETYPE hComp = NULL;
	OMX_CALLBACKTYPE oCallbacks;
	SampleCompTestCtxt *pContext;
	SampleCompTestCtxt oAppData;

	int ch1, ch2;
	int pass;
	int while_pass = 0, loc_diff = 0;

	pContext = &oAppData;
	printf(" Entering : %s \n", __FUNCTION__);
	memset(pContext, 0x0, sizeof(SampleCompTestCtxt));

	oCallbacks.EventHandler = SampleTest_EventHandler;
	oCallbacks.EmptyBufferDone = SampleTest_EmptyBufferDone;
	oCallbacks.FillBufferDone = SampleTest_FillBufferDone;
	printf("\nCalling sem create\n");
	/* Initialize Events to Track callbacks  */
	TIMM_OSAL_SemaphoreCreate(&pContext->hStateSetEvent, 0);
	TIMM_OSAL_SemaphoreCreate(&pContext->hPortDisableEvent, 0);
	//TIMM_OSAL_MutexObtain(pContext->hStateSetEvent, TIMM_OSAL_SUSPEND);
	printf("\nSem created\n");

	pContext->pInputfile = fopen(INPUT_FILE, "rb");
	if (NULL == pContext->pInputfile)
	{
		eError = OMX_ErrorInsufficientResources;
		//goto OMX_TEST_BAIL;
	}
	printf("\nInput file opened\n");
	pContext->pOutputFile = fopen(NON_TUN_OUTPUT_FILE, "wb");
	if (NULL == pContext->pOutputFile)
	{
		eError = OMX_ErrorInsufficientResources;
		//goto OMX_TEST_BAIL;
	}

	/* Initialize OpenMAX */
	printf("\nInitialize OpenMAX\n");
	eError = OMX_Init();
	OMX_TEST_BAIL_IF_ERROR(eError);
	/* Load a component  */
	printf("\nLoad a component\n");
	eError =
	    OMX_GetHandle(&hComp, (OMX_STRING) "OMX.TI.DUCATI1.MISC.SAMPLE",
	    pContext, &oCallbacks);
	OMX_TEST_BAIL_IF_ERROR(eError);
	pContext->hComp = hComp;
printf ("\neError = 0x%x\n", eError);
if(hComp)
	printf("\nhComp = 0x%x\n", hComp);
	/* Verify that the component is in Loaded state */
	printf("\nVerify that the component is in Loaded state\n");

	eError = OMX_GetState(pContext->hComp, &pContext->eState);
	OMX_TEST_BAIL_IF_ERROR(eError);
	if (OMX_StateLoaded != pContext->eState)
	{
		OMX_TEST_SET_ERROR_BAIL(OMX_ErrorUndefined,
		    "not in loaded state \n");
	}

	/* detect all Audio ports on the component */
	OMX_TEST_INIT_STRUCT(pContext->sPortParam[0], OMX_PORT_PARAM_TYPE);
	eError = OMX_GetParameter(hComp, OMX_IndexParamAudioInit,
	    (OMX_PTR) & pContext->sPortParam[0]);
	OMX_TEST_BAIL_IF_ERROR(eError);

	/* detect all video ports on the component */
	OMX_TEST_INIT_STRUCT(pContext->sPortParam[1], OMX_PORT_PARAM_TYPE);
	eError = OMX_GetParameter(hComp, OMX_IndexParamVideoInit,
	    (OMX_PTR) & pContext->sPortParam[1]);
	OMX_TEST_BAIL_IF_ERROR(eError);

	/* detect all image ports on the component */
	OMX_TEST_INIT_STRUCT(pContext->sPortParam[2], OMX_PORT_PARAM_TYPE);
	eError = OMX_GetParameter(hComp, OMX_IndexParamImageInit,
	    (OMX_PTR) & pContext->sPortParam[2]);
	OMX_TEST_BAIL_IF_ERROR(eError);

	/* detect all other ports on the component */
	OMX_TEST_INIT_STRUCT(pContext->sPortParam[3], OMX_PORT_PARAM_TYPE);
	eError = OMX_GetParameter(hComp, OMX_IndexParamOtherInit,
	    (OMX_PTR) & pContext->sPortParam[3]);
	OMX_TEST_BAIL_IF_ERROR(eError);

	pContext->nPorts = pContext->sPortParam[0].nPorts +
	    pContext->sPortParam[1].nPorts +
	    pContext->sPortParam[2].nPorts + pContext->sPortParam[3].nPorts;

	pContext->bClientAllocBuf = OMX_SAMPLE_USEBUF;
	if (pContext->bClientAllocBuf == OMX_TRUE)
	{
		printf(" Client does Allocation of buffers \n");
	} else
	{
		printf(" Component does Allocation of buffers \n");
	}

	/* Transition to Idle state */

	eError = SampleTest_TransitionWait(OMX_StateIdle, pContext);
	OMX_TEST_BAIL_IF_ERROR(eError);
	/* Transition to Executing state */
	eError = SampleTest_TransitionWait(OMX_StateExecuting, pContext);
	OMX_TEST_BAIL_IF_ERROR(eError);
	printf("\nAbout to start processing buffers\n");

	/*  process buffers   */

	while (pContext->nBufDoneCalls < OMX_TEST_BUFFERS_OF_TRAFFIC)
	{

		eError = SampleTest_WriteInBuffers(pContext);
		OMX_TEST_BAIL_IF_ERROR(eError);

		eError = SampleTest_ReadOutBuffers(pContext);
		OMX_TEST_BAIL_IF_ERROR(eError);
		while_pass++;
		//printf("\n WHILE PROCESS LOOP COUNT:  BufDoneCount = %d %d",
		//    while_pass, pContext->nBufDoneCalls);

		//printf("\n Waiting on Sample component to respond");

	}

	gTest = 0;

	/* Transition back to Idle state  */
	eError = SampleTest_TransitionWait(OMX_StateIdle, pContext);
	OMX_TEST_BAIL_IF_ERROR(eError);

	/* Trasnition back to Loaded state */
	eError = SampleTest_TransitionWait(OMX_StateLoaded, pContext);
	OMX_TEST_BAIL_IF_ERROR(eError);

      OMX_TEST_BAIL:

	fclose(pContext->pInputfile);
	fclose(pContext->pOutputFile);

	if (eError == OMX_ErrorNone)
	{
		eError = OMX_FreeHandle(pContext->hComp);
		eError = OMX_Deinit();
	} else
	{
		SampleTest_TransitionWait(OMX_StateInvalid, pContext);
		SampleTest_DeInitBuffers(pContext);

		OMX_FreeHandle(pContext->hComp);
		OMX_Deinit();
	}

	TIMM_OSAL_SemaphoreDelete(pContext->hStateSetEvent);
	TIMM_OSAL_SemaphoreDelete(pContext->hPortDisableEvent);

	/* emit the Test Result */
	if (OMX_ErrorNone != eError)
	{
		printf(" TestCase Failed and returned an error:: %s \n",
		    OMX_TEST_ErrorToString(eError));
	} else
	{
		printf
		    ("\nTest case has ended, now comparing input and output files\n");
		pContext->pInputfile = fopen(INPUT_FILE, "rb");
		if (NULL == pContext->pInputfile)
		{
			printf("\n Error in opening INPUT_FILE");
			eError = OMX_ErrorInsufficientResources;
		}

		pContext->pOutputFile = fopen(NON_TUN_OUTPUT_FILE, "rb");
		if (NULL == pContext->pOutputFile)
		{
			printf("\n Error in opening NON_TUN_OUTPUT_FILE");
			eError = OMX_ErrorInsufficientResources;
		}
		pass = 1;
		while (1)
		{
			if (eError != OMX_ErrorNone)
			{
				pass = 0;
				break;
			}
			ch1 = fgetc(pContext->pInputfile);
			ch2 = fgetc(pContext->pOutputFile);
			loc_diff++;
			if (ch1 == EOF || ch2 == EOF)
			{
				break;
			}
			if (ch1 != ch2)
			{
				pass = 0;
				printf("\n \n");
				printf
				    ("\n FILE SIZE = 320 KB - NUMBER OF ITERATIONS = 20 (10 for INPUT AND 10 FOR OUTPUT buffers\n");
				printf
				    ("\n ################### LOCATION OF DIFFERENCE: %d ################### \n",
				    loc_diff);
				break;
			}
		}
		fclose(pContext->pInputfile);
		fclose(pContext->pOutputFile);
		if (pass == 1)
			printf(" Test Case has Passed\n");
		else
		{
			printf("\nTest case has failed. (EOF not reached)\n");
			eError = OMX_ErrorUndefined;
		}
	}

	if (eError == OMX_ErrorNone)
	{
		printf(" Test Case has Passed :) \n");
	} else
	{
		printf("\nTest case has failed.(OMX Error)\n");
	}
}


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/generic/memory/lib/utils/count_dimm.H $            */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2022                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file count_dimm.H
/// @brief Count the DIMM attached to a target
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Jacob Harvey <jlharvey@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP

#ifndef _MSS_COUNT_DIMM_H_
#define _MSS_COUNT_DIMM_H_

#include <fapi2.H>
#include <generic/memory/lib/utils/find.H>
#include <generic/memory/lib/utils/c_str.H>

namespace mss
{
///
/// @brief Return the count of the number of DIMM attached to a target
/// @tparam T the fapi2::TargetType
/// @param[in] i_target a target
/// @return size_t the count of DIMM attached
///
template< fapi2::TargetType T >
inline size_t count_dimm(const fapi2::Target<T>& i_target)
{
    // Sanity check that we have DIMM. Be sure to ask the platform, not eff_config, as
    // in the case of an over-ride and there are no DIMM in the config, we want to let
    // people know. Which is how we found we needed to add this code ...
    size_t l_dimm_count = find_targets<fapi2::TARGET_TYPE_DIMM>(i_target).size();
    return l_dimm_count;
}

///
/// @brief Return the count of the number of DIMM attached to a target - DIMM speicalization
/// @param[in] i_target a target
/// @return size_t the count of DIMM attached
///
template< >
inline size_t count_dimm(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target)
{
    // You can only ever have one DIMM on a DIMM target
    return 1;
}

///
/// @brief Return the count of the number of DIMM attached to a vector of targets
/// @tparam T the fapi2::TargetType
/// @param[in] i_target a vector of targets
/// @return size_t the count of DIMM attached
///
template< fapi2::TargetType T >
inline size_t count_dimm(const std::vector<fapi2::Target<T>>& i_targets)
{
    size_t l_dimm_count = 0;

    for (const auto& l_target : i_targets)
    {
        l_dimm_count += count_dimm(l_target);
    }

    return l_dimm_count;
}

///
/// @brief Return the count of the number of MEM port attached to a target.
/// @tparam T the fapi2::TargetType
/// @param[in] i_target a target
/// @param[in] i_state [optional] fapi2 target state (defaults to TARGET_STATE_FUNCTIONAL)
/// @return size_t the count of MEM port attached
/// @note Use this function to count "present and nonfunctional" DIMMs
///
template< fapi2::TargetType T >
inline size_t count_mem_port(const fapi2::Target<T>& i_target,
                             fapi2::TargetState i_state = fapi2::TARGET_STATE_FUNCTIONAL)
{
    size_t l_mem_port_count = find_targets<fapi2::TARGET_TYPE_MEM_PORT>(i_target, i_state).size();
    return l_mem_port_count;
}

///
/// @brief Return the count of the number of MEM port attached to a target.
/// @tparam T the fapi2::TargetType
/// @param[in] i_target a target
/// @param[in] i_state [optional] fapi2 target state (defaults to TARGET_STATE_FUNCTIONAL)
/// @return size_t the count of MEM port attached
/// @note Use this function to count "present and nonfunctional" DIMMs
///
template< >
inline size_t count_mem_port(const fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>& i_target,
                             fapi2::TargetState i_state)
{
    // We currently have only one DIMM on a MEM port
    return 1;
}

///
/// @brief Return the count of the number of MEM port attached to a vector of targets.
/// @tparam T the fapi2::TargetType
/// @param[in] i_target a vector of targets
/// @param[in] i_state [optional] fapi2 target state (defaults to TARGET_STATE_FUNCTIONAL)
/// @return size_t the count of MEM port attached
/// @note Use this function to count "present and nonfunctional" DIMMs
///
template< fapi2::TargetType T >
inline size_t count_mem_port(const std::vector<fapi2::Target<T>>& i_targets,
                             fapi2::TargetState i_state = fapi2::TARGET_STATE_FUNCTIONAL )
{
    size_t l_mem_port_count = 0;

    for (const auto& l_target : i_targets)
    {
        l_mem_port_count += count_mem_port(l_target, i_state);
    }

    return l_mem_port_count;
}

///
/// @brief Return the count of the number of MEM attached to a proc chip - DIMM speicalization
/// @param[in] i_target a target
/// @param[in] i_state [optional] fapi2 target state (defaults to TARGET_STATE_FUNCTIONAL)
/// @return size_t the count of MEM attached
/// @note Use this function to count "present and nonfunctional" DIMMs
///
template< >
inline size_t count_mem_port(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
                             fapi2::TargetState i_state)
{
    const auto& l_ocmb = find_targets<fapi2::TARGET_TYPE_OCMB_CHIP>(i_target, i_state);

    return count_mem_port(l_ocmb, i_state);
}

}
#endif


text:
<?php
require_once(INCLUDE_DIR.'/class.plugin.php');
require_once(INCLUDE_DIR.'/class.forms.php');

class FormsAuthConfig extends PluginConfig {
	function getOptions() {
		return array(
			'formsauth_enable_staff' => new BooleanField(array(
				'id' => 'formsauth_enable_staff',
				'label' => 'Staff',
				'configuration' => array('desc' => 'Enable forms authentication for staff logins')
			)),
			'formsauth_enable_user' => new BooleanField(array(
				'id' => 'formsauth_enable_user',
				'label' => 'Users',
				'configuration' => array('desc' => 'Enable forms authentication for user logins')
			)),
			'formsauth_cookie' => new TextboxField(array(
				'id' => 'formsauth_cookie',
				'label' => 'Forms Auth Cookie',
				'configuration' => array('desc' => 'The name of the cookie used by ASP.NET FormsAuthentication', 'length' => 50)
			)),
			'authcheck_url' => new TextboxField(array(
				'id' => 'authcheck_url',
				'label' => 'Authentication URL',
				'length' => 100,
				'configuration' => array('desc' => 'The URL that will check the cookie and respond with proper json', 'length' => 500)
			)),
			'external_link_url' => new TextboxField(array(
				'id' => 'external_link_url',
				'label' => 'External Link URL',
				'length' => 100,
				'configuration' => array('desc' => 'URL for the external login page', 'length' => 500)
			)),
			'external_link_text' => new TextboxField(array(
				'id' => 'external_link_text',
				'label' => 'External Link Text',
				'length' => 100,
				'configuration' => array('desc' => 'Link text for the external login page', 'length' => 500)
			))
		);
	}

	/* override to set the title */
	function getForm() {
		$result = parent::getForm();
		$result->title = "Forms Auth";
		/*echo '
';
		echo 'Current Cookies:';
		echo '
';
		foreach ($_COOKIE as $key => $value)
			echo "
$key
";
		echo '
';
		echo '
';*/
		return $result;
	}

	function pre_save(&$config, &$errors) {
		global $msg;

		if (!$errors)
			$msg = 'Configuration updated successfully';

		return true;
	}
}
?>


text:
package cn.magic.library;

import android.animation.TypeEvaluator;
import android.graphics.Bitmap;

/**
 * An abstract Animator Evaluator define class, assigned to {@link ValueState}.
 * You can extends this class to define yourself customer flying animator,
 * When you extends this class, please add your new animator type to {@link AnimatorCreater}
 * and {@link MagicFlyLinearLayout} attrs.
 */

public abstract class AbsAnimatorEvaluator implements TypeEvaluator<ValueState> {
    private int mMeasuredWith;
    private int mMeasuredHeigh;
    private Bitmap mBitmap;

    public AbsAnimatorEvaluator(int width, int heigh, Bitmap bitmap) {
        this.mMeasuredWith = width;
        this.mMeasuredHeigh = heigh;
        this.mBitmap = bitmap;
    }

    public int getMeasuredWith() {
        return mMeasuredWith;
    }

    public int getMeasuredHeigh() {
        return mMeasuredHeigh;
    }

    public Bitmap getBitmap() {
        return mBitmap;
    }

    public abstract ValueState createAnimatorStart();
    public abstract ValueState createAnimatorEnd();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<litepal>
    <dbname value="gps"/>
    <version value="1" />
    <list>
        <mapping class="com.gps.sweeprobot.database.GpsMapBean"/>
        <mapping class="com.gps.sweeprobot.database.Task"/>
        <mapping class="com.gps.sweeprobot.model.taskqueue.bean.TaskPoint"/>
    </list>
</litepal>


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));

var _utils = require("../utils");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const isUrlFunc = /url/i;
const isImageSetFunc = /^(?:-webkit-)?image-set$/i;
const needParseDeclaration = /(?:url|(?:-webkit-)?image-set)\(/i;

function getNodeFromUrlFunc(node) {
  return node.nodes && node.nodes[0];
}

function getWebpackIgnoreCommentValue(index, nodes, inBetween) {
  if (index === 0 && typeof inBetween !== "undefined") {
    return inBetween;
  }

  let prevValueNode = nodes[index - 1];

  if (!prevValueNode) {
    // eslint-disable-next-line consistent-return
    return;
  }

  if (prevValueNode.type === "space") {
    if (!nodes[index - 2]) {
      // eslint-disable-next-line consistent-return
      return;
    }

    prevValueNode = nodes[index - 2];
  }

  if (prevValueNode.type !== "comment") {
    // eslint-disable-next-line consistent-return
    return;
  }

  const matched = prevValueNode.value.match(_utils.WEBPACK_IGNORE_COMMENT_REGEXP);
  return matched && matched[2] === "true";
}

function shouldHandleURL(url, declaration, result, options) {
  if (url.length === 0) {
    result.warn(`Unable to find uri in '${declaration.toString()}'`, {
      node: declaration
    });
    return {
      requestable: false,
      needResolve: false
    };
  }

  return (0, _utils.isURLRequestable)(url, options);
}

function parseDeclaration(declaration, key, result, options) {
  if (!needParseDeclaration.test(declaration[key])) {
    return;
  }

  const parsed = (0, _postcssValueParser.default)(declaration.raws && declaration.raws.value && declaration.raws.value.raw ? declaration.raws.value.raw : declaration[key]);
  let inBetween;

  if (declaration.raws && declaration.raws.between) {
    const lastCommentIndex = declaration.raws.between.lastIndexOf("/*");
    const matched = declaration.raws.between.slice(lastCommentIndex).match(_utils.WEBPACK_IGNORE_COMMENT_REGEXP);

    if (matched) {
      inBetween = matched[2] === "true";
    }
  }

  let isIgnoreOnDeclaration = false;
  const prevNode = declaration.prev();

  if (prevNode && prevNode.type === "comment") {
    const matched = prevNode.text.match(_utils.WEBPACK_IGNORE_COMMENT_REGEXP);

    if (matched) {
      isIgnoreOnDeclaration = matched[2] === "true";
    }
  }

  let needIgnore;
  const parsedURLs = [];
  parsed.walk((valueNode, index, valueNodes) => {
    if (valueNode.type !== "function") {
      return;
    }

    if (isUrlFunc.test(valueNode.value)) {
      needIgnore = getWebpackIgnoreCommentValue(index, valueNodes, inBetween);

      if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
        if (needIgnore) {
          // eslint-disable-next-line no-undefined
          needIgnore = undefined;
        }

        return;
      }

      const {
        nodes
      } = valueNode;
      const isStringValue = nodes.length !== 0 && nodes[0].type === "string";
      let url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
      url = (0, _utils.normalizeUrl)(url, isStringValue);
      const {
        requestable,
        needResolve
      } = shouldHandleURL(url, declaration, result, options); // Do not traverse inside `url`

      if (!requestable) {
        // eslint-disable-next-line consistent-return
        return false;
      }

      const queryParts = url.split("!");
      let prefix;

      if (queryParts.length > 1) {
        url = queryParts.pop();
        prefix = queryParts.join("!");
      }

      parsedURLs.push({
        declaration,
        parsed,
        node: getNodeFromUrlFunc(valueNode),
        prefix,
        url,
        needQuotes: false,
        needResolve
      }); // eslint-disable-next-line consistent-return

      return false;
    } else if (isImageSetFunc.test(valueNode.value)) {
      for (const [innerIndex, nNode] of valueNode.nodes.entries()) {
        const {
          type,
          value
        } = nNode;

        if (type === "function" && isUrlFunc.test(value)) {
          needIgnore = getWebpackIgnoreCommentValue(innerIndex, valueNode.nodes);

          if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
            if (needIgnore) {
              // eslint-disable-next-line no-undefined
              needIgnore = undefined;
            } // eslint-disable-next-line no-continue

            continue;
          }

          const {
            nodes
          } = nNode;
          const isStringValue = nodes.length !== 0 && nodes[0].type === "string";
          let url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
          url = (0, _utils.normalizeUrl)(url, isStringValue);
          const {
            requestable,
            needResolve
          } = shouldHandleURL(url, declaration, result, options); // Do not traverse inside `url`

          if (!requestable) {
            // eslint-disable-next-line consistent-return
            return false;
          }

          const queryParts = url.split("!");
          let prefix;

          if (queryParts.length > 1) {
            url = queryParts.pop();
            prefix = queryParts.join("!");
          }

          parsedURLs.push({
            declaration,
            parsed,
            node: getNodeFromUrlFunc(nNode),
            prefix,
            url,
            needQuotes: false,
            needResolve
          });
        } else if (type === "string") {
          needIgnore = getWebpackIgnoreCommentValue(innerIndex, valueNode.nodes);

          if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
            if (needIgnore) {
              // eslint-disable-next-line no-undefined
              needIgnore = undefined;
            } // eslint-disable-next-line no-continue

            continue;
          }

          let url = (0, _utils.normalizeUrl)(value, true);
          const {
            requestable,
            needResolve
          } = shouldHandleURL(url, declaration, result, options); // Do not traverse inside `url`

          if (!requestable) {
            // eslint-disable-next-line consistent-return
            return false;
          }

          const queryParts = url.split("!");
          let prefix;

          if (queryParts.length > 1) {
            url = queryParts.pop();
            prefix = queryParts.join("!");
          }

          parsedURLs.push({
            declaration,
            parsed,
            node: nNode,
            prefix,
            url,
            needQuotes: true,
            needResolve
          });
        }
      } // Do not traverse inside `image-set`
      // eslint-disable-next-line consistent-return

      return false;
    }
  }); // eslint-disable-next-line consistent-return

  return parsedURLs;
}

const plugin = (options = {}) => {
  return {
    postcssPlugin: "postcss-url-parser",

    prepare(result) {
      const parsedDeclarations = [];
      return {
        Declaration(declaration) {
          const {
            isSupportDataURL,
            isSupportAbsoluteURL
          } = options;
          const parsedURL = parseDeclaration(declaration, "value", result, {
            isSupportDataURL,
            isSupportAbsoluteURL
          });

          if (!parsedURL) {
            return;
          }

          parsedDeclarations.push(...parsedURL);
        },

        async OnceExit() {
          if (parsedDeclarations.length === 0) {
            return;
          }

          const resolvedDeclarations = await Promise.all(parsedDeclarations.map(async parsedDeclaration => {
            const {
              url,
              needResolve
            } = parsedDeclaration;

            if (options.filter) {
              const needKeep = await options.filter(url);

              if (!needKeep) {
                // eslint-disable-next-line consistent-return
                return;
              }
            }

            if (!needResolve) {
              // eslint-disable-next-line consistent-return
              return parsedDeclaration;
            }

            const splittedUrl = url.split(/(\?)?#/);
            const [pathname, query, hashOrQuery] = splittedUrl;
            let hash = query ? "?" : "";
            hash += hashOrQuery ? `#${hashOrQuery}` : "";
            const {
              resolver,
              rootContext
            } = options;
            const request = (0, _utils.requestify)(pathname, rootContext, Boolean(resolver));

            if (!resolver) {
              // eslint-disable-next-line consistent-return
              return { ...parsedDeclaration,
                url: request,
                hash
              };
            }

            const resolvedURL = await (0, _utils.resolveRequests)(resolver, options.context, [...new Set([request, url])]);

            if (!resolvedURL) {
              // eslint-disable-next-line consistent-return
              return;
            } // eslint-disable-next-line consistent-return

            return { ...parsedDeclaration,
              url: resolvedURL,
              hash
            };
          }));
          const urlToNameMap = new Map();
          const urlToReplacementMap = new Map();
          let hasUrlImportHelper = false;

          for (let index = 0; index <= resolvedDeclarations.length - 1; index++) {
            const item = resolvedDeclarations[index];

            if (!item) {
              // eslint-disable-next-line no-continue
              continue;
            }

            if (!hasUrlImportHelper) {
              options.imports.push({
                type: "get_url_import",
                importName: "___CSS_LOADER_GET_URL_IMPORT___",
                url: options.urlHandler(require.resolve("../runtime/getUrl.js")),
                index: -1
              });
              hasUrlImportHelper = true;
            }

            const {
              url,
              prefix
            } = item;
            const newUrl = prefix ? `${prefix}!${url}` : url;
            let importName = urlToNameMap.get(newUrl);

            if (!importName) {
              importName = `___CSS_LOADER_URL_IMPORT_${urlToNameMap.size}___`;
              urlToNameMap.set(newUrl, importName);
              options.imports.push({
                type: "url",
                importName,
                url: options.resolver ? options.urlHandler(newUrl) : JSON.stringify(newUrl),
                index
              });
            }

            const {
              hash,
              needQuotes
            } = item;
            const replacementKey = JSON.stringify({
              newUrl,
              hash,
              needQuotes
            });
            let replacementName = urlToReplacementMap.get(replacementKey);

            if (!replacementName) {
              replacementName = `___CSS_LOADER_URL_REPLACEMENT_${urlToReplacementMap.size}___`;
              urlToReplacementMap.set(replacementKey, replacementName);
              options.replacements.push({
                replacementName,
                importName,
                hash,
                needQuotes
              });
            } // eslint-disable-next-line no-param-reassign

            item.node.type = "word"; // eslint-disable-next-line no-param-reassign

            item.node.value = replacementName; // eslint-disable-next-line no-param-reassign

            item.declaration.value = item.parsed.toString();
          }
        }

      };
    }

  };
};

plugin.postcss = true;
var _default = plugin;
exports.default = _default;


text:
package metrics

import (
	"context"
	"net/http"
	"testing"
	"time"

	"github.com/containous/traefik/types"
	"github.com/stvp/go-udp-testing"
)

func TestStatsD(t *testing.T) {
	udp.SetAddr(":18125")
	// This is needed to make sure that UDP Listener listens for data a bit longer, otherwise it will quit after a millisecond
	udp.Timeout = 5 * time.Second

	statsdRegistry := RegisterStatsd(context.Background(), &types.Statsd{Address: ":18125", PushInterval: "1s"})
	defer StopStatsd()

	if !statsdRegistry.IsEnabled() {
		t.Errorf("Statsd registry should return true for IsEnabled()")
	}

	expected := []string{
		// We are only validating counts, as it is nearly impossible to validate latency, since it varies every run
		"traefik.backend.request.total:2.000000|c\n",
		"traefik.backend.retries.total:2.000000|c\n",
		"traefik.backend.request.duration:10000.000000|ms",
		"traefik.config.reload.total:1.000000|c\n",
		"traefik.config.reload.total:1.000000|c\n",
		"traefik.entrypoint.request.total:1.000000|c\n",
		"traefik.entrypoint.request.duration:10000.000000|ms",
		"traefik.entrypoint.connections.open:1.000000|g\n",
		"traefik.backend.server.up:1.000000|g\n",
	}

	udp.ShouldReceiveAll(t, expected, func() {
		statsdRegistry.BackendReqsCounter().With("service", "test", "code", string(http.StatusOK), "method", http.MethodGet).Add(1)
		statsdRegistry.BackendReqsCounter().With("service", "test", "code", string(http.StatusNotFound), "method", http.MethodGet).Add(1)
		statsdRegistry.BackendRetriesCounter().With("service", "test").Add(1)
		statsdRegistry.BackendRetriesCounter().With("service", "test").Add(1)
		statsdRegistry.BackendReqDurationHistogram().With("service", "test", "code", string(http.StatusOK)).Observe(10000)
		statsdRegistry.ConfigReloadsCounter().Add(1)
		statsdRegistry.ConfigReloadsFailureCounter().Add(1)
		statsdRegistry.EntrypointReqsCounter().With("entrypoint", "test").Add(1)
		statsdRegistry.EntrypointReqDurationHistogram().With("entrypoint", "test").Observe(10000)
		statsdRegistry.EntrypointOpenConnsGauge().With("entrypoint", "test").Set(1)
		statsdRegistry.BackendServerUpGauge().With("backend:test", "url", "http://127.0.0.1").Set(1)
	})
}


text:
<?php
namespace Topxia\AdminBundle\Controller;

use Topxia\Common\Paginator;
use Topxia\Common\ArrayToolkit;
use Symfony\Component\HttpFoundation\Request;

class TeacherController extends BaseController
{
    public function indexAction(Request $request)
    {
        $conditions = $request->query->all();
        $conditions = $this->fillOrgCode($conditions);
        $conditions['roles'] = 'ROLE_TEACHER';
        $paginator = new Paginator(
            $this->get('request'),
            $this->getUserService()->searchUserCount($conditions),
            20
        );

        $users = $this->getUserService()->searchUsers(
            $conditions,
            array('createdTime', 'DESC'),
            $paginator->getOffsetCount(),
            $paginator->getPerPageCount()
        );

        return $this->render('TopxiaAdminBundle:Teacher:index.html.twig', array(
            'users'     => $users,
            'paginator' => $paginator
        ));
    }

    public function promoteAction(Request $request, $id)
    {
        $user = $this->getUserService()->getUser($id);
        $type = $request->query->get('type');

        if ($request->getMethod() == 'POST') {
            $number = $request->request->get('number');
            $user   = $this->getUserService()->promoteUser($id, $number);
            $type   = $request->request->get('type');

            if ($type == 'promoteList') {
                return $this->render('TopxiaAdminBundle:Teacher:teacher-promote-tr.html.twig', array('user' => $user));
            }

            if ($type == 'teacherList') {
                return $this->render('TopxiaAdminBundle:Teacher:tr.html.twig', array('user' => $user));
            }
        }

        return $this->render('TopxiaAdminBundle:Teacher:teacher-promote-modal.html.twig', array(
            'user' => $user,
            'type' => $type
        ));
    }

    public function promoteListAction(Request $request)
    {
        $user = $this->getCurrentUser();
        $fields     = $request->query->all();
        $conditions = array(
            'roles'    => 'ROLE_TEACHER',
            'promoted' => 1
        );
        $conditions = array_merge($conditions, $fields);
        $conditions = $this->fillOrgCode($conditions);

        $paginator = new Paginator(
            $this->get('request'),
            $this->getUserService()->searchUserCount($conditions),
            20
        );

        $users = $this->getUserService()->searchUsers(
            $conditions,
            array('promotedSeq', 'ASC', 'promotedTime', 'DESC'),
            $paginator->getOffsetCount(),
            $paginator->getPerPageCount()
        );

        return $this->render('TopxiaAdminBundle:Teacher:teacher-promote-list.html.twig', array(
            'users'     => $users,
            'paginator' => $paginator
        ));
    }

    public function promoteCancelAction(Request $request, $id)
    {
        $user = $this->getUserService()->cancelPromoteUser($id);

        return $this->render('TopxiaAdminBundle:Teacher:tr.html.twig', array('user' => $user));
    }

    protected function getUserService()
    {
        return $this->getServiceKernel()->createService('User.UserService');
    }
}


text:
package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/tools/remotecommand"
	"k8s.io/client-go/util/exec"
)

// Args for exec.
type Args struct {
	Pod       string
	Container string
	Namespace string
	Command   []string
	Arg       string
}

type writer struct {
	Str []string
}

func (w *writer) Write(p []byte) (n int, err error) {
	str := string(p)
	if len(str) > 0 {
		w.Str = append(w.Str, str)
	}
	return len(str), nil
}

func homeDir() string {
	if h := os.Getenv("HOME"); h != "" {
		return h
	}
	return os.Getenv("USERPROFILE")
}

func getK8SConfigInternal() *rest.Config {
	config, err := rest.InClusterConfig()
	if err != nil {
		panic(err.Error())
	}
	return config
}

func getK8SConfigExternal() *rest.Config {
	var kubeconfig *string
	if home := homeDir(); home != "" {
		kubeconfig = flag.String(
			"kubeconfig",
			filepath.Join(home, ".kube", "config"),
			"(optional) absolute path to the kubeconfig file",
		)
	} else {
		kubeconfig = flag.String(
			"kubeconfig",
			"",
			"absolute path to the kubeconfig file",
		)
	}
	flag.Parse()

	// use the current context in kubeconfig
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err.Error())
	}

	return config
}

func newK8SClient(config *rest.Config) *kubernetes.Clientset {
	kubeClient, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}
	return kubeClient
}

func kubeExec(
	config *rest.Config,
	k8s *kubernetes.Clientset,
	args *Args,
) error {
	// check pod exists
	pod, err :=
		k8s.CoreV1().Pods(args.Namespace).Get(args.Pod, metav1.GetOptions{})
	if err != nil {
		return err
	}

	// check container exists
	if args.Container != "" {
		notFound := true
		for _, container := range pod.Spec.Containers {
			if container.Name == args.Container {
				notFound = false
				break
			}
		}
		if notFound {
			return fmt.Errorf(`Container "%v" not found`, args.Container)
		}
	}

	// execute command
	req := k8s.CoreV1().RESTClient().Post().
		Resource("pods").
		Name(args.Pod).
		Namespace(args.Namespace).
		SubResource("exec").
		Param("container", args.Container)
	req.VersionedParams(&v1.PodExecOptions{
		Container: args.Container,
		Command:   args.Command,
		Stdin:     true,
		Stdout:    true,
		Stderr:    true,
	}, scheme.ParameterCodec)

	rc, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
	if err != nil {
		return err
	}

	stdIn := strings.NewReader(args.Arg)
	stdOut := &writer{}
	stdErr := &writer{}

	err = rc.Stream(remotecommand.StreamOptions{
		Stdin:  stdIn,
		Stdout: stdOut,
		Stderr: stdErr,
		Tty:    false,
	})

	var exitCode int
	if err == nil {
		exitCode = 0
	} else {
		if exitErr, ok := err.(exec.ExitError); ok && exitErr.Exited() {
			exitCode = exitErr.ExitStatus()
		} else {
			return fmt.Errorf("failed to find exit code")
		}
	}

	fmt.Printf("Exit Code: %d\n", exitCode)
	fmt.Printf("Stdout: %s\n", strings.Join(stdOut.Str, "|"))
	fmt.Printf("Stderr: %s\n", strings.Join(stdErr.Str, "|"))

	return nil
}

func main() {
	args := &Args{
		Pod:       "exocompute-containers-example-loop",
		Container: "exocompute-containers-example-loop",
		Namespace: "default",
		Command:   []string{"echo", "hello"},
		Arg:       "1",
	}

	config := getK8SConfigInternal()
	k8s := newK8SClient(config)
	err := kubeExec(config, k8s, args)
	if err != nil {
		fmt.Printf("Error executing command: %v\n", err)
	}
}