text:
<?php

use Mockery as m;
use KodiComponents\Navigation\Contracts\PageInterface;
use SleepingOwl\Admin\Model\ModelConfigurationManager;

class ModelConfigurationManagerTest extends TestCase
{
    public function tearDown()
    {
        m::close();
    }

    /**
     * @param string $class
     *
     * @return ModelConfigurationManager|PHPUnit_Framework_MockObject_MockObject
     */
    protected function getConfiguration($class = ModelConfigurationManagerTestModel::class)
    {
        return $this->getMockForAbstractClass(ModelConfigurationManager::class, [$this->app, $class]);
    }

    /**
     * @covers ModelConfigurationManager::__construct
     * @covers ModelConfigurationManager::getClass
     * @covers ModelConfigurationManager::getModel
     * @covers ModelConfigurationManager::getRepository
     * @covers ModelConfigurationManager::getAlias
     */
    public function test_constructor()
    {
        $model = $this->getConfiguration();

        $this->assertEquals(ModelConfigurationManagerTestModel::class, $model->getClass());
        $this->assertInstanceOf(ModelConfigurationManagerTestModel::class, $model->getModel());
        $this->assertInstanceOf(\SleepingOwl\Admin\Contracts\Repositories\RepositoryInterface::class, $model->getRepository());
        $this->assertEquals('model_configuration_manager_test_models', $model->getAlias());
    }

    /**
     * @covers ModelConfigurationManager::getTitle
     */
    public function test_gets_title()
    {
        $model = $this->getConfiguration();
        $this->assertEquals('Model Configuration Manager Test Models', $model->getTitle());
    }

    /**
     * @covers ModelConfigurationManager::getIcon
     * @covers ModelConfigurationManager::setIcon
     */
    public function test_gets_and_sets_icon()
    {
        $model = $this->getConfiguration();

        $this->assertEquals(
            $model,
            $model->setIcon('fa fa-test')
        );

        $this->assertEquals('fa fa-test', $model->getIcon());
    }

    /**
     * @covers ModelConfigurationManager::getCreateTitle
     */
    public function test_gets_create_title()
    {
        $model = $this->getConfiguration();

        $this->getTranslatorMock()
            ->shouldReceive('trans')
            ->once()
            ->with('sleeping_owl::lang.model.create', ['title' => $model->getTitle()], null)
            ->andReturn('string');

        $this->assertEquals('string', $model->getCreateTitle());
    }

    /**
     * @covers ModelConfigurationManager::getEditTitle
     */
    public function test_gets_edit_title()
    {
        $model = $this->getConfiguration();

        $this->getTranslatorMock()
            ->shouldReceive('trans')
            ->once()
            ->with('sleeping_owl::lang.model.edit', ['title' => $model->getTitle()], null)
            ->andReturn('string');

        $this->assertEquals('string', $model->getEditTitle());
    }

    /**
     * @covers ModelConfigurationManager::setEventDispatcher
     * @covers ModelConfigurationManager::fireEvent
     */
    public function test_firing_events_with_halt_default_model()
    {
        $model = $this->getConfiguration();

        $model->setEventDispatcher($event = m::mock(\Illuminate\Contracts\Events\Dispatcher::class));
        $event->shouldReceive('until')->once()->andReturn(true);

        $return = $model->fireEvent('test');
        $this->assertTrue($return);
    }

    /**
     * @covers ModelConfigurationManager::setEventDispatcher
     * @covers ModelConfigurationManager::fireEvent
     */
    public function test_firing_events_with_halt()
    {
        $model = $this->getConfiguration();
        $modelObject = m::mock(ModelConfigurationManagerTestModel::class);

        $model->setEventDispatcher($event = m::mock(\Illuminate\Contracts\Events\Dispatcher::class));
        $event->shouldReceive('until')->once()->andReturnUsing(function ($event, $array) use ($modelObject, $model) {
            $this->assertEquals('sleeping_owl.section.test1: ModelConfigurationManagerTestModel', $event);
            $this->assertEquals($model, $array[0]);
            $this->assertEquals($modelObject, $array[1]);

            return 'hello world';
        });

        $return = $model->fireEvent('test1', true, $modelObject);
        $this->assertEquals('hello world', $return);
    }

    public function test_firing_events_without_halt()
    {
        $model = $this->getConfiguration();

        $model->setEventDispatcher($event = m::mock(\Illuminate\Contracts\Events\Dispatcher::class));
        $event->shouldNotReceive('until');
        $event->shouldReceive('fire')->once()->andReturn(false);

        $return = $model->fireEvent('test', false);
        $this->assertFalse($return);
    }

    public function test_registering_events()
    {
        $model = $this->getConfiguration();
        $model->setEventDispatcher($event = m::mock(\Illuminate\Contracts\Events\Dispatcher::class));

        $events = ['creating', 'created', 'updating', 'updated', 'deleting', 'deleted', 'restoring', 'restored'];
        $event->shouldReceive('listen')->times(count($events));

        foreach ($events as $event) {
            $model->{$event}('test');
        }
    }

    /**
     * @covers ModelConfigurationManager::__call
     */
    public function test_registering_event()
    {
        $model = $this->getConfiguration();
        $model->setEventDispatcher($event = m::mock(\Illuminate\Contracts\Events\Dispatcher::class));

        $callback = 'callback';

        $event->shouldReceive('listen')->once()->withArgs([
            'sleeping_owl.section.creating: ModelConfigurationManagerTestModel',
            $callback,
            140,
        ]);

        $model->creating($callback, 140);
    }

    /**
     * @expectedException BadMethodCallException
     */
    public function test_registering_wrong_event()
    {
        $model = $this->getConfiguration();
        $model->setEventDispatcher($event = m::mock(\Illuminate\Contracts\Events\Dispatcher::class));

        $model->test(140);
    }

    /**
     * @covers ModelConfigurationManager::addToNavigation
     */
    public function test_adds_navigation_page()
    {
        $model = $this->getConfiguration();

        $this->app['sleeping_owl.navigation'] = $navigation = m::mock(\SleepingOwl\Admin\Navigation::class);
        $navigation->shouldReceive('addPage')->once()->andReturnUsing(function ($page) {
            $this->assertInstanceOf(PageInterface::class, $page);
        });

        $this->assertInstanceOf(PageInterface::class, $model->addToNavigation(400));
    }

    /**
     * @covers ModelConfigurationManager::can
     */
    public function test_access_checking_disable_access_check()
    {
        $model = $this->getConfiguration();

        $this->app[Illuminate\Contracts\Auth\Access\Gate::class] = $gate = m::mock(\Illuminate\Contracts\Auth\Access\Gate::class);
        $gate->shouldNotReceive('allows');
        $this->assertTrue($model->can('test', $model->getModel()));
    }

    /**
     * @covers ModelConfigurationManager::enableAccessCheck
     * @covers ModelConfigurationManager::disableAccessCheck
     */
    public function test_access_checking_enable_access_check()
    {
        $model = $this->getConfiguration();

        $modelObject = $model->getModel();

        $this->assertEquals($model, $model->enableAccessCheck());

        $this->app[Illuminate\Contracts\Auth\Access\Gate::class] = $gate = m::mock(\Illuminate\Contracts\Auth\Access\Gate::class);
        $gate->shouldReceive('allows')->once()->withArgs(['test', [$model, $modelObject]])->andReturn(false);

        $this->assertFalse($model->can('test', $model->getModel()));

        $this->assertEquals($model, $model->disableAccessCheck());
        $this->assertTrue($model->can('test', $model->getModel()));
    }

    /**
     * @covers ModelConfigurationManager::setControllerClass
     * @covers ModelConfigurationManager::getControllerClass
     * @covers ModelConfigurationManager::hasCustomControllerClass
     */
    public function test_gets_and_sets_controller_class()
    {
        $model = $this->getConfiguration();

        $this->assertNull($model->getControllerClass());

        $this->assertEquals($model, $model->setControllerClass('test'));

        $this->assertEquals('test', $model->getControllerClass());
        $this->assertFalse($model->hasCustomControllerClass());

        $model->setControllerClass(ModelConfigurationManagerTestController::class);
        $this->assertEquals(ModelConfigurationManagerTestController::class, $model->getControllerClass());
        $this->assertTrue($model->hasCustomControllerClass());
    }

    /**
     * @covers ModelConfigurationManager::getDisplayUrl
     */
    public function test_gets_display_url()
    {
        $model = $this->getConfiguration();

        $this->getRouterMock()->shouldReceive('route')->once()->withArgs([
            'admin.model',
            [$model->getAlias(), 'test'],
            true,
        ])->andReturn('http://site.com');

        $this->assertEquals('http://site.com', $model->getDisplayUrl(['test']));
    }

    /**
     * @covers ModelConfigurationManager::getCreateUrl
     */
    public function test_gets_create_url()
    {
        $model = $this->getConfiguration();

        $this->getRouterMock()->shouldReceive('route')->once()->withArgs([
            'admin.model.create',
            [$model->getAlias(), 'test'],
            true,
        ])->andReturn('http://site.com');

        $this->assertEquals('http://site.com', $model->getCreateUrl(['test']));
    }

    /**
     * @covers ModelConfigurationManager::getStoreUrl
     */
    public function test_gets_store_url()
    {
        $model = $this->getConfiguration();

        $this->getRouterMock()->shouldReceive('route')->once()->withArgs([
            'admin.model.store',
            $model->getAlias(),
            true,
        ])->andReturn('http://site.com');

        $this->assertEquals('http://site.com', $model->getStoreUrl());
    }

    /**
     * @covers ModelConfigurationManager::getEditUrl
     */
    public function test_gets_edit_url()
    {
        $model = $this->getConfiguration();

        $this->getRouterMock()->shouldReceive('route')->once()->withArgs([
            'admin.model.edit',
            [$model->getAlias(), 1],
            true,
        ])->andReturn('http://site.com');

        $this->assertEquals('http://site.com', $model->getEditUrl(1));
    }

    /**
     * @covers ModelConfigurationManager::getUpdateUrl
     */
    public function test_gets_update_url()
    {
        $model = $this->getConfiguration();

        $this->getRouterMock()->shouldReceive('route')->once()->withArgs([
            'admin.model.update',
            [$model->getAlias(), 1],
            true,
        ])->andReturn('http://site.com');

        $this->assertEquals('http://site.com', $model->getUpdateUrl(1));
    }

    /**
     * @covers ModelConfigurationManager::getDeleteUrl
     */
    public function test_gets_delete_url()
    {
        $model = $this->getConfiguration();

        $this->getRouterMock()->shouldReceive('route')->once()->withArgs([
            'admin.model.delete',
            [$model->getAlias(), 1],
            true,
        ])->andReturn('http://site.com');

        $this->assertEquals('http://site.com', $model->getDeleteUrl(1));
    }

    /**
     * @covers ModelConfigurationManager::getDestroyUrl
     */
    public function test_gets_destroy_url()
    {
        $model = $this->getConfiguration();

        $this->getRouterMock()->shouldReceive('route')->once()->withArgs([
            'admin.model.destroy',
            [$model->getAlias(), 1],
            true,
        ])->andReturn('http://site.com');

        $this->assertEquals('http://site.com', $model->getDestroyUrl(1));
    }

    /**
     * @covers ModelConfigurationManager::getRestoreUrl
     */
    public function test_gets_restore_url()
    {
        $model = $this->getConfiguration();

        $this->getRouterMock()->shouldReceive('route')->once()->withArgs([
            'admin.model.restore',
            [$model->getAlias(), 1],
            true,
        ])->andReturn('http://site.com');

        $this->assertEquals('http://site.com', $model->getRestoreUrl(1));
    }

