text:
#include "Renderer.h"
#include "math/Rect.h"
#include "Actor.h"
#include "MemoryTexture.h"
#include "ImageDataOperations.h"
#include "AnimationFrame.h"
#include "VertexDeclaration.h"
#include "gl/VideoDriverGLES20.h"

#include "ZipFileSystem.h"
#include "system_data.h"
#include "UberShaderProgram.h"

namespace oxygine
{
	bool _premultipliedRender = true;
	bool Renderer::getPremultipliedAlphaRender()
	{
		return _premultipliedRender;
	}

	void Renderer::setPremultipliedAlphaRender(bool pre)
	{
		_premultipliedRender = pre;
	}

	//Renderer::Stats Renderer::statsPrev;
	//Renderer::Stats Renderer::statsCurrent;
	bool _restored = false;
	spNativeTexture Renderer::white;
	std::vector<unsigned char> Renderer::indices8;
	std::vector<unsigned short> Renderer::indices16;
	size_t _maxVertices = 0;
	UberShaderProgram Renderer::uberShader;
	std::vector<unsigned char> Renderer::uberShaderBody;

	template<class V, class XY>
	void fillQuad(V *v, const RectF &uv, XY *positions, const Color &color)
	{
		const XY &p1 = positions[0];
		const XY &p2 = positions[1];
		const XY &p3 = positions[2];
		const XY &p4 = positions[3];

		V vt;
		vt.color = color.rgba();
		vt.z = 0;

		vt.x = p1.x;
		vt.y = p1.y;
		vt.u = uv.pos.x;
		vt.v = uv.pos.y;
		*v = vt;
		++v;

		vt.x = p2.x;
		vt.y = p2.y;
		vt.u = uv.pos.x;
		vt.v = uv.getBottom();
		*v = vt;
		++v;

		vt.x = p3.x;
		vt.y = p3.y;
		vt.u = uv.getRight();
		vt.v = uv.pos.y;
		*v = vt;
		++v;

		vt.x = p4.x;
		vt.y = p4.y;
		vt.u = uv.getRight();
		vt.v = uv.getBottom();
		*v = vt;
		++v;
	}

	void Renderer::initialize()
	{
		indices8.reserve(60 * 4);
		for (int t = 0; t < 60; t += 1)
		{
			int i = t * 4;
			indices8.push_back(i + 0);
			indices8.push_back(i + 1);
			indices8.push_back(i + 2);

			indices8.push_back(i + 2);
			indices8.push_back(i + 1);
			indices8.push_back(i + 3);
		}

		indices16.reserve(12000 * 6);
		for (int t = 0; t < 12000; t += 1)
		{
			int i = t * 4;
			indices16.push_back(i + 0);
			indices16.push_back(i + 1);
			indices16.push_back(i + 2);

			indices16.push_back(i + 2);
			indices16.push_back(i + 1);
			indices16.push_back(i + 3);
		}

		_maxVertices = indices16.size()/3 * 2;

		file::buffer shaderBody;
		file::read("shader.glsl", shaderBody, ep_ignore_error);
        uberShaderBody = shaderBody.data;
		if (!shaderBody.getSize())
		{
			file::Zips zp;
			zp.add(system_data, system_size);
			zp.read("system/shader.glsl", shaderBody);
			uberShaderBody = shaderBody.data;
		}

		uberShader.init(uberShaderBody);

		restore();
	}

	void Renderer::release()
	{
		indices8.clear();
		indices16.clear();
		uberShader.release();
		uberShaderBody.clear();
		if (white)
			white->release();
		white = 0;
	}

	void Renderer::reset()
	{
		_restored = false;
		if (white)
			white->release();
		white = 0;
		uberShader.release();
	}

	void Renderer::restore()
	{
		MemoryTexture memwhite;
		memwhite.init(4, 4, TF_R8G8B8A8);

		oxygine::operations::op_fill fill;
		ImageData im = memwhite.lock();
		oxygine::operations::applyOperation(fill, im);

		white = IVideoDriver::instance->createTexture();
		white->setName("!renderer. white");
		white->init(im, false);
		white->setLinearFiltration(false);

		setDefaultSettings();
		_restored = true;
	}

	Renderer::Renderer(IVideoDriver *driver):_rt(0), _driver(driver),
		_viewport(0,0,0,0), _program(0), _uberShader(0), _blend(blend_disabled),
		_shaderFlags(0), _clipMask(0,0,0,0), _vdecl(0)
	{
		if (!driver)
			driver = IVideoDriver::instance;

		if (driver)
			setDriver(driver);

		_vertices.reserve(32 * 1000);
		setPrimaryColor(Color(0xffffffff));

		//_view.identity();
		//_proj.identity();
		_transform.identity();
		_vp.identity();

		_uberShader = &uberShader;
	}

	Renderer::~Renderer()
	{
		drawBatch();
	}

	void Renderer::cleanup()
	{
		_base = 0;
		_mask = 0;
		_alpha =0;
		_vertices.resize(0);
	}

	void Renderer::setBlendMode(blend_mode blend)
	{
		if (_blend != blend)
		{
			drawBatch();

			switch (blend)
			{
			case blend_disabled:
				_driver->setState(IVideoDriver::STATE_BLEND, 0);
				break;
			case blend_premultiplied_alpha:
				_driver->setBlendFunc(IVideoDriver::BT_ONE, IVideoDriver::BT_ONE_MINUS_SRC_ALPHA);
				break;
			case blend_alpha:
				_driver->setBlendFunc(IVideoDriver::BT_SRC_ALPHA, IVideoDriver::BT_ONE_MINUS_SRC_ALPHA);
				break;
			case blend_add:
				_driver->setBlendFunc(IVideoDriver::BT_ONE, IVideoDriver::BT_ONE);
				break;
			//case blend_sub:
				//_driver->setBlendFunc(IVideoDriver::BT_ONE, IVideoDriver::BT_ONE);
				//glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
			//	break;
			default:
				OX_ASSERT(!"unknown blend");
			}

			if (_blend == blend_disabled)
			{
				_driver->setState(IVideoDriver::STATE_BLEND, 1);
			}
			_blend = blend;
		}
	}

	void Renderer::setDiffuse(const Diffuse &df)
	{
		setTexture_(df.base, df.alpha, df.premultiplied);
	}

	void Renderer::setTexture_(spNativeTexture base, spNativeTexture alpha, bool basePremultiplied)
	{
		if (base == 0 || base->getHandle() == 0)
			base = white;

		unsigned int shaderFlags = _shaderFlags;

		if (basePremultiplied)
			shaderFlags &= ~UberShaderProgram::ALPHA_PREMULTIPLY;
		else
			shaderFlags |= UberShaderProgram::ALPHA_PREMULTIPLY;

		if (alpha)
			shaderFlags |= UberShaderProgram::SEPARATE_ALPHA;
		else
			shaderFlags &= ~UberShaderProgram::SEPARATE_ALPHA;

//##ifdef OX_DEBUG
#if 0
		if (_base != base){OX_ASSERT(_alpha != alpha);}
		else{OX_ASSERT(_alpha == alpha);}
#endif //OX_DEBUG

		//no reason to check changed alpha because it is in pair with base
		if (_base != base || /*_alpha != alpha || */_shaderFlags != shaderFlags)
		{
			drawBatch();
		}

		_shaderFlags = shaderFlags;

		_base = base;
		_alpha = alpha;
	}

	void Renderer::setTransform(const transform &m)
	{
		_transform = m;
	}

	void Renderer::setShader(ShaderProgram *prog)
	{
		if (prog != _program)
		{
			_driver->setShaderProgram(prog);
			_driver->setUniform("mat", &_vp);
		}
		_program = prog;
	}

	void Renderer::setUberShaderProgram(UberShaderProgram* pr)
	{
		if (_uberShader != pr)
		{
			drawBatch();
		}

		_uberShader = pr;
	}

	const Color &Renderer::getPrimaryColor() const
	{
		return _primaryColor;
	}

	void Renderer::setPrimaryColor(const Color &c)
	{
		_primaryColor = c;
		_primaryColorPremultiplied = _primaryColor.premultiplied();
	}

	void Renderer::drawBatch()
	{
		if (!_vertices.empty())
		{
			ShaderProgram *prog = _uberShader->getShaderProgram(_shaderFlags)->program;
			setShader(prog);

			_driver->setTexture(UberShaderProgram::SAMPLER_BASE, _base);

			if (_alpha)
			{
				_driver->setTexture(UberShaderProgram::SAMPLER_ALPHA, _alpha);
			}

			if (_mask)
			{
				_driver->setTexture(UberShaderProgram::SAMPLER_MASK, _mask);

				Vector4 v(_clipMask.getLeft(), _clipMask.getTop(), _clipMask.getRight(), _clipMask.getBottom());
				_driver->setUniform("clip_mask", &v, 1);
			}

			UberShaderProgram::ShaderUniformsCallback cb = _uberShader->getShaderUniformsCallback();
			if (cb)
			{
				cb(_driver, prog);
			}

			size_t count = _vertices.size() / _vdecl->size;
			size_t indices = (count * 3)/2;

			if (indices <= indices8.size())
				getDriver()->draw(IVideoDriver::PT_TRIANGLES, _vdecl, &_vertices.front(), count, &indices8.front(), indices, false);
			else
				getDriver()->draw(IVideoDriver::PT_TRIANGLES, _vdecl, &_vertices.front(), count, &indices16.front(), indices, true);

			_vertices.resize(0);
			//b.shaderFlags = 0;
		}
	}

	bool checkT2P(const Rect &viewport, const Matrix &vp, const vertexPCT2 *v1, const vertexPCT2 *v2, int w, int h)
	{
		Vector3 p1(v1->x, v1->y, 0);
		Vector3 p2(v2->x, v2->y, 0);

		p1 = vp.transformVec3(p1);
		p2 = vp.transformVec3(p2);

		Vector2 half = viewport.getSize().cast<Vector2>() / 2;
		p1.x = p1.x * half.x + half.x;
		p1.y = p1.y * half.y + half.y;

		p2.x = p2.x * half.x + half.x;
		p2.y = p2.y * half.y + half.y;

		Vector2 tc1(v1->u, v1->v);
		Vector2 tc2(v2->u, v2->v);
		Vector3 dp_ = p1 - p2;
		Vector2 dp(dp_.x, dp_.y);
		dp.x = scalar::abs(dp.x);
		dp.y = scalar::abs(dp.y);

		Vector2 dtc = tc1 - tc2;
		dtc.x = scalar::abs(dtc.x) * w;
		dtc.y = scalar::abs(dtc.y) * h;

		const float EPS = 0.05f;

		Vector2 d = dp - dtc;
		if (scalar::abs(d.x) >= EPS || scalar::abs(d.y) >= EPS)
			return false;

		p1.x = scalar::abs(p1.x);
		p1.y = scalar::abs(p1.y);

		if (scalar::abs(p1.x - int(p1.x + EPS)) > EPS ||
			scalar::abs(p1.y - int(p1.y + EPS)) > EPS)
			return false;

		return true;
	}

	bool _showTexel2PixelErrors = false;

#ifdef OXYGINE_DEBUG_T2P
	void Renderer::showTexel2PixelErrors(bool show)
	{
		_showTexel2PixelErrors = show;
	}
#endif

