text:
<?php

namespace Cloudtek\DynamoDM\Test\Persister;

use Cloudtek\DynamoDM\Test\BaseTest;
use Documents\CmsArticle;
use Documents\CmsComment;
use Documents\Ecommerce\ConfigurableProduct;
use Documents\Ecommerce\Currency;
use Documents\Functional\SameCollection1;
use Documents\Functional\SameCollection2;

class PersistenceBuilderTest extends BaseTest
{
    private $pb;

    public function setUp()
    {
        parent::setUp();
        $this->pb = $this->dm->getUnitOfWork()->getPersistenceBuilder();
    }

    public function tearDown()
    {
        unset($this->pb);
        parent::tearDown();
    }

    public function testQueryBuilderUpdateWithDiscriminatorMap()
    {
        $testCollection = new SameCollection1();
        $id = '4f28aa84acee413889000001';

        $testCollection->id = $id;
        $testCollection->name = 'First entry';
        $this->dm->persist($testCollection);
        $this->dm->flush();
        $this->uow->computeChangeSets();

        /**
         * @var \Cloudtek\DynamoDM\Expression\Builder $qb
         */
        $qb = $this->dm->createQueryBuilder('Documents\Functional\SameCollection1');
        $qb->update()
            ->attr('ok')->set(true)
            ->attr('test')->set('OK! TEST')
            ->attr('id')->equals($id);

        $query = $qb->getQuery();
        $query->execute();

        $this->dm->refresh($testCollection);

        $this->assertEquals('OK! TEST', $testCollection->test);
    }

    public function testFindWithOrOnCollectionWithDiscriminatorMap()
    {
        $sameCollection1 = new SameCollection1();
        $sameCollection2a = new SameCollection2();
        $sameCollection2b = new SameCollection2();
        $ids = array(
            '4f28aa84acee413889000001',
            '4f28aa84acee41388900002a',
            '4f28aa84acee41388900002b'
        );

        $sameCollection1->id = $ids[0];
        $sameCollection1->name = 'First entry in SameCollection1';
        $sameCollection1->test = 1;
        $this->dm->persist($sameCollection1);
        $this->dm->flush();

        $sameCollection2a->id = $ids[1];
        $sameCollection2a->name = 'First entry in SameCollection2';
        $sameCollection2a->ok = true;
        $this->dm->persist($sameCollection2a);
        $this->dm->flush();

        $sameCollection2b->id = $ids[2];
        $sameCollection2b->name = 'Second entry in SameCollection2';
        $sameCollection2b->w00t = '!!';
        $this->dm->persist($sameCollection2b);
        $this->dm->flush();

        $this->uow->computeChangeSets();

        /**
         * @var \Cloudtek\DynamoDM\Expression\Builder $qb
         */
        $qb = $this->dm->createQueryBuilder(SameCollection2::class);
        $qb
            ->attr('id')->in($ids)
            ->select('id')->hydrate(false);

        $query = $qb->getQuery();
        $debug = $query->debug('query');
        $results = $query->execute();

        $this->assertInstanceOf(Iterator::class, $results);

        $targetClass = $this->dm->getClassMetadata(SameCollection2::class);
        $MongoId1 = $targetClass->getDatabaseIdentifierValue($ids[1]);

        $this->assertEquals($MongoId1, $debug['_id']['$in'][1]);

        $this->assertCount(2, $results->toArray());
    }

    public function testPrepareUpdateDataDoesNotIncludeId()
    {
        $article = new CmsArticle();
        $article->topic = 'persistence builder test';
        $this->dm->persist($article);
        $this->dm->flush();
        $this->dm->clear();

        $article = $this->dm->getRepository(get_class($article))->find($article->id);
        $article->id = null;
        $article->topic = 'test';

        $this->uow->computeChangeSets();
        $data = $this->pb->prepareUpdateData($article);
        $this->assertFalse(isset($data['$unset']['_id']));
    }

    public function testPrepareInsertDataWithCreatedReferenceOne()
    {
        $article = new CmsArticle();
        $article->title = 'persistence builder test';
        $this->dm->persist($article);
        $this->dm->flush();
        $comment = new CmsComment();
        $comment->article = $article;

        $this->dm->persist($comment);
        $this->uow->computeChangeSets();

        $expectedData = array(
            'article' => array(
                '$db' => DOCTRINE_DYNAMODB_DATABASE,
                '$id' => new \MongoId($article->id),
                '$ref' => 'CmsArticle'
            ),
            'nullableAttribute' => null,
        );
        $this->assertDocumentInsertData($expectedData, $this->pb->prepareInsertData($comment));
    }

    public function testPrepareInsertDataWithFetchedReferenceOne()
    {
        $article = new CmsArticle();
        $article->title = 'persistence builder test';
        $this->dm->persist($article);
        $this->dm->flush();
        $this->dm->clear();

        $article = $this->dm->find(get_class($article), $article->id);
        $comment = new CmsComment();
        $comment->article = $article;

        $this->dm->persist($comment);
        $this->uow->computeChangeSets();

        $expectedData = array(
            'article' => array(
                '$db' => DOCTRINE_DYNAMODB_DATABASE,
                '$id' => new \MongoId($article->id),
                '$ref' => 'CmsArticle'
            )
        );
        $this->assertDocumentInsertData($expectedData, $this->pb->prepareInsertData($comment));
    }

    public function testPrepareUpsertData()
    {
        $article = new CmsArticle();
        $article->title = 'persistence builder test';
        $this->dm->persist($article);
        $this->dm->flush();
        $this->dm->clear();

        $article = $this->dm->find(get_class($article), $article->id);
        $comment = new CmsComment();
        $comment->topic = 'test';
        $comment->text = 'text';
        $comment->article = $article;

        $this->dm->persist($comment);
        $this->uow->computeChangeSets();

        $expectedData = array(
            '$set' => array(
                'topic' => 'test',
                'text' => 'text',
                'article' => array(
                    '$db' => DOCTRINE_DYNAMODB_DATABASE,
                    '$id' => new \MongoId($article->id),
                    '$ref' => 'CmsArticle'
                ),
                '_id' => new \MongoId($comment->id),
            ),
            '$setOnSirt' => ['nullableAttribute' => null],
        );
        $this->assertEquals($expectedData, $this->pb->prepareUpsertData($comment));
    }

    /**
     * @dataProvider getDocumentsAndExpectedData
     */
    public function testPrepareInsertData($document, array $expectedData)
    {
        $this->dm->persist($document);
        $this->uow->computeChangeSets();
        $this->assertDocumentInsertData($expectedData, $this->pb->prepareInsertData($document));
    }

    /**
     * Provides data for @see PersistenceBuilderTest::testPrepareInsertData()
     * Returns arrays of array(document => expected data)
     *
     * @return array
     */
    public function getDocumentsAndExpectedData()
    {
        return array(
            array(new ConfigurableProduct('Test Product'), array('name' => 'Test Product')),
            array(new Currency('USD', 1), array('name' => 'USD', 'multiplier' => 1)),
        );
    }

    private function assertDocumentInsertData(array $expectedData, array $preparedData = null)
    {
        foreach ($preparedData as $key => $value) {
            if ($key === '_id') {
                $this->assertInstanceOf('MongoId', $value);
                continue;
            }
            $this->assertEquals($expectedData[$key], $value);
        }
        if ( ! isset($preparedData['_id'])) {
            $this->fail('insert data should always contain id');
        }
        unset($preparedData['_id']);
        $this->assertEquals(array_keys($expectedData), array_keys($preparedData));
    }

    public function testAdvancedQueriesOnReferenceWithDiscriminatorMap()
    {
        $article = new CmsArticle();
        $article->id = '4f8373f952fbfe7411000001';
        $article->title = 'advanced queries test';
        $this->dm->persist($article);
        $this->dm->flush();

        $comment = new CmsComment();
        $comment->id = '4f8373f952fbfe7411000002';
        $comment->article = $article;
        $this->dm->persist($comment);
        $this->dm->flush();

        $this->uow->computeChangeSets();

        $articleId = (string) $article->id;
        $commentId = (string) $comment->id;

        /**
         * @var \Cloudtek\DynamoDM\Query\Builder $qb
         */
        $qb = $this->dm->createQueryBuilder(CmsComment::class);
        $qb
            ->attr('article.id')->in(array($articleId));

        $query = $qb->getQuery();
        $results = $query->execute();

        $this->assertInstanceOf(Iterator::class, $results);

        $singleResult = $results->getSingleResult();
        $this->assertInstanceOf(CmsComment::class, $singleResult);

        $this->assertEquals($commentId, $singleResult->id);

        $this->assertInstanceOf(CmsArticle::class, $singleResult->article);

        $this->assertEquals($articleId, $singleResult->article->id);
        $this->assertCount(1, $results->toArray());
    }
}


text:
package edu.columbia.cs.psl.test.phosphor.runtime;

public class MethodReflectionImplicitITCase extends MethodReflectionObjTagITCase {
}

redpajama_set_name: RedPajamaGithub


text:
namespace gf {
    namespace reader {

        class Alternative : public gf::RefBase {
        private:
            std::vector<std::string> tokens;
            std::vector<std::string> prefix;

        public:
            Alternative(const std::vector<std::string>& tokens, const std::vector<std::string>& prefix);
            virtual ~Alternative();

            virtual const std::vector<std::string>& getAlt1() const;
            virtual const std::vector<std::string>& getAlt2() const;

            virtual std::string toString() const;
        };

    }
}

#endif


text:
import OrchestraView      from 'OpenOrchestra/Application/View/OrchestraView'
import LoadingButtonMixin from 'OpenOrchestra/Service/Form/Mixin/LoadingButtonMixin'

/**
 * @class AbstractFormView
 */
class AbstractFormView extends mix(OrchestraView).with(LoadingButtonMixin)
{
    /**
     * Constructor
     */
    constructor (options) {
        super(options);
        if (this.constructor === AbstractFormView) {
            throw TypeError("Can not construct abstract class");
        }
    }

    /**
     * Pre initialize
     * @param {Object} options
     */
    preinitialize(options) {
        this.events = {
            'click button.submit-form': '_submit',
            'keydown form': '_preventSubmitEnter'
        };
    }

    /**
     * Initialize
     * @param {Form} form
     */
    initialize({form}) {
        this._form = form;
        this._$formRegion = this.$el;
        this._form.on('form:post_submit', $.proxy(this._resetSubmitButton, this));
    }

    /**
     * Render
     */
    render() {
        this._renderForm();

        return this;
    }

    /**
     * Refresh render
     */
    refreshRender() {
        Backbone.Events.trigger('form:deactivate', this);
        this._renderForm();
    }

    /**
     * Render a form
     *
     * @private
     */
    _renderForm() {
        this._$formRegion.html('');
        for (let message of this._form.$messages) {
            this._$formRegion.append(message);
        }
        this._$formRegion.append(this._form.$form);
        Backbone.Events.trigger('form:activate', this);

        return this;
    }

    /**
     * @param  {Object} event
     *
     * @return {Object}
     */
    getStatusCodeForm(event) {}

    /**
     * Submit form
     * @param {object} event
     */
    _submit(event) {
        event.preventDefault();
        this.activateLoading($(event.currentTarget));
        this._form.submit(this.getStatusCodeForm(event));
    }

    /**
     * Reset laading submit button
     * @private
     */
    _resetSubmitButton() {
        this.resetLoadingButton($('button.submit-form', this.$el));
    }

    /**
     * @param {Object} event
     * @private
     */
    _preventSubmitEnter(event) {
        if (13 === event.keyCode)  {
            event.preventDefault();
            return false;
        }
    }

    /**
     * @return {Form}
     */
    getForm() {
        return this._form;
    }
}

export default AbstractFormView;


text:
package beaform.gui.search;

import java.awt.BorderLayout;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import beaform.entities.Formula;
import beaform.gui.formulaeditor.FormulaEditor;
import beaform.gui.search.tree.FormulaTree;
import beaform.gui.subwindows.InterchangableWindow;
import beaform.search.SearchFormulaTask;
import beaform.search.SearchFormulasByTagTask;

/**
 * A search GUI.
 *
 * @author Steven Post
 *
 */
public final class SearchGui extends Observable implements InterchangableWindow, Observer {