    /**
     * @covers ModelConfigurationManager::getMessageOnCreate
     */
    public function test_gets_message_on_create()
    {
        $model = $this->getConfiguration();

        $this->getTranslatorMock()
            ->shouldReceive('trans')
            ->once()
            ->with('sleeping_owl::lang.message.created', null, null)
            ->andReturn('string');

        $this->assertEquals('string', $model->getMessageOnCreate());
    }

    /**
     * @covers ModelConfigurationManager::getMessageOnUpdate
     */
    public function test_gets_message_on_update()
    {
        $model = $this->getConfiguration();

        $this->getTranslatorMock()
            ->shouldReceive('trans')
            ->once()
            ->with('sleeping_owl::lang.message.updated', null, null)
            ->andReturn('string');

        $this->assertEquals('string', $model->getMessageOnUpdate());
    }

    /**
     * @covers ModelConfigurationManager::getMessageOnDelete
     */
    public function test_gets_message_on_delete()
    {
        $model = $this->getConfiguration();

        $this->getTranslatorMock()
            ->shouldReceive('trans')
            ->once()
            ->with('sleeping_owl::lang.message.deleted', null, null)
            ->andReturn('string');

        $this->assertEquals('string', $model->getMessageOnDelete());
    }

    /**
     * @covers ModelConfigurationManager::getMessageOnRestore
     */
    public function test_gets_message_on_restore()
    {
        $model = $this->getConfiguration();

        $this->getTranslatorMock()
            ->shouldReceive('trans')
            ->once()
            ->with('sleeping_owl::lang.message.restored', null, null)
            ->andReturn('string');

        $this->assertEquals('string', $model->getMessageOnRestore());
    }

    /**
     * @covers ModelConfigurationManager::getMessageOnDestroy
     */
    public function test_gets_message_on_destroy()
    {
        $model = $this->getConfiguration();

        $this->getTranslatorMock()
            ->shouldReceive('trans')
            ->once()
            ->with('sleeping_owl::lang.message.destroyed', null, null)
            ->andReturn('string');

        $this->assertEquals('string', $model->getMessageOnDestroy());
    }
}

class ModelConfigurationManagerTestModel extends \Illuminate\Database\Eloquent\Model
{
}

class ModelConfigurationManagerTestController
{
}


text:
<?php

class Google_Service_SASPortalTesting_SasPortalBulkCreateDeviceRequest extends Google_Model
{
  public $csv;

  public function setCsv($csv)
  {
    $this->csv = $csv;
  }
  public function getCsv()
  {
    return $this->csv;
  }
}

redpajama_set_name: RedPajamaGithub


text:
using namespace arangodb::cache;

TEST(CacheTransactionalManagerTest,
     verify_that_transaction_term_is_maintained_correctly) {
  TransactionManager transactions;
  Transaction* tx1;
  Transaction* tx2;
  Transaction* tx3;

  ASSERT_EQ(0ULL, transactions.term());

  tx1 = transactions.begin(false);
  ASSERT_EQ(1ULL, transactions.term());
  transactions.end(tx1);
  ASSERT_EQ(2ULL, transactions.term());

  tx1 = transactions.begin(false);
  ASSERT_EQ(3ULL, transactions.term());
  tx2 = transactions.begin(false);
  ASSERT_EQ(3ULL, transactions.term());
  transactions.end(tx1);
  ASSERT_EQ(3ULL, transactions.term());
  transactions.end(tx2);
  ASSERT_EQ(4ULL, transactions.term());

  tx1 = transactions.begin(true);
  ASSERT_EQ(4ULL, transactions.term());
  tx2 = transactions.begin(false);
  ASSERT_EQ(5ULL, transactions.term());
  transactions.end(tx2);
  ASSERT_EQ(5ULL, transactions.term());
  transactions.end(tx1);
  ASSERT_EQ(6ULL, transactions.term());

  tx1 = transactions.begin(true);
  ASSERT_EQ(6ULL, transactions.term());
  tx2 = transactions.begin(false);
  ASSERT_EQ(7ULL, transactions.term());
  transactions.end(tx2);
  ASSERT_EQ(7ULL, transactions.term());
  tx3 = transactions.begin(true);
  ASSERT_EQ(7ULL, transactions.term());
  transactions.end(tx1);
  ASSERT_EQ(8ULL, transactions.term());
  transactions.end(tx3);
  ASSERT_EQ(8ULL, transactions.term());

  tx1 = transactions.begin(true);
  ASSERT_EQ(8ULL, transactions.term());
  tx2 = transactions.begin(false);
  ASSERT_EQ(9ULL, transactions.term());
  transactions.end(tx2);
  ASSERT_EQ(9ULL, transactions.term());
  tx3 = transactions.begin(true);
  ASSERT_EQ(9ULL, transactions.term());
  transactions.end(tx3);
  ASSERT_EQ(9ULL, transactions.term());
  tx2 = transactions.begin(false);
  ASSERT_EQ(9ULL, transactions.term());
  tx3 = transactions.begin(false);
  ASSERT_EQ(9ULL, transactions.term());
  transactions.end(tx3);
  ASSERT_EQ(9ULL, transactions.term());
  transactions.end(tx2);
  ASSERT_EQ(9ULL, transactions.term());
  transactions.end(tx1);
  ASSERT_EQ(10ULL, transactions.term());
}


text:
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';

export default createSvgIcon(
  <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M7 2v11h3v9l7-12h-4l3-8z" /></g></React.Fragment>
, 'FlashOnOutlined');


text:
(function () {
'use strict';

angular.module('RestaurantMenu')
.config(RoutesConfig);

RoutesConfig.$inject = ['$stateProvider', '$urlRouterProvider'];
function RoutesConfig($stateProvider, $urlRouterProvider) {

  // Redirect to home page if no other URL matches
  $urlRouterProvider.otherwise('/');

  // *** Set up UI states ***
  $stateProvider

  // Home page
  .state('home', {
    url: '/',
    templateUrl: 'src/shoppinglist/templates/home.template.html'
  })

  // Premade list page
  .state('categoryList', {
    url: '/categories',
    templateUrl: 'src/shoppinglist/templates/main-categorylist.template.html',
    controller: 'MainShoppingListController as mainList',
    resolve: {
      items: ['ShoppingListService', function (ShoppingListService) {
        return ShoppingListService.getItems();
      }]
    }
  })

  .state('itemDetail', {
    url: '/item-detail/{itemId}',
    templateUrl: 'src/shoppinglist/templates/item-detail.template.html',
    controller: 'ItemDetailController as itemDetail',
    resolve: {
      item: ['$stateParams', 'ShoppingListService',
            function ($stateParams, ShoppingListService) {
              return ShoppingListService.getItems()
                .then(function (items) {
                  return items[$stateParams.itemId];
                });
            }]
    }
  });
}

})();


text:
import {RequestManager, RequestNetworkError} from '../requestManager.js';

interface MockRequest {
  resolve: Function;
  reject: Function;
  id: number;
  url: string;
}

class MockedRequestManager extends RequestManager {
  private resolvers: Function[];
  private rejectors: Function[];
  public requestsDispatched: number;
  constructor(maxRequests = 10, maxRetries = 3) {
    super(maxRequests, maxRetries);
    this.resolvers = [];
    this.rejectors = [];
    this.requestsDispatched = 0;
  }
  protected _promiseFromUrl(url) {
    return new Promise((resolve, reject) => {
      const mockJSON = {
        ok: true,
        json() {
          return url;
        },
        url,
        status: 200,
      };
      const mockFailedRequest: any = {
        ok: false,
        url,
        status: 502,
      };
      const mockFailure = new RequestNetworkError(mockFailedRequest, url);
      this.resolvers.push(() => {
        resolve(mockJSON);
      });
      this.rejectors.push(() => {
        reject(mockFailure);
      });
      this.requestsDispatched++;
    });
  }
  public resolveFakeRequest() {
    this.resolvers.pop()();
  }
  public rejectFakeRequest() {
    this.rejectors.pop()();
  }
  public dispatchAndResolve() {
    // Wait for at least one request to be dispatched, then resolve it.
    this.waitForDispatch(1).then(() => this.resolveFakeRequest());
  }
  public waitForDispatch(num) {
    return waitForCondition(() => {
      return this.requestsDispatched >= num;
    });
  }
}

/** Create a promise that returns when *check* returns true.
 * May cause a test timeout if check never becomes true.
 */

function waitForCondition(check: () => boolean): Promise<any> {
  return new Promise((resolve, reject) => {
    const go = () => {
      if (check()) {
        resolve();
      }
      setTimeout(go, 2);
    };
    go();
  });
}

describe('backend', () => {
  describe('request manager', () => {
    it('request loads JSON properly', (done) => {
      const rm = new RequestManager();
      const promise = rm.request('data/example.json');
      promise.then(
          (response) => {
            chai.assert.deepEqual(response, {foo: 3, bar: 'zoidberg'});
            done();
          },
          (reject) => {
            throw new Error(reject);
          });
    });

    it('rejects on bad url', (done) => {
      const rm = new RequestManager(5, 0);
      const badUrl = '_bad_url_which_doesnt_exist.json';
      const promise = rm.request(badUrl);
      promise.then(
          (success) => {
            done(new Error('the promise should have rejected'));
          },
          (reject: RequestNetworkError) => {
            chai.assert.include(reject.message, '404');
            chai.assert.include(reject.message, badUrl);
            chai.assert.equal(reject.req.status, 404);
            done();
          });
    });

    it('can retry if requests fail', (done) => {
      const rm = new MockedRequestManager(3, 5);
      const r = rm.request('foo');
      rm.waitForDispatch(1)
          .then(() => {
            rm.rejectFakeRequest();
            return rm.waitForDispatch(2);
          })
          .then(() => rm.resolveFakeRequest());
      r.then((success) => done());
    });

    it('retries at most maxRetries times', (done) => {
      const MAX_RETRIES = 2;
      const rm = new MockedRequestManager(3, MAX_RETRIES);
      const r = rm.request('foo');
      rm.waitForDispatch(1)
          .then(() => {
            rm.rejectFakeRequest();
            return rm.waitForDispatch(2);
          })
          .then(() => {
            rm.rejectFakeRequest();
            return rm.waitForDispatch(3);
          })
          .then(() => {
            rm.rejectFakeRequest();
          });

      r.then(
          (success) => done(new Error('The request should have failed')),
          (failure) => done());
    });

    it('requestManager only sends maxRequests requests at a time', (done) => {
      const rm = new MockedRequestManager(3);
      const r0 = rm.request('1');
      const r1 = rm.request('2');
      const r2 = rm.request('3');
      const r3 = rm.request('4');
      chai.assert.equal(rm.activeRequests(), 3, 'three requests are active');
      chai.assert.equal(
          rm.outstandingRequests(), 4, 'four requests are pending');
      rm.waitForDispatch(3)
          .then(() => {
            chai.assert.equal(
                rm.activeRequests(), 3, 'three requests are still active (1)');
            chai.assert.equal(
                rm.requestsDispatched, 3, 'three requests were dispatched');
            rm.resolveFakeRequest();
            return rm.waitForDispatch(4);
          })
          .then(() => {
            chai.assert.equal(
                rm.activeRequests(), 3, 'three requests are still active (2)');
            chai.assert.equal(
                rm.requestsDispatched, 4, 'four requests were dispatched');
            chai.assert.equal(
                rm.outstandingRequests(), 3, 'three requests are pending');
            rm.resolveFakeRequest();
            rm.resolveFakeRequest();
            rm.resolveFakeRequest();
            return r3;
          })
          .then(() => {
            chai.assert.equal(rm.activeRequests(), 0, 'all requests finished');
            chai.assert.equal(
                rm.outstandingRequests(), 0, 'no requests pending');
            done();
          });
    });

    it('queue continues after failures', (done) => {
      const rm = new MockedRequestManager(1, 0);
      const r0 = rm.request('1');
      const r1 = rm.request('2');
      rm.waitForDispatch(1).then(() => {
        rm.rejectFakeRequest();
      });

      r0.then(
            (success) => done(new Error('r0 should have failed')),
            (failure) => 'unused_argument')
          .then(() => rm.resolveFakeRequest());

      // When the first request rejects, it should decrement nActiveRequests
      // and then launch remaining requests in queue (i.e. this one)
      r1.then((success) => done(), (failure) => done(new Error(failure)));
    });

    it('queue is LIFO', (done) => {
      /* This test is a bit tricky.
       * We want to verify that the RequestManager queue has LIFO semantics.
       * So we construct three requests off the bat: A, B, C.
       * So LIFO semantics ensure these will resolve in order A, C, B.
       * (Because the A request launches immediately when we create it, it's
       * not in queue)
       * Then after resolving A, C moves out of queue, and we create X.
       * So expected final order is A, C, X, B.
       * We verify this with an external var that counts how many requests were
       * resolved.
       */
      const rm = new MockedRequestManager(1);
      let nResolved = 0;
      function assertResolutionOrder(expectedSpotInSequence) {
        return () => {
          nResolved++;
          chai.assert.equal(expectedSpotInSequence, nResolved);
        };
      }

      function launchThirdRequest() {
        rm.request('started late but goes third')
            .then(assertResolutionOrder(3))
            .then(() => rm.dispatchAndResolve());
      }

      rm.request('first')
          .then(
              assertResolutionOrder(1))  // Assert that this one resolved first
          .then(launchThirdRequest)
          .then(() => rm.dispatchAndResolve());  // then trigger the next one

      rm.request('this one goes fourth')  // created second, will go last
          .then(assertResolutionOrder(
              4))       // assert it was the fourth to get resolved
          .then(done);  // finish the test

      rm.request('second')
          .then(assertResolutionOrder(2))
          .then(() => rm.dispatchAndResolve());

      rm.dispatchAndResolve();
    });

    it('requestManager can clear queue', (done) => {
      const rm = new MockedRequestManager(1);
      let requestsResolved = 0;
      let requestsRejected = 0;
      const success = () => requestsResolved++;
      const failure = (err) => {
        chai.assert.equal(err.name, 'RequestCancellationError');
        requestsRejected++;
      };
      const finishTheTest = () => {
        chai.assert.equal(rm.activeRequests(), 0, 'no requests still active');
        chai.assert.equal(
            rm.requestsDispatched, 1, 'only one req was ever dispatched');
        chai.assert.equal(rm.outstandingRequests(), 0, 'no pending requests');
        chai.assert.equal(requestsResolved, 1, 'one request got resolved');
        chai.assert.equal(
            requestsRejected, 4, 'four were cancelled and threw errors');
        done();
      };
      rm.request('0').then(success, failure).then(finishTheTest);
      rm.request('1').then(success, failure);
      rm.request('2').then(success, failure);
      rm.request('3').then(success, failure);
      rm.request('4').then(success, failure);
      chai.assert.equal(rm.activeRequests(), 1, 'one req is active');
      rm.waitForDispatch(1).then(() => {
        chai.assert.equal(rm.activeRequests(), 1, 'one req is active');
        chai.assert.equal(rm.requestsDispatched, 1, 'one req was dispatched');
        chai.assert.equal(rm.outstandingRequests(), 5, 'five reqs outstanding');
        rm.clearQueue();
        rm.resolveFakeRequest();
        // resolving the first request triggers finishTheTest
      });
    });
  });
});