	void Renderer::setMask(spNativeTexture mask, const RectF &srcRect, const RectF &destRect, const transform &t, bool channelR)
	{
		if (_mask != mask)
		{
			drawBatch();
		}

		_clipUV = ClipUV(
			t.transform(destRect.getLeftTop()),
			t.transform(destRect.getRightTop()),
			t.transform(destRect.getLeftBottom()),
			srcRect.getLeftTop(),
			srcRect.getRightTop(),
			srcRect.getLeftBottom());

		_mask = mask;
		if (_vdecl->bformat != VERTEX_PCT2T2)
			_vdecl = _driver->getVertexDeclaration(VERTEX_PCT2T2);
		_clipMask = srcRect;
		Vector2 v(1.0f / mask->getWidth(), 1.0f / mask->getHeight());
		_clipMask.expand(v, v);

		_shaderFlags |= UberShaderProgram::MASK;
		if (channelR)
			_shaderFlags |= UberShaderProgram::MASK_R_CHANNEL;
	}

	void Renderer::removeMask()
	{
		drawBatch();

		_mask = 0;
		_shaderFlags &= ~(UberShaderProgram::MASK | UberShaderProgram::MASK_R_CHANNEL);
		_vdecl = _driver->getVertexDeclaration(VERTEX_PCT2);
	}

	Vector2	Renderer::getMaskedUV(const Vector2 &pos)
	{
		Vector2 uv = _clipUV.calc(pos);
		return uv;
	}

	void Renderer::draw(const RectF &srcRect, const RectF &destRect)
	{
		const Color* color = &_primaryColor;
		if (_blend == blend_premultiplied_alpha)
			color = &_primaryColorPremultiplied;

		if (_mask)
		{
			vertexPCT2T2 v[4];
			fillQuadT(v, srcRect, destRect, _transform, *color);

			for (int i = 0; i < 4; ++i)
			{
				Vector2 uv = _clipUV.calc(Vector2(v[i].x, v[i].y));
				v[i].u2 = uv.x;
				v[i].v2 = uv.y;
			}

			_vertices.insert(_vertices.end(), (unsigned char*)v, (unsigned char*)v + sizeof(v));
		}
		else
		{
			vertexPCT2 v[4];
			fillQuadT(v, srcRect, destRect, _transform, *color);

#ifdef OXYGINE_DEBUG_T2P
			if (_base != white && _showTexel2PixelErrors)
			{
				bool t = checkT2P(_viewport, _vp, &v[0], &v[3], _base->getWidth(), _base->getHeight());
				if (!t)
				{
					float c = (sinf((float)getTimeMS()/200 + v[0].x * v[0].y) + 1)/2.0f;
					Color b = interpolate(Color(rand() % 255, rand() % 255,rand() % 255, 255), *color, c);
					fillQuadT(v, srcRect, destRect, _transform, b);
				}
			}
#endif

			_vertices.insert(_vertices.end(), (unsigned char*)v, (unsigned char*)v + sizeof(v));
		}

		if (_vertices.size()/sizeof(_vdecl->size) >= _maxVertices)
			drawBatch();
	}

	void Renderer::draw(const void *data, int size, bvertex_format format)
	{
		if (_vdecl->bformat != format)
		{
			drawBatch();
			_vdecl = _driver->getVertexDeclaration(format);
		}

		int num = size / _vdecl->size;
		size_t currentNum = _vertices.size() / _vdecl->size;
		if (currentNum + num >= _maxVertices)
		{
			drawBatch();
		}

		_vertices.insert(_vertices.end(), (unsigned char*)data, (unsigned char*)data + size);
	}

	void Renderer::setDefaultSettings()
	{
		/*
		_blend = blend_disabled;
		IVideoDriver* instance = IVideoDriver::instance;
		instance->setState(IVideoDriver::STATE_BLEND, 0);
		*/
		/*

		instance->setState(IVideoDriver::STATE_BLEND, 1);
		instance->setBlendFunc(IVideoDriver::BT_ONE, IVideoDriver::BT_ONE);
		*/
	}

	void Renderer::initCoordinateSystem(int width, int height, bool flipU)
	{
		Matrix view = makeViewMatrix(width, height, flipU);
		Matrix proj;
		//initialize projection matrix
		Matrix::orthoLH(proj, (float)width, (float)height, 0, 1);

		setViewProjTransform(view, proj);
	}

	void Renderer::setViewProjTransform(const Matrix &view, const Matrix &proj)
	{
		_vp = view * proj;
	}

	IVideoDriver *Renderer::getDriver()
	{
		return _driver;
	}

	void Renderer::setDriver(IVideoDriver *driver)
	{
		_driver = driver;
	}

	void Renderer::resetSettings()
	{
		_blend = blend_disabled;
		_driver->setState(IVideoDriver::STATE_BLEND, 0);
		_uberShader = &uberShader;
		_program = 0;
	}

	bool Renderer::begin(spNativeTexture rt, const Rect &viewport, const Color *clearColor)
	{
		if (!_restored)
			return false;

		//if (!getDriver()->isReady())
		//	return false;
		_rt = rt;

		if (_rt)
		{
			getDriver()->setRenderTarget(_rt);
		}

		_viewport = viewport;
		_program = 0;

		getDriver()->begin(viewport, clearColor);
		_vdecl = _driver->getVertexDeclaration(VERTEX_PCT2);
		_base = 0;
		_mask = 0;
		_alpha = 0;
		_program = 0;
		_vertices.resize(0);
		resetSettings();

		return true;
	}

	void Renderer::end()
	{
		drawBatch();

		if (_rt)
		{
			getDriver()->setRenderTarget(0);
		}

		_rt = 0;
	}
}


text:
package org.strongback;

import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;

import org.strongback.annotation.ThreadSafe;

/**
 * A threadsafe {@link DataRecorder} that allows for switches, motors and other functions to be registered, and then to
 * {@link #start() start} recording the values.
 *
 * @author Randall Hauch
 */
@ThreadSafe
final class DataRecorderDriver implements Executable {

    private final DataRecorderChannels channels;
    private final Function<Iterable<DataRecorderChannel>, DataWriter> writerFactory;
    private final AtomicReference<DataWriter> writer = new AtomicReference<>(NULL_WRITER);

    DataRecorderDriver(DataRecorderChannels channels, Function<Iterable<DataRecorderChannel>, DataWriter> writerFactory) {
        this.channels = channels;
        this.writerFactory = writerFactory != null ? writerFactory : (channelIter) -> NULL_WRITER;
    }

    protected boolean isRunning() {
        return writer.get() != NULL_WRITER;
    }

    public synchronized void start() {
        writer.getAndUpdate((existing) -> existing == NULL_WRITER ? writerFactory.apply(channels) : existing);
    }

    public synchronized void flush() {
        writer.get().close(); // reopens if necessary
    }

    public synchronized void stop() {
        // We will always replace the existing data writer with NULL_WRITER, but only after we do this do we close the
        // writer. These steps are done in a very strict and ordered manner to ensure the non-NULL_WRITER is always closed.
        AtomicReference<DataWriter> unclosed = new AtomicReference<>();
        try {
            writer.getAndUpdate((existing) -> {
                if (existing != NULL_WRITER) unclosed.set(existing);
                return NULL_WRITER;
            });
        } finally {
            if (unclosed.get() != null) {
                unclosed.get().close();
            }
        }
    }

    @Override
    public void execute(long timeInMillis) {
        writer.get().write(timeInMillis);
    }

    private static final DataWriter NULL_WRITER = new DataWriter() {
        @Override
        public void write(long time) {
        }

        @Override
        public void close() {
        }
    };
}

redpajama_set_name: RedPajamaGithub