	private static final Logger LOG = LoggerFactory.getLogger(SearchGui.class);

	private final SearchGuiUI searchguiUI;

	/** The index of the formula tree on the target panel */
	private static final int FORMULA_TREE_LOC = 3;

	public SearchGui() {
		this.searchguiUI = new SearchGuiUI(this);
	}

	public void search() {
		final SearchType searchType = this.searchguiUI.getSearchType();

		switch (searchType) {
			case FORMULA:
				searchFormula();
				break;
			case TAG:
				searchTag();
				break;
			default:
				if (LOG.isErrorEnabled()) {
					LOG.error(searchType + " is an unknown search");
				}
				break;
		}
	}

	private void searchTag() {
		final String searchText = this.searchguiUI.getSearchText();
		final SearchFormulasByTagTask task = new SearchFormulasByTagTask(searchText);
		final Future<List<Formula>> searchresult = SearchTaskHandler.addTask(task);
		SearchTaskHandler.addTask(new RenderFormulaSearchByTagResult(searchresult, this));
	}

	private void searchFormula() {
		final String searchText = this.searchguiUI.getSearchText();
		final SearchFormulaTask task = new SearchFormulaTask(searchText);
		final Future<Formula> searchresult = SearchTaskHandler.addTask(task);
		SearchTaskHandler.addTask(new RenderFormulaSearchResult(searchresult, this));
	}

	/**
	 * Set the search results in a view.
	 *
	 * @param formulaTree the search results
	 */
	public void setSearchResults(final FormulaTree formulaTree) {
		if (this.searchguiUI.getPanel().getComponentCount() > FORMULA_TREE_LOC) {
			this.searchguiUI.getPanel().remove(FORMULA_TREE_LOC);
		}
		formulaTree.addToPanel(this.searchguiUI.getPanel(), BorderLayout.CENTER);
		this.searchguiUI.getPanel().revalidate();
	}

	@Override
	public void replace() {
		this.setChanged();
		this.notifyObservers(this.searchguiUI.getPanel());
	}

	@Override
	public void update(Observable o, Object arg) {
		if (o instanceof FormulaTree && arg instanceof Formula) {
			Formula form = (Formula) arg;
			FormulaEditor editor = new FormulaEditor(form);
			this.setChanged();
			this.notifyObservers(editor);
		}
	}

}


text:
layout: default
title: CAS - SAML2 Metadata Management
category: Protocols
---

{% include variables.html %}

# REST - SAML2 Metadata Management

Similar to the Dynamic Metadata Query Protocol (MDQ), SAML service provider metadata may also be fetched using a more traditional REST
interface. This is a simpler option that does not require one to deploy a compliant MDQ server and provides the
flexibility of producing SP metadata using any programming language or framework.

Support is enabled by including the following module in the overlay:

{% include_cached casmodule.html group="org.apereo.cas" module="cas-server-support-saml-idp-metadata-rest" %}

Use the below snippet as an example to fetch metadata from REST endpoints:

```json
{
  "@class" : "org.apereo.cas.support.saml.services.SamlRegisteredService",
  "serviceId" : "the-entity-id-of-the-sp",
  "name" : "SAMLService",
  "id" : 10000003,
  "evaluationOrder" : 10,
  "metadataLocation" : "rest://"
}
```

Metadata Location

The metadata location in the registration record above needs to be specified as rest:// to signal to
CAS that SAML metadata for registered service provider must be fetched from REST endpoints defined in CAS configuration.

Requests are submitted to REST endpoints with `entityId` as the parameter and `Content-Type: application/xml` as the header. Upon
a successful `200 - OK` response status, CAS expects the body of the HTTP response to match the below snippet:

```json
{
   "id":1000,
   "name":"SAML Metadata For Service Provider",
   "value":"...",
   "signature":"..."
}
```

{% include_cached casproperties.html properties="cas.authn.saml-idp.metadata.rest" %}

## Identity Provider Metadata

Metadata artifacts that belong to CAS as a SAML2 identity provider
may also be managed and stored via REST APIs. Artifacts such as the metadata, signing and
encryption keys, etc are passed along to an external API
endpoint in the following structure as the request body:

```json
{
    "signingCertificate": "...",
    "signingKey": "...",
    "encryptionCertificate": "...",
    "encryptionKey": "...",
    "metadata": "...",
    "appliesTo": "CAS"
}
```

The URL endpoint, defined in CAS settings is expected to be available at a path that ends in `/idp`, which is added onto the URL endpoint by CAS automatically.
The API is expected to produce a successful `200 - OK` response status on all operations outlined below:

| Method | Description                                                                                |
|--------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `GET`  | The response is expected to produce a JSON document outlining keys and metadata as indicated above. An `appliesTo` parameter may be passed to indicate the document owner and applicability, where a value of `CAS` indicates the CAS server as the global owner of the metadata and keys. |
| `POST` | Store the metadata and keys to finalize the metadata generation process. The request body contains the JSON document that outlines metadata and keys as indicated above.                                                                                |

## Per Service

Identity provider metadata, certificates and keys can also be defined on a per-service basis to override the global defaults.
Metadata documents that would be applicable to a service definition need to adjust the `appliesTo` field in the metadata
document to carry the service definition's name and numeric identifier using the `[service-name]-[service-numeric-identifier]` format.


text:
<?php

$baseDir = \dirname(__DIR__);
/** @psalm-suppress UnresolvableInclude */
require_once \sprintf('%s/vendor/autoload.php', $baseDir);

use fkooman\OAuth\Server\BearerValidator;
use fkooman\OAuth\Server\ClientInfo;
use fkooman\OAuth\Server\Exception\OAuthException;
use fkooman\OAuth\Server\Http\JsonResponse;
use fkooman\OAuth\Server\SodiumSigner;
use fkooman\OAuth\Server\Storage;

try {
    // persistent storage for access_token authorizations
    $storage = new Storage(new PDO(\sprintf('sqlite:%s/data/db.sqlite', $baseDir)));
    $storage->init();

    // callback to "convert" a client_id into a ClientInfo object, typically
    // this configuration comes from a configuration file or database...
    $getClientInfo = function ($clientId) {
        $oauthClients = [
            // we only have one client here with client_id "demo_client"...
            'demo_client' => [
                'redirect_uri_list' => ['http://localhost:8081/callback.php'],
                'display_name' => 'Demo Client',
                'client_secret' => 'demo_secret',
                //'require_approval' => false,
            ],
        ];

        // if the client with this client_id does not exist, we return false...
        if (!\array_key_exists($clientId, $oauthClients)) {
            return false;
        }

        return new ClientInfo($oauthClients[$clientId]);
    };

    $bearerValidator = new BearerValidator(
        $storage,
        $getClientInfo,
        new SodiumSigner(
            // see README on how to generate a "server.key"
            \file_get_contents('server.key')
        )
    );

    switch ($_SERVER['REQUEST_METHOD']) {
        case 'GET':
        case 'HEAD':
            // get the "Authorization" header from the HTTP request
            $authorizationHeader = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : null;

            // obtain tokenInfo from the "Authorization", this contains the
            // user_id the authorization is bound to, as well as some other
            // information, e.g. approved "scope"
            $tokenInfo = $bearerValidator->validate($authorizationHeader);

            // require both the "foo" and "bar" scope
            $tokenInfo->requireAllScope(['foo', 'bar']);
            // require any of "foo" or "bar" scope
            //$tokenInfo->requireAnyScope(['foo', 'bar']);

            // use "helper" JsonResponse here, typically your HTTP framework
            // will provide this...
            $jsonResponse = new JsonResponse(
                ['user_id' => $tokenInfo->getUserId()]
            );
            $jsonResponse->send();
            break;
        default:
            // typically your HTTP framework would take care of this, but here
            // in "plain" PHP we have to take care of it...
            $jsonResponse = new JsonResponse(
                ['error' => 'invalid_request', 'error_description' => 'Method Not Allowed'],
                ['Allow' => 'GET,HEAD'],
                405
            );
            $jsonResponse->send();
    }
} catch (OAuthException $e) {
    // the Exception contains an JsonResponse
    \error_log(\var_export($e->getJsonResponse(), true));
    $e->getJsonResponse()->send();
} catch (Exception $e) {
    // typically your HTTP framework would take care of this, but here
    // in "plain" PHP we have to take care of it... here we catch all
    // "internal server" errors
    $jsonResponse = new JsonResponse(
        ['error' => 'server_error', 'error_description' => $e->getMessage()],
        [],
        500
    );
    $jsonResponse->send();
}


text:
Please refer to https://github.com/UKForeignOffice/loi-application-service for setup instructions

## About

This repo complements the LOI Application Service by adding the ability to take payments provided by GOV.UK PAY

## Generating css

Run the following to convert sass to css if you are making any styling updates

```./node_modules/sass/sass.js --no-source-map ./sass/importer.scss ./public/importer.css```


text:
require "helper"

describe Google::Cloud::PubSub::Schema, :reference, :mock_pubsub do
  let(:schema_id) { "my-schema" }
  let(:schema) { Google::Cloud::PubSub::Schema.from_name schema_id, :FULL, pubsub.service }
  let(:message_data) { { "name" => "Alaska", "post_abbr" => "AK" }.to_json }
  let(:message_data_invalid) { { "BAD_VALUE" => nil }.to_json }
  let(:message_encoding) { :JSON }
  let(:definition) { "Schema definition" }

  it "knows its attributes" do
    _(schema.name).must_equal schema_path(schema_id)
    _(schema.type).must_be :nil?
    _(schema.definition).must_be :nil?
  end

  it "knows its view state" do
    _(schema).must_be :reference?
    _(schema).wont_be :resource?
    _(schema).wont_be :resource_partial?
    _(schema.resource_full?).must_equal false
  end

  it "validates a message" do
    mock = Minitest::Mock.new
    res = Google::Cloud::PubSub::V1::ValidateMessageResponse.new # always empty
    mock.expect :validate_message, res, parent: project_path, name: schema_path(schema_id), schema: nil, message: message_data, encoding: message_encoding.to_s
    pubsub.service.mocked_schemas = mock

    _(schema.validate_message message_data, message_encoding).must_equal true

    mock.verify
  end

  it "validates an invalid message" do
    stub = Object.new
    def stub.validate_message *args
      raise Google::Cloud::InvalidArgumentError.new("Request contains an invalid argument.")
    end
    pubsub.service.mocked_schemas = stub

    _(schema.validate_message message_data, message_encoding).must_equal false
  end

  it "deletes itself" do
    mock = Minitest::Mock.new
    mock.expect :delete_schema, nil, name: schema_path(schema_id)
    pubsub.service.mocked_schemas = mock

    schema.delete

    mock.verify
  end

  it "reloads itself" do
    get_res = Google::Cloud::PubSub::V1::Schema.new schema_hash(schema_id)
    mock = Minitest::Mock.new
    mock.expect :get_schema, get_res, name: schema_path(schema_id), view: 2
    pubsub.service.mocked_schemas = mock

    schema.reload!

    _(schema).wont_be :reference?
    _(schema).must_be :resource?
    _(schema).wont_be :resource_partial?
    _(schema).must_be :resource_full?

    mock.verify
  end

  it "reloads itself with view option" do
    get_res = Google::Cloud::PubSub::V1::Schema.new schema_hash(schema_id, definition: nil)
    mock = Minitest::Mock.new
    mock.expect :get_schema, get_res, name: schema_path(schema_id), view: 1
    pubsub.service.mocked_schemas = mock

    schema.reload! view: :basic

    _(schema).wont_be :reference?
    _(schema).must_be :resource?
    _(schema.resource_partial?).must_equal true
    _(schema.resource_full?).must_equal false

    mock.verify
  end

  it "checks if it exists with RPC" do
    get_res = Google::Cloud::PubSub::V1::Schema.new schema_hash(schema_id, definition: definition)
    mock = Minitest::Mock.new
    mock.expect :get_schema, get_res, name: schema_path(schema_id), view: 2
    pubsub.service.mocked_schemas = mock

    _(schema.exists?).must_equal true

    _(schema).wont_be :reference?
    _(schema).must_be :resource?
    _(schema.resource_partial?).must_equal false
    _(schema.resource_full?).must_equal true

    mock.verify
  end