text:
@implementation GZYRecomendUser

-(instancetype)initWithDic:(NSDictionary *)dic{
    if (self = [super init]) {
        [self setValue:dic[@"screen_name"] forKeyPath:@"screen_name"];
        [self setValue:dic[@"fans_count"] forKeyPath:@"fans_count"];
        [self setValue:dic[@"header"] forKeyPath:@"header"];
    }
    return self;
}

+(instancetype)userWithDic:(NSDictionary *)dic{

    return [[self alloc] initWithDic:dic];

}

+(NSArray *)usersWithDicArray:(NSArray<NSDictionary *> *)array{

    NSMutableArray *usersArray = [NSMutableArray array];

    for (NSDictionary *dic in array) {
        GZYRecomendUser *user = [GZYRecomendUser userWithDic:dic];
        [usersArray addObject:user];
    }

    return usersArray;
}

@end


text:
<?xml encoding="utf-8" ?>
<Grid Margin="10" >
    <Grid.Resources>
    </Grid.Resources>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="80*" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="20*" />
    </Grid.ColumnDefinitions>
    <DockPanel Margin="0" Background="LightBlue" LastChildFill="{Binding Path=IsChecked,ElementName=lcf}" >
        <Button Content="Left" MinWidth="100" />
        <Button Content="Right" DockPanel.Dock="Right" />
        <Button Content="Top" DockPanel.Dock="Top" MinHeight="50" />
        <Button Content="Bottom" DockPanel.Dock="Bottom" MinHeight="60" />
        <TextBox Text="LastFill" MaxLines="0" MinWidth="120" MinHeight="80" />
    </DockPanel>
    <GridSplitter Width="4" Grid.Column="1" Cursor="Splith" >
        <GridSplitter.Template>
            <ControlTemplate TargetType="GridSplitter">
                <Rectangle Fill="SkyBlue" />
            </ControlTemplate>
        </GridSplitter.Template>
    </GridSplitter>
    <StackPanel Grid.Row="0" Grid.Column="2" MinWidth="20" Background="WhiteSmoke" >
        <CheckBox Name="lcf" Content="LastChildFill" Margin="5" IsChecked="True" />
    </StackPanel>
</Grid>


text:
package lia.indexing;

import junit.framework.TestCase;

import lia.common.TestUtil;

import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.analysis.WhitespaceAnalyzer;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.index.Term;

import java.io.IOException;

// From chapter 2
public class IndexingTest extends TestCase {
  protected String[] ids = {"1", "2"};
  protected String[] unindexed = {"Netherlands", "Italy"};
  protected String[] unstored = {"Amsterdam has lots of bridges",
                                 "Venice has lots of canals"};
  protected String[] text = {"Amsterdam", "Venice"};

  private Directory directory;

  protected void setUp() throws Exception {     //1
    directory = new RAMDirectory();

    IndexWriter writer = getWriter();           //2

    for (int i = 0; i < ids.length; i++) {      //3
      Document doc = new Document();
      doc.add(new Field("id", ids[i],
                        Field.Store.YES,
                        Field.Index.NOT_ANALYZED));
      doc.add(new Field("country", unindexed[i],
                        Field.Store.YES,
                        Field.Index.NO));
      doc.add(new Field("contents", unstored[i],
                        Field.Store.NO,
                        Field.Index.ANALYZED));
      doc.add(new Field("city", text[i],
                        Field.Store.YES,
                        Field.Index.ANALYZED));
      writer.addDocument(doc);
    }
    writer.close();
  }

  private IndexWriter getWriter() throws IOException {            // 2
    return new IndexWriter(directory, new WhitespaceAnalyzer(),   // 2
                           IndexWriter.MaxFieldLength.UNLIMITED); // 2
  }

  protected int getHitCount(String fieldName, String searchString)
    throws IOException {
    IndexSearcher searcher = new IndexSearcher(directory); //4
    Term t = new Term(fieldName, searchString);
    Query query = new TermQuery(t);                        //5
    int hitCount = TestUtil.hitCount(searcher, query);     //6
    searcher.close();
    return hitCount;
  }

  public void testIndexWriter() throws IOException {
    IndexWriter writer = getWriter();
    assertEquals(ids.length, writer.numDocs());            //7
    writer.close();
  }

  public void testIndexReader() throws IOException {
    IndexReader reader = IndexReader.open(directory);
    assertEquals(ids.length, reader.maxDoc());             //8
    assertEquals(ids.length, reader.numDocs());            //8
    reader.close();
  }

  /*
    #1 Run before every test
    #2 Create IndexWriter
    #3 Add documents
    #4 Create new searcher
    #5 Build simple single-term query
    #6 Get number of hits
    #7 Verify writer document count
    #8 Verify reader document count
  */

  public void testDeleteBeforeOptimize() throws IOException {
    IndexWriter writer = getWriter();
    assertEquals(2, writer.numDocs()); //A
    writer.deleteDocuments(new Term("id", "1"));  //B
    writer.commit();
    assertTrue(writer.hasDeletions());    //1
    assertEquals(2, writer.maxDoc());    //2
    assertEquals(1, writer.numDocs());   //2
    writer.close();
  }

  public void testDeleteAfterOptimize() throws IOException {
    IndexWriter writer = getWriter();
    assertEquals(2, writer.numDocs());
    writer.deleteDocuments(new Term("id", "1"));
    writer.optimize();                //3
    writer.commit();
    assertFalse(writer.hasDeletions());
    assertEquals(1, writer.maxDoc());  //C
    assertEquals(1, writer.numDocs()); //C
    writer.close();
  }

  /*
    #A 2 docs in the index
    #B Delete first document
    #C 1 indexed document, 0 deleted documents
    #1 Index contains deletions
    #2 1 indexed document, 1 deleted document
    #3 Optimize compacts deletes
  */

  public void testUpdate() throws IOException {

    assertEquals(1, getHitCount("city", "Amsterdam"));

    IndexWriter writer = getWriter();

    Document doc = new Document();                   //A
    doc.add(new Field("id", "1",
                      Field.Store.YES,
                      Field.Index.NOT_ANALYZED));    //A
    doc.add(new Field("country", "Netherlands",
                      Field.Store.YES,
                      Field.Index.NO));              //A
    doc.add(new Field("contents",
                      "Den Haag has a lot of museums",
                      Field.Store.NO,
                      Field.Index.ANALYZED));       //A
    doc.add(new Field("city", "Den Haag",
                      Field.Store.YES,
                      Field.Index.ANALYZED));       //A

    writer.updateDocument(new Term("id", "1"),       //B
                          doc);                      //B
    writer.close();

    assertEquals(0, getHitCount("city", "Amsterdam"));//C
    assertEquals(1, getHitCount("city", "Haag"));     //D
  }

  /*
    #A Create new document with "Haag" in city field
    #B Replace original document with new version
    #C Verify old document is gone
    #D Verify new document is indexed
  */

  public void testMaxFieldLength() throws IOException {

    assertEquals(1, getHitCount("contents", "bridges"));  //1

    IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), //2
                                         new IndexWriter.MaxFieldLength(1)); //2
    Document doc = new Document();                        // 3
    doc.add(new Field("contents",
                      "these bridges can't be found",    // 3
                      Field.Store.NO, Field.Index.ANALYZED));   // 3
    writer.addDocument(doc);   // 3
    writer.close();   // 3

    assertEquals(1, getHitCount("contents", "bridges"));   //4
  }

  /*
    #1 One initial document has bridges
    #2 Create writer with maxFieldLength 1
    #3 Index document with bridges
    #4 Document can't be found
  */

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syst. mycol. (Lundae) 1: 371 (1821)

#### Original name
Polyporus sanguineus f. sanguineus

### Remarks
null


text:
package com.comcast.money.core.context

import io.opentelemetry.context.{ Context, ContextStorage, Scope }

trait ContextStorageFilter {
  def attach(context: Context, storage: ContextStorage): Scope
}


text:
"""

Test driver for LDAP gateway plugin

"""

import sys
import uuid
import time
import datetime
from ammo import AmmoMessages_pb2
from ammo.AndroidConnector import AndroidConnector

from twisted.internet import reactor