text:
"""
    ORCID Member

    No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)  # noqa: E501

    OpenAPI spec version: Latest

    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

import pprint
import re  # noqa: F401

import six
from orcid_api_v3.models.addresses_v30_rc2 import AddressesV30Rc2  # noqa: F401,E501
from orcid_api_v3.models.biography_v30_rc2 import BiographyV30Rc2  # noqa: F401,E501
from orcid_api_v3.models.emails_v30_rc2 import EmailsV30Rc2  # noqa: F401,E501
from orcid_api_v3.models.keywords_v30_rc2 import KeywordsV30Rc2  # noqa: F401,E501
from orcid_api_v3.models.last_modified_date_v30_rc2 import LastModifiedDateV30Rc2  # noqa: F401,E501
from orcid_api_v3.models.name_v30_rc2 import NameV30Rc2  # noqa: F401,E501
from orcid_api_v3.models.other_names_v30_rc2 import OtherNamesV30Rc2  # noqa: F401,E501
from orcid_api_v3.models.person_external_identifiers_v30_rc2 import PersonExternalIdentifiersV30Rc2  # noqa: F401,E501
from orcid_api_v3.models.researcher_urls_v30_rc2 import ResearcherUrlsV30Rc2  # noqa: F401,E501

class PersonV30Rc2(object):
    """NOTE: This class is auto generated by the swagger code generator program.

    Do not edit the class manually.
    """
    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {
        'last_modified_date': 'LastModifiedDateV30Rc2',
        'name': 'NameV30Rc2',
        'other_names': 'OtherNamesV30Rc2',
        'biography': 'BiographyV30Rc2',
        'researcher_urls': 'ResearcherUrlsV30Rc2',
        'emails': 'EmailsV30Rc2',
        'addresses': 'AddressesV30Rc2',
        'keywords': 'KeywordsV30Rc2',
        'external_identifiers': 'PersonExternalIdentifiersV30Rc2',
        'path': 'str'
    }

    attribute_map = {
        'last_modified_date': 'last-modified-date',
        'name': 'name',
        'other_names': 'other-names',
        'biography': 'biography',
        'researcher_urls': 'researcher-urls',
        'emails': 'emails',
        'addresses': 'addresses',
        'keywords': 'keywords',
        'external_identifiers': 'external-identifiers',
        'path': 'path'
    }

    def __init__(self, last_modified_date=None, name=None, other_names=None, biography=None, researcher_urls=None, emails=None, addresses=None, keywords=None, external_identifiers=None, path=None):  # noqa: E501
        """PersonV30Rc2 - a model defined in Swagger"""  # noqa: E501
        self._last_modified_date = None
        self._name = None
        self._other_names = None
        self._biography = None
        self._researcher_urls = None
        self._emails = None
        self._addresses = None
        self._keywords = None
        self._external_identifiers = None
        self._path = None
        self.discriminator = None
        if last_modified_date is not None:
            self.last_modified_date = last_modified_date
        if name is not None:
            self.name = name
        if other_names is not None:
            self.other_names = other_names
        if biography is not None:
            self.biography = biography
        if researcher_urls is not None:
            self.researcher_urls = researcher_urls
        if emails is not None:
            self.emails = emails
        if addresses is not None:
            self.addresses = addresses
        if keywords is not None:
            self.keywords = keywords
        if external_identifiers is not None:
            self.external_identifiers = external_identifiers
        if path is not None:
            self.path = path

    @property
    def last_modified_date(self):
        """Gets the last_modified_date of this PersonV30Rc2.  # noqa: E501

        :return: The last_modified_date of this PersonV30Rc2.  # noqa: E501
        :rtype: LastModifiedDateV30Rc2
        """
        return self._last_modified_date

    @last_modified_date.setter
    def last_modified_date(self, last_modified_date):
        """Sets the last_modified_date of this PersonV30Rc2.

        :param last_modified_date: The last_modified_date of this PersonV30Rc2.  # noqa: E501
        :type: LastModifiedDateV30Rc2
        """

        self._last_modified_date = last_modified_date

    @property
    def name(self):
        """Gets the name of this PersonV30Rc2.  # noqa: E501

        :return: The name of this PersonV30Rc2.  # noqa: E501
        :rtype: NameV30Rc2
        """
        return self._name

    @name.setter
    def name(self, name):
        """Sets the name of this PersonV30Rc2.

        :param name: The name of this PersonV30Rc2.  # noqa: E501
        :type: NameV30Rc2
        """

        self._name = name

    @property
    def other_names(self):
        """Gets the other_names of this PersonV30Rc2.  # noqa: E501

        :return: The other_names of this PersonV30Rc2.  # noqa: E501
        :rtype: OtherNamesV30Rc2
        """
        return self._other_names

    @other_names.setter
    def other_names(self, other_names):
        """Sets the other_names of this PersonV30Rc2.

        :param other_names: The other_names of this PersonV30Rc2.  # noqa: E501
        :type: OtherNamesV30Rc2
        """

        self._other_names = other_names

    @property
    def biography(self):
        """Gets the biography of this PersonV30Rc2.  # noqa: E501

        :return: The biography of this PersonV30Rc2.  # noqa: E501
        :rtype: BiographyV30Rc2
        """
        return self._biography

    @biography.setter
    def biography(self, biography):
        """Sets the biography of this PersonV30Rc2.

        :param biography: The biography of this PersonV30Rc2.  # noqa: E501
        :type: BiographyV30Rc2
        """

        self._biography = biography

    @property
    def researcher_urls(self):
        """Gets the researcher_urls of this PersonV30Rc2.  # noqa: E501

        :return: The researcher_urls of this PersonV30Rc2.  # noqa: E501
        :rtype: ResearcherUrlsV30Rc2
        """
        return self._researcher_urls

    @researcher_urls.setter
    def researcher_urls(self, researcher_urls):
        """Sets the researcher_urls of this PersonV30Rc2.

        :param researcher_urls: The researcher_urls of this PersonV30Rc2.  # noqa: E501
        :type: ResearcherUrlsV30Rc2
        """

        self._researcher_urls = researcher_urls

    @property
    def emails(self):
        """Gets the emails of this PersonV30Rc2.  # noqa: E501

        :return: The emails of this PersonV30Rc2.  # noqa: E501
        :rtype: EmailsV30Rc2
        """
        return self._emails

    @emails.setter
    def emails(self, emails):
        """Sets the emails of this PersonV30Rc2.

        :param emails: The emails of this PersonV30Rc2.  # noqa: E501
        :type: EmailsV30Rc2
        """

        self._emails = emails

    @property
    def addresses(self):
        """Gets the addresses of this PersonV30Rc2.  # noqa: E501

        :return: The addresses of this PersonV30Rc2.  # noqa: E501
        :rtype: AddressesV30Rc2
        """
        return self._addresses

    @addresses.setter
    def addresses(self, addresses):
        """Sets the addresses of this PersonV30Rc2.

        :param addresses: The addresses of this PersonV30Rc2.  # noqa: E501
        :type: AddressesV30Rc2
        """

        self._addresses = addresses

    @property
    def keywords(self):
        """Gets the keywords of this PersonV30Rc2.  # noqa: E501

        :return: The keywords of this PersonV30Rc2.  # noqa: E501
        :rtype: KeywordsV30Rc2
        """
        return self._keywords

    @keywords.setter
    def keywords(self, keywords):
        """Sets the keywords of this PersonV30Rc2.

        :param keywords: The keywords of this PersonV30Rc2.  # noqa: E501
        :type: KeywordsV30Rc2
        """

        self._keywords = keywords

    @property
    def external_identifiers(self):
        """Gets the external_identifiers of this PersonV30Rc2.  # noqa: E501

        :return: The external_identifiers of this PersonV30Rc2.  # noqa: E501
        :rtype: PersonExternalIdentifiersV30Rc2
        """
        return self._external_identifiers

    @external_identifiers.setter
    def external_identifiers(self, external_identifiers):
        """Sets the external_identifiers of this PersonV30Rc2.

        :param external_identifiers: The external_identifiers of this PersonV30Rc2.  # noqa: E501
        :type: PersonExternalIdentifiersV30Rc2
        """

        self._external_identifiers = external_identifiers

    @property
    def path(self):
        """Gets the path of this PersonV30Rc2.  # noqa: E501

        :return: The path of this PersonV30Rc2.  # noqa: E501
        :rtype: str
        """
        return self._path

    @path.setter
    def path(self, path):
        """Sets the path of this PersonV30Rc2.

        :param path: The path of this PersonV30Rc2.  # noqa: E501
        :type: str
        """

        self._path = path

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value
        if issubclass(PersonV30Rc2, dict):
            for key, value in self.items():
                result[key] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, PersonV30Rc2):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        return not self == other


text:
<Type Name="Response" FullName="Mono.Upcoming.Response">
  <TypeSignature Language="C#" Value="public class Response" />
  <AssemblyInfo>
    <AssemblyName>Mono.Upcoming</AssemblyName>
    <AssemblyVersion>0.0.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.Object</BaseTypeName>
  </Base>
  <Interfaces />
  <Attributes>
    <Attribute>
      <AttributeName>System.Xml.Serialization.XmlRoot(DataType="", ElementName="rsp", IsNullable=True, Namespace=null)</AttributeName>
    </Attribute>
  </Attributes>
  <Members>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public Response ();" />
      <MemberType>Constructor</MemberType>
      <Parameters />
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Status">
      <MemberSignature Language="C#" Value="public Mono.Upcoming.Status Status;" />
      <MemberType>Field</MemberType>
      <Attributes>
        <Attribute>
          <AttributeName>System.Xml.Serialization.XmlAttribute(AttributeName="stat", DataType="", Form=System.Xml.Schema.XmlSchemaForm.None, Namespace=null, Type=null)</AttributeName>
        </Attribute>
      </Attributes>
      <ReturnValue>
        <ReturnType>Mono.Upcoming.Status</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Categories">
      <MemberSignature Language="C#" Value="public Mono.Upcoming.Category[] Categories;" />
      <MemberType>Field</MemberType>
      <Attributes>
        <Attribute>
          <AttributeName>System.Xml.Serialization.XmlElement(DataType="", ElementName="category", Form=System.Xml.Schema.XmlSchemaForm.None, Namespace=null, IsNullable=False, Type=null)</AttributeName>
        </Attribute>
      </Attributes>
      <ReturnValue>
        <ReturnType>Mono.Upcoming.Category[]</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Countries">
      <MemberSignature Language="C#" Value="public Mono.Upcoming.Country[] Countries;" />
      <MemberType>Field</MemberType>
      <Attributes>
        <Attribute>
          <AttributeName>System.Xml.Serialization.XmlElement(DataType="", ElementName="country", Form=System.Xml.Schema.XmlSchemaForm.None, Namespace=null, IsNullable=False, Type=null)</AttributeName>
        </Attribute>
      </Attributes>
      <ReturnValue>
        <ReturnType>Mono.Upcoming.Country[]</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Events">
      <MemberSignature Language="C#" Value="public Mono.Upcoming.Event[] Events;" />
      <MemberType>Field</MemberType>
      <Attributes>
        <Attribute>
          <AttributeName>System.Xml.Serialization.XmlElement(DataType="", ElementName="event", Form=System.Xml.Schema.XmlSchemaForm.None, Namespace=null, IsNullable=False, Type=null)</AttributeName>
        </Attribute>
      </Attributes>
      <ReturnValue>
        <ReturnType>Mono.Upcoming.Event[]</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Groups">
      <MemberSignature Language="C#" Value="public Mono.Upcoming.Group[] Groups;" />
      <MemberType>Field</MemberType>
      <Attributes>
        <Attribute>
          <AttributeName>System.Xml.Serialization.XmlElement(DataType="", ElementName="group", Form=System.Xml.Schema.XmlSchemaForm.None, Namespace=null, IsNullable=False, Type=null)</AttributeName>
        </Attribute>
      </Attributes>
      <ReturnValue>
        <ReturnType>Mono.Upcoming.Group[]</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Metros">
      <MemberSignature Language="C#" Value="public Mono.Upcoming.Metro[] Metros;" />
      <MemberType>Field</MemberType>
      <Attributes>
        <Attribute>
          <AttributeName>System.Xml.Serialization.XmlElement(DataType="", ElementName="metro", Form=System.Xml.Schema.XmlSchemaForm.None, Namespace=null, IsNullable=False, Type=null)</AttributeName>
        </Attribute>
      </Attributes>
      <ReturnValue>
        <ReturnType>Mono.Upcoming.Metro[]</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="States">
      <MemberSignature Language="C#" Value="public Mono.Upcoming.State[] States;" />
      <MemberType>Field</MemberType>
      <Attributes>
        <Attribute>
          <AttributeName>System.Xml.Serialization.XmlElement(DataType="", ElementName="state", Form=System.Xml.Schema.XmlSchemaForm.None, Namespace=null, IsNullable=False, Type=null)</AttributeName>
        </Attribute>
      </Attributes>
      <ReturnValue>
        <ReturnType>Mono.Upcoming.State[]</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Token">
      <MemberSignature Language="C#" Value="public Mono.Upcoming.Token Token;" />
      <MemberType>Field</MemberType>
      <Attributes>
        <Attribute>
          <AttributeName>System.Xml.Serialization.XmlElement(DataType="", ElementName="token", Form=System.Xml.Schema.XmlSchemaForm.None, Namespace=null, IsNullable=False, Type=null)</AttributeName>
        </Attribute>
      </Attributes>
      <ReturnValue>
        <ReturnType>Mono.Upcoming.Token</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Users">
      <MemberSignature Language="C#" Value="public Mono.Upcoming.User[] Users;" />
      <MemberType>Field</MemberType>
      <Attributes>
        <Attribute>
          <AttributeName>System.Xml.Serialization.XmlElement(DataType="", ElementName="user", Form=System.Xml.Schema.XmlSchemaForm.None, Namespace=null, IsNullable=False, Type=null)</AttributeName>
        </Attribute>
      </Attributes>
      <ReturnValue>
        <ReturnType>Mono.Upcoming.User[]</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Venues">
      <MemberSignature Language="C#" Value="public Mono.Upcoming.Venue[] Venues;" />
      <MemberType>Field</MemberType>
      <Attributes>
        <Attribute>
          <AttributeName>System.Xml.Serialization.XmlElement(DataType="", ElementName="venue", Form=System.Xml.Schema.XmlSchemaForm.None, Namespace=null, IsNullable=False, Type=null)</AttributeName>
        </Attribute>
      </Attributes>
      <ReturnValue>
        <ReturnType>Mono.Upcoming.Venue[]</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Watches">
      <MemberSignature Language="C#" Value="public Mono.Upcoming.Watch[] Watches;" />
      <MemberType>Field</MemberType>
      <Attributes>
        <Attribute>
          <AttributeName>System.Xml.Serialization.XmlElement(DataType="", ElementName="watchlist", Form=System.Xml.Schema.XmlSchemaForm.None, Namespace=null, IsNullable=False, Type=null)</AttributeName>
        </Attribute>
      </Attributes>
      <ReturnValue>
        <ReturnType>Mono.Upcoming.Watch[]</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
  </Members>
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
</Type>


text:
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2011 BiGCaT Bioinformatics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.pathvisio.wikipathways.client;

import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

/**
 * The RPC service for the wikipathways search.
 * @author thomas
 */
@RemoteServiceRelativePath("wikipathwaysSearch")
public interface SearchService extends RemoteService {
	public static final int TIMEOUT = 60000;

	/**
	 * Perform a search.
	 * @param query The search query
	 * @return The results
	 */
	public Result[] search(Query query);

	/**
	 * Wait for a preview image to be converted on the server.
	 * This method will return after the image is generated, or after
	 * {@link #TIMEOUT} milliseconds have passed.
	 * @param id
	 */
	public void waitForImage(String id);

	/**
	 * Get the names for all supported database systems.
	 */
	public String[] getSystemNames();

	/**
	 * Get the names of all supported organisms.
	 */
	public String[] getOrganismNames();
}


text:
import pytest

from flexget.components.variables.variables import Variables
from flexget.event import fire_event
from flexget.manager import Session

@pytest.mark.usefixtures('tmpdir')
class TestVariablesFromFile:
    config = """
        variables: __tmp__/variables.yml
        tasks:
          test_variable_from_file:
            mock:
              - { title: 'test', location: 'http://mock'}
            if:
              - '{? test_variable ?}': accept

          test_variables_alongside_jinja:
            mock:
            - title: title 1
              entry_var: foo
            set:
              a_field: first {?bar_var?} then {{entry_var|default("shouldn't happen")}} {{fake_field|default("end")}}
            accept_all: yes
    """

    @pytest.mark.filecopy('variables.yml', '__tmp__/variables.yml')
    def test_variable_from_file(self, execute_task, manager):
        task = execute_task('test_variable_from_file')
        assert len(task.accepted) == 1

    @pytest.mark.filecopy('variables.yml', '__tmp__/variables.yml')
    def test_variables_alongside_jinja(self, execute_task):
        task = execute_task('test_variables_alongside_jinja')
        assert len(task.accepted) == 1
        assert task.accepted[0]['a_field'] == 'first bar then foo end'

class TestVariablesFromConfig:
    config = """
      variables:
        mock_entry_list:
        - title: a
        - title: b
        integer: 2
      tasks:
        test_int_var:
          mock:
          - title: a
          - title: b
          - title: c
          accept_all: yes
          limit_new: "{? integer ?}"
        test_var_mock:
          mock: "{? mock_entry_list ?}"
    """

    def test_complex_var(self, execute_task):
        task = execute_task('test_var_mock')
        assert len(task.all_entries) == 2
        assert task.all_entries[1]['title'] == 'b'

    def test_int_var(self, execute_task):
        task = execute_task('test_int_var')
        assert len(task.all_entries) == 3
        assert len(task.accepted) == 2

class TestVariablesFromDB:
    config = """
        variables: yes
        tasks:
          test_variable_from_db:
            mock:
              - { title: 'test', location: 'http://mock'}
            if:
              - '{? test_variable_db ?}': accept

    """

    def test_variable_from_db(self, execute_task, manager):
        with Session() as session:
            s = Variables(variables={'test_variable_db': True})
            session.add(s)

        fire_event('manager.before_config_validate', manager.config, manager)

        task = execute_task('test_variable_from_db')
        assert len(task.accepted) == 1


text:
import { CUSTOM_ELEMENTS_SCHEMA, DebugElement, NgModule } from '@angular/core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { By } from '@angular/platform-browser';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { MatDialogRef } from '@angular/material';
import { ObservableMedia, MatchMedia } from '@angular/flex-layout';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Rx';

import { SharedModule } from './../shared/shared.module';
import { MimeMaterialModule } from './../shared/mime-material.module';
import { ContentSearchDialogComponent } from './content-search-dialog.component';
import { MimeViewerIntl } from './../core/intl/viewer-intl';
import { IiifManifestService } from './../core/iiif-manifest-service/iiif-manifest-service';
import { IiifContentSearchService } from './../core/iiif-content-search-service/iiif-content-search.service';
import { MimeResizeService } from './../core/mime-resize-service/mime-resize.service';
import { MimeDomHelper } from './../core/mime-dom-helper';
import { FullscreenService } from './../core/fullscreen-service/fullscreen.service';
import { ViewerService } from './../core/viewer-service/viewer.service';
import { Hit } from './../core/models/search-result';

describe('ContentSearchDialogComponent', () => {
  let component: ContentSearchDialogComponent;
  let fixture: ComponentFixture<ContentSearchDialogComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        NoopAnimationsModule,
        SharedModule,
        HttpClientTestingModule
      ],
      declarations: [
        ContentSearchDialogComponent
      ],
      providers: [
        MimeViewerIntl,
        IiifManifestService,
        IiifContentSearchService,
        MimeResizeService,
        MimeDomHelper,
        FullscreenService,
        { provide: MatDialogRef, useClass: MatDialogRefMock },
        { provide: ObservableMedia, useClass: MediaMock },
        { provide: ViewerService, useClass: ViewerServiceMock }
      ]
    })
      .compileComponents();
  }));

  beforeEach(async(() => {
    fixture = TestBed.createComponent(ContentSearchDialogComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

  it('should be created', () => {
    expect(component).toBeTruthy();
  });

  it('should display desktop toolbar',
    inject([ObservableMedia], (media: ObservableMedia) => {
      spyOn(media, 'isActive').and.returnValue(false);

      fixture.detectChanges();

      const heading: DebugElement = fixture.debugElement.query(By.css('.heading-desktop'));
      expect(heading).not.toBeNull();
    }));

  it('should display mobile toolbar',
    inject([ObservableMedia], (media: ObservableMedia) => {
      spyOn(media, 'isActive').and.returnValue(true);

      fixture.detectChanges();

      const heading: DebugElement = fixture.debugElement.query(By.css('.heading-desktop'));
      expect(heading).toBeNull();
    }));

  it('should go to hit and close dialog when selected on mobile',
    inject([ObservableMedia, ViewerService, MatDialogRef],
      (media: ObservableMedia, viewerService: ViewerService, dialogRef: MatDialogRef<ContentSearchDialogComponent>) => {
      spyOn(media, 'isActive').and.returnValue(true);
      spyOn(viewerService, 'goToPage').and.callThrough();
      spyOn(dialogRef, 'close').and.callThrough();
      component.currentSearch = 'dummysearch';
      component.hits = [
        new Hit({
          index: 0,
          match: 'querystring'
        })
      ];
      component.numberOfHits = 1;
      fixture.detectChanges();

      const hits = fixture.debugElement.queryAll(By.css('.hit'));
      hits[0].triggerEventHandler('click', null);

      fixture.detectChanges();
      expect(viewerService.goToPage).toHaveBeenCalled();
      expect(dialogRef.close).toHaveBeenCalled();
    }));

    it('should go to hit and when selected on desktop',
    inject([ObservableMedia, ViewerService, MatDialogRef],
      (media: ObservableMedia, viewerService: ViewerService, dialogRef: MatDialogRef<ContentSearchDialogComponent>) => {
      spyOn(media, 'isActive').and.returnValue(false);
      spyOn(viewerService, 'goToPage').and.callThrough();
      spyOn(dialogRef, 'close').and.callThrough();
      component.currentSearch = 'dummysearch';
      component.hits = [
        new Hit({
          index: 0,
          match: 'querystring'
        })
      ];
      component.numberOfHits = 1;
      fixture.detectChanges();

      const hits = fixture.debugElement.queryAll(By.css('.hit'));
      hits[0].triggerEventHandler('click', null);

      fixture.detectChanges();
      expect(viewerService.goToPage).toHaveBeenCalled();
      expect(dialogRef.close).not.toHaveBeenCalled();
    }));

});

class MatDialogRefMock {
  close(): void {}
}

class MediaMock {
  isActive(m: string) {
    return false;
  }
}

class ViewerServiceMock {
  pageChanged = new Subject<number>();
  get onPageChange(): Observable<number> {
    return this.pageChanged.asObservable();
  }

  public goToPreviousPage(): void { }

  public goToNextPage(): void { }

  public goToPage(index: number): void { }

}


text:
module Mongo
  class Server
    class ConnectionPool

      # A FIFO queue of connections to be used by the connection pool. This is
      # based on mperham's connection pool, implemented with a queue instead of a
      # stack.
      #
      # @since 2.0.0
      class Queue
        extend Forwardable

        # Size of the queue delegates to the wrapped queue.
        def_delegators :queue, :size

        # The default max size for the queue.
        MAX_SIZE = 5.freeze

        # The default min size for the queue.
        MIN_SIZE = 1.freeze

        # The default timeout, in seconds, to wait for a connection.
        WAIT_TIMEOUT = 1.freeze

        # @return [ Array ] queue The underlying array of connections.
        attr_reader :queue

        # @return [ Mutex ] mutex The mutex used for synchronization.
        attr_reader :mutex

        # @return [ Hash ] options The options.
        attr_reader :options

        # @return [ ConditionVariable ] resource The resource.
        attr_reader :resource

        # Dequeue a connection from the queue, waiting for the provided timeout
        # for an item if none is in the queue.
        #
        # @example Dequeue a connection.
        #   queue.dequeue
        #
        # @return [ Mongo::Pool::Connection ] The next connection.
        #
        # @since 2.0.0
        def dequeue
          mutex.synchronize do
            dequeue_connection
          end
        end

        # Disconnect all connections in the queue.
        #
        # @example Disconnect all connections.
        #   queue.disconnect!
        #
        # @return [ true ] Always true.
        #
        # @since 2.1.0
        def disconnect!
          mutex.synchronize do
            queue.each{ |connection| connection.disconnect! }
            true
          end
        end

        # Enqueue a connection in the queue.
        #
        # @example Enqueue a connection.
        #   queue.enqueue(connection)
        #
        # @param [ Mongo::Pool::Connection ] connection The connection.
        #
        # @since 2.0.0
        def enqueue(connection)
          mutex.synchronize do
            queue.unshift(connection)
            resource.broadcast
          end
        end

        # Initialize the new queue. Will yield the block the number of times for
        # the initial size of the queue.
        #
        # @example Create the queue.
        #   Mongo::Pool::Queue.new(max_pool_size: 5) { Connection.new }
        #
        # @param [ Hash ] options The options.
        #
        # @option options [ Integer ] :max_pool_size The maximum size.
        # @option options [ Integer ] :min_pool_size The minimum size.
        # @option options [ Float ] :wait_queue_timeout The time to wait, in
        #   seconds, for a free connection.
        #
        # @since 2.0.0
        def initialize(options = {}, &block)
          @block = block
          @connections = 0
          @options = options
          @queue = Array.new(min_size) { create_connection }
          @mutex = Mutex.new
          @resource = ConditionVariable.new
        end

        # Get a pretty printed string inspection for the queue.
        #
        # @example Inspect the queue.
        #   queue.inspect
        #
        # @return [ String ] The queue inspection.
        #
        # @since 2.0.0
        def inspect
          "#<Mongo::Pool::Queue:0x#{object_id} min_size=#{min_size} max_size=#{max_size} " +
            "wait_timeout=#{wait_timeout} current_size=#{queue.size}>"
        end

        # Get the maximum size of the queue.
        #
        # @example Get the max size.
        #   queue.max_size
        #
        # @return [ Integer ] The maximum size of the queue.
        #
        # @since 2.0.0
        def max_size
          @max_size ||= options[:max_pool_size] || MAX_SIZE
        end

        # Get the minimum size of the queue.
        #
        # @example Get the min size.
        #   queue.min_size
        #
        # @return [ Integer ] The minimum size of the queue.
        #
        # @since 2.0.0
        def min_size
          @min_size ||= options[:min_pool_size] || MIN_SIZE
        end

        # The time to wait, in seconds, for a connection to become available.
        #
        # @example Get the wait timeout.
        #   queue.wait_timeout
        #
        # @return [ Float ] The queue wait timeout.
        #
        # @since 2.0.0
        def wait_timeout
          @wait_timeout ||= options[:wait_queue_timeout] || WAIT_TIMEOUT
        end

        private

        def dequeue_connection
          deadline = Time.now + wait_timeout
          loop do
            return queue.pop unless queue.empty?
            connection = create_connection
            return connection if connection
            wait_for_next!(deadline)
          end
        end

        def create_connection
          if @connections < max_size
            @connections += 1
            @block.call
          end
        end

        def wait_for_next!(deadline)
          wait = deadline - Time.now
          if wait <= 0
            raise Timeout::Error.new("Timed out attempting to dequeue connection after #{wait_timeout} sec.")
          end
          resource.wait(mutex, wait)
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>Qt 4.8: List of All Members for QMatrix4x4</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />

  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />

      Home

    Qt Reference Documentation

Qt HOME

DEV

          DOC

BLOG

Qt 4.8

ALL VERSIONS

API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

Examples

Examples

Tutorials

Demos

QML Examples

          Search index:

          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />

 Close

All | API | Articles | Examples

 results:

            </fieldset>
          </form>

            API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

            Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

            Examples

Examples

Tutorials

Demos

QML Examples

Home

Modules

QtGui

QMatrix4x4

A

A

A

                Print

List of All Members for QMatrix4x4

This is the complete list of members for QMatrix4x4, including inherited members.

QMatrix4x4 ()

QMatrix4x4 ( const qreal * )

QMatrix4x4 ( qreal, qreal, qreal, qreal, qreal, qreal, qreal, qreal, qreal, qreal, qreal, qreal, qreal, qreal, qreal, qreal )

QMatrix4x4 ( const QGenericMatrix<N, M, qreal> & )

QMatrix4x4 ( const QTransform & )

QMatrix4x4 ( const QMatrix & )

column ( int ) const : QVector4D

constData () const : const qreal *

copyDataTo ( qreal * ) const

data () : qreal *

data () const : const qreal *

determinant () const : qreal

fill ( qreal )

flipCoordinates ()

frustum ( qreal, qreal, qreal, qreal, qreal, qreal )

inverted ( bool * ) const : QMatrix4x4

isIdentity () const : bool

lookAt ( const QVector3D &, const QVector3D &, const QVector3D & )

map ( const QPoint & ) const : QPoint

map ( const QPointF & ) const : QPointF

map ( const QVector3D & ) const : QVector3D

map ( const QVector4D & ) const : QVector4D

mapRect ( const QRect & ) const : QRect

mapRect ( const QRectF & ) const : QRectF

mapVector ( const QVector3D & ) const : QVector3D

normalMatrix () const : QMatrix3x3

optimize ()

ortho ( qreal, qreal, qreal, qreal, qreal, qreal )

ortho ( const QRect & )

ortho ( const QRectF & )

perspective ( qreal, qreal, qreal, qreal )

rotate ( qreal, const QVector3D & )

rotate ( const QQuaternion & )

rotate ( qreal, qreal, qreal, qreal )

row ( int ) const : QVector4D

scale ( const QVector3D & )

scale ( qreal, qreal )

scale ( qreal, qreal, qreal )

scale ( qreal )

setColumn ( int, const QVector4D & )

setRow ( int, const QVector4D & )

setToIdentity ()

toAffine () const : QMatrix

toGenericMatrix () const : QGenericMatrix<N, M, qreal>

toTransform () const : QTransform

toTransform ( qreal ) const : QTransform

translate ( const QVector3D & )

translate ( qreal, qreal )

translate ( qreal, qreal, qreal )

transposed () const : QMatrix4x4

operator QVariant () const

operator!= ( const QMatrix4x4 & ) const : bool

operator() ( int, int ) const : const qreal &

operator() ( int, int ) : qreal &

operator*= ( const QMatrix4x4 & ) : QMatrix4x4 &

operator*= ( qreal ) : QMatrix4x4 &

operator+= ( const QMatrix4x4 & ) : QMatrix4x4 &

operator-= ( const QMatrix4x4 & ) : QMatrix4x4 &

operator/= ( qreal ) : QMatrix4x4 &

operator== ( const QMatrix4x4 & ) const : bool

      <acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
      subsidiaries. Documentation contributions included herein are the copyrights of
      their respective owners.

      The documentation provided herein is licensed under the terms of the
      GNU Free Documentation
      License version 1.3 as published by the Free Software Foundation.

      Documentation sources may be obtained from
      www.qt-project.org.

      Digia, Qt and their respective logos are trademarks of Digia Plc
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. Privacy Policy


text:
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Text.RegularExpressions;

namespace TF2_FastDL
{
	/// <summary>
	/// Description of LocalizationManager.
	/// </summary>
	internal static class LocalizationManager
	{
		private static Assembly assembly = Assembly.GetExecutingAssembly();
		private static string currentCulture = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
		private const string fileName = "strings";
		private static Regex regexStrings = new Regex("(?<name>\\S+?)\\s*?=\\s?(?<value>.+)");

		/// <summary>
		/// This method should be called as early as possible so we could tell the user what's really wrong.
		/// However, if it's not called it's not THAT worse.
		/// </summary>
		public static void Initialize()
		{
			string[] resources = assembly.GetManifestResourceNames();
			bool success = false;
			bool successEn = false;
			for (int i = 0; i < resources.Length; i++)
			{
				if (resources[i].Contains(fileName + "_" + currentCulture + ".txt"))
				{
					success = true;
				}
				else if (resources[i].Contains(fileName + "_en.txt"))
				{
					successEn = true;
				}
				if (success && successEn)
				{
					break;
				}
			}
			// This should never happen.. if so this is critical
			if (!successEn)
			{
				throw new MissingManifestResourceException();
			}
			if (!success)
			{
				currentCulture = "en";
			}
		}

		/// <summary>
		/// Gets a localized string.
		/// </summary>
		/// <param name="name">The name of the string.</param>
		/// <returns>Returns the localized string in the current culture.</returns>
		/// <exception cref="ArgumentNullException">name or locale is null.</exception>
		public static string GetLocalizedString(string name)
		{
			return GetLocalizedString(name, currentCulture);
		}

		/// <summary>
		/// Gets a localized string.
		/// </summary>
		/// <param name="name">The name of the string.</param>
		/// <param name="locale">The two-letter-string of the culture the string should be returned.</param>
		/// <returns>Returns the localized string in the given culture.</returns>
		/// <exception cref="ArgumentNullException">name or locale is null.</exception>
		public static string GetLocalizedString(string name, string locale)
		{
			if (name == null || locale == null)
			{
				throw new ArgumentNullException((name == null) ? "name" : "locale");
			}

			try
			{
				using (StreamReader sr = new StreamReader(assembly.GetManifestResourceStream(typeof(LocalizationManager).Namespace + "." + fileName + "_" + locale + ".txt")))
				{
					while (!sr.EndOfStream)
					{
						string text = sr.ReadLine();
						// One line comments will be ignored
						if (text.StartsWith("#") || text.StartsWith(";") || text.StartsWith("//"))
						{
							continue;
						}
						Match match = regexStrings.Match(text);
						if (match.Groups["name"].Value == name)
						{
							return match.Groups["value"].Value;
						}
					}
				}
			}
			catch (FileNotFoundException ex)
			{
				if (locale != "en")
				{
					return GetLocalizedString(name, "en");
				}
				throw ex;
			}

			if (locale != "en")
			{
				return GetLocalizedString(name, "en");
			}

			return null;
		}
	}
}


text:
package de.eich.utils;

public class StringUtils {

	public static String tabs(int n){
		String tabs = "";
		for(int i=0; i<n; i++)
			tabs += "\t";
		return tabs;
	}

}


text:
<?php
namespace empire\framework\tests\cookie\transceiver;

define('IPC_FILE', __DIR__ . DIRECTORY_SEPARATOR . "defaultcookietransceiver_ipc.json");
$decoded = json_decode(file_get_contents(IPC_FILE), true);
$bootstrap = $decoded['bootstrap'];
require $bootstrap;

use empire\framework\cookie\Cookie;
use empire\framework\cookie\transceiver\DefaultCookieTransceiver;
use empire\framework\request\Request;

$transceiver = new DefaultCookieTransceiver();

$request = new Request();
$method = $request->get('method', INPUT_GET, Request::TYPE_STRING, '#^[a-zA-Z]+$#');

$arguments = unserialize(base64_decode($_POST['arguments']));

// call the method
call_user_func_array(__NAMESPACE__ . '\\' . $method, $arguments);

function send(Cookie $cookie) {
	global $transceiver;
	$transceiver->send($cookie);
	echo base64_encode(serialize(null));
}

function receive($name) {
	global $transceiver;
	$cookie = $transceiver->receive($name);
	echo base64_encode(serialize($cookie));
}


text:
Use `FaradayMiddleware::Gzip` to automatically decompress response bodies. If the "Accept-Encoding" header wasn't set in the request, this sets it to "gzip,deflate" and appropriately handles the compressed response from the server. This resembles what Ruby does internally in Net::HTTP#get.

This middleware is NOT necessary when these adapters are used:

- `net_http`
- `net_http_persistent`
- `em_http`


text:
#ifndef PHP_MCRYPT_FILTER_H
#define PHP_MCRYPT_FILTER_H

extern php_stream_filter_factory php_mcrypt_filter_factory;

PHP_MINIT_FUNCTION(mcrypt_filter);
PHP_MSHUTDOWN_FUNCTION(mcrypt_filter);
PHP_MINFO_FUNCTION(mcrypt_filter);

#endif	/* PHP_MCRYPT_FILTER_H */

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * indent-tabs-mode: t
 * End:
 */


text:
#ifndef __MPH_to_H
#define __MPH_to_H

// M3E:
#include <sys/cdefs.h>

__BEGIN_DECLS

/** \brief Map minimal perfect hash of an interface ID to its class index. */

extern const signed char
    MPH_to_3DGroup[MPH_MAX],
    MPH_to_AudioPlayer[MPH_MAX],
    MPH_to_AudioRecorder[MPH_MAX],
    MPH_to_Engine[MPH_MAX],
    MPH_to_LEDDevice[MPH_MAX],
    MPH_to_Listener[MPH_MAX],
    MPH_to_MetadataExtractor[MPH_MAX],
    MPH_to_MidiPlayer[MPH_MAX],
    MPH_to_OutputMix[MPH_MAX],
    MPH_to_Vibra[MPH_MAX],
    MPH_to_MediaPlayer[MPH_MAX];

/** \brief Maximum number of interfaces on a single object. */
#define MAX_INDEX 32

__END_DECLS

#endif // !defined(__MPH_to_H)


text:
class ContextMenuContentTypeAppMode : public ContextMenuContentType {
 public:
  ContextMenuContentTypeAppMode(const ContextMenuContentTypeAppMode&) = delete;
  ContextMenuContentTypeAppMode& operator=(
      const ContextMenuContentTypeAppMode&) = delete;

  ~ContextMenuContentTypeAppMode() override;

  // ContextMenuContentType overrides.
  bool SupportsGroup(int group) override;

 protected:
  explicit ContextMenuContentTypeAppMode(
      const content::ContextMenuParams& params);

 private:
  friend class ContextMenuContentTypeFactory;
};

#endif  // CHROME_BROWSER_RENDERER_CONTEXT_MENU_CONTEXT_MENU_CONTENT_TYPE_APP_MODE_H_


text:
id: 132
title: Mister M em nova JSR Date and Time API
date: 2007-02-07T15:14:55+00:00
author: Claudio Miranda
layout: post
permalink: /2007/02/Mister-M-em-nova-JSR-Date-and-Time-API/
categories:
  - Java
---
Michael Nascimento Santos, que trabalha conosco na Summa, fez um clone seu para trabalhar em uma nova JSR a Date and Time API. Essa JSR terá influência do projeto de código livre Joda Date and Time API, pois o autor é participante da JSR também.

Ainda não li a proposta da JSR, mas algo que causa um pouco de trabalho, é atualizar o horário de verão, pois como as datas de ínicio e término variam em todas as ocorrências, é necessário atualizar o SO e JVM para refletir corretamente essas datas.

Até o ano passado era necessário efetuar o download do código fonte do JDK (não é o src.zip) e compilar o pacote javazic e baseado no arquivo de timezone novo (arquivo texto), gerar o novo arquivo de timezone (binário) e colocar no $JAVA_HOME/jre/lib/zi. Atualmente isso já consegue ser aliviado através da ferramenta TZUpdate que a Sun lançou ano passado.

Não sei se essa parte estará na JSR (vou ler mais tarde).

Ademais a API de Date e Time do Java precisa de algumas melhorias na API, para tornar mais fácil o uso dela. Ainda não esbarrei em algum problema sério que fizesse que eu usasse o JodaTime por exemplo (pelo que visualizei no guia de exemplo, é bem fácil).

Pela brincadeira do clone do Michael Nascimento, pois possui tantas atividades, que só clonando para conseguir fazer tantas atividades.

Desejo sucesso e que a API esteja disponível no JDK 7.


text:
====================
 Multi Website Demo
====================

After installation:

* Log out from database or open new incognito window
* Log in to database. At this moment module updates website settings according
  to domain you use. You need to do it only once.
* Open ``Website Admin >> Configuration >> Websites`` -- you can see list of websites with domain addresses
* Open one of addreses -- it opens related website

For more information see Documentation for `Real Multi Website <https://apps.odoo.com/apps/modules/13.0/website_multi_company_demo>`_ module.


text:
#ifndef __itkLocalVariationImageFilter_h
#define __itkLocalVariationImageFilter_h

#include "itkImageToImageFilter.h"
#include "itkImage.h"

namespace itk
{

  template<class TPixelType>
  class SquaredEuclideanMetric
  {
  public:
    static double Calc(TPixelType p);
  };

/** \class LocalVariationImageFilter
 * \brief Calculates the local variation in each pixel
 *
 * Reference: Tony F. Chan et al., The digital TV filter and nonlinear denoising
 *
 * \sa Image
 * \sa Neighborhood
 * \sa NeighborhoodOperator
 * \sa NeighborhoodIterator
 *
 * \ingroup IntensityImageFilters
 */
template <class TInputImage, class TOutputImage>
class LocalVariationImageFilter :
    public ImageToImageFilter< TInputImage, TOutputImage >
{
public:
  /** Extract dimension from input and output image. */
  itkStaticConstMacro(InputImageDimension, unsigned int,
                      TInputImage::ImageDimension);
  itkStaticConstMacro(OutputImageDimension, unsigned int,
                      TOutputImage::ImageDimension);

  /** Convenient typedefs for simplifying declarations. */
  typedef TInputImage InputImageType;
  typedef TOutputImage OutputImageType;

  /** Standard class typedefs. */
  typedef LocalVariationImageFilter Self;
  typedef ImageToImageFilter< InputImageType, OutputImageType> Superclass;
  typedef SmartPointer<Self> Pointer;
  typedef SmartPointer<const Self>  ConstPointer;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(LocalVariationImageFilter, ImageToImageFilter);

  /** Image typedef support. */
  typedef typename InputImageType::PixelType InputPixelType;
  typedef typename OutputImageType::PixelType OutputPixelType;

  typedef typename InputImageType::RegionType InputImageRegionType;
  typedef typename OutputImageType::RegionType OutputImageRegionType;

  typedef typename InputImageType::SizeType InputSizeType;

  /** MedianImageFilter needs a larger input requested region than
   * the output requested region.  As such, MedianImageFilter needs
   * to provide an implementation for GenerateInputRequestedRegion()
   * in order to inform the pipeline execution model.
   *
   * \sa ImageToImageFilter::GenerateInputRequestedRegion() */
  virtual void GenerateInputRequestedRegion()
    throw(InvalidRequestedRegionError);

protected:
  LocalVariationImageFilter();
  virtual ~LocalVariationImageFilter() {}
  void PrintSelf(std::ostream& os, Indent indent) const;

  /** MedianImageFilter can be implemented as a multithreaded filter.
   * Therefore, this implementation provides a ThreadedGenerateData()
   * routine which is called for each processing thread. The output
   * image data is allocated automatically by the superclass prior to
   * calling ThreadedGenerateData().  ThreadedGenerateData can only
   * write to the portion of the output image specified by the
   * parameter "outputRegionForThread"
   *
   * \sa ImageToImageFilter::ThreadedGenerateData(),
   *     ImageToImageFilter::GenerateData() */
  void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread,
                            ThreadIdType threadId );

private:
  LocalVariationImageFilter(const Self&); //purposely not implemented
  void operator=(const Self&); //purposely not implemented
};

} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkLocalVariationImageFilter.txx"
#endif

#endif //LocalVariationImageFilter


text:
title: Step Line Chart
order: 1
---


text:
<?php

/**
 * @namespace
 */
namespace ZendTest\Controller\Router;
use Zend\Translator;
use Zend\Controller\Router\Route;

/**
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Controller
 * @group      Zend_Controller_Router
 */
class RouteTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Server backup
     *
     * @var array
     */
    protected $_server = array();

    /**
     * Setup test
     *
     * @return void
     */
    public function setUp()
    {
        // Backup server array
        $this->_server = $_SERVER;

        // Clean host env
        unset($_SERVER['HTTP_HOST'],
            $_SERVER['HTTPS'], $_SERVER['SERVER_NAME'], $_SERVER['SERVER_PORT']);

       // Set translator
       $translator = new Translator\Translator('arrayAdapter', array('foo' => 'en_foo', 'bar' => 'en_bar'), 'en');
       $translator->addTranslation(array('foo' => 'de_foo', 'bar' => 'de_bar'), 'de');
       $translator->setLocale('en');

       \Zend\Registry::set('Zend_Translate', $translator);
    }

    /**
     * Clean
     *
     * @return void
     */
    public function tearDown()
    {
        // Restore server array
        $_SERVER = $this->_server;

        // Remove translator and locale
        \Zend\Registry::set('Zend_Translate', null);
        \Zend\Registry::set('Zend_Locale', null);
        Route\Route::setDefaultTranslator(null);
        Route\Route::setDefaultLocale(null);
    }

    public function testStaticMatch()
    {
        $route = new Route\Route('users/all');
        $values = $route->match('users/all');

        $this->assertSame(array(), $values);
    }

    public function testStaticUTFMatch()
    {
        $route = new Route\Route('żółć');
        $values = $route->match('żółć');

        $this->assertSame(array(), $values);
    }

    public function testURLDecode()
    {
        $route = new Route\Route('żółć');
        $values = $route->match('%C5%BC%C3%B3%C5%82%C4%87');

        $this->assertSame(array(), $values);
    }

    public function testStaticPathShorterThanParts()
    {
        $route = new Route\Route('users/a/martel');
        $values = $route->match('users/a');

        $this->assertSame(false, $values);
    }

    public function testStaticPathLongerThanParts()
    {
        $route = new Route\Route('users/a');
        $values = $route->match('users/a/martel');

        $this->assertEquals(false, $values);
    }

    public function testStaticMatchWithDefaults()
    {
        $route = new Route\Route('users/all', array('controller' => 'ctrl'));
        $values = $route->match('users/all');

        $this->assertEquals('ctrl', $values['controller']);
    }

    public function testNotMatched()
    {
        $route = new Route\Route('users/all');
        $values = $route->match('users/martel');

        $this->assertEquals(false, $values);
    }

    public function testNotMatchedWithVariablesAndDefaults()
    {
        $route = new Route\Route(':controller/:action', array('controller' => 'index', 'action' => 'index'));
        $values = $route->match('archive/action/bogus');

        $this->assertEquals(false, $values);
    }

    public function testNotMatchedWithVariablesAndStatic()
    {
        $route = new Route\Route('archive/:year/:month');
        $values = $route->match('ctrl/act/2000');

        $this->assertEquals(false, $values);
    }

    public function testStaticMatchWithWildcard()
    {
        $route = new Route\Route('news/view/*', array('controller' => 'news', 'action' => 'view'));
        $values = $route->match('news/view/show/all/year/2000/empty');

        $this->assertEquals('news', $values['controller']);
        $this->assertEquals('view', $values['action']);
        $this->assertEquals('all', $values['show']);
        $this->assertEquals('2000', $values['year']);
        $this->assertEquals(null, $values['empty']);
    }

    public function testWildcardWithUTF()
    {
        $route = new Route\Route('news/*', array('controller' => 'news', 'action' => 'view'));
        $values = $route->match('news/klucz/wartość/wskaźnik/wartość');

        $this->assertEquals('news', $values['controller']);
        $this->assertEquals('view', $values['action']);
        $this->assertEquals('wartość', $values['klucz']);
        $this->assertEquals('wartość', $values['wskaźnik']);
    }

    public function testWildcardURLDecode()
    {
        $route = new Route\Route('news/*', array('controller' => 'news', 'action' => 'view'));
        $values = $route->match('news/wska%C5%BAnik/warto%C5%9B%C4%87');

        $this->assertEquals('news', $values['controller']);
        $this->assertEquals('view', $values['action']);
        $this->assertEquals('wartość', $values['wskaźnik']);
    }

    public function testVariableValues()
    {
        $route = new Route\Route(':controller/:action/:year');
        $values = $route->match('ctrl/act/2000');

        $this->assertEquals('ctrl', $values['controller']);
        $this->assertEquals('act', $values['action']);
        $this->assertEquals('2000', $values['year']);
    }

    public function testVariableUTFValues()
    {
        $route = new Route\Route('test/:param');
        $values = $route->match('test/aä');

        $this->assertEquals('aä', $values['param']);
    }

    public function testOneVariableValue()
    {
        $route = new Route\Route(':action', array('controller' => 'ctrl', 'action' => 'action'));
        $values = $route->match('act');

        $this->assertEquals('ctrl', $values['controller']);
        $this->assertEquals('act', $values['action']);
    }

    public function testVariablesWithDefault()
    {
        $route = new Route\Route(':controller/:action/:year', array('year' => '2006'));
        $values = $route->match('ctrl/act');

        $this->assertEquals('ctrl', $values['controller']);
        $this->assertEquals('act', $values['action']);
        $this->assertEquals('2006', $values['year']);
    }

    public function testVariablesWithNullDefault() // Kevin McArthur
    {
        $route = new Route\Route(':controller/:action/:year', array('year' => null));
        $values = $route->match('ctrl/act');

        $this->assertEquals('ctrl', $values['controller']);
        $this->assertEquals('act', $values['action']);
        $this->assertNull($values['year']);
    }

    public function testVariablesWithDefaultAndValue()
    {
        $route = new Route\Route(':controller/:action/:year', array('year' => '2006'));
        $values = $route->match('ctrl/act/2000');

        $this->assertEquals('ctrl', $values['controller']);
        $this->assertEquals('act', $values['action']);
        $this->assertEquals('2000', $values['year']);
    }

    public function testVariablesWithRequirementAndValue()
    {
        $route = new Route\Route(':controller/:action/:year', null, array('year' => '\d+'));
        $values = $route->match('ctrl/act/2000');

        $this->assertEquals('ctrl', $values['controller']);
        $this->assertEquals('act', $values['action']);
        $this->assertEquals('2000', $values['year']);
    }

    public function testVariablesWithRequirementAndIncorrectValue()
    {
        $route = new Route\Route(':controller/:action/:year', null, array('year' => '\d+'));
        $values = $route->match('ctrl/act/2000t');

        $this->assertEquals(false, $values);
    }

    public function testVariablesWithDefaultAndRequirement()
    {
        $route = new Route\Route(':controller/:action/:year', array('year' => '2006'), array('year' => '\d+'));
        $values = $route->match('ctrl/act/2000');

        $this->assertEquals('ctrl', $values['controller']);
        $this->assertEquals('act', $values['action']);
        $this->assertEquals('2000', $values['year']);
    }

    public function testVariablesWithDefaultAndRequirementAndIncorrectValue()
    {
        $route = new Route\Route(':controller/:action/:year', array('year' => '2006'), array('year' => '\d+'));
        $values = $route->match('ctrl/act/2000t');

        $this->assertEquals(false, $values);
    }

    public function testVariablesWithDefaultAndRequirementAndWithoutValue()
    {
        $route = new Route\Route(':controller/:action/:year', array('year' => '2006'), array('year' => '\d+'));
        $values = $route->match('ctrl/act');

        $this->assertEquals('ctrl', $values['controller']);
        $this->assertEquals('act', $values['action']);
        $this->assertEquals('2006', $values['year']);
    }

    public function testVariablesWithWildcardAndNumericKey()
    {
        $route = new Route\Route(':controller/:action/:next/*');
        $values = $route->match('c/a/next/2000/show/all/sort/name');

        $this->assertEquals('c', $values['controller']);
        $this->assertEquals('a', $values['action']);
        $this->assertEquals('next', $values['next']);
        $this->assertTrue(array_key_exists('2000', $values));
    }

    public function testRootRoute()
    {
        $route = new Route\Route('/');
        $values = $route->match('');

        $this->assertEquals(array(), $values);
    }

    public function testAssemble()
    {
        $route = new Route\Route('authors/:name');
        $url = $route->assemble(array('name' => 'martel'));

        $this->assertEquals('authors/martel', $url);
    }

    public function testAssembleWithoutValue()
    {
        $route = new Route\Route('authors/:name');
        try {
            $url = $route->assemble();
        } catch (\Exception $e) {
            return true;
        }

        $this->fail();
    }

    public function testAssembleWithDefault()
    {
        $route = new Route\Route('authors/:name', array('name' => 'martel'));
        $url = $route->assemble();

        $this->assertEquals('authors', $url);
    }

    public function testAssembleWithDefaultAndValue()
    {
        $route = new Route\Route('authors/:name', array('name' => 'martel'));
        $url = $route->assemble(array('name' => 'mike'));

        $this->assertEquals('authors/mike', $url);
    }

    public function testAssembleWithWildcardMap()
    {
        $route = new Route\Route('authors/:name/*');
        $url = $route->assemble(array('name' => 'martel'));

        $this->assertEquals('authors/martel', $url);
    }

    public function testAssembleWithReset()
    {
        $route = new Route\Route('archive/:year/*', array('controller' => 'archive', 'action' => 'show'));
        $values = $route->match('archive/2006/show/all/sort/name');

        $url = $route->assemble(array('year' => '2005'), true);

        $this->assertEquals('archive/2005', $url);
    }

    public function testAssembleWithReset2()
    {
        $route = new Route\Route(':controller/:action/*', array('controller' => 'archive', 'action' => 'show'));
        $values = $route->match('users/list');

        $url = $route->assemble(array(), true);

        $this->assertEquals('', $url);
    }

    public function testAssembleWithReset3()
    {
        $route = new Route\Route('archive/:year/*', array('controller' => 'archive', 'action' => 'show', 'year' => 2005));
        $values = $route->match('archive/2006/show/all/sort/name');

        $url = $route->assemble(array(), true);

        $this->assertEquals('archive', $url);
    }

    public function testAssembleWithReset4()
    {
        $route = new Route\Route(':controller/:action/*', array('controller' => 'archive', 'action' => 'show'));
        $values = $route->match('users/list');

        $url = $route->assemble(array('action' => 'display'), true);

        $this->assertEquals('archive/display', $url);
    }

    public function testAssembleWithReset5()
    {
        $route = new Route\Route('*', array('controller' => 'index', 'action' => 'index'));
        $values = $route->match('key1/value1/key2/value2');

        $url = $route->assemble(array('key1' => 'newvalue'), true);

        $this->assertEquals('key1/newvalue', $url);
    }

    public function testAssembleWithWildcardAndAdditionalParameters()
    {
        $route = new Route\Route('authors/:name/*');
        $url = $route->assemble(array('name' => 'martel', 'var' => 'value'));

        $this->assertEquals('authors/martel/var/value', $url);
    }

    public function testAssembleWithUrlVariablesReuse()
    {
        $route = new Route\Route('archives/:year/:month');
        $values = $route->match('archives/2006/07');
        $this->assertInternalType('array', $values);

        $url = $route->assemble(array('month' => '03'));
        $this->assertEquals('archives/2006/03', $url);
    }

    /**
     * @group ZF-7917
     */
    public function testAssembleWithGivenDataEqualsDefaults()
    {
        $route = new Route\Route('index/*', array(
            'module'     => 'default',
            'controller' => 'index',
            'action'     => 'index'
        ));

        $this->assertEquals('index', $route->assemble(array(
            'module'     => 'default',
            'controller' => 'index',
            'action'     => 'index'
        )));
    }

    public function testWildcardUrlVariablesOverwriting()
    {
        $route = new Route\Route('archives/:year/:month/*', array('controller' => 'archive'));
        $values = $route->match('archives/2006/07/controller/test/year/10000/sort/author');
        $this->assertInternalType('array', $values);

        $this->assertEquals('archive', $values['controller']);
        $this->assertEquals('2006', $values['year']);
        $this->assertEquals('07', $values['month']);
        $this->assertEquals('author', $values['sort']);
    }

    public function testGetDefaults()
    {
        $route = new Route\Route('users/all',
                    array('controller' => 'ctrl', 'action' => 'act'));

        $values = $route->getDefaults();

        $this->assertInternalType('array', $values);
        $this->assertEquals('ctrl', $values['controller']);
        $this->assertEquals('act', $values['action']);
    }

    public function testGetDefault()
    {
        $route = new Route\Route('users/all',
                    array('controller' => 'ctrl', 'action' => 'act'));

        $this->assertEquals('ctrl', $route->getDefault('controller'));
        $this->assertEquals(null, $route->getDefault('bogus'));
    }

    public function testGetInstance()
    {

        $routeConf = array(
            'route' => 'users/all',
            'defaults' => array(
                'controller' => 'ctrl'
            )
        );

        $config = new \Zend\Config\Config($routeConf);
        $route = Route\Route::getInstance($config);

        $this->assertInstanceOf('Zend\Controller\Router\Route\Route', $route);

        $values = $route->match('users/all');

        $this->assertEquals('ctrl', $values['controller']);

    }

    public function testAssembleResetDefaults()
    {
        $route = new Route\Route(':controller/:action/*', array('controller' => 'index', 'action' => 'index'));

        $values = $route->match('news/view/id/3');

        $url = $route->assemble(array('controller' => null));
        $this->assertEquals('index/view/id/3', $url);

        $url = $route->assemble(array('action' => null));
        $this->assertEquals('news/index/id/3', $url);

        $url = $route->assemble(array('action' => null, 'id' => null));
        $this->assertEquals('news', $url);
    }

    public function testAssembleWithRemovedDefaults() // Test for ZF-1197
    {
        $route = new Route\Route(':controller/:action/*', array('controller' => 'index', 'action' => 'index'));

        $url = $route->assemble(array('id' => 3));
        $this->assertEquals('index/index/id/3', $url);

        $url = $route->assemble(array('action' => 'test'));
        $this->assertEquals('index/test', $url);

        $url = $route->assemble(array('action' => 'test', 'id' => 3));
        $this->assertEquals('index/test/id/3', $url);

        $url = $route->assemble(array('controller' => 'test'));
        $this->assertEquals('test', $url);

        $url = $route->assemble(array('controller' => 'test', 'action' => 'test'));
        $this->assertEquals('test/test', $url);

        $url = $route->assemble(array('controller' => 'test', 'id' => 3));
        $this->assertEquals('test/index/id/3', $url);

        $url = $route->assemble(array());
        $this->assertEquals('', $url);

        $route->match('ctrl');

        $url = $route->assemble(array('id' => 3));
        $this->assertEquals('ctrl/index/id/3', $url);

        $url = $route->assemble(array('action' => 'test'));
        $this->assertEquals('ctrl/test', $url);

        $url = $route->assemble();
        $this->assertEquals('ctrl', $url);

        $route->match('index');

        $url = $route->assemble();
        $this->assertEquals('', $url);
    }

    /**
     * Test guarding performance. Test may be failing on slow systems and shouldn't be failing on production.
     * This test is not critical in nature - it allows keeping changes performant.
     */

    /**
     * This test is commented out because performance testing should be done separately from unit
     * testing. It will be ported to a performance regression suite when such a suite is available.
     */
//    public function testRoutePerformance()
//    {
//        $count = 10000;
//        $expectedTime = 1;
//
//        $info = "This test may be failing on slow systems and shouldn't be failing on production. Tests if " . ($count / 10) . " complicated routes can be matched in a tenth of a second. Actual test matches " . $count . " times to make the test more reliable.";
//
//        $route = new Zend_Controller_Router_Route('archives/:year/:month/*', array('controller' => 'archive'));
//
//        $time_start = microtime(true);
//
//        for ($i = 1; $i <= $count; $i++) {
//            $values = $route->match('archives/2006/' . $i . '/controller/test/year/' . $i . '/sort/author');
//        }
//
//        $time_end = microtime(true);
//        $time = $time_end - $time_start;
//
//        $this->assertLessThan($expectedTime, $time, $info);
//    }

    public function testForZF2543()
    {
        $route = new Route\Route('families/:action/*', array('module' => 'default', 'controller' => 'categories', 'action' => 'index'));
        $this->assertEquals('families', $route->assemble());

        $values = $route->match('families/edit/id/4');
        $this->assertInternalType('array', $values);

        $this->assertEquals('families/edit/id/4', $route->assemble());
    }

    public function testEncode()
    {
        $route = new Route\Route(':controller/:action/*', array('controller' => 'index', 'action' => 'index'));

        $url = $route->assemble(array('controller' => 'My Controller'), false, true);
        $this->assertEquals('My+Controller', $url);

        $url = $route->assemble(array('controller' => 'My Controller'), false, false);
        $this->assertEquals('My Controller', $url);

        $token = $route->match('en/foo/id/My Value');

        $url = $route->assemble(array(), false, true);
        $this->assertEquals('en/foo/id/My+Value', $url);

        $url = $route->assemble(array('id' => 'My Other Value'), false, true);
        $this->assertEquals('en/foo/id/My+Other+Value', $url);

        $route = new Route\Route(':controller/*', array('controller' => 'My Controller'));
        $url = $route->assemble(array('id' => 1), false, true);
        $this->assertEquals('My+Controller/id/1', $url);
    }

    public function testPartialMatch()
    {
        $route = new Route\Route(':lang/:temp', array('lang' => 'pl'), array('temp' => '\d+'));

        $values = $route->match('en/tmp/ctrl/action/id/1', true);

        $this->assertFalse($values);

        $route = new Route\Route(':lang/:temp', array('lang' => 'pl'));

        $values = $route->match('en/tmp/ctrl/action/id/1', true);

        $this->assertInternalType('array', $values);
        $this->assertEquals('en', $values['lang']);
        $this->assertEquals('tmp', $values['temp']);
        $this->assertEquals('en/tmp', $route->getMatchedPath());

    }

    /**
     * Translated behaviour
     */
    public function testStaticTranslationAssemble()
    {
        $route = new Route\Route('foo/@foo');
        $url   = $route->assemble();

        $this->assertEquals('foo/en_foo', $url);
    }

    public function testStaticTranslationMatch()
    {
        $route  = new Route\Route('foo/@foo');
        $values = $route->match('foo/en_foo');

        $this->assertTrue(is_array($values));
    }

    public function testDynamicTranslationAssemble()
    {
        $route = new Route\Route('foo/:@myvar');
        $url   = $route->assemble(array('myvar' => 'foo'));

        $this->assertEquals('foo/en_foo', $url);
    }

    public function testDynamicTranslationMatch()
    {
        $route  = new Route\Route('foo/:@myvar');
        $values = $route->match('foo/en_foo');

        $this->assertEquals($values['myvar'], 'foo');
    }

    public function testTranslationMatchWrongLanguage()
    {
        $route  = new Route\Route('foo/@foo');
        $values = $route->match('foo/de_foo');

        $this->assertFalse($values);
    }

    public function testTranslationAssembleLocaleInstanceOverride()
    {
        $route = new Route\Route('foo/@foo', null, null, null, 'de');
        $url   = $route->assemble();

        $this->assertEquals('foo/de_foo', $url);
    }

    public function testTranslationAssembleLocaleParamOverride()
    {
        $route = new Route\Route('foo/@foo');
        $url   = $route->assemble(array('@locale' => 'de'));

        $this->assertEquals('foo/de_foo', $url);
    }

    public function testTranslationAssembleLocaleStaticOverride()
    {
        Route\Route::setDefaultLocale('de');

        $route = new Route\Route('foo/@foo');
        $url   = $route->assemble();

        $this->assertEquals('foo/de_foo', $url);
    }

    public function testTranslationAssembleLocaleRegistryOverride()
    {
        \Zend\Registry::set('Zend_Locale', 'de');

        $route = new Route\Route('foo/@foo');
        $url   = $route->assemble();

        $this->assertEquals('foo/de_foo', $url);
    }

    public function testTranslationAssembleTranslatorInstanceOverride()
    {
        $translator = new Translator\Translator('arrayAdapter', array('foo' => 'en_baz'), 'en');

        $route = new Route\Route('foo/@foo', null, null, $translator);
        $url   = $route->assemble();

        $this->assertEquals('foo/en_baz', $url);
    }

    public function testTranslationAssembleTranslatorStaticOverride()
    {
        $translator = new Translator\Translator('arrayAdapter', array('foo' => 'en_baz'), 'en');

        Route\Route::setDefaultTranslator($translator);

        $route = new Route\Route('foo/@foo');
        $url   = $route->assemble();

        $this->assertEquals('foo/en_baz', $url);
    }

    public function testTranslationAssembleTranslatorRegistryOverride()
    {
        $translator = new Translator\Translator('arrayAdapter', array('foo' => 'en_baz'), 'en');

        \Zend\Registry::set('Zend_Translate', $translator);

        $route = new Route\Route('foo/@foo');
        $url   = $route->assemble();

        $this->assertEquals('foo/en_baz', $url);
    }

    public function testTranslationAssembleTranslatorNotFound()
    {
        \Zend\Registry::set('Zend_Translate', null);

        $route = new Route\Route('foo/@foo');

        try {
            $url = $route->assemble();
            $this->fail('Expected Zend_Controller_Router_Exception was not raised');
        } catch (\Zend\Controller\Router\Exception $e) {
            $this->assertEquals('Could not find a translator', $e->getMessage());
        }
    }

    public function testEscapedSpecialCharsWithoutTranslation()
    {
        $route = new Route\Route('::foo/@@bar/:foo');

        $path = $route->assemble(array('foo' => 'bar'));
        $this->assertEquals($path, ':foo/@bar/bar');

        $values = $route->match(':foo/@bar/bar');
        $this->assertEquals($values['foo'], 'bar');
    }

    public function testEscapedSpecialCharsWithTranslation()
    {
        $route = new Route\Route('::foo/@@bar/:@myvar');

        $path = $route->assemble(array('myvar' => 'foo'));
        $this->assertEquals($path, ':foo/@bar/en_foo');

        $values = $route->match(':foo/@bar/en_foo');
        $this->assertEquals($values['myvar'], 'foo');
    }
}


text:
package org.spoofax.jsglr2.integrationtest.recovery;

import java.util.Arrays;
import java.util.stream.Stream;

import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.spoofax.jsglr2.integrationtest.BaseTestWithRecoverySdf3ParseTables;
import org.spoofax.jsglr2.integrationtest.MessageDescriptor;
import org.spoofax.jsglr2.messages.Severity;
import org.spoofax.terms.ParseError;

public class RecoveryMessagesTest extends BaseTestWithRecoverySdf3ParseTables {

    public RecoveryMessagesTest() {
        super("recovery.sdf3", false, false, false);
    }

    @TestFactory public Stream<DynamicTest> testRecovery() throws ParseError {
        return testMessages("y", Arrays.asList(
        //@formatter:off
            new MessageDescriptor("Invalid syntax", Severity.ERROR, 0, 1, 1, 1)
        //@formatter:on
        ), getTestVariants(isRecoveryVariant));
    }

}


text:
define(
({
	buttonOk: "OK",
	buttonCancel: "Cancelar",
	buttonSave: "Salvar",
	itemClose: "Fechar"
})
);


text:
Node* buildAST(TokenStream stream, Node* root = nullptr, Node* p = nullptr) {
    if (stream.findInflection()!=-1) {
        TokenStream left, right;
        Token inflection;
        stream.split(inflection,left,right);
        Node* n = new Node(p, root, "operator", inflection.data, nullptr, nullptr);
        if (root==nullptr) root=n;
        n->left=buildAST(left, root, n);
        n->right=buildAST(right, root, n);
        return n;
    }
    else {
        Token t = stream.get(1);
        if (t.data!="(") {
            if (t.type=="function") {
                Node *n = new Node(p, root, t.type, t.data, nullptr, nullptr);
                if (root == nullptr) root = n;
                stream.breakBrackets();
                n->left=buildAST(stream, root, n);
                return n;
            }
            if (t.type=="constant") {
                Node *n = new Node(p, root, t.type, t.data, nullptr, nullptr);
                if (root == nullptr) root = n;
                return n;
            }
            if (t.type=="variable") {
                Node *n = new Node(p, root, t.type, t.data, nullptr, nullptr);
                if (n->root==nullptr) n->root=n;
                return (Node*)n;
            }
        }
        else {
            stream.breakBrackets();
            return buildAST(stream, root, p);
        }
    }
}


text:
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { ClarityModule } from '@clr/angular';
import { RouterTestingModule } from '@angular/router/testing';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { SecurityServiceMock } from '../../../tests/api/security.service.mock';
import { AboutServiceMock } from '../../../tests/api/about.service.mock';
import { NotificationServiceMock } from '../../../tests/service/notification.service.mock';
import { By } from '@angular/platform-browser';
import { throwError } from 'rxjs';
import { TaskServiceMock } from '../../../tests/api/task.service.mock';
import { CleanupComponent } from './cleanup.component';
import { TaskExecution } from '../../../shared/model/task-execution.model';
import { ContextServiceMock } from '../../../tests/service/context.service.mock';

describe('tasks-jobs/executions/cleanup/cleanup.component.ts', () => {

  let component: CleanupComponent;
  let fixture: ComponentFixture<CleanupComponent>;
  let executions: TaskExecution[];

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [
        CleanupComponent
      ],
      imports: [
        FormsModule,
        ClarityModule,
        RouterTestingModule.withRoutes([]),
        BrowserAnimationsModule,
      ],
      providers: [
        SecurityServiceMock.provider,
        AboutServiceMock.provider,
        NotificationServiceMock.provider,
        TaskServiceMock.provider,
        ContextServiceMock.provider
      ]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CleanupComponent);
    component = fixture.componentInstance;
    NotificationServiceMock.mock.clearAll();
    executions = [
      TaskExecution.parse({ executionId: 'foo' }),
      TaskExecution.parse({ executionId: 'bar' }),
    ];
  });

  it('should be created', () => {
    fixture.detectChanges();
    expect(component).toBeTruthy();
  });

  it('should destroy a task', async (done) => {
    component.open([executions[0]]);
    fixture.detectChanges();
    await fixture.whenStable();
    fixture.detectChanges();
    const title = fixture.debugElement.query(By.css('.modal-title-wrapper')).nativeElement;
    expect(title.textContent).toContain('Confirm Clean Up Task Execution(s)');
    fixture.debugElement.query(By.css('.modal-footer .btn-danger')).nativeElement.click();
    fixture.detectChanges();
    await fixture.whenStable();
    expect(NotificationServiceMock.mock.successNotifications[0].title).toBe('Clean up task execution(s)');
    expect(NotificationServiceMock.mock.successNotifications[0].message)
      .toBe('1 task execution(s) cleaned up.');
    done();
  });

  it('should destroy tasks', async (done) => {
    component.open(executions);
    fixture.detectChanges();
    await fixture.whenStable();
    fixture.detectChanges();
    const title = fixture.debugElement.query(By.css('.modal-title-wrapper')).nativeElement;
    expect(title.textContent).toContain('Confirm Clean Up Task Execution(s)');
    fixture.debugElement.query(By.css('.modal-footer .btn-danger')).nativeElement.click();
    fixture.detectChanges();
    await fixture.whenStable();
    expect(NotificationServiceMock.mock.successNotifications[0].title).toBe('Clean up task execution(s)');
    expect(NotificationServiceMock.mock.successNotifications[0].message)
      .toBe('2 task execution(s) cleaned up.');
    done();
  });

  it('should display an error', async (done) => {
    spyOn(TaskServiceMock.mock, 'executionsClean').and.callFake(() => {
      return throwError(new Error('Fake error'));
    });
    component.open([executions[0]]);
    fixture.detectChanges();
    await fixture.whenStable();
    fixture.detectChanges();
    const title = fixture.debugElement.query(By.css('.modal-title-wrapper')).nativeElement;
    expect(title.textContent).toContain('Confirm Clean Up Task Execution(s)');
    fixture.debugElement.query(By.css('.modal-footer .btn-danger')).nativeElement.click();
    fixture.detectChanges();
    await fixture.whenStable();
    expect(NotificationServiceMock.mock.errorNotification[0].title).toBe('An error occurred');
    done();
  });

});