end


text:
from typing import Dict, Union, Optional

from google.cloud.aiplatform.metadata import constants
from google.cloud.aiplatform.metadata.artifact import _Artifact
from google.cloud.aiplatform.metadata.context import _Context
from google.cloud.aiplatform.metadata.execution import _Execution
from google.cloud.aiplatform.metadata.metadata_store import _MetadataStore

class _MetadataService:
    """Contains the exposed APIs to interact with the Managed Metadata Service."""

    def __init__(self):
        self._experiment = None
        self._run = None
        self._metrics = None

    def reset(self):
        """Reset all _MetadataService fields to None"""
        self._experiment = None
        self._run = None
        self._metrics = None

    @property
    def experiment_name(self) -> Optional[str]:
        """Return the experiment name of the _MetadataService, if experiment is not set, return None"""
        if self._experiment:
            return self._experiment.display_name
        return None

    @property
    def run_name(self) -> Optional[str]:
        """Return the run name of the _MetadataService, if run is not set, return None"""
        if self._run:
            return self._run.display_name
        return None

    def set_experiment(self, experiment: str, description: Optional[str] = None):
        """Setup a experiment to current session.

        Args:
            experiment (str):
                Required. Name of the experiment to assign current session with.
            description (str):
                Optional. Description of an experiment.
        """

        _MetadataStore.get_or_create()
        context = _Context.get_or_create(
            resource_id=experiment,
            display_name=experiment,
            description=description,
            schema_title=constants.SYSTEM_EXPERIMENT,
            schema_version=constants.SCHEMA_VERSIONS[constants.SYSTEM_EXPERIMENT],
            metadata=constants.EXPERIMENT_METADATA,
        )
        if context.schema_title != constants.SYSTEM_EXPERIMENT:
            raise ValueError(
                f"Experiment name {experiment} has been used to create other type of resources "
                f"({context.schema_title}) in this MetadataStore, please choose a different experiment name."
            )

        if description and context.description != description:
            context.update(metadata=context.metadata, description=description)

        self._experiment = context

    def start_run(self, run: str):
        """Setup a run to current session.

        Args:
            run (str):
                Required. Name of the run to assign current session with.
        Raise:
            ValueError if experiment is not set. Or if run execution or metrics artifact
            is already created but with a different schema.
        """

        if not self._experiment:
            raise ValueError(
                "No experiment set for this run. Make sure to call aiplatform.init(experiment='my-experiment') "
                "before trying to start_run. "
            )
        run_execution_id = f"{self._experiment.name}-{run}"
        run_execution = _Execution.get_or_create(
            resource_id=run_execution_id,
            display_name=run,
            schema_title=constants.SYSTEM_RUN,
            schema_version=constants.SCHEMA_VERSIONS[constants.SYSTEM_RUN],
        )
        if run_execution.schema_title != constants.SYSTEM_RUN:
            raise ValueError(
                f"Run name {run} has been used to create other type of resources ({run_execution.schema_title}) "
                "in this MetadataStore, please choose a different run name."
            )
        self._experiment.add_artifacts_and_executions(
            execution_resource_names=[run_execution.resource_name]
        )

        metrics_artifact_id = f"{self._experiment.name}-{run}-metrics"
        metrics_artifact = _Artifact.get_or_create(
            resource_id=metrics_artifact_id,
            display_name=metrics_artifact_id,
            schema_title=constants.SYSTEM_METRICS,
            schema_version=constants.SCHEMA_VERSIONS[constants.SYSTEM_METRICS],
        )
        if metrics_artifact.schema_title != constants.SYSTEM_METRICS:
            raise ValueError(
                f"Run name {run} has been used to create other type of resources ({metrics_artifact.schema_title}) "
                "in this MetadataStore, please choose a different run name."
            )
        run_execution.add_artifact(
            artifact_resource_name=metrics_artifact.resource_name, input=False
        )

        self._run = run_execution
        self._metrics = metrics_artifact

    def log_params(self, params: Dict[str, Union[float, int, str]]):
        """Log single or multiple parameters with specified key and value pairs.

        Args:
            params (Dict):
                Required. Parameter key/value pairs.
        """

        self._validate_experiment_and_run(method_name="log_params")
        # query the latest run execution resource before logging.
        execution = _Execution.get_or_create(
            resource_id=self._run.name,
            schema_title=constants.SYSTEM_RUN,
            schema_version=constants.SCHEMA_VERSIONS[constants.SYSTEM_RUN],
        )
        execution.update(metadata=params)

    def log_metrics(self, metrics: Dict[str, Union[float, int]]):
        """Log single or multiple Metrics with specified key and value pairs.

        Args:
            metrics (Dict):
                Required. Metrics key/value pairs. Only flot and int are supported format for value.
        Raises:
            TypeError if value contains unsupported types.
            ValueError if Experiment or Run is not set.
        """

        self._validate_experiment_and_run(method_name="log_metrics")
        self._validate_metrics_value_type(metrics)
        # query the latest metrics artifact resource before logging.
        artifact = _Artifact.get_or_create(
            resource_id=self._metrics.name,
            schema_title=constants.SYSTEM_METRICS,
            schema_version=constants.SCHEMA_VERSIONS[constants.SYSTEM_METRICS],
        )
        artifact.update(metadata=metrics)

    def get_experiment_df(
        self, experiment: Optional[str] = None
    ) -> "pd.DataFrame":  # noqa: F821
        """Returns a Pandas DataFrame of the parameters and metrics associated with one experiment.

            Example:

            aiplatform.init(experiment='exp-1')
            aiplatform.start_run(run='run-1')
            aiplatform.log_params({'learning_rate': 0.1})
            aiplatform.log_metrics({'accuracy': 0.9})

            aiplatform.start_run(run='run-2')
            aiplatform.log_params({'learning_rate': 0.2})
            aiplatform.log_metrics({'accuracy': 0.95})

            Will result in the following DataFrame
            ___________________________________________________________________________
            | experiment_name | run_name      | param.learning_rate | metric.accuracy |
            ---------------------------------------------------------------------------
            | exp-1           | run-1         | 0.1                 | 0.9             |
            | exp-1           | run-2         | 0.2                 | 0.95            |
            ---------------------------------------------------------------------------

            Args:
                experiment (str):
                Name of the Experiment to filter results. If not set, return results of current active experiment.

            Returns:
                Pandas Dataframe of Experiment with metrics and parameters.

            Raise:
                NotFound exception if experiment does not exist.
                ValueError if given experiment is not associated with a wrong schema.
            """

        if not experiment:
            experiment = self._experiment.name

        source = "experiment"
        experiment_resource_name = self._get_experiment_or_pipeline_resource_name(
            name=experiment, source=source, expected_schema=constants.SYSTEM_EXPERIMENT,
        )

        return self._query_runs_to_data_frame(
            context_id=experiment,
            context_resource_name=experiment_resource_name,
            source=source,
        )

    def get_pipeline_df(self, pipeline: str) -> "pd.DataFrame":  # noqa: F821
        """Returns a Pandas DataFrame of the parameters and metrics associated with one pipeline.

        Args:
            pipeline: Name of the Pipeline to filter results.

        Returns:
            Pandas Dataframe of Pipeline with metrics and parameters.

        Raise:
            NotFound exception if experiment does not exist.
            ValueError if given experiment is not associated with a wrong schema.
        """

        source = "pipeline"
        pipeline_resource_name = self._get_experiment_or_pipeline_resource_name(
            name=pipeline, source=source, expected_schema=constants.SYSTEM_PIPELINE
        )

        return self._query_runs_to_data_frame(
            context_id=pipeline,
            context_resource_name=pipeline_resource_name,
            source=source,
        )

    def _validate_experiment_and_run(self, method_name: str):
        if not self._experiment:
            raise ValueError(
                f"No experiment set. Make sure to call aiplatform.init(experiment='my-experiment') "
                f"before trying to {method_name}. "
            )
        if not self._run:
            raise ValueError(
                f"No run set. Make sure to call aiplatform.start_run('my-run') before trying to {method_name}. "
            )

    @staticmethod
    def _validate_metrics_value_type(metrics: Dict[str, Union[float, int]]):
        """Verify that metrics value are with supported types.

        Args:
            metrics (Dict):
                Required. Metrics key/value pairs. Only flot and int are supported format for value.
        Raises:
            TypeError if value contains unsupported types.
        """

        for key, value in metrics.items():
            if isinstance(value, int) or isinstance(value, float):
                continue
            raise TypeError(
                f"metrics contain unsupported value types. key: {key}; value: {value}; type: {type(value)}"
            )

    @staticmethod
    def _get_experiment_or_pipeline_resource_name(
        name: str, source: str, expected_schema: str
    ) -> str:
        """Get the full resource name of the Context representing an Experiment or Pipeline.

        Args:
            name (str):
                Name of the Experiment or Pipeline.
            source (str):
                Identify whether the this is an Experiment or a Pipeline.
            expected_schema (str):
                expected_schema identifies the expected schema used for Experiment or Pipeline.

        Returns:
            The full resource name of the Experiment or Pipeline Context.

        Raise:
            NotFound exception if experiment or pipeline does not exist.
        """

        context = _Context(resource_name=name)

        if context.schema_title != expected_schema:
            raise ValueError(
                f"Please provide a valid {source} name. {name} is not a {source}."
            )
        return context.resource_name

    def _query_runs_to_data_frame(
        self, context_id: str, context_resource_name: str, source: str
    ) -> "pd.DataFrame":  # noqa: F821
        """Get metrics and parameters associated with a given Context into a Dataframe.

        Args:
            context_id (str):
                Name of the Experiment or Pipeline.
            context_resource_name (str):
                Full resource name of the Context associated with an Experiment or Pipeline.
            source (str):
                Identify whether the this is an Experiment or a Pipeline.

        Returns:
            The full resource name of the Experiment or Pipeline Context.
        """

        filter = f'schema_title="{constants.SYSTEM_RUN}" AND in_context("{context_resource_name}")'
        run_executions = _Execution.list(filter=filter)

        context_summary = []
        for run_execution in run_executions:
            run_dict = {
                f"{source}_name": context_id,
                "run_name": run_execution.display_name,
            }
            run_dict.update(
                self._execution_to_column_named_metadata(
                    "param", run_execution.metadata
                )
            )

            for metric_artifact in run_execution.query_input_and_output_artifacts():
                run_dict.update(
                    self._execution_to_column_named_metadata(
                        "metric", metric_artifact.metadata
                    )
                )

            context_summary.append(run_dict)

        try:
            import pandas as pd
        except ImportError:
            raise ImportError(
                "Pandas is not installed and is required to get dataframe as the return format. "
                'Please install the SDK using "pip install python-aiplatform[full]"'
            )

        return pd.DataFrame(context_summary)

    @staticmethod
    def _execution_to_column_named_metadata(
        metadata_type: str, metadata: Dict,
    ) -> Dict[str, Union[int, float, str]]:
        """Returns a dict of the Execution/Artifact metadata with column names.

        Args:
          metadata_type: The type of this execution properties (param, metric).
          metadata: Either an Execution or Artifact metadata field.

        Returns:
          Dict of custom properties with keys mapped to column names
        """

        return {
            ".".join([metadata_type, key]): value for key, value in metadata.items()
        }

metadata_service = _MetadataService()


text:
<?php

namespace Solve\Slot\Blocks;

/**
 * Class ElseBlock
 * @package Solve\Slot\Blocks
 *
 * @version 1.0
 * @author Alexandr Viniychuk <alexandr.viniychuk@icloud.com>
 */
class ElseBlock extends BaseBlock {

    public function processBlockStart() {
        return '<?php else: ?>';
    }
}