#==============================================
# main()
#==============================================
def main():
    sys.stdout.write("Android Gateway Pull Test\n")
    if len(sys.argv) != 3:
        sys.stderr.write("Usage: %s <host> <port> \n" % sys.argv[0])
        sys.exit(-1)

    deviceName = "device:test/" + uuid.uuid1().hex
    userName = "user:test/" + uuid.uuid1().hex
    connector = AndroidConnector(sys.argv[1], int(sys.argv[2]), deviceName, userName, "")

    try:
        connector.start()
        connector.waitForAuthentication()

        # Pull request options... For LDAP pull, only the first two are important (as of now)
        mimetype = "ammo/edu.vu.isis.ammo.launcher.contact_pull"
        query = "cn=John"
        maxResults = 0
        startFromCount = 0
        liveQuery = False

        # Send the pull request
        connector.pullRequest(mimetype, query, "", maxResults, startFromCount, liveQuery)

        while True:
            while(connector.isDataAvailable()):
                result = connector.dequeueMessage()
                if(result != None):
                    (msg, receivedTime) = result
                    print "Message received at:", receivedTime
                    print msg
            time.sleep(0.5)
    except KeyboardInterrupt:
        sys.stdout.write("Got ^C...  Closing\n")
        reactor.callFromThread(reactor.stop)
    except:
        sys.stderr.write("Unexpected error...  dying.\n")
        reactor.callFromThread(reactor.stop)
        raise

#---------------------------

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


text:
<!doctype html>

  <title>player.js iframe</title>
  <link href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,600" rel="stylesheet" type="text/css">
  <link href="/styles.css" rel="stylesheet" type="text/css">

player.js iframe

YouTube

        <button class="controls__play">Play</button>
        <button class="controls__pause">Pause</button>
        <button class="controls__play_ready">Play (Ready)</button>
        <button class="controls__pause_ready">Pause (Ready)</button>
        <button class="controls__get-paused">Get paused</button>
        <button class="controls__mute">Mute</button>
        <button class="controls__unmute">Unmute</button>
        <button class="controls__get-muted">Get muted</button>

          Set volume
          <input type="range" min="0" max="100" value="0" id="set-volume" class="controls__set-volume">

        <button class="controls__get-volume">Get volume</button>
        <button class="controls__get-duration">Get duration</button>

          Set current time
          <input type="range" min="0" max="0" value="0" id="set-current-time" class="controls__set-current-time">

        <button class="controls__get-current-time">Get current time</button>

          Set loop
          <input type="radio" name="set-loop-1" id="controls__set-loop-false" checked>
          false
          <input type="radio" name="set-loop-1" id="controls__set-loop-true">
          true

        <button class="controls__get-loop">Get loop</button>

YouTube Playlist w/ video ID

        <button class="controls__play">Play</button>
        <button class="controls__pause">Pause</button>
        <button class="controls__play_ready">Play (Ready)</button>
        <button class="controls__pause_ready">Pause (Ready)</button>
        <button class="controls__get-paused">Get paused</button>
        <button class="controls__mute">Mute</button>
        <button class="controls__unmute">Unmute</button>
        <button class="controls__get-muted">Get muted</button>

          Set volume
          <input type="range" min="0" max="100" value="0" id="set-volume" class="controls__set-volume">

        <button class="controls__get-volume">Get volume</button>
        <button class="controls__get-duration">Get duration</button>

          Set current time
          <input type="range" min="0" max="0" value="0" id="set-current-time" class="controls__set-current-time">

        <button class="controls__get-current-time">Get current time</button>

          Set loop
          <input type="radio" name="set-loop-1" id="controls__set-loop-false" checked>
          false
          <input type="radio" name="set-loop-1" id="controls__set-loop-true">
          true

        <button class="controls__get-loop">Get loop</button>

YouTube Playlist (standalone)

        <button class="controls__play">Play</button>
        <button class="controls__pause">Pause</button>
        <button class="controls__play_ready">Play (Ready)</button>
        <button class="controls__pause_ready">Pause (Ready)</button>
        <button class="controls__get-paused">Get paused</button>
        <button class="controls__mute">Mute</button>
        <button class="controls__unmute">Unmute</button>
        <button class="controls__get-muted">Get muted</button>

          Set volume
          <input type="range" min="0" max="100" value="0" id="set-volume" class="controls__set-volume">

        <button class="controls__get-volume">Get volume</button>
        <button class="controls__get-duration">Get duration</button>

          Set current time
          <input type="range" min="0" max="0" value="0" id="set-current-time" class="controls__set-current-time">

        <button class="controls__get-current-time">Get current time</button>

          Set loop
          <input type="radio" name="set-loop-1" id="controls__set-loop-false" checked>
          false
          <input type="radio" name="set-loop-1" id="controls__set-loop-true">
          true

        <button class="controls__get-loop">Get loop</button>

Vimeo

        <button class="controls__play">Play</button>
        <button class="controls__pause">Pause</button>
        <button class="controls__play_ready">Play (Ready)</button>
        <button class="controls__pause_ready">Pause (Ready)</button>
        <button class="controls__get-paused">Get paused</button>
        <button class="controls__mute">Mute</button>
        <button class="controls__unmute">Unmute</button>
        <button class="controls__get-muted">Get muted</button>

          Set volume
          <input type="range" min="0" max="100" value="0" id="set-volume" class="controls__set-volume">

        <button class="controls__get-volume">Get volume</button>
        <button class="controls__get-duration">Get duration</button>

          Set current time
          <input type="range" min="0" max="0" value="0" id="set-current-time" class="controls__set-current-time">

        <button class="controls__get-current-time">Get current time</button>

          Set loop
          <input type="radio" name="set-loop-2" id="controls__set-loop-false" checked>
          false
          <input type="radio" name="set-loop-2" id="controls__set-loop-true">
          true

        <button class="controls__get-loop">Get loop</button>

Vimeo via unlisted URL

        <button class="controls__play">Play</button>
        <button class="controls__pause">Pause</button>
        <button class="controls__play_ready">Play (Ready)</button>
        <button class="controls__pause_ready">Pause (Ready)</button>
        <button class="controls__get-paused">Get paused</button>
        <button class="controls__mute">Mute</button>
        <button class="controls__unmute">Unmute</button>
        <button class="controls__get-muted">Get muted</button>

          Set volume
          <input type="range" min="0" max="100" value="0" id="set-volume" class="controls__set-volume">

        <button class="controls__get-volume">Get volume</button>
        <button class="controls__get-duration">Get duration</button>

          Set current time
          <input type="range" min="0" max="0" value="0" id="set-current-time" class="controls__set-current-time">

        <button class="controls__get-current-time">Get current time</button>

          Set loop
          <input type="radio" name="set-loop-2" id="controls__set-loop-false" checked>
          false
          <input type="radio" name="set-loop-2" id="controls__set-loop-true">
          true

        <button class="controls__get-loop">Get loop</button>


text:
const JSONRPC = require("../index");
const AllTests = require("./Tests/AllTests");

const sleep = require("sleep-promise");

const chalk = require("chalk");

let Threads;
try
{
	Threads = require("worker_threads");
}
catch(error)
{
	// console.error(error);
}

process.on(
	"unhandledRejection",
	async(reason, promise) =>
	{
		console.log("[" + process.pid + (Threads && !Threads.isMainThread ? ` worker thread ID ${Threads.threadId}` : "") + "] Unhandled Rejection at: Promise", promise, "reason", reason);
		process.exitCode = 1;

		if(Threads && !Threads.isMainThread)
		{
			// Give time for thread to flush to stdout.
			await sleep(2000);
		}

		process.exit(process.exitCode);
	}
);

process.on(
	"uncaughtException",
	async(error) => {
		console.log("[" + process.pid + (Threads && !Threads.isMainThread ? ` worker thread ID ${Threads.threadId}` : "") + "] Unhandled exception.");
		console.error(error);
		process.exitCode = 1;

		if(Threads && !Threads.isMainThread)
		{
			// Give time for thread to flush to stdout.
			await sleep(2000);
		}

		process.exit(process.exitCode);
	}
);

(
	async () =>
	{
		const bBenchmarkMode = true;

		let nPasses = 5;
		let allTests;
		while(nPasses--)
		{
			console.log("heapTotal before first benchmark: " + Math.round(process.memoryUsage().heapTotal / 1024 / 1024, 2) + " MB");

			//console.log("===== http (500 calls in parallel)");
			//allTests = new AllTests(bBenchmarkMode, /*bWebSocketMode*/ false, undefined, undefined, undefined, /*bDisableVeryLargePacket*/ true);
			//await allTests.runTests();
			//global.gc();
			//console.log("heapTotal after gc(): " + Math.round(process.memoryUsage().heapTotal / 1024 / 1024, 2) + " MB");
			//console.log("");

			// uws is consistently slower than ws when benchmarking with a few open connections (2) with the same number of calls.
			// Most of the randomness was disabled when tested.
			// Tested on nodejs 7.8.0, Windows 10, 64 bit.
			// https://github.com/uWebSockets/uWebSockets/issues/585

			console.log(chalk.cyan("===== ws (RPC API calls in parallel, over as many reused connections as possible)"));
			allTests = new AllTests(bBenchmarkMode, /*bWebSocketMode*/ true, require("ws"), require("ws").Server, undefined, /*bDisableVeryLargePacket*/ true);
			await allTests.runTests();
			global.gc();
			console.log("heapTotal after gc(): " + Math.round(process.memoryUsage().heapTotal / 1024 / 1024, 2) + " MB");
			console.log("");

			let bUwsLoaded = false;
			try
			{
				// Requires a compilation toolset to be installed if precompiled binaries are not available.
				require("uws");
				bUwsLoaded = true;
			}
			catch(error)
			{
				console.error(error);
			}

			if(bUwsLoaded)
			{
				console.log(chalk.cyan("===== uws (RPC API calls in parallel, over as many reused connections as possible)"));
				allTests = new AllTests(bBenchmarkMode, /*bWebSocketMode*/ true, require("uws"), require("uws").Server, JSONRPC.WebSocketAdapters.uws.WebSocketWrapper, /*bDisableVeryLargePacket*/ true);
				allTests.websocketServerPort = allTests.httpServerPort + 1;
				await allTests.runTests();
				global.gc();
				console.log("heapTotal after gc(): " + Math.round(process.memoryUsage().heapTotal / 1024 / 1024, 2) + " MB");
				console.log("");

				console.log(chalk.cyan("===== uws.Server, ws.Client (RPC API calls in parallel, over as many reused connections as possible)"));
				allTests = new AllTests(bBenchmarkMode, /*bWebSocketMode*/ true, require("ws"), require("uws").Server, JSONRPC.WebSocketAdapters.uws.WebSocketWrapper, /*bDisableVeryLargePacket*/ true);
				allTests.websocketServerPort = allTests.httpServerPort + 1;
				await allTests.runTests();
				global.gc();
				console.log("heapTotal after gc(): " + Math.round(process.memoryUsage().heapTotal / 1024 / 1024, 2) + " MB");
				console.log("");

				console.log(chalk.cyan("===== ws.Server, uws.Client (RPC API API calls in parallel, over as many reused connections as possible)"));
				allTests = new AllTests(bBenchmarkMode, /*bWebSocketMode*/ true, require("uws"), require("ws").Server, JSONRPC.WebSocketAdapters.uws.WebSocketWrapper, /*bDisableVeryLargePacket*/ true);
				allTests.websocketServerPort = allTests.httpServerPort + 1;
				await allTests.runTests();
				global.gc();
				console.log("heapTotal after gc(): " + Math.round(process.memoryUsage().heapTotal / 1024 / 1024, 2) + " MB");
				console.log("");
			}
		}

		console.log("[" + process.pid + "] Finished benchmarking.");

		process.exit(0);
	}
)();


text:
package by.bsuir.mpp.computershop.utils.supplier.entity.impl;

import by.bsuir.mpp.computershop.entity.Customer;
import by.bsuir.mpp.computershop.utils.TestHelper;
import by.bsuir.mpp.computershop.utils.supplier.entity.EntityLongSupplier;

public class CustomerEntitySupplier implements EntityLongSupplier<Customer> {

    @Override
    public Customer getValidEntityWithoutId() {
        Customer result = new Customer();
        result.setId(null);
        result.setName(TestHelper.nextString());
        result.setDescription(TestHelper.nextString());
        return result;
    }

    @Override
    public Customer getInvalidEntity() {
        return null;
    }

}


text:
<?php declare(strict_types=1);

namespace PHPUnit\Metadata\Parser;

use const JSON_THROW_ON_ERROR;
use function json_decode;
use function str_starts_with;
use PHPUnit\Framework\Attributes\After as AfterAttribute;
use PHPUnit\Framework\Attributes\AfterClass as AfterClassAttribute;
use PHPUnit\Framework\Attributes\BackupGlobals as BackupGlobalsAttribute;
use PHPUnit\Framework\Attributes\BackupStaticProperties as BackupStaticPropertiesAttribute;
use PHPUnit\Framework\Attributes\Before as BeforeAttribute;
use PHPUnit\Framework\Attributes\BeforeClass as BeforeClassAttribute;
use PHPUnit\Framework\Attributes\CodeCoverageIgnore as CodeCoverageIgnoreAttribute;
use PHPUnit\Framework\Attributes\CoversClass as CoversClassAttribute;
use PHPUnit\Framework\Attributes\CoversFunction as CoversFunctionAttribute;
use PHPUnit\Framework\Attributes\CoversNothing as CoversNothingAttribute;
use PHPUnit\Framework\Attributes\DataProvider as DataProviderAttribute;
use PHPUnit\Framework\Attributes\DataProviderExternal as DataProviderExternalAttribute;
use PHPUnit\Framework\Attributes\Depends as DependsAttribute;
use PHPUnit\Framework\Attributes\DependsExternal as DependsExternalAttribute;
use PHPUnit\Framework\Attributes\DependsExternalUsingDeepClone as DependsExternalUsingDeepCloneAttribute;
use PHPUnit\Framework\Attributes\DependsExternalUsingShallowClone as DependsExternalUsingShallowCloneAttribute;
use PHPUnit\Framework\Attributes\DependsOnClass as DependsOnClassAttribute;
use PHPUnit\Framework\Attributes\DependsOnClassUsingDeepClone as DependsOnClassUsingDeepCloneAttribute;
use PHPUnit\Framework\Attributes\DependsOnClassUsingShallowClone as DependsOnClassUsingShallowCloneAttribute;
use PHPUnit\Framework\Attributes\DependsUsingDeepClone as DependsUsingDeepCloneAttribute;
use PHPUnit\Framework\Attributes\DependsUsingShallowClone as DependsUsingShallowCloneAttribute;
use PHPUnit\Framework\Attributes\DoesNotPerformAssertions as DoesNotPerformAssertionsAttribute;
use PHPUnit\Framework\Attributes\ExcludeGlobalVariableFromBackup as ExcludeGlobalVariableFromBackupAttribute;
use PHPUnit\Framework\Attributes\ExcludeStaticPropertyFromBackup as ExcludeStaticPropertyFromBackupAttribute;
use PHPUnit\Framework\Attributes\Group as GroupAttribute;
use PHPUnit\Framework\Attributes\Large as LargeAttribute;
use PHPUnit\Framework\Attributes\Medium as MediumAttribute;
use PHPUnit\Framework\Attributes\PostCondition as PostConditionAttribute;
use PHPUnit\Framework\Attributes\PreCondition as PreConditionAttribute;
use PHPUnit\Framework\Attributes\PreserveGlobalState as PreserveGlobalStateAttribute;
use PHPUnit\Framework\Attributes\RequiresFunction as RequiresFunctionAttribute;
use PHPUnit\Framework\Attributes\RequiresMethod as RequiresMethodAttribute;
use PHPUnit\Framework\Attributes\RequiresOperatingSystem as RequiresOperatingSystemAttribute;
use PHPUnit\Framework\Attributes\RequiresOperatingSystemFamily as RequiresOperatingSystemFamilyAttribute;
use PHPUnit\Framework\Attributes\RequiresPhp as RequiresPhpAttribute;
use PHPUnit\Framework\Attributes\RequiresPhpExtension as RequiresPhpExtensionAttribute;
use PHPUnit\Framework\Attributes\RequiresPhpunit as RequiresPhpunitAttribute;
use PHPUnit\Framework\Attributes\RequiresSetting as RequiresSettingAttribute;
use PHPUnit\Framework\Attributes\RunClassInSeparateProcess as RunClassInSeparateProcessAttribute;
use PHPUnit\Framework\Attributes\RunInSeparateProcess as RunInSeparateProcessAttribute;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses as RunTestsInSeparateProcessesAttribute;
use PHPUnit\Framework\Attributes\Small as SmallAttribute;
use PHPUnit\Framework\Attributes\Test as TestAttribute;
use PHPUnit\Framework\Attributes\TestDox as TestDoxAttribute;
use PHPUnit\Framework\Attributes\TestWith as TestWithAttribute;
use PHPUnit\Framework\Attributes\TestWithJson as TestWithJsonAttribute;
use PHPUnit\Framework\Attributes\Ticket as TicketAttribute;
use PHPUnit\Framework\Attributes\UsesClass as UsesClassAttribute;
use PHPUnit\Framework\Attributes\UsesFunction as UsesFunctionAttribute;
use PHPUnit\Metadata\After;
use PHPUnit\Metadata\AfterClass;
use PHPUnit\Metadata\BackupGlobals;
use PHPUnit\Metadata\BackupStaticProperties;
use PHPUnit\Metadata\Before;
use PHPUnit\Metadata\BeforeClass;
use PHPUnit\Metadata\CodeCoverageIgnore;
use PHPUnit\Metadata\CoversClass;
use PHPUnit\Metadata\CoversFunction;
use PHPUnit\Metadata\CoversNothing;
use PHPUnit\Metadata\DataProvider;
use PHPUnit\Metadata\DependsOnClass;
use PHPUnit\Metadata\DependsOnMethod;
use PHPUnit\Metadata\DoesNotPerformAssertions;
use PHPUnit\Metadata\ExcludeGlobalVariableFromBackup;
use PHPUnit\Metadata\ExcludeStaticPropertyFromBackup;
use PHPUnit\Metadata\Group;
use PHPUnit\Metadata\MetadataCollection;
use PHPUnit\Metadata\PostCondition;
use PHPUnit\Metadata\PreCondition;
use PHPUnit\Metadata\PreserveGlobalState;
use PHPUnit\Metadata\RequiresFunction;
use PHPUnit\Metadata\RequiresMethod;
use PHPUnit\Metadata\RequiresOperatingSystem;
use PHPUnit\Metadata\RequiresOperatingSystemFamily;
use PHPUnit\Metadata\RequiresPhp;
use PHPUnit\Metadata\RequiresPhpExtension;
use PHPUnit\Metadata\RequiresPhpunit;
use PHPUnit\Metadata\RequiresSetting;
use PHPUnit\Metadata\RunClassInSeparateProcess;
use PHPUnit\Metadata\RunInSeparateProcess;
use PHPUnit\Metadata\RunTestsInSeparateProcesses;
use PHPUnit\Metadata\Test;
use PHPUnit\Metadata\TestDox;
use PHPUnit\Metadata\TestWith;
use PHPUnit\Metadata\UsesClass;
use PHPUnit\Metadata\UsesFunction;
use PHPUnit\Metadata\Version\ConstraintRequirement;
use ReflectionClass;
use ReflectionMethod;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class AttributeParser implements Parser
{
    /**
     * @psalm-param class-string $className
     */
    public function forClass(string $className): MetadataCollection
    {
        $result = [];

        foreach ((new ReflectionClass($className))->getAttributes() as $attribute) {
            if (!str_starts_with($attribute->getName(), 'PHPUnit\\Framework\\Attributes\\')) {
                continue;
            }

            $attributeInstance = $attribute->newInstance();

            switch ($attribute->getName()) {
                case BackupGlobalsAttribute::class:
                    $result[] = new BackupGlobals($attributeInstance->enabled());

                    break;

                case BackupStaticPropertiesAttribute::class:
                    $result[] = new BackupStaticProperties($attributeInstance->enabled());

                    break;

                case CodeCoverageIgnoreAttribute::class:
                    $result[] = new CodeCoverageIgnore;

                    break;

                case CoversClassAttribute::class:
                    $result[] = new CoversClass($attributeInstance->className());

                    break;

                case CoversFunctionAttribute::class:
                    $result[] = new CoversFunction($attributeInstance->functionName());

                    break;

                case CoversNothingAttribute::class:
                    $result[] = new CoversNothing;

                    break;

                case DoesNotPerformAssertionsAttribute::class:
                    $result[] = new DoesNotPerformAssertions;

                    break;

                case ExcludeGlobalVariableFromBackupAttribute::class:
                    $result[] = new ExcludeGlobalVariableFromBackup($attributeInstance->globalVariableName());

                    break;

                case ExcludeStaticPropertyFromBackupAttribute::class:
                    $result[] = new ExcludeStaticPropertyFromBackup(
                        $attributeInstance->className(),
                        $attributeInstance->propertyName()
                    );

                    break;

                case GroupAttribute::class:
                    $result[] = new Group($attributeInstance->name());

                    break;

                case LargeAttribute::class:
                    $result[] = new Group('large');

                    break;

                case MediumAttribute::class:
                    $result[] = new Group('medium');

                    break;

                case PreserveGlobalStateAttribute::class:
                    $result[] = new PreserveGlobalState($attributeInstance->enabled());

                    break;

                case RequiresMethodAttribute::class:
                    $result[] = new RequiresMethod(
                        $attributeInstance->className(),
                        $attributeInstance->methodName()
                    );

                    break;

                case RequiresFunctionAttribute::class:
                    $result[] = new RequiresFunction($attributeInstance->functionName());

                    break;

                case RequiresOperatingSystemAttribute::class:
                    $result[] = new RequiresOperatingSystem($attributeInstance->regularExpression());

                    break;

                case RequiresOperatingSystemFamilyAttribute::class:
                    $result[] = new RequiresOperatingSystemFamily($attributeInstance->operatingSystemFamily());

                    break;

                case RequiresPhpAttribute::class:
                    $result[] = new RequiresPhp(
                        ConstraintRequirement::from(
                            $attributeInstance->versionRequirement()
                        )
                    );

                    break;

                case RequiresPhpExtensionAttribute::class:
                    $versionConstraint = null;

                    if ($attributeInstance->hasVersionRequirement()) {
                        $versionConstraint = ConstraintRequirement::from(
                            $attributeInstance->versionRequirement()
                        );
                    }

                    $result[] = new RequiresPhpExtension(
                        $attributeInstance->extension(),
                        $versionConstraint
                    );

                    break;

                case RequiresPhpunitAttribute::class:
                    $result[] = new RequiresPhpunit(
                        ConstraintRequirement::from(
                            $attributeInstance->versionRequirement()
                        )
                    );

                    break;

                case RequiresSettingAttribute::class:
                    $result[] = new RequiresSetting(
                        $attributeInstance->setting(),
                        $attributeInstance->value()
                    );

                    break;

                case RunClassInSeparateProcessAttribute::class:
                    $result[] = new RunClassInSeparateProcess;

                    break;

                case RunTestsInSeparateProcessesAttribute::class:
                    $result[] = new RunTestsInSeparateProcesses;

                    break;

                case SmallAttribute::class:
                    $result[] = new Group('small');

                    break;

                case TestDoxAttribute::class:
                    $result[] = new TestDox($attributeInstance->text());

                    break;

                case TicketAttribute::class:
                    $result[] = new Group($attributeInstance->text());

                    break;

                case UsesClassAttribute::class:
                    $result[] = new UsesClass($attributeInstance->className());

                    break;

                case UsesFunctionAttribute::class:
                    $result[] = new UsesFunction($attributeInstance->functionName());

                    break;
            }
        }

        return MetadataCollection::fromArray($result);
    }

    /**
     * @psalm-param class-string $className
     */
    public function forMethod(string $className, string $methodName): MetadataCollection
    {
        $result = [];

        foreach ((new ReflectionMethod($className, $methodName))->getAttributes() as $attribute) {
            if (!str_starts_with($attribute->getName(), 'PHPUnit\\Framework\\Attributes\\')) {
                continue;
            }

            $attributeInstance = $attribute->newInstance();

            switch ($attribute->getName()) {
                case AfterAttribute::class:
                    $result[] = new After;

                    break;

                case AfterClassAttribute::class:
                    $result[] = new AfterClass;

                    break;

                case BackupGlobalsAttribute::class:
                    $result[] = new BackupGlobals($attributeInstance->enabled());

                    break;

                case BackupStaticPropertiesAttribute::class:
                    $result[] = new BackupStaticProperties($attributeInstance->enabled());

                    break;

                case BeforeAttribute::class:
                    $result[] = new Before;

                    break;

                case BeforeClassAttribute::class:
                    $result[] = new BeforeClass;

                    break;

                case CodeCoverageIgnoreAttribute::class:
                    $result[] = new CodeCoverageIgnore;

                    break;

                case CoversNothingAttribute::class:
                    $result[] = new CoversNothing;

                    break;

                case DataProviderAttribute::class:
                    $result[] = new DataProvider($className, $attributeInstance->methodName());

                    break;

                case DataProviderExternalAttribute::class:
                    $result[] = new DataProvider($attributeInstance->className(), $attributeInstance->methodName());

                    break;

                case DependsAttribute::class:
                    $result[] = new DependsOnMethod($className, $attributeInstance->methodName(), false, false);

                    break;

                case DependsUsingDeepCloneAttribute::class:
                    $result[] = new DependsOnMethod($className, $attributeInstance->methodName(), true, false);

                    break;

                case DependsUsingShallowCloneAttribute::class:
                    $result[] = new DependsOnMethod($className, $attributeInstance->methodName(), false, true);

                    break;

                case DependsExternalAttribute::class:
                    $result[] = new DependsOnMethod($attributeInstance->className(), $attributeInstance->methodName(), false, false);

                    break;

                case DependsExternalUsingDeepCloneAttribute::class:
                    $result[] = new DependsOnMethod($attributeInstance->className(), $attributeInstance->methodName(), true, false);

                    break;

                case DependsExternalUsingShallowCloneAttribute::class:
                    $result[] = new DependsOnMethod($attributeInstance->className(), $attributeInstance->methodName(), false, true);

                    break;

                case DependsOnClassAttribute::class:
                    $result[] = new DependsOnClass($attributeInstance->className(), false, false);

                    break;

                case DependsOnClassUsingDeepCloneAttribute::class:
                    $result[] = new DependsOnClass($attributeInstance->className(), true, false);

                    break;

                case DependsOnClassUsingShallowCloneAttribute::class:
                    $result[] = new DependsOnClass($attributeInstance->className(), false, true);

                    break;

                case DoesNotPerformAssertionsAttribute::class:
                    $result[] = new DoesNotPerformAssertions;

                    break;

                case ExcludeGlobalVariableFromBackupAttribute::class:
                    $result[] = new ExcludeGlobalVariableFromBackup($attributeInstance->globalVariableName());

                    break;

                case ExcludeStaticPropertyFromBackupAttribute::class:
                    $result[] = new ExcludeStaticPropertyFromBackup(
                        $attributeInstance->className(),
                        $attributeInstance->propertyName()
                    );

                    break;

                case GroupAttribute::class:
                    $result[] = new Group($attributeInstance->name());

                    break;

                case PostConditionAttribute::class:
                    $result[] = new PostCondition;

                    break;

                case PreConditionAttribute::class:
                    $result[] = new PreCondition;

                    break;

                case PreserveGlobalStateAttribute::class:
                    $result[] = new PreserveGlobalState($attributeInstance->enabled());

                    break;

                case RequiresMethodAttribute::class:
                    $result[] = new RequiresMethod(
                        $attributeInstance->className(),
                        $attributeInstance->methodName()
                    );

                    break;

                case RequiresFunctionAttribute::class:
                    $result[] = new RequiresFunction($attributeInstance->functionName());

                    break;

                case RequiresOperatingSystemAttribute::class:
                    $result[] = new RequiresOperatingSystem($attributeInstance->regularExpression());

                    break;

                case RequiresOperatingSystemFamilyAttribute::class:
                    $result[] = new RequiresOperatingSystemFamily($attributeInstance->operatingSystemFamily());

                    break;

                case RequiresPhpAttribute::class:
                    $result[] = new RequiresPhp(
                        ConstraintRequirement::from(
                            $attributeInstance->versionRequirement()
                        )
                    );

                    break;

                case RequiresPhpExtensionAttribute::class:
                    $versionConstraint = null;

                    if ($attributeInstance->hasVersionRequirement()) {
                        $versionConstraint = ConstraintRequirement::from(
                            $attributeInstance->versionRequirement()
                        );
                    }

                    $result[] = new RequiresPhpExtension(
                        $attributeInstance->extension(),
                        $versionConstraint
                    );

                    break;

                case RequiresPhpunitAttribute::class:
                    $result[] = new RequiresPhpunit(
                        ConstraintRequirement::from(
                            $attributeInstance->versionRequirement()
                        )
                    );

                    break;

                case RequiresSettingAttribute::class:
                    $result[] = new RequiresSetting(
                        $attributeInstance->setting(),
                        $attributeInstance->value()
                    );

                    break;

                case RunInSeparateProcessAttribute::class:
                    $result[] = new RunInSeparateProcess;

                    break;

                case TestAttribute::class:
                    $result[] = new Test;

                    break;

                case TestDoxAttribute::class:
                    $result[] = new TestDox($attributeInstance->text());

                    break;

                case TestWithAttribute::class:
                    $result[] = new TestWith($attributeInstance->data());

                    break;

                case TestWithJsonAttribute::class:
                    $result[] = new TestWith(json_decode($attributeInstance->json(), true, 512, JSON_THROW_ON_ERROR));

                    break;

                case TicketAttribute::class:
                    $result[] = new Group($attributeInstance->text());

                    break;
            }
        }

        return MetadataCollection::fromArray($result);
    }

    /**
     * @psalm-param class-string $className
     */
    public function forClassAndMethod(string $className, string $methodName): MetadataCollection
    {
        return $this->forClass($className)->mergeWith(
            $this->forMethod($className, $methodName)
        );
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace EraserBotFrontend
{
    /// <summary>
    /// Represents an installed model and all its available skins. The Model class is only
    /// used in conjunction with the mesh renderer.
    /// </summary>
    class Model
    {
        string modelName;
        List<string> skins = new List<string>();

        /// <summary>
        ///
        /// </summary>
        /// <param name="modelName"></param>
        /// <param name="modelSkins"></param>
        public Model(string modelName, string[] modelSkins)
        {
            this.modelName = modelName;
            skins.AddRange(modelSkins);
        }

        /// <summary>
        /// Filename of the model, minus the file extension.
        /// </summary>
        public string Name
        {
            get { return modelName; }
            set { modelName = value; }
        }

        /// <summary>
        /// string array containing the names of all installed skins available for the model.
        /// </summary>
        public string[] Skins
        {
            get { return skins.ToArray(); }
            set { skins.AddRange(value); }
        }
    }
}


text:
=head1 LICENSE

See the NOTICE file distributed with this work for additional information
regarding copyright ownership.

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.

=cut

# POD documentation - main docs before the code

=pod

=head1 NAME

Bio::EnsEMBL::Compara::RunnableDB::ncRNAtrees::Ktreedist

=cut

=head1 SYNOPSIS

my $db           = Bio::EnsEMBL::Compara::DBAdaptor->new($locator);
my $ktreedist = Bio::EnsEMBL::Compara::RunnableDB::ncRNAtrees::Ktreedist->new
  (
   -db         => $db,
   -input_id   => $input_id,
   -analysis   => $analysis
  );
$ktreedist->fetch_input(); #reads from DB
$ktreedist->run();
$ktreedist->write_output(); #writes to DB

=cut

=head1 DESCRIPTION

=cut

=head1 CONTACT

Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.

=cut

=head1 APPENDIX

The rest of the documentation details each of the object methods.
Internal methods are usually preceded with a _

=cut

package Bio::EnsEMBL::Compara::RunnableDB::GeneTrees::Ktreedist;

use strict;
use warnings;
use Data::Dumper;
use Bio::EnsEMBL::Compara::Graph::NewickParser;

use base ('Bio::EnsEMBL::Compara::RunnableDB::GeneTrees::TreeBest');

sub param_defaults {
    return {
        'ref_tree_clusterset'   => undef,
        'alternative_trees'     => undef,
        'reroot_with_sdi'       => 1,
    };
}

=head2 fetch_input

    Title   :   fetch_input
    Usage   :   $self->fetch_input
    Function:   Fetches input data from the database
    Returns :   none
    Args    :   none

=cut

sub fetch_input {
  my( $self) = @_;

    # Fetch sequences:
  $self->param('gene_tree', $self->compara_dba->get_GeneTreeAdaptor->fetch_by_dbID($self->param('gene_tree_id')) );

  if ($self->check_members) {
      $self->complete_early("Ktreedist.pm: All members have the same sequence.");
  }

  $self->load_input_trees;

  unless (scalar(keys %{$self->param('inputtrees_unrooted')})) {
    $self->complete_early("No trees with non-0 distances. Nothing to compute");
  }

  $self->require_executable('ktreedist_exe');
}

=head2 run

    Title   :   run
    Usage   :   $self->run
    Function:   runs something
    Returns :   none
    Args    :   none

=cut

sub run {
  my $self = shift;

  #If re-root we run the method otherwise we just copy over from the unrooted hash
  if ($self->param('reroot_with_sdi') ) {
    $self->reroot_inputtrees;
  }else{
    $self->param('inputtrees_rooted', $self->param('inputtrees_unrooted'));
  }

  $self->run_ktreedist;
}

=head2 write_output

    Title   :   write_output
    Usage   :   $self->write_output
    Function:   stores something
    Returns :   none
    Args    :   none

=cut

sub write_output {
  my $self = shift;
  $self->call_within_transaction( sub {
    $self->store_ktreedist_score;
  });
}

sub post_cleanup {
  my $self = shift;

  if(my $gene_tree = $self->param('gene_tree')) {
    $gene_tree->release_tree;
    $self->param('gene_tree', undef);
  }

  $self->SUPER::post_cleanup if $self->can("SUPER::post_cleanup");
}

##########################################
#
# internal methods
#
##########################################

## We want to make sure that all the members don't have the same sequence,
## otherwise, ktreedist will fail
sub check_members {
    my ($self) = @_;
    my $tree = $self->param('gene_tree');
    my %seqs;
    my %ref_tree_seq_member_ids;
    for my $leaf (@{$tree->get_all_leaves}) {
        $seqs{$leaf->sequence_id}++;
        $ref_tree_seq_member_ids{$leaf->seq_member_id} = $leaf;
    }
    $self->param('ref_tree_seq_member_ids', \%ref_tree_seq_member_ids);

    if (scalar(keys %seqs) == 1) {
        return 1
    }
    return 0;
}

sub run_ktreedist {
  my $self = shift;

  my $root_id = $self->param('gene_tree')->root_id;
  my $ktreedist_exe = $self->param('ktreedist_exe');
  my $temp_directory = $self->worker_temp_directory;

  my $comparisonfilename = $temp_directory . "/" . $root_id . ".ct";
  my $referencefilename = $temp_directory .  "/" .$root_id . ".rt";
  open(my $ct_fh, '>', $comparisonfilename) or die $!;
  print $ct_fh "#NEXUS\n\n";
  print $ct_fh "Begin TREES;\n\n";
  foreach my $method (keys %{$self->param('inputtrees_rooted')}) {
    my $inputtree = $self->param('inputtrees_rooted')->{$method};
    die ($method." is not defined in inputtrees_rooted")  unless (defined $inputtree);
    # KtreeDist doesn't understand NHX tags, and needs each tree on a single line
    my $newick_string = $inputtree;
    $newick_string =~ s/\[[^\]]*\]//g;
    $newick_string =~ s/\n//g;

    $self->throw("error with newick tree") unless (defined($newick_string));
    print $ct_fh "TREE    $method = $newick_string\n";
  }
  print $ct_fh "End;\n\n";
  close $ct_fh;

  my $reference_tree = $self->param('ref_tree_clusterset') ? $self->param('gene_tree')->alternative_trees->{$self->param('ref_tree_clusterset')} : $self->param('gene_tree');
  my $reference_string = $reference_tree->newick_format('ryo', '%{-m}%{"_"-X}:%{d}');
  my $ref_label = $self->param('gene_tree')->clusterset_id;

  $self->throw("error with newick tree") unless (defined($reference_string));

  $self->_spurt($referencefilename, join("\n",
          "#NEXUS\n",
          "Begin TREES;\n",
          "TREE    $ref_label = $reference_string",
          "End;\n",
      ));

  my $cmd = [$ktreedist_exe, '-a', '-rt', $referencefilename, '-ct', $comparisonfilename];
  my $runCmd = $self->run_command($cmd);
  if ($runCmd->exit_code) {
      if ($runCmd->err =~ /Substitution loop at.*ktreedist line 1777/) {
          # The tree is too big for ktreedist
          $self->complete_early('Ktreedist is not able to compute distances');
      }
      $runCmd->die_with_log;
  }
  my @output = split/\n/, $runCmd->out;

  my $ktreedist_score = $self->param('ktreedist_score', {});
  foreach my $line (@output) {
    if ($line =~ /\s+(\S+)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\d+)/) {
      my ($tag,$k_score,$scale_factor,$symm_difference,$n_partitions) = ($1,$2,$3,$4,$5);
      print "Parsing: $root_id,$tag,$k_score,$scale_factor,$symm_difference,$n_partitions\n" if ($self->debug);
      $ktreedist_score->{$root_id}{$k_score}{_tag}{$tag}{k_score} = $k_score;
      $ktreedist_score->{$root_id}{$k_score}{_tag}{$tag}{scale_factor} = $scale_factor;
      $ktreedist_score->{$root_id}{$k_score}{_tag}{$tag}{symm_difference} = $symm_difference;
      $ktreedist_score->{$root_id}{$k_score}{_tag}{$tag}{n_partitions} = $n_partitions;
    }
  }

  return 1;
}