text:
.owl-carousel .owl-wrapper:after{content:".";display:block;clear:both;visibility:hidden;line-height:0;height:0;}
.owl-carousel{display:none;position:relative;width:100%;-ms-touch-action:pan-y;}
.owl-carousel .owl-wrapper{display:none;position:relative;-webkit-transform:translate3d(0px, 0px, 0px);}
.owl-carousel .owl-wrapper-outer{overflow:hidden;position:relative;width:100%;}
.owl-carousel .owl-wrapper-outer.autoHeight{-webkit-transition:height 500ms ease-in-out;-moz-transition:height 500ms ease-in-out;-ms-transition:height 500ms ease-in-out;-o-transition:height 500ms ease-in-out;transition:height 500ms ease-in-out;}
.owl-carousel .owl-item{float:left;}
.owl-controls .owl-page,
.owl-controls .owl-buttons div{cursor:pointer;}
.owl-controls{-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-tap-highlight-color:rgba(0, 0, 0, 0);}
.grabbing{cursor:url(grabbing.png) 8 8, move;}
.owl-carousel .owl-wrapper,
.owl-carousel .owl-item{-webkit-backface-visibility:hidden;-moz-backface-visibility:hidden;-ms-backface-visibility:hidden;-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);-ms-transform:translate3d(0,0,0);}
/**//**//**/.owl-theme .owl-controls{margin-top:10px;text-align:center;}
.owl-theme .owl-controls .owl-buttons div{color:#FFF;display:inline-block;zoom:1;*display:inline;margin:5px;padding:3px 10px;font-size:12px;-webkit-border-radius:30px;-moz-border-radius:30px;border-radius:30px;background:#869791;filter:Alpha(Opacity=50);opacity:0.5;}
.owl-theme .owl-controls.clickable .owl-buttons div:hover{filter:Alpha(Opacity=100);opacity:1;text-decoration:none;}
.owl-theme .owl-controls .owl-page{display:inline-block;zoom:1;*display:inline;}
.owl-theme .owl-controls .owl-page span{display:block;width:12px;height:12px;margin:5px 7px;filter:Alpha(Opacity=50);opacity:0.5;-webkit-border-radius:20px;-moz-border-radius:20px;border-radius:20px;background:#869791;}
.owl-theme .owl-controls .owl-page.active span,
.owl-theme .owl-controls.clickable .owl-page:hover span{filter:Alpha(Opacity=100);opacity:1;}
.owl-theme .owl-controls .owl-page span.owl-numbers{height:auto;width:auto;color:#FFF;padding:2px 10px;font-size:12px;-webkit-border-radius:30px;-moz-border-radius:30px;border-radius:30px;}
.owl-item.loading{min-height:150px;background:url(AjaxLoader.gif) no-repeat center center}
/**//**//**/.owl-origin{-webkit-perspective:1200px;-webkit-perspective-origin-x:50%;-webkit-perspective-origin-y:50%;-moz-perspective:1200px;-moz-perspective-origin-x:50%;-moz-perspective-origin-y:50%;perspective:1200px;}
.owl-fade-out{z-index:10;-webkit-animation:fadeOut .7s both ease;-moz-animation:fadeOut .7s both ease;animation:fadeOut .7s both ease;}
.owl-fade-in{-webkit-animation:fadeIn .7s both ease;-moz-animation:fadeIn .7s both ease;animation:fadeIn .7s both ease;}
.owl-backSlide-out{-webkit-animation:backSlideOut 1s both ease;-moz-animation:backSlideOut 1s both ease;animation:backSlideOut 1s both ease;}
.owl-backSlide-in{-webkit-animation:backSlideIn 1s both ease;-moz-animation:backSlideIn 1s both ease;animation:backSlideIn 1s both ease;}
.owl-goDown-out{-webkit-animation:scaleToFade .7s ease both;-moz-animation:scaleToFade .7s ease both;animation:scaleToFade .7s ease both;}
.owl-goDown-in{-webkit-animation:goDown .6s ease both;-moz-animation:goDown .6s ease both;animation:goDown .6s ease both;}
.owl-fadeUp-in{-webkit-animation:scaleUpFrom .5s ease both;-moz-animation:scaleUpFrom .5s ease both;animation:scaleUpFrom .5s ease both;}
.owl-fadeUp-out{-webkit-animation:scaleUpTo .5s ease both;-moz-animation:scaleUpTo .5s ease both;animation:scaleUpTo .5s ease both;}
@-webkit-keyframes empty{0%{opacity:1}
}
@-moz-keyframes empty{0%{opacity:1}
}
@keyframes empty{0%{opacity:1}
}
@-webkit-keyframes fadeIn{0%{opacity:0;}
100%{opacity:1;}
}
@-moz-keyframes fadeIn{0%{opacity:0;}
100%{opacity:1;}
}
@keyframes fadeIn{0%{opacity:0;}
100%{opacity:1;}
}
@-webkit-keyframes fadeOut{0%{opacity:1;}
100%{opacity:0;}
}
@-moz-keyframes fadeOut{0%{opacity:1;}
100%{opacity:0;}
}
@keyframes fadeOut{0%{opacity:1;}
100%{opacity:0;}
}
@-webkit-keyframes backSlideOut{25%{opacity:.5;-webkit-transform:translateZ(-500px);}
75%{opacity:.5;-webkit-transform:translateZ(-500px) translateX(-200%);}
100%{opacity:.5;-webkit-transform:translateZ(-500px) translateX(-200%);}
}
@-moz-keyframes backSlideOut{25%{opacity:.5;-moz-transform:translateZ(-500px);}
75%{opacity:.5;-moz-transform:translateZ(-500px) translateX(-200%);}
100%{opacity:.5;-moz-transform:translateZ(-500px) translateX(-200%);}
}
@keyframes backSlideOut{25%{opacity:.5;transform:translateZ(-500px);}
75%{opacity:.5;transform:translateZ(-500px) translateX(-200%);}
100%{opacity:.5;transform:translateZ(-500px) translateX(-200%);}
}
@-webkit-keyframes backSlideIn{0%, 25%{opacity:.5;-webkit-transform:translateZ(-500px) translateX(200%);}
75%{opacity:.5;-webkit-transform:translateZ(-500px);}
100%{opacity:1;-webkit-transform:translateZ(0) translateX(0);}
}
@-moz-keyframes backSlideIn{0%, 25%{opacity:.5;-moz-transform:translateZ(-500px) translateX(200%);}
75%{opacity:.5;-moz-transform:translateZ(-500px);}
100%{opacity:1;-moz-transform:translateZ(0) translateX(0);}
}
@keyframes backSlideIn{0%, 25%{opacity:.5;transform:translateZ(-500px) translateX(200%);}
75%{opacity:.5;transform:translateZ(-500px);}
100%{opacity:1;transform:translateZ(0) translateX(0);}
}
@-webkit-keyframes scaleToFade{to{opacity:0;-webkit-transform:scale(.8);}
}
@-moz-keyframes scaleToFade{to{opacity:0;-moz-transform:scale(.8);}
}
@keyframes scaleToFade{to{opacity:0;transform:scale(.8);}
}
@-webkit-keyframes goDown{from{-webkit-transform:translateY(-100%);}
}
@-moz-keyframes goDown{from{-moz-transform:translateY(-100%);}
}
@keyframes goDown{from{transform:translateY(-100%);}
}
@-webkit-keyframes scaleUpFrom{from{opacity:0;-webkit-transform:scale(1.5);}
}
@-moz-keyframes scaleUpFrom{from{opacity:0;-moz-transform:scale(1.5);}
}
@keyframes scaleUpFrom{from{opacity:0;transform:scale(1.5);}
}
@-webkit-keyframes scaleUpTo{to{opacity:0;-webkit-transform:scale(1.5);}
}
@-moz-keyframes scaleUpTo{to{opacity:0;-moz-transform:scale(1.5);}
}
@keyframes scaleUpTo{to{opacity:0;transform:scale(1.5);}
}


text:
from setuptools import setup, find_packages

setup(name='aws-es-connection',
      version='0.2',
      description='Python Elasticsearch Client connection class for AWS Elasticsearch Service',
      author='Scott VanDenPlas',
      author_email='scott@elelsee.com',
      url='https://github.com/elelsee/aws-es-connection',
      packages=find_packages(),
      py_modules=['awses'],
      install_requires=['boto', 'elasticsearch'])


text:
RSpec.describe "path sources" do
  describe "bundle update --source" do
    it "shows the previous version of the gem when updated from path source" do
      build_lib "activesupport", "2.3.5", :path => lib_path("rails/activesupport")

      install_gemfile <<-G
      gem "activesupport", :path => "#{lib_path("rails/activesupport")}"
      G

      build_lib "activesupport", "3.0", :path => lib_path("rails/activesupport")

      bundle "update --source activesupport"
      expect(out).to include("Using activesupport 3.0 (was 2.3.5) from source at `#{lib_path("rails/activesupport")}`")
    end
  end
end


text:
package com.ibm.actor.test;

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.sound.midi.Instrument;
import javax.sound.midi.MidiChannel;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.Soundbank;
import javax.sound.midi.Synthesizer;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import com.ibm.actor.AbstractActor;
import com.ibm.actor.Actor;
import com.ibm.actor.DefaultActorManager;
import com.ibm.actor.DefaultActorManager.ActorRunnable;
import com.ibm.actor.DefaultMessage;
import com.ibm.actor.Message;
import com.ibm.actor.logging.DefaultLogger;
import com.ibm.actor.utils.Utils;

/**
 * A GUI for running and visualizing Actors.
 * The implementation of this GUI is not discussed in this associated article.
 *
 * @author BFEIGENB
 *
 */
public class ActorDemo extends JPanel implements ChangeListener {
	// TODO: move to new package once imports/publics sorted out

	public static final int METER_HEIGHT = 50;
	public static final int METER_WIDTH = 300;
	public static final int VIEWPORT_WIDTH = 500;
	public static final int VIEWPORT_HEIGHT = 400;

	DefaultActorManager actorManager;

	protected JLabel messageLine, titleLine;
	// protected JTextField optionsField;
	protected JComboBox demosBox;
	protected JButton runButton, stopButton, nextButton, randomizeButton, addTaskButton, removeTaskButton;
	protected JSplitPane splitPane;
	protected JSlider stepSlider;
	protected JLabel stepLabel, threadCountLabel;
	protected JCheckBox transparentCheckBox;
	protected JTextArea logArea;
	protected JSpinner threadCounter;

	protected JRadioButton noSoundButton, soundWhenIdleButton, soundWhenBusyButton;

	protected Sequencer sequencer;
	protected Sequence sequence;
	protected Synthesizer synthesizer;
	protected Instrument instruments[];

	public Instrument[] getInstruments() {
		return instruments;
	}

	protected int currentChannel;

	public int getCurrentChannel() {
		return currentChannel;
	}

	public void setCurrentChannel(int currentChannel) {
		this.currentChannel = currentChannel;
	}

	public void startNote(int note, int attack) {
		if (isMidiOpen()) {
			midiChannels[currentChannel].noteOn(note, attack);
		}
	}

	public void stopNote(int note, int attack) {
		if (isMidiOpen()) {
			midiChannels[currentChannel].noteOff(note, attack);
		}
	}

	public void stopAllNotes() {
		if (isMidiOpen()) {
			midiChannels[currentChannel].allNotesOff();
		}
	}

	MidiChannel[] midiChannels;

	public MidiChannel[] getMidiChannels() {
		return midiChannels;
	}

	public boolean isMidiOpen() {
		return synthesizer != null && synthesizer.isOpen();
	}

	public void setupMidi() throws Exception {
		synthesizer = MidiSystem.getSynthesizer();
		synthesizer.open();
		midiChannels = synthesizer.getChannels();
		sequencer = MidiSystem.getSequencer();
		sequence = new Sequence(Sequence.PPQ, 10);
		Soundbank sb = synthesizer.getDefaultSoundbank();
		if (sb != null) {
			instruments = synthesizer.getDefaultSoundbank().getInstruments();
			for (int i = 0; i < instruments.length; i++) {
				System.out.printf("%4d: %s%n", i, instruments[i]);
			}
			if (instruments.length > 0) {
				synthesizer.loadInstrument(instruments[0]);
				midiChannels[currentChannel].programChange(0);
			}
			if (instruments.length > 14) {
				synthesizer.loadInstrument(instruments[14]);
				midiChannels[currentChannel].programChange(14);
			}
		}
	}

	public void shutdownMidi() {
		if (synthesizer != null) {
			synthesizer.close();
		}
		if (sequencer != null) {
			sequencer.close();
		}
		sequencer = null;
		synthesizer = null;
		instruments = null;
	}

	public void initUI(JFrame frame) {
		JPanel cp = (JPanel) frame.getContentPane();
		cp.setLayout(new BorderLayout(5, 5));

		splitPane = new JSplitPane();
		cp.add(splitPane, BorderLayout.CENTER);

		JPanel main = new JPanel(new BorderLayout(5, 5));
		splitPane.setLeftComponent(main);

		JPanel topPanel = new JPanel();
		main.add(topPanel, BorderLayout.NORTH);
		buildTopPanel(topPanel);

		JPanel bottomPanel = new JPanel();
		main.add(bottomPanel, BorderLayout.SOUTH);
		buildBottomPanel(bottomPanel);

		logArea = new JTextArea();
		logArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
		splitPane.setRightComponent(new JScrollPane(logArea));
		DefaultLogger.getDefaultInstance().setIncludeCaller(false);
		DefaultLogger.getDefaultInstance().setLogToFile(false);
		DefaultLogger.getDefaultInstance().setLogArea(logArea);
	}

	protected void buildTopPanel(JPanel inputs) {
		inputs.setBorder(new EmptyBorder(5, 5, 5, 5));
		GridBagLayout gbl = new GridBagLayout();
		inputs.setLayout(gbl);
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.insets = new Insets(1, 2, 1, 2);

		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.gridwidth = 2;
		gbc.gridheight = 1;
		titleLine = new JLabel("Nothing selected");
		titleLine.setHorizontalAlignment(JLabel.CENTER);
		inputs.add(titleLine, gbc);

		gbc.gridx = 0;
		gbc.gridy = 1;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weightx = 1;
		// optionsField = new JTextField(50);
		// optionsField.setText("pc");
		// inputs.add(optionsField, gbc);
		String[] testNames = DefaultActorTest.getTestNames();
		String[] xtestNames = new String[testNames.length + 1];
		System.arraycopy(testNames, 0, xtestNames, 0, testNames.length);
		xtestNames[testNames.length] = "All demos in sequence";
		demosBox = new JComboBox(xtestNames);
		inputs.add(demosBox, gbc);
		demosBox.setSelectedIndex(demosBox.getItemCount() - 1);

		gbc.gridx = 0;
		gbc.gridy = 2;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		final int maxSends = 50;
		sendRateBar = new JProgressBar(JProgressBar.HORIZONTAL, 0, maxSends);
		sendRateBar.setBackground(Color.LIGHT_GRAY.brighter());
		sendRateBar.setStringPainted(true);
		sendRateBar.addChangeListener(new ChangeListener() {
			@Override
			public void stateChanged(ChangeEvent e) {
				int value = sendRateBar.getValue();
				sendRateBar.setString(String
						.format(value > maxSends - 1 ? (">=" + maxSends + " mps") : "%d mps", value));
			}
		});
		inputs.add(sendRateBar, gbc);

		gbc.gridx = 0;
		gbc.gridy = 3;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		final int maxThreads = 50; // actorManager.getThreads().length * 2;
		dispatchRateBar = new JProgressBar(JProgressBar.HORIZONTAL, 0, maxThreads);
		dispatchRateBar.setBackground(Color.LIGHT_GRAY.brighter());
		dispatchRateBar.setStringPainted(true);
		dispatchRateBar.addChangeListener(new ChangeListener() {
			@Override
			public void stateChanged(ChangeEvent e) {
				int value = dispatchRateBar.getValue();
				dispatchRateBar.setString(String.format(value > maxThreads - 1 ? (">=" + maxThreads + " cps")
						: "%d dps", value));
			}
		});
		inputs.add(dispatchRateBar, gbc);

		gbc.gridx = 0;
		gbc.gridy = 4;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.fill = GridBagConstraints.BOTH;
		trendLineView = new ImageView();
		trendLineView.setPreferredSize(new Dimension(METER_WIDTH, METER_HEIGHT));
		inputs.add(trendLineView, gbc);

		gbc.gridx = 1;
		gbc.gridy = 4;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weightx = 0.30;
		stepSlider = new JSlider(4, 9, 8);
		stepSlider.setMajorTickSpacing(1);
		stepSlider.setPaintLabels(true);
		stepSlider.addChangeListener(new ChangeListener() {
			@Override
			public void stateChanged(ChangeEvent e) {
				stepLabel.setText(formatSteps());
			}
		});
		inputs.add(stepSlider, gbc);

		gbc.gridx = 2;
		gbc.gridy = 4;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weightx = 0.15;
		stepLabel = new JLabel("", JLabel.RIGHT);
		stepLabel.setText(formatSteps());
		inputs.add(stepLabel, gbc);

		gbc.gridx = 1;
		gbc.gridy = 1;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weightx = 0.15;
		runButton = new JButton("Start");
		inputs.add(runButton, gbc);
		runButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				doStart();
				doRun();
			}
		});

		gbc.gridx = 2;
		gbc.gridy = 1;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weightx = 0.15;
		stopButton = new JButton("Stop");
		stopButton.setEnabled(false);
		inputs.add(stopButton, gbc);
		stopButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				doStop();
				messageLine.setText("Stopped");
				stopButton.setEnabled(false);
				runButton.setEnabled(true);
			}
		});

		gbc.gridx = 1;
		gbc.gridy = 2;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weightx = 0.15;
		randomizeButton = new JButton("Redistribute");
		inputs.add(randomizeButton, gbc);
		randomizeButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (actorManager != null) {
					actorManager.randomizeActors();
				}
			}
		});

		gbc.gridx = 1;
		gbc.gridy = 3;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weightx = 0.15;
		addTaskButton = new JButton("Add Task");
		inputs.add(addTaskButton, gbc);
		addTaskButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (actorManager != null) {
					Thread t = actorManager.addThread("new" + taskId++);
					t.start();
				}
			}
		});

		gbc.gridx = 2;
		gbc.gridy = 3;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weightx = 0.15;
		removeTaskButton = new JButton("Remove Task");
		inputs.add(removeTaskButton, gbc);
		removeTaskButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (actorManager != null) {
					Thread[] ta = actorManager.getThreads();
					for (Thread t : ta) {
						if (t.getName().startsWith("new")) {
							actorManager.removeThread(t.getName());
							break;
						}
					}
				}
			}
		});

		gbc.gridx = 1;
		gbc.gridy = 5;
		gbc.gridwidth = 2;
		gbc.gridheight = 1;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weightx = 0.30;
		transparentCheckBox = new JCheckBox("Transparent Actors");
		transparentCheckBox.setSelected(true);
		transparentCheckBox.addChangeListener(new ChangeListener() {

			@Override
			public void stateChanged(ChangeEvent e) {
				isTransparentActors = transparentCheckBox.isSelected();
			}
		});
		inputs.add(transparentCheckBox, gbc);

		gbc.gridx = 0;
		gbc.gridy = 6;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		//gbc.weightx = 0.15;
		ButtonGroup bg = new ButtonGroup();
		JPanel soundPanel = new JPanel();
		noSoundButton = new JRadioButton("No Sound");
		soundPanel.add(noSoundButton);
		bg.add(noSoundButton);
		soundWhenIdleButton = new JRadioButton("Idle");
		soundPanel.add(soundWhenIdleButton);
		bg.add(soundWhenIdleButton);
		soundWhenBusyButton = new JRadioButton("Busy");
		soundPanel.add(soundWhenBusyButton);
		bg.add(soundWhenBusyButton);
		noSoundButton.setSelected(true);
		inputs.add(soundPanel, gbc);

		gbc.gridx = 1;
		gbc.gridy = 6;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weightx = 0.15;
		SpinnerNumberModel model = new SpinnerNumberModel(10, 2, 25, 1);
		threadCounter = new JSpinner(model);
		threadCounter.addChangeListener(new ChangeListener() {

			@Override
			public void stateChanged(ChangeEvent e) {
				threadCount = (Integer) threadCounter.getValue();
			}
		});
		inputs.add(threadCounter, gbc);

		gbc.gridx = 2;
		gbc.gridy = 6;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weightx = 0.15;
		threadCountLabel = new JLabel("Thread Count", JLabel.RIGHT);
		inputs.add(threadCountLabel, gbc);

	}

	protected int threadCount = 10;

	protected int taskId;

	protected boolean isTransparentActors = true;

	protected JProgressBar sendRateBar, dispatchRateBar;

	private String formatSteps() {
		return String.format("%d steps", (int) Math.pow(2, stepSlider.getValue()));
	}

	protected ImageView trendLineView;

	protected ImageView threadHistoryView;

	protected ImageView mainActorView;
	protected ImageView[] subActorViews;
	protected final int subActorViewCount = 5;

	protected void buildBottomPanel(JPanel views) {
		views.setLayout(new BorderLayout(5, 5));

		JPanel mp = new JPanel(new BorderLayout(5, 5));
		views.add(mp, BorderLayout.CENTER);

		threadHistoryView = new ImageView();
		threadHistoryView.setPreferredSize(new Dimension(VIEWPORT_WIDTH, VIEWPORT_HEIGHT / 5));
		mp.add(threadHistoryView, BorderLayout.NORTH);

		mainActorView = new ImageView();
		mainActorView.setPreferredSize(new Dimension(VIEWPORT_WIDTH, VIEWPORT_HEIGHT));
		mp.add(mainActorView, BorderLayout.CENTER);

		JPanel gp = new JPanel(new GridLayout(0, subActorViewCount, 5, 5));
		mp.add(gp, BorderLayout.SOUTH);
		subActorViews = new ImageView[subActorViewCount];
		for (int i = 0; i < subActorViewCount; i++) {
			ImageView av = new ImageView();
			subActorViews[i] = av;
			av.setPreferredSize(new Dimension((VIEWPORT_WIDTH - subActorViewCount * 5) / subActorViewCount,
					VIEWPORT_HEIGHT / 5));
			gp.add(av);
		}

		messageLine = new JLabel(" ");
		views.add(messageLine, BorderLayout.SOUTH);
	}

	protected String reduceName(String name) {
		return name.toLowerCase().replaceAll("\\s+", "");
	}

	protected void doRun() {
		runButton.setEnabled(false);
		// nextButton.setEnabled(true);
		stopButton.setEnabled(true);
		logArea.setText("");
		logArea.setCaretPosition(0);
		// final String[] args = optionsField.getText().split("\\s+");
		int selectedIndex = demosBox.getSelectedIndex();
		if (selectedIndex >= 0) {
			// mySize = getSize();

			setTitle((String) demosBox.getSelectedItem());
			final String args = selectedIndex < demosBox.getItemCount() - 1 ? reduceName(DefaultActorTest
					.getTestNames()[selectedIndex]) : "*";
			Thread t = new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						if ("*".equals(args)) {
							for (String name : DefaultActorTest.getTestNames()) {
								doStart();
								setTitle(name);
								runTest(reduceName(name));
								doStop();
								try {
									Thread.sleep(10 * 1000);
								} catch (InterruptedException e) {
									break;
								}
							}
						} else {
							doStart();
							runTest(args);
							doStop();
						}
					} finally {
						SwingUtilities.invokeLater(new Runnable() {
							public void run() {
								// TODO: make multiple runs possible
								// runButton.setEnabled(true);
								stopButton.setEnabled(false);
								runButton.setEnabled(true);
								messageLine.setText("Done");
							}
						});
					}
				}
			});
			t.setDaemon(true);
			t.start();
		}
	}

	protected void doStart() {
		if (updater != null) {
			updater.interrupt();
		}
		updater = new Thread(new UpdateRunnable());
		updating = true;
		updater.setDaemon(true);
		updater.start();
	}

	protected void doNext() {
		// TODO: finish
		doStop();
		runButton.setEnabled(false);
		// nextButton.setEnabled(true);
		stopButton.setEnabled(true);
		logArea.setText("");
		logArea.setCaretPosition(0);
		// final String[] args = optionsField.getText().split("\\s+");
		int selectedIndex = demosBox.getSelectedIndex();
		if (selectedIndex >= 0) {
			selectedIndex++;
			// mySize = getSize();

			setTitle((String) demosBox.getSelectedItem());
			final String args = selectedIndex < demosBox.getItemCount() - 1 ? reduceName(DefaultActorTest
					.getTestNames()[selectedIndex]) : "*";
			Thread t = new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						if ("*".equals(args)) {
							for (String name : DefaultActorTest.getTestNames()) {
								doStart();
								setTitle(name);
								runTest(reduceName(name));
								doStop();
								try {
									Thread.sleep(10 * 1000);
								} catch (InterruptedException e) {
									break;
								}
							}
						} else {
							doStart();
							runTest(args);
							doStop();
						}
					} finally {
						SwingUtilities.invokeLater(new Runnable() {
							public void run() {
								// TODO: make multiple runs possible
								// runButton.setEnabled(true);
								stopButton.setEnabled(false);
								runButton.setEnabled(true);
								messageLine.setText("Done");
							}
						});
					}
				}
			});
			t.setDaemon(true);
			t.start();
		}
	}

	protected void doStop() {
		test.terminateRun();
		updating = false;
	}

	public String getMessage() {
		final String[] res = new String[1];
		if (messageLine != null) {
			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					res[0] = messageLine.getText();
				}
			});
		}
		return res[0];
	}

	public void setMessage(final String message) {
		if (messageLine != null) {
			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					messageLine.setText(message != null ? message : "");
				}
			});
		}
	}

	public String getTitle() {
		final String[] res = new String[1];
		if (titleLine != null) {
			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					res[0] = titleLine.getText();
				}
			});
		}
		return res[0];
	}

	public void setTitle(final String message) {
		if (titleLine != null) {
			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					titleLine.setText(message != null ? message : "");
				}
			});
		}
	}

	// volatile Dimension mySize;

	volatile boolean updating;

	public static final int TIMES_PER_SECOND = 10;

	protected class UpdateRunnable implements Runnable {
		boolean inRun;
		@Override
		public void run() {
			if (inRun) {
				return;
			}
			inRun = true;
			actorColorMap.clear();
			int xiteration = 0;
			while (updating) {
				try {
					Utils.sleep(1000 / TIMES_PER_SECOND);
					if (xiteration % TIMES_PER_SECOND == 0) {
						updateRates();
					}
					if (xiteration % (5 * TIMES_PER_SECOND) == 0) {
						renderSnapshots();
					}

					ImageView avMain = mainActorView;
					BufferedImage bi = new BufferedImage(avMain.getWidth(), avMain.getHeight(),
							BufferedImage.TYPE_INT_ARGB);
					Graphics g = bi.getGraphics();
					renderTo(g, bi.getWidth(), bi.getHeight());
					avMain.setImage(bi);
					// System.out.printf("repaint: %s%n", renderImage1);
					SwingUtilities.invokeLater(new Runnable() {
						@Override
						public void run() {
							// System.out.printf("**** repaint%n");
							mainActorView.repaint();
							for (int i = 0; i < subActorViews.length; i++) {
								subActorViews[i].repaint();
							}
							threadHistoryView.repaint();
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
				}
				xiteration++;
			}
			updateRates();
			inRun = false;
		}

		protected void renderSnapshots() {
			// System.out.printf("**** UpdateRunnable run: %d %n",
			// xiteration);
			int last = subActorViews.length - 1;
			for (int i = 0; i < last; i++) {
				ImageView av = subActorViews[i];
				ImageView avNext = subActorViews[i + 1];
				BufferedImage bi = avNext.getImage();
				addTimeStamp(-(last - i + 1) * 5, bi);
				av.setImage(bi);
			}
			ImageView avLast = subActorViews[last];
			BufferedImage bi = new BufferedImage(avLast.getWidth(), avLast.getHeight(),
					BufferedImage.TYPE_INT_ARGB);
			Graphics g = bi.getGraphics();
			renderTo(g, bi.getWidth(), bi.getHeight());
			addTimeStamp(-5, bi);
			avLast.setImage(bi);
		}

		protected void updateRates() {
			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					int sendPerSecondCount = -1, dispatchPerSecondCount = -1;
					if (actorManager != null) {
						if (sendRateBar != null) {
							sendPerSecondCount = actorManager.getSendPerSecondCount();
							sendRateBar.setValue(sendPerSecondCount);
						}
						if (dispatchRateBar != null) {
							dispatchPerSecondCount = actorManager.getDispatchPerSecondCount();
							dispatchRateBar.setValue(dispatchPerSecondCount);
						}
						// System.out.printf("rates: sendPerSecondCount=%d, dispatchPerSecondCount=%d%n",
						// sendPerSecondCount, dispatchPerSecondCount);
						if (trendLineView != null) {
							trendLineView.setImage(renderTrendLine(actorManager.getTrendValue(),
									actorManager.getMaxTrendValue()));
						}
					}
				}
			});
		}

		protected void addTimeStamp(int delta, BufferedImage bi) {
			if (bi != null) {
				Graphics g = bi.getGraphics();
				g.setColor(Color.CYAN);
				g.fillRect(0, 0, 20, 15);
				g.setColor(Color.BLACK);
				g.drawString(String.format("%d", delta), 0, 14);
			}
		}
	}

	protected BufferedImage trendLineImage;

	public BufferedImage getTrendLineImage() {
		return trendLineImage;
	}

	protected Thread updater;

	protected static Random rand = new Random();

	// TOOD: need more contrast in colors.
	// may need to manually define the colors
	protected static List<Color> colors = new ArrayList<Color>();
	static {
		/*
		 * for (int r = 0; r < 3; r++) { for (int g = 0; g < 3; g++) { for (int
		 * b = 0; b < 3; b++) { // don't get too close to white Color c = new
		 * Color(128 + rand.nextInt(100), 128 + rand.nextInt(100), 128 +
		 * rand.nextInt(100)); if (!colors.contains(c)) { colors.add(c); } } } }
		 */
		int r = 0, g = 0, b = 0;
		for (int i = 0; colors.size() < 64 && i < 1000; i++) {
			Color c = new Color(Math.min(128, (150 + r) % 256), Math.min(128, (128 + g) % 256), Math.min(128,
					(128 + b) % 256)).brighter();
			int dist = Integer.MAX_VALUE;
			for (Color xc : colors) {
				int xdist = getColorDistance(xc, c);
				if (dist > xdist) {
					dist = xdist;
				}
			}
			if (dist > 25) {
				// Utils.logger.trace("adding color %d: %s", colors.size(), c);
				colors.add(c);
			} else {
				// Utils.logger.trace("skipping color %d: %s", colors.size(),
				// c);
			}
			r += 81;
			g += 11;
			b += 59;
		}
	}

	protected static int getColorDistance(Color c1, Color c2) {
		int r = Math.abs(c1.getRed() - c2.getRed());
		int g = Math.abs(c1.getGreen() - c2.getGreen());
		int b = Math.abs(c1.getBlue() - c2.getBlue());
		return r + g + b;
	}

	protected Map<String, Color> actorColorMap = new HashMap<String, Color>();

	int errorY;

	protected void initThreadHistory(Thread[] threads) {
		for (Thread t : threads) {
			String name = t.getName();
			ThreadHistory th = threadHistoryMap.get(name);
			if (th == null) {
				th = new ThreadHistory();
				threadHistoryMap.put(name, th);
			}
		}
	}

	protected void renderTo(Graphics g, int width, int height) {
		// System.out.printf("renderTo: %dx%d%n", width, height);
		Graphics2D g2d = (Graphics2D) g;
		errorY = 0;

		if (actorManager != null) {
			Font f = g2d.getFont();
			try {
				if (width < 200 || height < 200) {
					g2d.setFont(new Font(f.getFontName(), f.getSize(), f.getSize() / 2));
				}
				Set<Actor> selfSends = new HashSet<Actor>();
				AbstractActor[] actors = actorManager.getActors();
				Thread[] threads = actorManager.getThreads();
				initThreadHistory(threads);

				int base = Math.min(width, height);
				g2d.setBackground(Color.LIGHT_GRAY.brighter());
				g2d.fillRect(0, 0, width, height);

				int tdiam = base / 20;
				int tradius = (int) (base * 0.85) / 2;

				int adiam = base / 15;
				int aradius = (int) (base * 0.7) / 2;

				// TODO: move positioning from here to setSize();
				Map<String, AbstractActor> actorMap = new HashMap<String, AbstractActor>();
				Map<String, Integer> actorXMap = new HashMap<String, Integer>();
				Map<String, Integer> actorYMap = new HashMap<String, Integer>();
				Map<String, Integer> actorIdMap = new HashMap<String, Integer>();

				double angle = 0;

				int count = 0, acount = 0;
				for (AbstractActor aa : actors) {
					String cname = aa.getClass().getName();
					actorIdMap.put(aa.getName(), acount++);
					if (!actorColorMap.containsKey(cname)) {
						actorColorMap.put(cname, colors.get(rand.nextInt(colors.size())));
					}
					angle = renderMessageConnections(g2d, actors, height, width, aradius, adiam, actorMap, actorXMap,
							actorYMap, angle, aa, colors.get(count++ % colors.size()), selfSends);
				}

				renderActors(g2d, selfSends, actors, adiam, actorXMap, actorYMap, actorIdMap);

				renderHistories(width, height, g2d, threads, tdiam, tradius, actorIdMap);
			} catch (Exception e) {
				paintError("renderTo", g2d, e);
			} finally {
				g2d.setFont(f);
			}
		}
	}

	protected void renderHistories(int width, int height, Graphics2D g2d, Thread[] threads, int tdiam, int tradius,
			Map<String, Integer> actorIdMap) {
		double angle;
		List<ThreadHistory> histories = new ArrayList<ThreadHistory>();
		angle = 0;
		for (Thread t : threads) {
			String name = t.getName();
			angle = renderThread(g2d, threads, height, width, tdiam, tradius, angle, t, actorIdMap);
			ThreadHistory th = threadHistoryMap.get(name);
			if (th != null) {
				th.setLast(name);
				histories.add(th);
			}
		}
		renderHistory(histories);
	}

	protected void renderActors(Graphics2D g2d, Set<Actor> selfSends, AbstractActor[] actors, int adiam,
			Map<String, Integer> actorXMap, Map<String, Integer> actorYMap, Map<String, Integer> actorIdMap) {
		int acount;
		acount = 0;
		for (AbstractActor aa : actors) {
			renderActor(g2d, adiam, actorXMap, actorYMap, actorColorMap, actorIdMap, aa, selfSends, acount++,
					actors.length);
		}
	}

	protected void renderHistory(List<ThreadHistory> histories) {
		int hvwidth = threadHistoryView.getWidth();
		int hvheight = threadHistoryView.getHeight();
		if (hvwidth > 0 && hvheight > 0) {
			BufferedImage bi = new BufferedImage(hvwidth, hvheight, BufferedImage.TYPE_INT_ARGB);
			Graphics2D biG2d = (Graphics2D) bi.getGraphics();
			biG2d.setColor(Color.LIGHT_GRAY.brighter());
			biG2d.fillRect(0, 0, hvwidth, hvheight);
			int hsize = histories.size();
			if (hsize > 0) {
				int noteStart = 30;
				int noteStep = (60 + hsize - 1) / hsize;
				int cwidth = (hvwidth + hsize - 1) / hsize;
				int pstart = 0;
				stopAllNotes();
				for (int i = 0; i < hsize; i++) {
					biG2d.setColor(Color.YELLOW);
					biG2d.fillRect(cwidth * i, 0, cwidth * (i + 1), hvheight);
					ThreadHistory threadHistory = histories.get(i);
					int max = threadHistory.getMaxCount();
					int cur = threadHistory.getRunningCount();
					String name = threadHistory.name;
					int start = (int) (hvheight * (double) (max - cur) / max);
					//System.out.printf("Start=%d, height=%d%n", start, hvheight);
					boolean busySelected = soundWhenBusyButton.isSelected();
					boolean idleSelected = soundWhenIdleButton.isSelected();
					if ((start <= hvheight / 5) && busySelected) {
						//System.out.printf("Start note busy%n");
						startNote(noteStart + i * noteStep, (500 * (max - cur)) / max);
					} else if ((start >= 4 * hvheight / 5 && start < hvheight) && idleSelected) {
						//System.out.printf("Start note idle%n");
						startNote(noteStart + i * noteStep, (500 * (max - cur)) / max);
					}
					biG2d.setColor(Color.GREEN);
					biG2d.fillRect(cwidth * i, start, cwidth * (i + 1), hvheight);
					biG2d.setColor(name != null && name.startsWith("new") ? Color.CYAN : Color.BLACK);
					biG2d.drawRect(cwidth * i, 0, cwidth * (i + 1), hvheight);

					biG2d.setColor(Color.MAGENTA);
					biG2d.setStroke(new BasicStroke(1));
					if (busySelected) {
						biG2d.drawLine(cwidth * i, hvheight / 5, cwidth * (i + 1), hvheight / 5);
					}
					if (idleSelected) {
						biG2d.drawLine(cwidth * i, 4 * hvheight / 5, cwidth * (i + 1), 4 * hvheight / 5);
					}

					if (i > 0) {
						biG2d.setColor(Color.RED);
						biG2d.setStroke(new BasicStroke(2));
						biG2d.drawLine(cwidth * (i - 1) + cwidth / 2, pstart, cwidth * i + cwidth / 2, start);
					}
					pstart = start;
				}
			} else {
				biG2d.setColor(Color.LIGHT_GRAY.brighter());
				biG2d.fillRect(0, 0, hvwidth, hvheight);
			}
			threadHistoryView.setImage(bi);
		}
	}

	protected class ThreadHistory {
		// public Thread thread;
		public boolean[] running;
		public String name;

		public ThreadHistory() {
			running = new boolean[TIMES_PER_SECOND];
		}

		public void setLast(boolean f) {
			for (int i = 0; i < running.length - 1; i++) {
				running[i] = running[i + 1];
			}
			running[running.length - 1] = f;
		}

		public void setLast(String name) {
			this.name = name;
			ActorRunnable ar = actorManager.getRunnable(name);
			setLast(ar != null && ar.hasThread);
		}

		public int getMaxCount() {
			return running.length;

		}

		public int getRunningCount() {
			int count = 0;
			for (int i = 0; i < running.length; i++) {
				if (running[i]) {
					count++;
				}
			}
			return count;
		}
	}

	protected Map<String, ThreadHistory> threadHistoryMap = new HashMap<String, ThreadHistory>();

	protected int safeGetInt(Map<String, Integer> map, String key) {
		Integer i = map.get(key);
		return i != null ? i : -1;
	}

	protected double renderMessageConnections(Graphics2D g2d, AbstractActor[] actors, int height, int width,
			int aradius, int adiam, Map<String, AbstractActor> actorMap, Map<String, Integer> actorXMap,
			Map<String, Integer> actorYMap, double angle, AbstractActor aa, Color color, Set<Actor> selfSends) {
		String actorName = aa.getName();
		actorMap.put(actorName, aa);
		int x = width / 2 + (int) (Math.cos(angle) * aradius);
		actorXMap.put(actorName, x);
		int y = height / 2 + (int) (Math.sin(angle) * aradius);
		actorYMap.put(actorName, y);
		angle += 2 * Math.PI / actors.length;

		Message[] sent = actorManager.getAndClearSentMessages(aa);
		if (sent != null && sent.length > 0) {
			for (Message m : sent) {
				Actor from = m.getSource(), to = aa;
				try {
					if (from != null) {
						if (from != to) {
							// System.out.printf("sent: %s to %s%n", from, to);
							String fromName = from.getName();
							int fx = safeGetInt(actorXMap, fromName), fy = safeGetInt(actorYMap, fromName);
							if (fx >= 0 && fy >= 0) {
								String toName = to.getName();
								int tx = safeGetInt(actorXMap, toName), ty = safeGetInt(actorYMap, toName);
								if (tx >= 0 && ty >= 0) {
									g2d.setColor(Color.RED);
									// g2d.setStroke(new BasicStroke(1,
									// BasicStroke.CAP_BUTT,
									// BasicStroke.JOIN_MITER, 10,
									// new float[] { 5, 2, 3, 2 }, 1));
									g2d.setStroke(new BasicStroke(4));
									g2d.drawLine(fx, fy, tx, ty);
									// System.out.printf("drawSend: (d,%d) -> (%d,%d)%n",
									// fx, fy, tx, ty);
								}
							}
						} else {
							selfSends.add(aa);
						}
					}
				} catch (Exception e) {
					paintError("send", g2d, e);
				}
			}
		}

		Map<String, Integer> fromToCounts = new HashMap<String, Integer>();
		DefaultMessage[] messages = aa.getMessages();
		for (DefaultMessage m : messages) {
			Actor from = m != null ? m.getSource() : null, to = aa;
			if (from != null) {
				try {
					String fromName = from.getName();
					int fx = safeGetInt(actorXMap, fromName), fy = safeGetInt(actorYMap, fromName);
					if (fx >= 0 && fy >= 0) {
						String toName = to.getName();
						int tx = safeGetInt(actorXMap, toName), ty = safeGetInt(actorYMap, toName);
						if (tx >= 0 && ty >= 0) {
							g2d.setColor(color);
							g2d.setStroke(new BasicStroke(2));
							g2d.drawLine(fx, fy, tx, ty);
							int dx = tx - fx, dy = ty - fy;
							int count = getCount(fromToCounts, fromName, toName);
							int markerWidth = (int) (adiam * (0.1 + 0.1 * count));
							int xx = fx + (int) (dx * 0.85) - markerWidth / 2, xy = fy + (int) (dy * 0.85)
									- markerWidth / 2;
							g2d.fillOval(xx, xy, markerWidth, markerWidth);
						}
					}
				} catch (Exception e) {
					paintError("pending", g2d, e);
				}
			}
		}
		return angle;
	}

	protected int getCount(Map<String, Integer> fromToCounts, String fromName, String toName) {
		String fromToName = fromName + toName;
		Integer count = fromToCounts.get(fromToName);
		if (count == null) {
			count = 0;
		}
		count++;
		fromToCounts.put(fromToName, count);
		return count;
	}

	protected double renderThread(Graphics2D g2d, Thread[] threads, int height, int width, int tdiam, int tradius,
			double angle, Thread t, Map<String, Integer> actorIdMap) {
		try {
			int x = width / 2 + (int) (Math.cos(angle) * tradius);
			int y = height / 2 + (int) (Math.sin(angle) * tradius);
			ActorRunnable ar = actorManager.getRunnable(t.getName());
			if (ar != null) {
				g2d.setColor(ar.hasThread ? Color.GREEN.darker() : Color.YELLOW);
				g2d.fillRect(x - tdiam / 2, y - tdiam / 2, tdiam, tdiam);
				Actor a = ar.actor;
				if (ar.hasThread && a != null) {
					int theight = tdiam / 2;
					Color c = actorColorMap.get(a.getClass().getName());
					if (c != null) {
						g2d.setColor(c);
						g2d.fillOval(x - theight / 2, y - theight / 2, theight, theight);
					}
					Integer count = actorIdMap.get(a.getName());
					if (count != null) {
						g2d.setColor(Color.BLACK);
						g2d.drawString(Integer.toString(count), x - tdiam / 2, y
								+ (y > height / 2 ? tdiam + 10 : -tdiam - 10));
					}
				}
			}
			angle += 2 * Math.PI / threads.length;
		} catch (Exception e) {
			paintError("thread", g2d, e);
		}
		return angle;
	}

	protected void renderActor(Graphics2D g2d, int adiam, Map<String, Integer> actorXMap,
			Map<String, Integer> actorYMap, Map<String, Color> actorColorMap, Map<String, Integer> actorIdMap,
			AbstractActor aa, Set<Actor> selfSends, int index, int total) {
		try {
			String name = aa.getName();
			int x = safeGetInt(actorXMap, name), y = safeGetInt(actorYMap, name);
			if (x >= 0 && y >= 0) {
				Color acolor = actorColorMap.get(aa.getClass().getName());
				if (acolor == null) {
					acolor = Color.RED;
				}
				Color xacolor = aa.getHasThread() ? acolor.darker() : acolor;
				g2d.setColor(xacolor);
				if (selfSends.contains(aa)) {
					// System.out.printf("renderActor: self %s%n", aa);
					g2d.drawOval(x - adiam / 2, y - adiam / 2, adiam, adiam);
				} else {
					Color c = isTransparentActors ? new Color(xacolor.getRed(), xacolor.getGreen(), xacolor.getBlue(),
							150) : xacolor;
					g2d.setColor(c);
					// System.out.printf("renderActor: other %s%n", aa);
					g2d.fillOval(x - adiam / 2, y - adiam / 2, adiam, adiam);
					if (adiam > 20) {
						g2d.setColor(Color.BLACK);
						g2d.drawOval(x - adiam / 2, y - adiam / 2, adiam, adiam);
					}
				}
				// g2d.setFont(font);
				// g2d.setColor(Color.BLACK);
				// if (name.length() > 10) {
				// name = name.substring(name.length() - 10);
				// }
				// g2d.drawString(name, x - adiam / 2, y);
				if (index == total - 1) {
					Integer count = actorIdMap.get(name);
					if (count != null) {
						g2d.setColor(Color.BLACK);
						g2d.drawString(Integer.toString(count), x - 10, y + 5);
					}
				}
			}
		} catch (Exception e) {
			paintError("actor", g2d, e);
		}
	}

	protected BufferedImage renderTrendLine(int trendValue, int maxTrendValue) {
		BufferedImage bi = new BufferedImage(METER_WIDTH, METER_HEIGHT, BufferedImage.TYPE_INT_ARGB);
		int width = bi.getWidth();
		int halfWidth = width / 2;
		int height = bi.getHeight();
		// System.out.printf("renderTrendLine %dx%d: %d, %d%n", width, height,
		// trendValue, maxTrendValue);

		Graphics2D g2d = (Graphics2D) bi.getGraphics();
		// g2d.scale(1, 1);
		g2d.setColor(Color.LIGHT_GRAY.brighter());
		g2d.fillRect(0, 0, width, height);

		int atv = Math.abs(trendValue);
		Color c = Color.GREEN;
		if (atv > maxTrendValue / 3) {
			c = Color.YELLOW;
			if (atv > maxTrendValue * 2 / 3) {
				c = Color.ORANGE;
			}
			if (atv > maxTrendValue) {
				c = Color.RED;
			}
		}
		g2d.setColor(c);
		int tlv = Math.min(atv, maxTrendValue);
		int xl = halfWidth * tlv / maxTrendValue;
		int textX = 0;
		if (trendValue < 0) {
			g2d.fillRect(halfWidth - xl, 0, xl, height);
			textX = halfWidth + 5;
		} else {
			g2d.fillRect(halfWidth, 0, xl, height);
			textX = 5;
		}

		g2d.setColor(Color.BLACK);
		g2d.setFont(new Font("monospace", Font.BOLD, 24));
		g2d.drawString(String.format("%d", trendValue), textX, height / 2);
		g2d.setStroke(new BasicStroke(2));
		g2d.drawLine(halfWidth, 1, halfWidth, height - 2);

		g2d.setColor(Color.DARK_GRAY);
		g2d.drawRect(1, 1, width - 1, height - 2);
		return bi;
	}

	volatile BufferedImage renderImageMain;

	protected void paintError(String from, Graphics2D g2d, Exception e) {
		g2d.setColor(Color.RED);
		errorY += 50;
		g2d.drawString(e.toString(), 25, errorY);
		System.out.printf("paint exception %s: %s%n", from, e);
		e.printStackTrace(System.out);
	}

	Font font;

	public void postShow() {
		Dimension d = getSize();
		double posn = d.width >= 800 ? 0.33 : (d.width >= 400 ? 0.40 : 0.50);
		splitPane.setDividerLocation(posn);
		font = new Font("Courier New", Font.PLAIN, 10);
	}

	@Override
	public void stateChanged(ChangeEvent e) {
		setMessage(String.format("Count down to halt: %d", test.getStepCount()));
	}

	DefaultActorTest test;

	public DefaultActorTest getTest() {
		return test;
	}

	public void setActorTest(DefaultActorTest test) {
		this.test = test;
	}

	public void runTest(String args) {
		actorManager = new DefaultActorManager();
		test = new DefaultActorTest();
		test.setActorManager(actorManager);
		// am.detachAllActors();
		if (!isMidiOpen()) {
			try {
				setupMidi();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		test.addChangeListener(this);
		int value = (int) Math.pow(2, stepSlider.getValue());
		test.run((args + " -sc:" + value + " -tc:" + threadCount).split("\\s+"));
		test.removeChangeListener(this);
		// am.detachAllActors();
		if (isMidiOpen()) {
			try {
				shutdownMidi();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {

		ActorDemo av = new ActorDemo();

		JFrame frame = new JFrame("ActorDemo v1.0");
		// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}

			@Override
			public void windowClosed(WindowEvent e) {
				System.exit(0);
			}
		});
		frame.setSize(1000, 850);
		av.initUI(frame);

		frame.setVisible(true);
		av.postShow();
		// av.runTest(args);

		Utils.logger.trace("Done");
	}
}


text:
using System.Collections.Generic;
using System.Linq;
using Manatee.Json;
using Manatee.Json.Serialization;

namespace Manatee.Trello.Json.Entities
{
	internal class ManateeMemberSearch : IJsonMemberSearch, IJsonSerializable
	{
		public List<IJsonMember> Members { get; set; }
		public IJsonBoard Board { get; set; }
		public int? Limit { get; set; }
		public bool? OnlyOrgMembers { get; set; }
		public IJsonOrganization Organization { get; set; }
		public string Query { get; set; }

		public void FromJson(JsonValue json, JsonSerializer serializer)
		{
			// This is the only return value that is an array at the root.
			if (json.Type != JsonValueType.Array) return;
			var array = json.Array;
			Members = array.Select(serializer.Deserialize<IJsonMember>).ToList();
		}
		public JsonValue ToJson(JsonSerializer serializer)
		{
			var json = new JsonObject
				{
					{"query", Query}
				};
			Limit.Serialize(json, serializer, "limit");
			Board.SerializeId(json, "idBoard");
			if (Organization != null)
			{
				Organization.SerializeId(json, "idOrganization");
				OnlyOrgMembers.Serialize(json, serializer, "onlyOrgMembers");
			}
			return json;
		}
	}
}


text:
package com.facebook.buck.core.rules.analysis.impl;

import com.facebook.buck.core.description.BaseDescription;
import com.facebook.buck.core.description.RuleDescription;
import com.facebook.buck.core.description.arg.BuildRuleArg;
import com.facebook.buck.core.graph.transformation.ComputationEnvironment;
import com.facebook.buck.core.graph.transformation.GraphComputation;
import com.facebook.buck.core.graph.transformation.model.ComputationIdentifier;
import com.facebook.buck.core.graph.transformation.model.ComputeKey;
import com.facebook.buck.core.graph.transformation.model.ComputeResult;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.targetgraph.TargetGraph;
import com.facebook.buck.core.model.targetgraph.TargetNode;
import com.facebook.buck.core.rules.DescriptionWithTargetGraph;
import com.facebook.buck.core.rules.ImmutableProviderCreationContext;
import com.facebook.buck.core.rules.LegacyProviderCompatibleDescription;
import com.facebook.buck.core.rules.ProviderCreationContext;
import com.facebook.buck.core.rules.actions.ActionCreationException;
import com.facebook.buck.core.rules.analysis.RuleAnalysisException;
import com.facebook.buck.core.rules.analysis.RuleAnalysisKey;
import com.facebook.buck.core.rules.analysis.RuleAnalysisResult;
import com.facebook.buck.core.rules.providers.collect.ProviderInfoCollection;
import com.facebook.buck.core.rules.providers.collect.impl.LegacyProviderInfoCollectionImpl;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

/**
 * The {@link GraphComputation} for performing the target graph to provider and action graph
 * transformation, with legacy compatible behaviour where we delegate to the {@link
 * com.facebook.buck.core.rules.LegacyProviderCompatibleDescription#createProviders(ProviderCreationContext,
 * BuildTarget, BuildRuleArg)}
 */
public class LegacyCompatibleRuleAnalysisComputation
    implements GraphComputation<RuleAnalysisKey, RuleAnalysisResult> {

  private final RuleAnalysisComputation delegate;
  private final TargetGraph targetGraph;

  public LegacyCompatibleRuleAnalysisComputation(
      RuleAnalysisComputation delegate, TargetGraph targetGraph) {
    this.delegate = delegate;
    this.targetGraph = targetGraph;
  }

  @Override
  public ComputationIdentifier<RuleAnalysisResult> getIdentifier() {
    return RuleAnalysisKey.IDENTIFIER;
  }

  @Override
  public RuleAnalysisResult transform(RuleAnalysisKey key, ComputationEnvironment env)
      throws ActionCreationException, RuleAnalysisException {
    return transformImpl(key, targetGraph.get(key.getBuildTarget()).cast(BuildRuleArg.class), env);
  }

  @Override
  public ImmutableSet<? extends ComputeKey<? extends ComputeResult>> discoverDeps(
      RuleAnalysisKey key, ComputationEnvironment env) {
    if (!isCompatibleDescription(targetGraph.get(key.getBuildTarget()).getDescription())) {
      return ImmutableSet.of();
    }
    return delegate.discoverDeps(key, env);
  }

  @Override
  public ImmutableSet<? extends ComputeKey<? extends ComputeResult>> discoverPreliminaryDeps(
      RuleAnalysisKey key) {
    if (!isCompatibleDescription(targetGraph.get(key.getBuildTarget()).getDescription())) {
      return ImmutableSet.of();
    }
    return delegate.discoverPreliminaryDeps(key);
  }

  private <T extends BuildRuleArg> RuleAnalysisResult transformImpl(
      RuleAnalysisKey key, TargetNode<T> targetNode, ComputationEnvironment env)
      throws ActionCreationException, RuleAnalysisException {
    BaseDescription<T> description = targetNode.getDescription();
    if (description instanceof RuleDescription) {
      return delegate.transform(key, env);
    } else if (description instanceof LegacyProviderCompatibleDescription) {
      return computeLegacyProviders(
          key, env, targetNode, (LegacyProviderCompatibleDescription<T>) description);
    } else if (description instanceof DescriptionWithTargetGraph) {
      return ImmutableLegacyProviderRuleAnalysisResultImpl.of(
          key.getBuildTarget(), LegacyProviderInfoCollectionImpl.of());
    }

    throw new IllegalStateException(
        String.format("Unknown Description type %s", description.getClass()));
  }

  private <T extends BuildRuleArg> RuleAnalysisResult computeLegacyProviders(
      RuleAnalysisKey key,
      ComputationEnvironment env,
      TargetNode<T> targetNode,
      LegacyProviderCompatibleDescription<T> description) {
    ProviderInfoCollection providerInfoCollection =
        description.createProviders(
            ImmutableProviderCreationContext.of(
                env.getDeps(RuleAnalysisKey.IDENTIFIER).values().stream()
                    .collect(
                        ImmutableMap.toImmutableMap(
                            RuleAnalysisResult::getBuildTarget,
                            RuleAnalysisResult::getProviderInfos)),
                targetNode.getFilesystem()),
            key.getBuildTarget(),
            targetNode.getConstructorArg());

    return ImmutableLegacyProviderRuleAnalysisResultImpl.of(
        key.getBuildTarget(), providerInfoCollection);
  }

  private boolean isCompatibleDescription(BaseDescription<?> description) {
    return description instanceof RuleDescription
        || description instanceof LegacyProviderCompatibleDescription;
  }
}


text:
import time

from .. import base

from girder.models.model_base import ValidationException
from girder.models.notification import ProgressState
from girder.utility.progress import ProgressContext

def setUpModule():
    base.startServer()

def tearDownModule():
    base.stopServer()

class NotificationTestCase(base.TestCase):
    def setUp(self):
        base.TestCase.setUp(self)

        self.admin = self.model('user').createUser(
            email='admin@email.com', login='admin', firstName='first',
            lastName='last', password='mypasswd')

    def _testStream(self, user, token=None):
        # Should only work for users or token sessions
        resp = self.request(path='/notification/stream', method='GET')
        self.assertStatus(resp, 401)
        self.assertEqual(
            resp.json['message'],
            'You must be logged in or supply a valid session token.')

        resp = self.request(path='/notification/stream', method='GET',
                            user=user, token=token, isJson=False,
                            params={'timeout': 0})
        self.assertStatusOk(resp)
        self.assertEqual(resp.collapse_body(), '')

        # Use a very high rate-limit interval so that we don't fail on slow
        # build boxes
        with ProgressContext(
                True, user=user, token=token, title='Test', total=100,
                interval=100) as progress:
            progress.update(current=1)

            # Rate limiting should make it so we didn't write the immediate
            # update within the time interval.
            resp = self.request(path='/notification/stream', method='GET',
                                user=user, token=token, isJson=False,
                                params={'timeout': 0})
            messages = self.getSseMessages(resp)
            self.assertEqual(len(messages), 1)
            self.assertEqual(messages[0]['type'], 'progress')
            self.assertEqual(messages[0]['data']['total'], 100)
            self.assertEqual(messages[0]['data']['current'], 0)
            self.assertFalse(ProgressState.isComplete(
                messages[0]['data']['state']))

            # Now use a very short interval to test that we do save changes
            progress.interval = 0.01
            time.sleep(0.02)
            progress.update(current=2)
            resp = self.request(path='/notification/stream', method='GET',
                                user=user, token=token, isJson=False,
                                params={'timeout': 0})
            messages = self.getSseMessages(resp)
            self.assertEqual(len(messages), 1)
            self.assertEqual(messages[0]['data']['current'], 2)
            # If we use a non-numeric value, nothing bad should happen
            time.sleep(0.02)
            progress.update(current='not_a_number')
            resp = self.request(path='/notification/stream', method='GET',
                                user=user, token=token, isJson=False,
                                params={'timeout': 0})
            messages = self.getSseMessages(resp)
            self.assertEqual(len(messages), 1)
            self.assertEqual(messages[0]['data']['current'], 'not_a_number')
            # Updating the progress without saving and then exiting should
            # send the update.
            progress.interval = 1000
            progress.update(current=3)

        # Exiting the context manager should flush the most recent update.
        resp = self.request(path='/notification/stream', method='GET',
                            user=user, token=token, isJson=False,
                            params={'timeout': 0})
        messages = self.getSseMessages(resp)
        self.assertEqual(len(messages), 1)
        self.assertEqual(messages[0]['data']['current'], 3)

        # Test a ValidationException within the progress context
        try:
            with ProgressContext(
                    True, user=user, token=token, title='Test',
                    total=100) as progress:
                raise ValidationException('Test Message')
        except ValidationException:
            pass

        # Exiting the context manager should flush the most recent update.
        resp = self.request(path='/notification/stream', method='GET',
                            user=user, token=token, isJson=False,
                            params={'timeout': 0})
        messages = self.getSseMessages(resp)
        self.assertEqual(messages[-1]['data']['message'],
                         'Error: Test Message')

    def testUserStream(self):
        self._testStream(self.admin)

    def testTokenStream(self):
        resp = self.request(path='/token/session', method='GET')
        self.assertStatusOk(resp)
        token = resp.json['token']
        tokenDoc = self.model('token').load(token, force=True, objectId=False)
        self._testStream(None, tokenDoc)


text:
<?php

namespace CurrencyCloud\Model;

use ArrayIterator;

class Beneficiaries extends PaginatedData
{

    /**
     * @var Beneficiary[]
     */
    private $beneficiaries;

    /**
     * @param Beneficiary[] $beneficiaries
     * @param Pagination $pagination
     */
    public function __construct(array $beneficiaries, Pagination $pagination)
    {
        parent::__construct($pagination);
        $this->beneficiaries = $beneficiaries;
    }

    /**
     * @return Beneficiary[]
     */
    public function getBeneficiaries()
    {
        return $this->beneficiaries;
    }

    /**
     * @inheritdoc
     */
    public function getIterator()
    {
        return new ArrayIterator($this->beneficiaries);
    }

    /**
     * @inheritdoc
     */
    public function count()
    {
        return count($this->beneficiaries);
    }
}


text:
package ru.stqa.pft.sandbox;

public class Rectangle {

  public double a;
  public double b;

  public Rectangle (double a, double b) {
    this.a = a;
    this.b= b;

    public  double area () {

    return this.a * this.b;

  }
}


text:
from quicli import *

@run
@argument
def test_function(arg1):
    pass