sub load_input_trees {
    my ($self) = @_;
    my $tree = $self->param('gene_tree');
    $self->param('inputtrees_unrooted', {});

    my %alternative_trees;
    if ($self->param('ref_tree_clusterset')){
        %alternative_trees = map { $_ => 1 } @{$self->param('alternative_trees')};
    }

    # Although the reference tree for KTreeDist is "ref_tree_clusterset", the
    # tree in which the members are removed is the "default" clusterset, i.e.
    # $self->param('gene_tree_id') because KTreeDist can deal with alternative
    # references
    my %removed_members = map { $_ => 1 } @{$self->compara_dba->get_GeneTreeAdaptor->fetch_all_removed_seq_member_ids_by_root_id($self->param('gene_tree_id'))};

    for my $other_tree (values %{$tree->alternative_trees}) {

        #If we have a different set of alternative trees and the tags are not specified, it will skip the current tree
        next if ($self->param('ref_tree_clusterset') && (!$alternative_trees{$other_tree->clusterset_id}));

        print "tree:" . $other_tree->clusterset_id . "\n" if ($self->debug);

        # ktreedist will crash if the trees being compared have different number of leaves.
        # This may be caused by a member being deleted from one tree only but the other
        # jobs running on the same family are still unaware that the gene has been
        # dropped and keep it.

        for my $leaf ( @{ $other_tree->get_all_leaves } ) {
            if ( !exists( $self->param('ref_tree_seq_member_ids')->{ $leaf->dbID } ) && ( exists( $removed_members{ $leaf->dbID } ) ) ) {
                print "\tremoving:" . $leaf->dbID . "\n" if ( $self->debug );
                $leaf->disavow_parent;
                $other_tree->minimize_tree;
            }
        }
        print "ref_tree_leaves:" . scalar( keys( %{ $self->param('ref_tree_seq_member_ids') } ) ) . "\tcomp_tree_leaves:" . scalar(@{ $other_tree->get_all_leaves }) . "\tafter removing:" . scalar(@{ $other_tree->get_all_leaves }) . "\n" if ( $self->debug );

        # We set all the branch lengths to 1 in trees that are missing branch lengths
        # (e.g raxml_parsimony), so that KtreeDist runs without crashing
        my $ryo_format = $self->check_distances_to_parent($other_tree) ? '%{-m}%{"_"-X}:%{d}' : '%{-m}%{"_"-X}:1';
        $self->param('inputtrees_unrooted')->{$other_tree->clusterset_id} = $other_tree->newick_format('ryo', $ryo_format);
    }
    return 1;
}

## We filter out all the trees with all the distance to parent equals to 0
## ktreedist will fail on them
sub check_distances_to_parent {
    my ($self, $tree) = @_;
    my $tot_dtp = 0;
    for my $node(@{$tree->get_all_nodes}) {
        $tot_dtp += $node->distance_to_parent;
    }
    print STDERR "TOT_DTP: $tot_dtp\n";

    return $tot_dtp;
}

sub reroot_inputtrees {
  my $self = shift;

  $self->param('inputtrees_rooted', {});
  foreach my $method (keys %{$self->param('inputtrees_unrooted')}) {
    my $inputtree = $self->param('inputtrees_unrooted')->{$method};

    # Parse the rooted tree string
    my $rootedstring = $self->run_treebest_sdi($inputtree, 1);

    # The string may be empty if the bison parser couldn't parse the tree
    # due to memory exhaustion
    if (not $rootedstring) {
        $self->warning(sprintf("Treebest could not root the '%s' tree due probably to memory exhaustion\n", $method));
        next;
    }

    $self->param('inputtrees_rooted')->{$method} = $rootedstring;
  }
}

sub store_ktreedist_score {
    my ($self) = @_;
    my $root_id = $self->param('gene_tree')->root_id;
    my $other_trees = $self->param('gene_tree')->alternative_trees;

    my $sth = $self->compara_dba->dbc->prepare
        ("REPLACE INTO ktreedist_score
                                            (node_id,
                                             tag,
                                             k_score,
                                             scale_factor,
                                             symm_difference,
                                             n_partitions,
                                             k_score_rank) VALUES (?,?,?,?,?,?,?)");

    my $count = 1;
    my $ktreedist_score_root_id = $self->param('ktreedist_score')->{$root_id};
    for my $k_score_as_rank (sort {$a <=> $b} keys %$ktreedist_score_root_id) {
        for my $tag (keys %{$ktreedist_score_root_id->{$k_score_as_rank}{_tag}}) {
            print STDERR "TAG: $tag\n" if ($self->debug);
            $other_trees->{$tag}->store_tag('k_score', $ktreedist_score_root_id->{$k_score_as_rank}{_tag}{$tag}{k_score});
            $other_trees->{$tag}->store_tag('k_score_rank', $count);

            my $k_score         = $ktreedist_score_root_id->{$k_score_as_rank}{_tag}{$tag}{k_score};
            my $scale_factor    = $ktreedist_score_root_id->{$k_score_as_rank}{_tag}{$tag}{scale_factor};
            my $symm_difference = $ktreedist_score_root_id->{$k_score_as_rank}{_tag}{$tag}{symm_difference};
            my $n_partitions    = $ktreedist_score_root_id->{$k_score_as_rank}{_tag}{$tag}{n_partitions};
            my $k_score_rank    = $count++;
            $sth->execute($root_id,
                          $tag,
                          $k_score,
                          $scale_factor,
                          $symm_difference,
                          $n_partitions,
                          $k_score_rank);
        }
    }
    $sth->finish;

}

1;


text:
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

from dependencies_resolver.utils import s3_utils

def download_dependencies(dependencies_data):
    """This function gets a list of dependencies and a remote repository.
    The dependencies are being downloaded to the specified location per
    dependency.

    :param dependencies_data: A JSON which contains a repository and a list
    of dependencies to be downloaded.
    :return: Nothing, unless an Exception is being raised.
    """
    # Removing the s3:// prefix from the repository name
    base_repository = dependencies_data['repository'][5:]
    dependencies = dependencies_data['dependencies']

    for dependency in dependencies:
        name = dependency['name']
        version = dependency['version']
        location = dependency['location']
        s3_utils.download(bucket=base_repository, name=name,
                          version=version, location=location,
                          s3path=dependency.get('s3path'))


text:
namespace Vingine {
	constexpr const std::array<ColorTy, 5> g_Colors = GetLogColors();

	std::shared_mutex Log::m_InstanceListMutex;
	std::unordered_map<std::string, Log*> Log::m_Instances = {};

	std::shared_mutex Log::m_ThreadListMutex;
	std::unordered_map<std::thread::id, std::string> Log::m_ThreadList = {};

	Log::Log(LogFlags logFlags, const std::string & logName) :
		mLogFlags(logFlags),
		mLogName(logName),
		mBuffer(new char[BUFFER_SIZE]),
		mConsoleStream(NULL) {

		if(bool(mLogFlags & LogFlags::Console))
			CreateConsole();

		if(bool(mLogFlags & LogFlags::File))
			CreateLogFile();

		std::unique_lock<std::shared_mutex> writeLock(m_InstanceListMutex);
		if(m_Instances.find(mLogName) != m_Instances.end())
			throw "Log-Name Redefinition";
		m_Instances[mLogName] = this;
	}

	Log::~Log() {
		LogI("Destroying Log!");

		if(mConsoleStream != NULL) {
			fclose(mConsoleStream);
			FreeConsole();
		}

		delete[] mBuffer;

		std::unique_lock<std::shared_mutex> writeLock(m_InstanceListMutex);
		m_Instances.erase(mLogName);
	}

	Log *Log::GetInstance(const std::string & logName) {
		std::shared_lock<std::shared_mutex> writeLock(m_InstanceListMutex);

		auto it = m_Instances.find(logName);
		if(it != m_Instances.end())
			return it->second;
		return nullptr;
	}

	bool Log::RegisterThreadName(const std::string & threadName) {
		std::unique_lock<std::shared_mutex> writeLock(m_ThreadListMutex);

		std::thread::id threadId = std::this_thread::get_id();
		auto it = m_ThreadList.find(threadId);
		if(it != m_ThreadList.end())
			return false;

		// Set thread name in Visual Studio debugger
		if constexpr(CurrentOS == OS::Windows) {
		#pragma pack(push,8)
			struct THREADNAME_INFO {
				DWORD dwType;		// Must be 0x1000.
				LPCSTR szName;		// Pointer to name (in user addr space).
				DWORD dwThreadID;	// Thread ID (-1=caller thread).
				DWORD dwFlags;		// Reserved for future use, must be zero.
			};
		#pragma pack(pop)

			auto SetThreadName = [](DWORD dwThreadID, const char* threadName) {
				constexpr DWORD MS_VC_EXCEPTION = 0x406D1388;	// Magic number for setting ThreadName

				THREADNAME_INFO info;
				info.dwType = 0x1000;
				info.szName = threadName;
				info.dwThreadID = dwThreadID;
				info.dwFlags = 0;
			#pragma warning(push)
			#pragma warning(disable: 6320 6322)
				__try {
					RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), reinterpret_cast<ULONG_PTR*>(&info));
				}
				__except(EXCEPTION_EXECUTE_HANDLER) {}
			#pragma warning(pop)
			};

			SetThreadName(static_cast<DWORD>(-1), threadName.c_str());
		}

		m_ThreadList[threadId] = threadName;
		return true;
	}

	std::string Log::GetThreadName(const std::thread::id & threadId) {
		std::shared_lock<std::shared_mutex> readLock(m_ThreadListMutex);

		auto it = m_ThreadList.find(threadId);
		if(it != m_ThreadList.end())
			return it->second;

		return "Unregistered";
	}

	void Log::Print(const DetailInformation & detailInfo, LogLevel level, const std::string & message) {
		mMutex.lock();

		try {
			sprintf_s(mBuffer, BUFFER_SIZE, message.c_str());

			Flush(level, detailInfo);

			mMutex.unlock();
		}
		catch(std::exception& e) {
			mMutex.unlock();
			throw(e);
		}

		if(bool(mLogFlags & LogFlags::FatalQuit)
		   && level == LogLevel::Fatal) {

			exit(-1);
		}
	}

	void Log::Print(const DetailInformation & detailInfo, LogLevel level, const char * message, ...) {
		mMutex.lock();

		try {
			static va_list variadic_list;
			va_start(variadic_list, message);
			vsprintf_s(mBuffer, BUFFER_SIZE, message, variadic_list);
			va_end(variadic_list);

			Flush(level, detailInfo);

			mMutex.unlock();
		}
		catch(std::exception& e) {
			mMutex.unlock();
			throw(e);
		}

		if(bool(mLogFlags & LogFlags::FatalQuit)
		   && level == LogLevel::Fatal) {

			exit(-1);
		}
	}

	void Log::Flush(LogLevel level, const DetailInformation & detailInfo) {
		// Color emphasize
		SetConsoleColor(level);

		// The error prefix
		char *prefix;
		switch(level) {
			case LogLevel::Information:
				prefix = " [INFO]";
				break;
			case LogLevel::Debug:
				prefix = "[DEBUG]";
				break;
			case LogLevel::Warning:
				prefix = " [WARN]";
				break;
			case LogLevel::Error:
				prefix = "[ERROR]";
				break;
			case LogLevel::Fatal:
				prefix = "[FATAL]";
				break;
		}
		*this << prefix;

		// Detailed information, e.g. time, file, line...
		LogFlags detailBits = mLogFlags & LogFlags::DetailAll;
		if(bool(detailBits)) {
			LogFlags highestBit = Utility::GetHighestOrderBit(detailBits);

			// Conditional delimiter
		#define CON_DEL(bit) << (bool(detailBits & highestBit) ? "" : "; ")

			*this << "<";
			if(bool(detailBits & LogFlags::DetailTime))
				*this << detailInfo.Time CON_DEL(DetailTime);
			if(bool(detailBits & LogFlags::DetailDate))
				*this << detailInfo.Date CON_DEL(DetailDate);
			if(bool(detailBits & LogFlags::DetailFile))
				*this << detailInfo.File CON_DEL(DetailFile);
			if(bool(detailBits & LogFlags::DetailLine))
				*this << detailInfo.Line CON_DEL(DetailLine);
			if(bool(detailBits & LogFlags::DetailFunction))
				*this << detailInfo.Function CON_DEL(DetailFunction);
			if(bool(detailBits & LogFlags::DetailThread))
				*this << detailInfo.Thread CON_DEL(DetailThread);
			*this << ">";

		#undef CON_DEL
		}

		*this << ": ";

		// Return to white
		SetConsoleColor(LogLevel::Information);

		// The message
		*this << mBuffer << "\n";
	}

	void Log::SetConsoleColor(LogLevel level) {
		if constexpr(CurrentOS == OS::Windows)
			SetConsoleTextAttribute(mConsoleHandle, g_Colors[static_cast<size_t>(level)]);
		else
			static_assert(CurrentOS == OS::Windows, "Current OS not supported!");
	}

	void Log::CreateConsole() {
		if constexpr(CurrentOS == OS::Windows) {
			AllocConsole();
			SetConsoleTitle("Vingine Console");

			if(freopen_s(&mConsoleStream, "CONOUT$", "w+", stdout) != 0)
				exit(2);

			//Clear the error state for each of the C++ standard stream objects. We need to do this, as
			//attempts to access the standard streams before they refer to a valid target will cause the
			//iostream objects to enter an error state. In versions of Visual Studio after 2005, this seems
			//to always occur during startup regardless of whether anything has been read from or written to
			//the console or not.
			std::wcout.clear();
			std::cout.clear();
			std::wcerr.clear();
			std::cerr.clear();

			glm::ivec2 size(1200, 600);
			glm::ivec2 position(size / 6);
			SetWindowPos(GetConsoleWindow(), nullptr, position.x, position.y, size.x, size.y, SWP_NOZORDER);

			mConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
		}
		else
			static_assert(CurrentOS == OS::Windows, "Current OS not supported!");
	}

	void Log::CreateLogFile() {
		/// TODO: Get date for file-name
		/// TODO: Create log folder
		mFileStream.open("debug.log");
	}
}


text:
<?php

namespace donatj\MockWebServer;

/**
 * MultiResponseInterface is used to vary the response to a request.
 */
interface MultiResponseInterface extends ResponseInterface {

	/**
	 * Called after each request is sent
	 *
	 * @internal
	 */
	public function next() : bool;

}


text:
/*
	A short library to manage the connections and calculus of MPU6050
	and HMC5883L intertial sensors
*/

#ifndef _IMUBOARD_
#define _IMUBOARD_

#define IMUB_MPU 1
#define IMUB_HMC 2

#define MPU_SLAVE_ADDR 0x68
#define HMC_SLAVE_ADDR 0x1E

#define IMUB_SR_1000 0
#define IMUB_SR_512  1
#define IMUB_SR_111  9

#include <linux/i2c-dev.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <string.h>

int IMUBInit();							//Open the I2C Channel and verify the sensors
int IMUBSampleRate(int sample_rate_divider); 			//Setup the sample rate
int IMUB_DLPF(int level);					//Setup the digital low pass filter (six levels {0-6})
int IMUBAccelScale(int g_scale);				//Setup the g scale, available scales are: 2,4,8,16 G, use this values
int IMUBPollRaw(float *data_dest); 				//Use  Poll method to sample the raw data
int IMUBPOllAngles(float *yaw, float *pitch, float *roll); 	//Use poll method to sample the processed angles
int IMUBClose(); //close all resources

#endif


text:
set -e

# Only make deployments from the master,
# PRs will not be deployed.
if [[ "${TRAVIS_PULL_REQUEST}" == "false" ]] && [[ "${TRAVIS_BRANCH}" == "master" ]]; then
    # Deploy app
    $(npm bin)/firebase deploy -P production \
        --token ${FIREBASE_TOKEN} \
        --non-interactive
fi


text:
package org.apache.hadoop.hive.serde2.teradata;

import com.google.common.io.BaseEncoding;
import junit.framework.TestCase;
import org.apache.hadoop.hive.common.type.Timestamp;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.io.TimestampWritableV2;
import org.apache.hadoop.io.BytesWritable;
import org.junit.Assert;

import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * Test the data type TIMESTAMP for Teradata binary format.
 */
public class TestTeradataBinarySerdeForTimeStamp extends TestCase {

  private final TeradataBinarySerde serde = new TeradataBinarySerde();
  private final Properties props = new Properties();

  protected void setUp() throws Exception {
    props.setProperty(serdeConstants.LIST_COLUMNS, "TD_TIMESTAMP");
    props.setProperty(serdeConstants.LIST_COLUMN_TYPES, "timestamp");
  }

  public void testTimestampPrecision6() throws Exception {
    props.setProperty(TeradataBinarySerde.TD_TIMESTAMP_PRECISION, "6");
    serde.initialize(null, props);

    //2012-10-01 12:00:00.110000
    BytesWritable in = new BytesWritable(
        BaseEncoding.base16().lowerCase().decode("00323031322d31302d30312031323a30303a30302e313130303030"));

    List<Object> row = (List<Object>) serde.deserialize(in);
    Timestamp ts = ((TimestampWritableV2) row.get(0)).getTimestamp();
    Assert.assertEquals(ts.getYear(), 2012);
    Assert.assertEquals(ts.getMonth(), 10);
    Assert.assertEquals(ts.getDay(), 1);
    Assert.assertEquals(ts.getHours(), 12);
    Assert.assertEquals(ts.getMinutes(), 0);
    Assert.assertEquals(ts.getSeconds(), 0);
    Assert.assertEquals(ts.getNanos(), 110000000);

    BytesWritable res = (BytesWritable) serde.serialize(row, serde.getObjectInspector());
    Assert.assertTrue(Arrays.equals(in.copyBytes(), res.copyBytes()));
  }

  public void testTimestampPrecision0() throws Exception {
    props.setProperty(TeradataBinarySerde.TD_TIMESTAMP_PRECISION, "0");
    serde.initialize(null, props);

    //2012-10-01 12:00:00
    BytesWritable in =
        new BytesWritable(BaseEncoding.base16().lowerCase().decode("00323031322d31302d30312031323a30303a3030"));

    List<Object> row = (List<Object>) serde.deserialize(in);
    Timestamp ts = ((TimestampWritableV2) row.get(0)).getTimestamp();
    Assert.assertEquals(ts.getYear(), 2012);
    Assert.assertEquals(ts.getMonth(), 10);
    Assert.assertEquals(ts.getDay(), 1);
    Assert.assertEquals(ts.getHours(), 12);
    Assert.assertEquals(ts.getMinutes(), 0);
    Assert.assertEquals(ts.getSeconds(), 0);
    Assert.assertEquals(ts.getNanos(), 0);

    BytesWritable res = (BytesWritable) serde.serialize(row, serde.getObjectInspector());
    Assert.assertTrue(Arrays.equals(in.copyBytes(), res.copyBytes()));
  }

  public void testTimestampPrecision3() throws Exception {
    props.setProperty(TeradataBinarySerde.TD_TIMESTAMP_PRECISION, "3");
    serde.initialize(null, props);

    //2012-10-01 12:00:00.345
    BytesWritable in =
        new BytesWritable(BaseEncoding.base16().lowerCase().decode("00323031322d31302d30312031323a30303a30302e333435"));

    List<Object> row = (List<Object>) serde.deserialize(in);
    Timestamp ts = ((TimestampWritableV2) row.get(0)).getTimestamp();
    Assert.assertEquals(ts.getYear(), 2012);
    Assert.assertEquals(ts.getMonth(), 10);
    Assert.assertEquals(ts.getDay(), 1);
    Assert.assertEquals(ts.getHours(), 12);
    Assert.assertEquals(ts.getMinutes(), 0);
    Assert.assertEquals(ts.getSeconds(), 0);
    Assert.assertEquals(ts.getNanos(), 345000000);

    BytesWritable res = (BytesWritable) serde.serialize(row, serde.getObjectInspector());
    Assert.assertTrue(Arrays.equals(in.copyBytes(), res.copyBytes()));
  }
}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
info: Check Function Expression for automatic semicolon insertion
es5id: 7.9_A5.5_T2
description: >
    Try use function f(o) {o.x = 1; return o;}; \n (new Object()).x;
    construction
---*/

//CHECK#1
var result = function f(o) {o.x = 1; return o;};
(new Object()).x;
if (typeof result !== "function") {
  $ERROR('#1: Check Function Expression for automatic semicolon insertion');
}


text:
module Danica
  class Equation::Builder
    attr_reader :variables

    def initialize(*variables, &block)
      @variables = variables
      instance_eval(&block)
    end

    def build
      vars = variables
      l = left
      r = right

      Class.new(Equation) do
        variables(*vars)

        define_method :left, l
        define_method :right, r
      end
    end

    def left(&block)
      @left = block if block_given?
      @left
    end

    def right(&block)
      @right = block if block_given?
      @right
    end
  end
end