text:
package moss

import (
	"fmt"
)

func (s *Store) snapshotRevert(revertTo Snapshot) error {
	s.m.Lock()
	defer s.m.Unlock()

	revertToFooter, ok := revertTo.(*Footer)
	if !ok {
		return fmt.Errorf("can only revert a footer")
	}

	fileNameCurr := FormatFName(s.nextFNameSeq - 1)
	if fileNameCurr != revertToFooter.fileName {
		return fmt.Errorf("snapshot too old, revertToSnapshot.fileName: %+v,"+
			" fileNameCurr: %s", revertToFooter.fileName, fileNameCurr)
	}

	persistOptions := StorePersistOptions{}
	footer, err := s.revertToSnapshot(revertToFooter, persistOptions)
	if err != nil {
		return err
	}

	err = s.persistFooter(revertToFooter.SegmentLocs[0].mref.fref.file, footer,
		persistOptions)
	if err != nil {
		footer.DecRef()
		return err
	}
	footerPrev := s.footer
	s.footer = footer // Owns the footer ref-count.
	s.totPersists++

	if footerPrev != nil {
		footerPrev.DecRef()
	}

	return nil
}

func (s *Store) revertToSnapshot(revertToFooter *Footer, options StorePersistOptions) (
	rv *Footer, err error) {
	if len(revertToFooter.SegmentLocs) <= 0 {
		return nil, fmt.Errorf("revert footer slocs <= 0")
	}

	mref := revertToFooter.SegmentLocs[0].mref
	if mref == nil || mref.fref == nil || mref.fref.file == nil {
		return nil, fmt.Errorf("revert footer parts nil")
	}

	slocs := append(SegmentLocs{}, revertToFooter.SegmentLocs...)
	slocs.AddRef()

	footer := &Footer{
		refs:        1,
		SegmentLocs: slocs,
		ss:          revertToFooter.ss,
	}

	for cName, childFooter := range revertToFooter.ChildFooters {
		newChildFooter, err := s.revertToSnapshot(childFooter, options)
		if err != nil {
			footer.DecRef()
			return nil, err
		}
		if len(footer.ChildFooters) == 0 {
			footer.ChildFooters = make(map[string]*Footer)
		}
		footer.ChildFooters[cName] = newChildFooter
	}

	return footer, nil
}


text:
package oic.simulator.serviceprovider.model;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.oic.simulator.AttributeProperty;
import org.oic.simulator.AttributeValue;
import org.oic.simulator.AttributeValue.ValueType;
import org.oic.simulator.BooleanProperty;
import org.oic.simulator.DoubleProperty;
import org.oic.simulator.IntegerProperty;
import org.oic.simulator.SimulatorResourceAttribute;
import org.oic.simulator.StringProperty;

import oic.simulator.serviceprovider.utils.Constants;
import oic.simulator.serviceprovider.utils.Utility;

public class AttributeHelper {
    private String      attributeName;
    private String      attributeType;
    private String      min;
    private String      max;
    private Set<String> allowedValues;
    private String      attributeDflValue;

    public enum ValidValuesType {
        RANGE, VALUESET, UNKNOWN
    }

    private ValidValuesType validValuesType;

    public AttributeHelper() {
        allowedValues = new HashSet<String>();
        setValidValuesType(ValidValuesType.UNKNOWN);
        min = max = "";
    }

    public AttributeHelper clone() {
        AttributeHelper att = new AttributeHelper();
        att.setAttributeName(attributeName);
        att.setAttributeType(attributeType);
        att.setMin(min);
        att.setMax(max);
        if (null != allowedValues) {
            Set<String> values = new HashSet<String>();
            values.addAll(allowedValues);
            att.setAllowedValues(values);
        }
        att.setAttributeDflValue(attributeDflValue);
        att.setValidValuesType(validValuesType);
        return att;
    }

    public String toString() {
        return attributeName + "," + attributeType + "," + attributeDflValue
                + "," + validValuesType + ",(" + min + max + "),("
                + allowedValues + ")";
    }

    public String getAttributeName() {
        return attributeName;
    }

    public void setAttributeName(String attributeName) {
        this.attributeName = attributeName;
    }

    public String getAttributeType() {
        return attributeType;
    }

    public void setAttributeType(String attributeType) {
        this.attributeType = attributeType;
    }

    public String getMin() {
        return min;
    }

    public void setMin(String min) {
        this.min = min;
    }

    public String getMax() {
        return max;
    }

    public void setMax(String max) {
        this.max = max;
    }

    public Set<String> getAllowedValues() {
        return allowedValues;
    }

    public void setAllowedValues(Set<String> allowedValues) {
        this.allowedValues = allowedValues;
    }

    public void addValueToAllowedValues(String value) {
        if (null != value && value.trim().length() > 0) {
            if (null == allowedValues) {
                allowedValues = new HashSet<String>();
            }
            allowedValues.add(value);
        }
    }

    public void removeValueFromAllowedValues(String value) {
        if (null != allowedValues && null != value && value.trim().length() > 0) {
            allowedValues.remove(value);
        }
    }

    public void removeAllCustomValues() {
        allowedValues.clear();
    }

    public String getAttributeDflValue() {
        return attributeDflValue;
    }

    public void setAttributeDflValue(String attributeDflValue) {
        this.attributeDflValue = attributeDflValue;
    }

    public ValidValuesType getValidValuesType() {
        return validValuesType;
    }

    public void setValidValuesType(ValidValuesType validValuesType) {
        this.validValuesType = validValuesType;
    }

    public boolean isValueValid(String value, String type) {
        if (null == value || value.trim().length() < 1 || null == type
                || type.trim().length() < 1)
            return false;
        if (type.equalsIgnoreCase(Constants.INT)) {
            return isIntValue(value);
        } else if (type.equalsIgnoreCase(Constants.DOUBLE)) {
            return isDoubleValue(value);
        } else if (type.equalsIgnoreCase(Constants.BOOL)) {
            return isBoolValue(value);
        }
        return true;
    }

    public boolean isBoolValue(String value) {
        boolean isBool = false;
        if (null != value
                && (value.equalsIgnoreCase("true") || value
                        .equalsIgnoreCase("false"))) {
            isBool = true;
        }
        return isBool;
    }

    public boolean isIntValue(String value) {
        boolean isInt = true;
        try {
            Integer.parseInt(value);
        } catch (Exception e) {
            isInt = false;
        }
        return isInt;
    }

    public boolean isDoubleValue(String value) {
        boolean isDouble = true;
        try {
            Double.parseDouble(value);
        } catch (Exception e) {
            isDouble = false;
        }
        return isDouble;
    }

    public boolean isRangeValid(String minStr, String maxStr, String type) {
        if (null == type || type.trim().isEmpty()) {
            return false;
        }
        boolean result = true;
        if (type.equals(Constants.INT)) {
            int min, max;
            try {
                min = Integer.parseInt(minStr);
                max = Integer.parseInt(maxStr);
                if (max <= min) {
                    result = false;
                }
            } catch (Exception e) {
                result = false;
            }
        } else if (type.equals(Constants.DOUBLE)) {
            double min, max;
            try {
                min = Double.parseDouble(minStr);
                max = Double.parseDouble(maxStr);
                if (max <= min) {
                    result = false;
                }
            } catch (Exception e) {
                result = false;
            }
        }
        return result;
    }

    public boolean isDefaultValueValid(String value) {
        if (null == attributeType || attributeType.trim().isEmpty()) {
            return false;
        }
        boolean result = true;
        if (attributeType.equals(Constants.STRING)) {
            if (validValuesType == ValidValuesType.VALUESET
                    && null != allowedValues) {
                result = allowedValues.contains(value);
            } else {
                result = true;
            }
        } else if (attributeType.equals(Constants.BOOL)) {
            String val = value.toLowerCase();
            if (!(val.equals("true") || val.equals("false"))) {
                result = false;
            }
        } else {
            if (validValuesType == ValidValuesType.RANGE) {
                if (attributeType.equals(Constants.INT)) {
                    int min, max, dflValue;
                    try {
                        min = Integer.parseInt(this.min);
                        max = Integer.parseInt(this.max);
                        dflValue = Integer.parseInt(value);
                        if (dflValue < min || dflValue > max) {
                            result = false;
                        }
                    } catch (Exception e) {
                        result = false;
                    }
                } else if (attributeType.equals(Constants.DOUBLE)) {
                    double min, max, dflValue;
                    try {
                        min = Double.parseDouble(this.min);
                        max = Double.parseDouble(this.max);
                        dflValue = Double.parseDouble(value);
                        boolean found = false;
                        for (double val = min; val <= max; val += 1.0) {
                            if (Double.compare(dflValue, val) == 0) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            result = false;
                        }
                    } catch (Exception e) {
                        result = false;
                    }
                }
            } else if (validValuesType == ValidValuesType.VALUESET
                    && null != allowedValues && !allowedValues.isEmpty()) {
                boolean found = false;
                if (attributeType.equals(Constants.INT)) {
                    Iterator<String> itr = allowedValues.iterator();
                    while (itr.hasNext()) {
                        String val = itr.next();
                        int v1 = Integer.parseInt(val);
                        int v2 = Integer.parseInt(value);
                        if (v1 == v2) {
                            found = true;
                            break;
                        }
                    }
                } else {
                    Iterator<String> itr = allowedValues.iterator();
                    while (itr.hasNext()) {
                        String val = itr.next();
                        double v1 = Double.parseDouble(val);
                        double v2 = Double.parseDouble(value);
                        if (Double.compare(v1, v2) == 0) {
                            found = true;
                            break;
                        }
                    }
                }
                if (!found) {
                    result = false;
                }
            }
        }
        return result;
    }

    public void setAllowedValuesByArray(String[] cusItems) {
        if (null == cusItems) {
            return;
        }
        for (String item : cusItems) {
            addValueToAllowedValues(item);
        }
    }

    public boolean isAllowedValueExist(String[] items, String value) {
        if (null == items || items.length < 1 || null == value
                || value.isEmpty())
            return false;
        for (String item : items) {
            if (value.equalsIgnoreCase(item)) {
                return true;
            }
        }
        return false;
    }

    public SimulatorResourceAttribute convertToSimulatorResourceAttribute() {
        AttributeValue attValue = null;
        AttributeProperty attProperty = null;
        SimulatorResourceAttribute simResAtt;

        ValueType valueType = Utility.getAttributeTypeEnum(attributeType);
        switch (valueType) {
            case INTEGER:
                IntegerProperty.Builder intPropertyBuilder = new IntegerProperty.Builder();
                attValue = new AttributeValue(
                        Integer.parseInt(attributeDflValue));

                // Set default value.
                intPropertyBuilder.setDefaultValue(Integer
                        .parseInt(attributeDflValue));

                if (validValuesType == ValidValuesType.VALUESET) {
                    // Set allowed values.
                    intPropertyBuilder.setValues(Utility
                            .convertSetToArrayInt(Utility
                                    .convertSetStringToSetObject(allowedValues,
                                            valueType)));
                } else if (validValuesType == ValidValuesType.RANGE) {
                    // Set Range.
                    intPropertyBuilder.setRange(Integer.parseInt(min),
                            Integer.parseInt(max));
                }
                attProperty = intPropertyBuilder.build();
                break;
            case DOUBLE:
                DoubleProperty.Builder dblPropertyBuilder = new DoubleProperty.Builder();
                attValue = new AttributeValue(
                        Double.parseDouble(attributeDflValue));

                // Set default value.
                dblPropertyBuilder.setDefaultValue(Double
                        .parseDouble(attributeDflValue));

                if (validValuesType == ValidValuesType.VALUESET) {
                    // Set allowed values.
                    dblPropertyBuilder.setValues(Utility
                            .convertSetToArrayDouble(Utility
                                    .convertSetStringToSetObject(allowedValues,
                                            valueType)));
                } else if (validValuesType == ValidValuesType.RANGE) {
                    // Set Range.
                    dblPropertyBuilder.setRange(Double.parseDouble(min),
                            Double.parseDouble(max));
                }
                attProperty = dblPropertyBuilder.build();
                break;
            case BOOLEAN:
                attValue = new AttributeValue(
                        Boolean.parseBoolean(attributeDflValue));
                BooleanProperty.Builder boolPropertyBuilder = new BooleanProperty.Builder();
                // Set Default Value.
                boolPropertyBuilder.setDefaultValue(Boolean
                        .parseBoolean(attributeDflValue));

                attProperty = boolPropertyBuilder.build();
                break;
            case STRING:
                attValue = new AttributeValue(attributeDflValue);
                StringProperty.Builder stringPropertyBuilder = new StringProperty.Builder();

                // Set Default Value.
                stringPropertyBuilder.setDefaultValue(attributeDflValue);

                if (validValuesType == ValidValuesType.VALUESET) {
                    // Set Allowed Values.
                    stringPropertyBuilder.setValues(Utility
                            .convertSetToArrayString(Utility
                                    .convertSetStringToSetObject(allowedValues,
                                            valueType)));
                }
                attProperty = stringPropertyBuilder.build();
                break;
            default:
                break;
        }
        simResAtt = new SimulatorResourceAttribute(attributeName, attValue,
                attProperty);
        return simResAtt;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace CycleCycleCycle.Tests.Utilities
{
    [TestClass]
    public class HtmlHelperExtensionsTests
    {

        #region Test LongDistance

        [TestMethod]
        public void Test_LongDistance_ReturnsKilometerFor1000Meters()
        {
            // Act
            string result = HtmlHelperExtensions.LongDistance(null, 1000);

            // Assert
            Assert.AreEqual("1 km", result);
        }

        [TestMethod]
        public void Test_LongDistance_RoundsDown()
        {
            // Act
            string result = HtmlHelperExtensions.LongDistance(null, 2400);

            // Assert
            Assert.AreEqual("2 km", result);
        }

        [TestMethod]
        public void Test_LongDistance_RoundsUp()
        {
            // Act
            string result = HtmlHelperExtensions.LongDistance(null, 2600);

            // Assert
            Assert.AreEqual("3 km", result);
        }

        #endregion

        #region Distance

        [TestMethod]
        public void Test_Distance_Returns1000MetersFor1000Meters()
        {
            // Act
            string result = HtmlHelperExtensions.Distance(null, 1000);

            // Assert
            Assert.AreEqual("1000 m", result);
        }

        [TestMethod]
        public void Test_Distance_RoundsDown()
        {
            // Act
            string result = HtmlHelperExtensions.Distance(null, 2100.1);

            // Assert
            Assert.AreEqual("2100 m", result);
        }

        [TestMethod]
        public void Test_Distance_RoundsUp()
        {
            // Act
            string result = HtmlHelperExtensions.Distance(null, 2100.6);

            // Assert
            Assert.AreEqual("2101 m", result);
        }

        #endregion

        #region Rating Tests

        [TestMethod]
        public void Test_AverageRating_Succeeds()
        {
            // Act
            string result = HtmlHelperExtensions.Rating(null, 3);

            // Assert
            Assert.AreEqual("3/5", result);
        }

        [TestMethod]
        public void Test_AverageRating_RoundsDown()
        {
            // Act
            string result = HtmlHelperExtensions.Rating(null, 4.8);

            // Assert
            Assert.AreEqual("4/5", result);
        }

        [TestMethod]
        public void Test_AverageRating_NullReturnsUnrated()
        {
            // Act
            string result = HtmlHelperExtensions.Rating(null, null);

            // Assert
            Assert.AreEqual("Unrated", result);
        }

        #endregion

        #region TimeTaken tests

        [TestMethod]
        public void Test_TimeTaken_NullReturnsNotRecorder()
        {
            // Act
            string result = HtmlHelperExtensions.TimeTaken(null, null);

            // Assert
            Assert.AreEqual("No time recorded", result);
        }

        [TestMethod]
        public void Test_TimeTaken_ReturnsFormattedString()
        {
            // Act
            string result = HtmlHelperExtensions.TimeTaken(null, new TimeSpan(1,2,3,4));

            // Assert
            Assert.AreEqual("2 hours 3 minutes 4 seconds", result);
        }

        #endregion
    }
}


text:
require 'spec_helper'
require 'simplecov'
require 'scrutinizer/ocular/formatter'

describe 'Scrutinizer::Ocular::Formatter' do
  def delete_coverage(coverage_file)
    File.delete(coverage_file) if File.exists? coverage_file
  end

  def fixture_path(relative_path)
    File.dirname(__FILE__) + '/fixtures/' + relative_path
  end

  let(:result) {
    SimpleCov::Result.new({
      fixture_path('foo.rb') => [nil, 2, 2, nil]
    })
  }

  let(:coverage_file) {
    '/tmp/local-formatter-cc.json'
  }

  before {
    delete_coverage(coverage_file)
  }

  after {
    delete_coverage(coverage_file)
  }

  describe "LocalOutputFormatter" do
    it "writes coverage to local file" do
      ENV['SCRUTINIZER_CC_FILE'] = coverage_file
      formatter = Scrutinizer::Ocular::LocalOutputFormatter.new
      formatter.format(result)

      output = File.open(coverage_file, 'r') do |file|
        file.read.to_s
      end

      output.should match(/^\[\{"name":"[^"]+\/foo\.rb","lines":\[null,2,2,null\]\}\]$/)
    end
  end

  describe "UploadingFormatter" do
    it "uploads code coverage" do
      ENV['SCRUTINIZER_REPOSITORY'] = 'foo/bar/baz'
      formatter = Scrutinizer::Ocular::UploadingFormatter.new
      output = Scrutinizer::Ocular::MemorizedOutput.new
      formatter.output = output
      formatter.format(result)

      output.output.should match(/Uploading code coverage/)
      output.output.should match(/Failed/)
      output.output.should match(/foo\/bar\/baz/)
    end
  end
end


text:
package tk.jackyliao123.algebra;

import java.io.Serializable;
import java.math.BigInteger;

public class Coefficient implements Serializable {

    char unknownChars[];
    Rational number;
    Rational[] unknown;

    public Coefficient(Rational num, Rational[] unknown, char[] chars) {
        unknownChars = chars;
        this.unknown = new Rational[unknownChars.length];
        this.number = num;
        this.unknown = unknown;
    }

    public Coefficient(Rational num, char[] chars) {
        unknownChars = chars;
        unknown = new Rational[unknownChars.length];
        number = num;
        for (int i = 0; i < unknownChars.length; i++) {
            unknown[i] = new Rational(new BigInteger("0"), new BigInteger("1"));
        }
    }

    public Coefficient(Rational num, Rational unk, char unkchar, char[] chars) {
        unknownChars = chars;
        unknown = new Rational[unknownChars.length];
        number = num;
        for (int i = 0; i < unknownChars.length; i++) {
            if (unknownChars[i] == unkchar)
                unknown[i] = unk;
            else
                unknown[i] = new Rational(new BigInteger("0"), new BigInteger("1"));
        }
    }

    public Coefficient(Rational unk, char unkchar, char[] chars) {
        unknownChars = chars;
        unknown = new Rational[unknownChars.length];
        number = new Rational(new BigInteger("0"), new BigInteger("1"));
        for (int i = 0; i < unknownChars.length; i++) {
            if (unknownChars[i] == unkchar)
                unknown[i] = unk;
            else
                unknown[i] = new Rational(new BigInteger("0"), new BigInteger("1"));
        }
    }

    public Coefficient add(Coefficient coefficient) {
        Rational[] unk = new Rational[unknown.length];
        for (int i = 0; i < unknown.length; i++) {
            unk[i] = unknown[i].add(coefficient.unknown[i]);
        }
        return new Coefficient(number.add(coefficient.number), unk, unknownChars);
    }

    public Coefficient subtract(Coefficient coefficient) {
        Rational[] unk = new Rational[unknown.length];
        for (int i = 0; i < unknown.length; i++) {
            unk[i] = unknown[i].subtract(coefficient.unknown[i]);
        }
        return new Coefficient(number.subtract(coefficient.number), unk, unknownChars);
    }

    public Coefficient multiply(Coefficient coefficient) {
        if (coefficient.isPureNumber()) {
            Rational[] unk = new Rational[unknown.length];
            for (int i = 0; i < unknown.length; i++) {
                unk[i] = unknown[i].multiply(coefficient.number);
            }
            return new Coefficient(number.multiply(coefficient.number), unk, unknownChars);
        } else if (isPureNumber()) {
            Rational[] unk = new Rational[unknown.length];
            for (int i = 0; i < unknown.length; i++) {
                unk[i] = coefficient.unknown[i].multiply(number);
            }
            return new Coefficient(coefficient.number.multiply(number), unk, unknownChars);
        } else {
            throw new ArithmeticException("Not a valid linear equation");
        }
    }

    public Coefficient divide(Coefficient coefficient) {
        if (!coefficient.isPureNumber()) {
            throw new ArithmeticException("Not a valid linear equation");
        }
        Rational[] unk = new Rational[unknown.length];
        for (int i = 0; i < unknown.length; i++) {
            unk[i] = unknown[i].divide(coefficient.number);
        }
        return new Coefficient(number.divide(coefficient.number), unk, unknownChars);
    }

    public boolean isPureNumber() {
        for (int i = 0; i < unknown.length; i++) {
            if (!unknown[i].equals(0)) {
                return false;
            }
        }
        return true;
    }

    public String toString() {
        String s = "" + number;
        for (int i = 0; i < unknown.length; i++) {
            s += " + " + unknown[i] + unknownChars[i];
        }
        return s;
    }

}


text:
<?php

use Fyuze\Http\Message\Message;
use PHPUnit\Framework\TestCase;

class HttpMessageTest extends TestCase
{
    /**
     * @var Message
     */
    protected $message;

    public function setUp()
    {
        $this->message = new Message();
    }

    public function testProtocolResolvesValidValue()
    {
        $message = $this->message->withProtocolVersion('1.0');

        $this->assertEquals('1.0', $message->getProtocolVersion());

        $message->withProtocolVersion('1.1');

        // Immutability test
        $this->assertEquals('1.0', $message->getProtocolVersion());
        $this->assertEquals('1.1', $message->withProtocolVersion('1.1')->getProtocolVersion());
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testProtocolThrowsErrorOnValidValue()
    {
        $this->message->withProtocolVersion('1.3');
    }

    public function testSetsAndGetsHeaders()
    {
        $message = (new \Fyuze\Http\Message\Message())->withHeader('foo', 'bar');

        $this->assertTrue($message->hasHeader('foo'));
        $this->assertTrue($message->hasHeader('fOO'));
        $this->assertEquals(['bar'], $message->getHeader('foo'));
        $this->assertEquals(['bar'], $message->getHeader('Foo'));
        $this->assertEmpty($message->getHeader('bar'));

        // Make sure empty value will still return an array
        $this->assertInternalType('array', $message->withHeader('bar', '')->getHeader('bar'));
        $this->assertEmpty($message->withHeader('bar', '')->getHeader('bar'));

        // Psr7 consumption test
        // Represent the headers as a string
        foreach ($message->getHeaders() as $name => $values) {
            $this->assertEquals('foo: bar', $name . ": " . implode(", ", $values));
        }

        // Emit headers iteratively:
        foreach ($message->getHeaders() as $name => $values) {
            foreach ($values as $value) {
                $this->assertEquals('foo: bar', sprintf('%s: %s', $name, $value));
            }
        }
    }

    public function testReturnsSameInstanceWithoutChangingValue()
    {
        $message = $this->message->withHeader('foo', 'bar');

        $this->assertEquals(['bar'], $message->getHeader('foo'));
        $this->assertSame($message, $message->withHeader('foo', 'bar'));
    }

    public function testCaseInsensitiveHeaderAndLine()
    {
        $message = $this->message->withHeader('foo', ['bar', 'baz']);

        $this->assertCount(2, $message->getHeader('FOO'));
        $this->assertEquals('bar, baz', $message->getHeaderLine('foo'));
    }

    public function testWithAddedHeader()
    {
        $message = $this->message->withHeader('foo', 'bar');
        $this->assertEquals(['bar'], $message->getHeader('foo'));

        $message = $message->withAddedHeader('foo', 'baz');
        $this->assertEquals(['bar', 'baz'], $message->getHeader('foo'));
    }

    public function testWithoutHeader()
    {
        $message = $this->message->withHeader('foo', 'bar');

        // Make sure we have our header
        $this->assertEquals(['bar'], $message->getHeader('foo'));

        $message = $message->withoutHeader('foo');
        $this->assertCount(0, $message->getHeaders());
    }

    public function testMessageHandlesStream()
    {
        $message = $this->message->withBody(
            Mockery::mock(\Fyuze\Http\Message\Stream::class)
        );

        $this->assertNotSame($this->message, $message);
        $this->assertInstanceOf(\Fyuze\Http\Message\Stream::class, $message->getBody());

    }

    public function testCloneReturnsSameInstanceWithoutChangeInValues()
    {
        $message = $this->message->withProtocolVersion('1.1');
        $this->assertSame(
            $message,
            $message->withProtocolVersion('1.1')
        );
    }
}


text:
const r = require('../r');
const _ = require('lodash');

function *update(table, id, json) {
    let rql = r.table(table).get(id);
    let result = yield rql.update(json, {returnChanges: 'always'}).run();
    return result.changes[0].new_val;
}

function *updateAll(rql, json) {
    let items = [];
    if (_.isArray(json) && json.length === 0) {
        return items;
    }
    let results = yield rql.update(json, {returnChanges: 'always'}).run();
    results.changes.forEach(function(item) {
        items.push(item.new_val);
    });
    return items;
}

function *insert(table, json, options) {
    let asArray = options ? options.toArray : false;
    if (_.isArray(json) && json.length === 0) {
        return asArray ? [] : {};
    }
    let rql = r.table(table);
    let result = yield rql.insert(json, {returnChanges: 'always'}).run();
    if (result.changes.length == 1) {
        let val = result.changes[0].new_val;
        return asArray ? [val] : val;
    } else {
        let results = [];
        result.changes.forEach(function(result) {
            results.push(result.new_val);
        });
        return results;
    }
}

module.exports = {
    insert: insert,
    update: update,
    updateAll: updateAll
};


text:
from __future__ import unicode_literals
"""
This package implements modules for input and output to and from VASP. It
imports the key classes form both vasp_input and vasp_output to allow most
classes to be simply called as pymatgen.io.vasp.Incar for example, to retain
backwards compatibility.
"""

from .inputs import *
from .outputs import *


text:
package com.nowellpoint.client.sforce.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Entity {
	String name() default "";
}


text:
namespace flutter {

class GPUSurfaceGL : public Surface {
 public:
  GPUSurfaceGL(GPUSurfaceGLDelegate* delegate, bool render_to_surface);

  // Creates a new GL surface reusing an existing GrContext.
  GPUSurfaceGL(sk_sp<GrContext> gr_context,
               GPUSurfaceGLDelegate* delegate,
               bool render_to_surface);

  ~GPUSurfaceGL() override;

  // |Surface|
  bool IsValid() override;

  // |Surface|
  std::unique_ptr<SurfaceFrame> AcquireFrame(const SkISize& size) override;

  // |Surface|
  SkMatrix GetRootTransformation() const override;

  // |Surface|
  GrContext* GetContext() override;

  // |Surface|
  flutter::ExternalViewEmbedder* GetExternalViewEmbedder() override;

  // |Surface|
  bool MakeRenderContextCurrent() override;

 private:
  GPUSurfaceGLDelegate* delegate_;
  sk_sp<GrContext> context_;
  sk_sp<SkSurface> onscreen_surface_;
  bool context_owner_;
  // TODO(38466): Refactor GPU surface APIs take into account the fact that an
  // external view embedder may want to render to the root surface. This is a
  // hack to make avoid allocating resources for the root surface when an
  // external view embedder is present.
  const bool render_to_surface_;
  bool valid_ = false;
  fml::WeakPtrFactory<GPUSurfaceGL> weak_factory_;

  bool CreateOrUpdateSurfaces(const SkISize& size);

  sk_sp<SkSurface> AcquireRenderSurface(
      const SkISize& untransformed_size,
      const SkMatrix& root_surface_transformation);

  bool PresentSurface(SkCanvas* canvas);

  FML_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceGL);
};

}  // namespace flutter

#endif  // SHELL_GPU_GPU_SURFACE_GL_H_


text:
<?php

namespace Magento\Framework\Profiler\Test\Unit\Driver\Standard\Output;

class FactoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Framework\Profiler\Driver\Standard\Output\Factory
     */
    protected $_factory;

    /**
     * @var string
     */
    protected $_defaultOutputPrefix = 'Magento_Framework_Profiler_Driver_Standard_Output_Test_';

    /**
     * @var string
     */
    protected $_defaultOutputType = 'default';

    protected function setUp()
    {
        $this->_factory = new \Magento\Framework\Profiler\Driver\Standard\Output\Factory(
            $this->_defaultOutputPrefix,
            $this->_defaultOutputType
        );
    }

    public function testConstructor()
    {
        $this->assertAttributeEquals($this->_defaultOutputPrefix, '_defaultOutputPrefix', $this->_factory);
        $this->assertAttributeEquals($this->_defaultOutputType, '_defaultOutputType', $this->_factory);
    }

    public function testDefaultConstructor()
    {
        $factory = new \Magento\Framework\Profiler\Driver\Standard\Output\Factory();
        $this->assertAttributeNotEmpty('_defaultOutputPrefix', $factory);
        $this->assertAttributeNotEmpty('_defaultOutputType', $factory);
    }

    /**
     * @dataProvider createDataProvider
     * @param array $configData
     * @param string $expectedClass
     */
    public function testCreate($configData, $expectedClass)
    {
        $driver = $this->_factory->create($configData);
        $this->assertInstanceOf($expectedClass, $driver);
        $this->assertInstanceOf('Magento\Framework\Profiler\Driver\Standard\OutputInterface', $driver);
    }

    /**
     * @return array
     */
    public function createDataProvider()
    {
        $defaultOutputClass = $this->getMockClass(
            'Magento\Framework\Profiler\Driver\Standard\OutputInterface',
            [],
            [],
            'Magento_Framework_Profiler_Driver_Standard_Output_Test_Default'
        );
        $testOutputClass = $this->getMockClass(
            'Magento\Framework\Profiler\Driver\Standard\OutputInterface',
            [],
            [],
            'Magento_Framework_Profiler_Driver_Standard_Output_Test_Test'
        );
        return [
            'Prefix and concrete type' => [['type' => 'test'], $testOutputClass],
            'Prefix and default type' => [[], $defaultOutputClass],
            'Concrete class' => [['type' => $testOutputClass], $testOutputClass]
        ];
    }

    public function testCreateUndefinedClass()
    {
        $this->setExpectedException(
            'InvalidArgumentException',
            sprintf(
                'Cannot create standard driver output, class "%s" doesn\'t exist.',
                'Magento_Framework_Profiler_Driver_Standard_Output_Test_Baz'
            )
        );
        $this->_factory->create(['type' => 'baz']);
    }

    public function testCreateInvalidClass()
    {
        $this->setExpectedException(
            'InvalidArgumentException',
            'Output class "stdClass" must implement \Magento\Framework\Profiler\Driver\Standard\OutputInterface.'
        );
        $this->_factory->create(['type' => 'stdClass']);
    }
}


text:
#ifndef MJOLNIR_POTENTIAL_GLOBAL_LENNARD_JONES_POTENTIAL_HPP
#define MJOLNIR_POTENTIAL_GLOBAL_LENNARD_JONES_POTENTIAL_HPP
#include <algorithm>
#include <utility>
#include <cmath>

namespace mjolnir
{

template<typename T> class System;

// Well-known Lennard-Jones interaction with Lorentz-Berthelot combining rules.
// This class contains sigmas and epsilons of the particles and calculates
// energy and derivative of the potential function.
template<typename realT>
class LennardJonesPotential
{
  public:
    using real_type = realT;

    struct parameter_type
    {
        real_type sigma;
        real_type epsilon;
    };

    static constexpr real_type default_cutoff() noexcept
    {
        return real_type(2.5);
    }

  public:

    explicit LennardJonesPotential(const real_type& cutoff_ratio) noexcept
        : cutoff_ratio_(cutoff_ratio), coef_at_cutoff_(
                std::pow(real_type(1) / cutoff_ratio, 12) -
                std::pow(real_type(1) / cutoff_ratio,  6))
    {}
    ~LennardJonesPotential() = default;

    real_type potential(const real_type r, const parameter_type& params) const noexcept
    {
        if(params.sigma * this->cutoff_ratio_ < r){return real_type(0);}

        const real_type sr1 = params.sigma / r;
        const real_type sr3 = sr1 * sr1 * sr1;
        const real_type sr6 = sr3 * sr3;

        return real_type(4) * params.epsilon *
                (sr6 * (sr6 - real_type(1)) - this->coef_at_cutoff_);
    }
    real_type derivative(const real_type r, const parameter_type& params) const noexcept
    {
        if(params.sigma * this->cutoff_ratio_ < r){return real_type(0);}

        const real_type rinv = 1 / r;
        const real_type sr1  = params.sigma * rinv;
        const real_type sr3  = sr1 * sr1 * sr1;
        const real_type sr6  = sr3 * sr3;

        return real_type(24) * params.epsilon *
                sr6 * (real_type(1) - real_type(2) * sr6) * rinv;
    }

    template<typename T>
    void initialize(const System<T>&) noexcept {return;}

    template<typename T>
    void update(const System<T>&) noexcept {return;}

    real_type cutoff_ratio()   const noexcept {return cutoff_ratio_;}
    real_type coef_at_cutoff() const noexcept {return coef_at_cutoff_;}

    static const char* name() noexcept {return "LennardJones";}

    // It takes per-particle parameters and return the maximum cutoff length.
    // CombinationRule normally uses this.
    // Note that, pair-parameter and per-particle parameter can differ from
    // each other. Lorentz-Bertherot uses the same parameter_type because it is
    // for L-J and L-J-like potentials that has {sigma, epsilon} for each
    // particle and also for each pair of particles.
    template<typename InputIterator>
    real_type max_cutoff(const InputIterator first, const InputIterator last) const noexcept
    {
        static_assert(std::is_same<
                typename std::iterator_traits<InputIterator>::value_type,
                parameter_type>::value, "");

        if(first == last) {return 1;}

        real_type max_sigma = 0;
        for(auto iter = first; iter != last; ++iter)
        {
            const auto& parameter = *iter;
            max_sigma = std::max(max_sigma, parameter.sigma);
        }
        return max_sigma * cutoff_ratio_;
    }
    // It returns absolute cutoff length using pair-parameter.
    // `CombinationTable` uses this.
    real_type absolute_cutoff(const parameter_type& params) const noexcept
    {
        return params.sigma * cutoff_ratio_;
    }

  private:

    real_type cutoff_ratio_;
    real_type coef_at_cutoff_;
};

#ifdef MJOLNIR_SEPARATE_BUILD
extern template class LennardJonesPotential<double>;
extern template class LennardJonesPotential<float >;
#endif// MJOLNIR_SEPARATE_BUILD

} // mjolnir
#endif /* MJOLNIR_LENNARD_JONES_POTENTIAL */


text:
#include <modules/basegl/processors/imageprocessing/imagechannelcombine.h>

#include <inviwo/core/datastructures/image/image.h>       // for Image
#include <inviwo/core/datastructures/image/imagetypes.h>  // for ImageType, ImageType::ColorOnly
#include <inviwo/core/ports/imageport.h>                  // for ImageInport, ImageOutport
#include <inviwo/core/processors/processor.h>             // for Processor
#include <inviwo/core/processors/processorinfo.h>         // for ProcessorInfo
#include <inviwo/core/processors/processorstate.h>        // for CodeState, CodeState::Experimental
#include <inviwo/core/processors/processortags.h>         // for Tags, Tags::GL
#include <inviwo/core/properties/invalidationlevel.h>     // for InvalidationLevel, Invalidation...
#include <inviwo/core/properties/optionproperty.h>        // for OptionPropertyOption
#include <inviwo/core/util/exception.h>                   // for Exception
#include <inviwo/core/util/formats.h>                     // for DataFormatBase, NumericType
#include <inviwo/core/util/glmvec.h>                      // for size2_t
#include <inviwo/core/util/sourcecontext.h>               // for IVW_CONTEXT
#include <modules/opengl/shader/shader.h>                 // for Shader
#include <modules/opengl/shader/shaderutils.h>            // for setUniforms
#include <modules/opengl/texture/textureunit.h>           // for TextureUnitContainer
#include <modules/opengl/texture/textureutils.h>          // for bindAndSetUniforms, activateAnd...

#include <algorithm>    // for max
#include <functional>   // for __base
#include <memory>       // for shared_ptr, make_shared
#include <string>       // for string
#include <string_view>  // for string_view
#include <type_traits>  // for remove_extent_t

#include <glm/vec2.hpp>  // for operator!=

namespace inviwo {

const ProcessorInfo ImageChannelCombine::processorInfo_{
    "org.inviwo.ImageChannelCombine",  // Class identifier
    "Image Channel Combine",           // Display name
    "Image Operation",                 // Category
    CodeState::Experimental,           // Code state
    Tags::GL,                          // Tags
};
const ProcessorInfo ImageChannelCombine::getProcessorInfo() const { return processorInfo_; }

ImageChannelCombine::ImageChannelCombine()
    : Processor()
    , inport0_("inport0", true)
    , inport1_("inport1", true)
    , inport2_("inport2", true)
    , inport3_("inport3", true)
    , outport_("outport", false)
    , rChannelSrc_("redChannel", "Red Channel",
                   {{"r", "Red", 0}, {"g", "Green", 1}, {"b", "Blue", 2}, {"a", "Alpha", 3}})
    , gChannelSrc_("greenChannel", "Green Channel",
                   {{"r", "Red", 0}, {"g", "Green", 1}, {"b", "Blue", 2}, {"a", "Alpha", 3}})
    , bChannelSrc_("blueChannel", "Blue Channel",
                   {{"r", "Red", 0}, {"g", "Green", 1}, {"b", "Blue", 2}, {"a", "Alpha", 3}})
    , aChannelSrc_("alphaChannel", "Alpha Channel",
                   {{"r", "Red", 0}, {"g", "Green", 1}, {"b", "Blue", 2}, {"a", "Alpha", 3}})
    , alpha_("alpha", "Alpha", 1.0f, 0.0f, 1.0f, 0.001f)
    , shader_("img_channel_combine.frag") {
    shader_.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); });

    addPort(inport0_);
    addPort(inport1_);
    addPort(inport2_);
    inport3_.setOptional(true);
    addPort(inport3_);

    addPort(outport_);

    addProperties(rChannelSrc_, gChannelSrc_, bChannelSrc_, aChannelSrc_, alpha_);
}

void ImageChannelCombine::process() {
    auto isSame = [](auto a, auto b, auto c) {
        if (a != b) return false;
        if (a != c) return false;
        return true;
    };
    auto img0 = inport0_.getData();
    auto img1 = inport1_.getData();
    auto img2 = inport2_.getData();
    auto img3 = inport3_.getData();

    if (isSame(img0->getDimensions(), img1->getDimensions(), img2->getDimensions()) &&
        (inport3_.isConnected() && img3 && img3->getDimensions() != img0->getDimensions())) {
        throw Exception("The image dimensions of all inports needs to be the same", IVW_CONTEXT);
    }

    if (inport0_.isChanged() || inport1_.isChanged() || inport2_.isChanged()) {
        const auto dimensions = inport0_.getData()->getDimensions();
        auto t1 = inport0_.getData()->getDataFormat()->getNumericType();
        auto t2 = inport1_.getData()->getDataFormat()->getNumericType();
        auto t3 = inport2_.getData()->getDataFormat()->getNumericType();
        NumericType type;
        if (t1 == t2 && t1 == t3) {
            // All have the same numType
            type = t1;
        } else if (t1 == NumericType::Float || t2 == NumericType::Float ||
                   t2 == NumericType::Float) {
            // At least one is a float type
            type = NumericType::Float;
        } else {
            // At least one are signed, and at least one are unsigned
            type = NumericType::Float;
        }

        auto p0 = inport0_.getData()->getDataFormat()->getPrecision();
        auto p1 = inport1_.getData()->getDataFormat()->getPrecision();
        auto p2 = inport2_.getData()->getDataFormat()->getPrecision();
        DataFormatBase::get(type, 4, std::max({p0, p1, p2}));

        auto img = std::make_shared<Image>(dimensions, DataVec4UInt8::get());
        outport_.setData(img);
    }

    utilgl::activateAndClearTarget(outport_);
    shader_.activate();
    TextureUnitContainer units;
    utilgl::bindAndSetUniforms(shader_, units, inport0_, ImageType::ColorOnly);
    utilgl::bindAndSetUniforms(shader_, units, inport1_, ImageType::ColorOnly);
    utilgl::bindAndSetUniforms(shader_, units, inport2_, ImageType::ColorOnly);
    if (inport3_.hasData()) {
        utilgl::bindAndSetUniforms(shader_, units, inport3_, ImageType::ColorOnly);
    }
    utilgl::setUniforms(shader_, outport_, rChannelSrc_, gChannelSrc_, bChannelSrc_, aChannelSrc_,
                        alpha_);
    shader_.setUniform("use_alpha_texture", inport3_.hasData());
    utilgl::setUniforms(shader_, outport_);
    utilgl::singleDrawImagePlaneRect();
    shader_.deactivate();
    utilgl::deactivateCurrentTarget();
}

}  // namespace inviwo


text:
from .copy_from import CopyMapping
from .copy_to import SQLCopyToCompiler, CopyToQuery
from .managers import CopyManager, CopyQuerySet
__version__ = '2.6.0'

__all__ = (
    'CopyManager',
    'CopyMapping',
    'CopyQuerySet',
    'CopyToQuery',
    'SQLCopyToCompiler'
)


text: pip install Mako


text:
class Admin::GatewayOptionValuesController < Admin::BaseController
  resource_controller

  belongs_to :gateway_configuration

  index.before do
    chosen_gateway = Gateway.find(params[:gw_id])
    @option_values = @gateway_configuration.gateway_option_values
    unless @gateway_configuration.gateway == chosen_gateway
      # show a blank set of values for editing purposes (original values preserved in DB until user posts the update)
      @option_values = []
      chosen_gateway.gateway_options.each do |option|
        @option_values << GatewayOptionValue.new(:gateway_option => option)
      end
    end
  end

  index.response do |wants|
    wants.html { render :partial => "options",
                        :layout => false,
                        :locals => {:option_values => @option_values} }
  end

end


text:
memo
====

Code snippets to be remembered


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Threading.Tasks;
using ArcGIS.Core.CIM;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Catalog;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Extensions;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;

namespace create_layer_file
{
    internal class Module1 : Module
    {
        private static Module1 _this = null;

        /// <summary>
        /// Retrieve the singleton instance to this module here
        /// </summary>
        public static Module1 Current
        {
            get
            {
                return _this ?? (_this = (Module1)FrameworkApplication.FindModule("create_layer_file_Module"));
            }
        }

        #region Overrides
        /// <summary>
        /// Called by Framework when ArcGIS Pro is closing
        /// </summary>
        /// <returns>False to prevent Pro from closing, otherwise True</returns>
        protected override bool CanUnload()
        {
            //TODO - add your business logic
            //return false to ~cancel~ Application close
            return true;
        }

        #endregion Overrides

    }
}


text:
using Helpful.TextParser.Model;

namespace Helpful.TextParser.Interface
{
    public interface ILineValueExtractorFactory
    {
        ILineValueExtractor Get(LineValueExtractorType lineValueExtractorType);
    }
}


text:
/*eslint-disable unicorn/filename-case */

import { expect } from '@integration/testing-tools';
import { StageManager } from '@serenity-js/core';
import { SceneFinished, SceneStarts, SceneTagged, TestRunFinishes } from '@serenity-js/core/lib/events';
import { ArbitraryTag, BrowserTag, CapabilityTag, ContextTag, CorrelationId, ExecutionSuccessful, FeatureTag, IssueTag, ManualTag, ThemeTag } from '@serenity-js/core/lib/model';
import { beforeEach, describe, it } from 'mocha';
import * as sinon from 'sinon';

import { SerenityBDDReporter } from '../../../../../src/stage';
import { SerenityBDDReport } from '../../../../../src/stage/crew/serenity-bdd-reporter/SerenityBDDJsonSchema';
import { given } from '../../given';
import { defaultCardScenario } from '../../samples';
import { create } from '../create';

describe('SerenityBDDReporter', () => {

    let stageManager: sinon.SinonStubbedInstance<StageManager>,
        reporter: SerenityBDDReporter;

    const sceneId = new CorrelationId('a-scene-id');

    beforeEach(() => {
        const env = create();

        stageManager    = env.stageManager;
        reporter        = env.reporter;
    });

    describe('produces a SerenityBDDReport that', () => {

        let report: SerenityBDDReport;

        describe('can be tagged', () => {

            beforeEach(() => {
                given(reporter).isNotifiedOfFollowingEvents(
                    new SceneStarts(sceneId, defaultCardScenario),
                );
            });

            describe('@manual', () => {

                it('is marked as automated (non-manual) by default', () => {
                    given(reporter).isNotifiedOfFollowingEvents(
                        new SceneFinished(sceneId, defaultCardScenario, new ExecutionSuccessful()),
                        new TestRunFinishes(),
                    );

                    report = stageManager.notifyOf.firstCall.lastArg.artifact.map(_ => _);

                    expect(report.manual).to.equal(false);
                });

                it('can be optionally tagged as manual', () => {
                    given(reporter).isNotifiedOfFollowingEvents(
                        new SceneTagged(sceneId, new ManualTag()),
                        new SceneFinished(sceneId, defaultCardScenario, new ExecutionSuccessful()),
                        new TestRunFinishes(),
                    );

                    report = stageManager.notifyOf.firstCall.lastArg.artifact.map(_ => _);

                    expect(report.manual).to.equal(true);
                    expect(report.tags).to.deep.include.members([{
                        name: 'Manual',
                        displayName: 'Manual',
                        type: 'External Tests',
                    }]);
                });
            });

            describe('@issue', () => {

                it('can be tagged with an issue number', () => {
                    given(reporter).isNotifiedOfFollowingEvents(
                        new SceneTagged(sceneId, new IssueTag('ABC-1234')),
                        new SceneTagged(sceneId, new IssueTag('DEF-5678')),
                        new SceneFinished(sceneId, defaultCardScenario, new ExecutionSuccessful()),
                        new TestRunFinishes(),
                    );

                    report = stageManager.notifyOf.firstCall.lastArg.artifact.map(_ => _);

                    expect(report.tags).to.deep.include.members([{
                        name:        'ABC-1234',
                        displayName: 'ABC-1234',
                        type:        'issue',
                    }, {
                        name:        'DEF-5678',
                        displayName: 'DEF-5678',
                        type:        'issue',
                    }]);

                    expect(report.issues).to.deep.equal([
                        'ABC-1234',
                        'DEF-5678',
                    ]);

                    expect(report.additionalIssues).to.deep.equal([
                        'ABC-1234',
                        'DEF-5678',
                    ]);
                });
            });

            describe('@arbitrary-tag', () => {

                it('can be tagged with an arbitrary tag', () => {
                    given(reporter).isNotifiedOfFollowingEvents(
                        new SceneTagged(sceneId, new ArbitraryTag('regression')),
                        new SceneFinished(sceneId, defaultCardScenario, new ExecutionSuccessful()),
                        new TestRunFinishes(),
                    );

                    report = stageManager.notifyOf.firstCall.lastArg.artifact.map(_ => _);

                    expect(report.tags).to.deep.include.members([{
                        name:        'regression',
                        displayName: 'regression',
                        type:        'tag',
                    }]);
                });
            });

            describe('to indicate that a scenario', () => {

                it('belongs to a feature', () => {
                    given(reporter).isNotifiedOfFollowingEvents(
                        new SceneTagged(sceneId, new FeatureTag('Checkout')),
                        new SceneFinished(sceneId, defaultCardScenario, new ExecutionSuccessful()),
                        new TestRunFinishes(),
                    );

                    report = stageManager.notifyOf.firstCall.lastArg.artifact.map(_ => _);

                    expect(report.tags).to.deep.include.members([{
                        name: 'Checkout',
                        type: 'feature',
                        displayName: 'Checkout',
                    }]);

                    expect(report.featureTag).to.deep.equal({
                        name: 'Checkout',
                        type: 'feature',
                        displayName: 'Checkout',
                    });
                });

                it('belongs to a capability', () => {
                    given(reporter).isNotifiedOfFollowingEvents(
                        new SceneTagged(sceneId, new CapabilityTag('E-Commerce')),
                        new SceneTagged(sceneId, new FeatureTag('Checkout')),
                        new SceneFinished(sceneId, defaultCardScenario, new ExecutionSuccessful()),
                        new TestRunFinishes(),
                    );

                    report = stageManager.notifyOf.firstCall.lastArg.artifact.map(_ => _);

                    expect(report.tags).to.deep.include.members([{
                        name: 'E-Commerce',
                        type: 'capability',
                        displayName: 'E-Commerce',
                    }, {
                        name: 'E-Commerce/Checkout',
                        type: 'feature',
                        displayName: 'Checkout',
                    }]);

                    expect(report.featureTag).to.deep.equal({
                        name: 'E-Commerce/Checkout',
                        type: 'feature',
                        displayName: 'Checkout',
                    });
                });

                it('belongs to a theme', () => {
                    given(reporter).isNotifiedOfFollowingEvents(
                        new SceneTagged(sceneId, new ThemeTag('Digital')),
                        new SceneTagged(sceneId, new CapabilityTag('E-Commerce')),
                        new SceneTagged(sceneId, new FeatureTag('Checkout')),
                        new SceneFinished(sceneId, defaultCardScenario, new ExecutionSuccessful()),
                        new TestRunFinishes(),
                    );

                    report = stageManager.notifyOf.firstCall.lastArg.artifact.map(_ => _);

                    expect(report.tags).to.deep.include.members([{
                        name: 'Digital',
                        type: 'theme',
                        displayName: 'Digital',
                    }, {
                        name: 'Digital/E-Commerce',
                        type: 'capability',
                        displayName: 'E-Commerce',
                    }, {
                        name: 'E-Commerce/Checkout',
                        type: 'feature',
                        displayName: 'Checkout',
                    }]);

                    expect(report.featureTag).to.deep.equal({
                        name: 'E-Commerce/Checkout',
                        type: 'feature',
                        displayName: 'Checkout',
                    });
                });

                describe('is executed in the context and', () => {

                    it('indicates the web browser where the test was executed', () => {
                        given(reporter).isNotifiedOfFollowingEvents(
                            new SceneTagged(sceneId, new BrowserTag('chrome', '80.0.3987.87')),
                            new SceneFinished(sceneId, defaultCardScenario, new ExecutionSuccessful()),
                            new TestRunFinishes(),
                        );

                        report = stageManager.notifyOf.firstCall.lastArg.artifact.map(_ => _);

                        expect(report.context).to.equal('chrome');

                        expect(report.tags).to.deep.include.members([{
                            browserName: 'chrome',
                            browserVersion: '80.0.3987.87',
                            name: 'chrome 80.0.3987.87',
                            displayName: 'chrome 80.0.3987.87',
                            type: 'browser',
                        }]);
                    });

                    it('indicates the operating system where the test was executed', () => {
                        given(reporter).isNotifiedOfFollowingEvents(
                            new SceneTagged(sceneId, new ContextTag('iphone')),
                            new SceneFinished(sceneId, defaultCardScenario, new ExecutionSuccessful()),
                            new TestRunFinishes(),
                        );

                        report = stageManager.notifyOf.firstCall.lastArg.artifact.map(_ => _);

                        expect(report.context).to.equal('iphone');

                        expect(report.tags).to.deep.include.members([{
                            name: 'iphone',
                            displayName: 'iphone',
                            type: 'context',
                        }]);
                    });

                    it('ensures that the user-specified context takes precedence over browser context', () => {
                        given(reporter).isNotifiedOfFollowingEvents(
                            new SceneTagged(sceneId, new BrowserTag('safari', '13.0.5')),
                            new SceneTagged(sceneId, new ContextTag('iphone')),
                            new SceneFinished(sceneId, defaultCardScenario, new ExecutionSuccessful()),
                            new TestRunFinishes(),
                        );

                        report = stageManager.notifyOf.firstCall.lastArg.artifact.map(_ => _);

                        expect(report.context).to.equal('iphone');

                        expect(report.tags).to.deep.include.members([{
                            name: 'safari 13.0.5',
                            displayName: 'safari 13.0.5',
                            type: 'browser',
                            browserName: 'safari',
                            browserVersion: '13.0.5',
                        }, {
                            name: 'iphone',
                            displayName: 'iphone',
                            type: 'context',
                        }]);
                    });
                });
            });
        });
    });
});


text:
package org.ovirt.engine.ui.webadmin.section.main.view.popup.host;

import org.ovirt.engine.core.common.businessentities.NetworkBootProtocol;
import org.ovirt.engine.core.common.businessentities.VdsNetworkInterface;
import org.ovirt.engine.core.common.businessentities.Network;
import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.core.compat.EventArgs;
import org.ovirt.engine.core.compat.IEventListener;
import org.ovirt.engine.core.compat.KeyValuePairCompat;
import org.ovirt.engine.core.compat.PropertyChangedEventArgs;
import org.ovirt.engine.ui.common.view.popup.AbstractModelBoundPopupView;
import org.ovirt.engine.ui.common.widget.Align;
import org.ovirt.engine.ui.common.widget.dialog.SimpleDialogPanel;
import org.ovirt.engine.ui.common.widget.editor.EntityModelCheckBoxEditor;
import org.ovirt.engine.ui.common.widget.editor.EntityModelLabelEditor;
import org.ovirt.engine.ui.common.widget.editor.EntityModelTextBoxEditor;
import org.ovirt.engine.ui.common.widget.editor.ListModelListBoxEditor;
import org.ovirt.engine.ui.common.widget.renderer.NullSafeRenderer;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.hosts.HostBondInterfaceModel;
import org.ovirt.engine.ui.webadmin.ApplicationConstants;
import org.ovirt.engine.ui.webadmin.ApplicationResources;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.host.HostBondPopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.widget.editor.EnumRadioEditor;

import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.inject.Inject;

public class HostBondPopupView extends AbstractModelBoundPopupView<HostBondInterfaceModel> implements HostBondPopupPresenterWidget.ViewDef {

    interface Driver extends SimpleBeanEditorDriver<HostBondInterfaceModel, HostBondPopupView> {
        Driver driver = GWT.create(Driver.class);
    }

    interface ViewUiBinder extends UiBinder<SimpleDialogPanel, HostBondPopupView> {
        ViewUiBinder uiBinder = GWT.create(ViewUiBinder.class);
    }

    @UiField(provided = true)
    @Path(value = "bond.selectedItem")
    ListModelListBoxEditor<Object> bondEditor;

    @UiField(provided = true)
    @Path(value = "network.selectedItem")
    ListModelListBoxEditor<Object> networkEditor;

    @UiField(provided = true)
    @Path(value = "bondingOptions.selectedItem")
    ListModelListBoxEditor<Object> bondingModeEditor;

    @UiField
    @Ignore
    EntityModelTextBoxEditor customEditor;

    @UiField(provided = true)
    EnumRadioEditor<NetworkBootProtocol> bootProtocol;

    @UiField
    @Ignore
    EntityModelLabelEditor bootProtocolLabel;

    @UiField
    @Path(value = "address.entity")
    EntityModelTextBoxEditor address;

    @UiField
    @Path(value = "subnet.entity")
    EntityModelTextBoxEditor subnet;

    @UiField
    @Path(value = "gateway.entity")
    EntityModelTextBoxEditor gateway;

    @UiField(provided = true)
    @Path(value = "checkConnectivity.entity")
    EntityModelCheckBoxEditor checkConnectivity;

    @UiField
    @Ignore
    Label message;

    @UiField
    @Ignore
    HTML info;

    @UiField
    @Ignore
    DockLayoutPanel layoutPanel;

    @UiField
    @Ignore
    VerticalPanel mainPanel;

    @UiField
    @Ignore
    VerticalPanel infoPanel;

    @UiField(provided = true)
    @Path(value = "commitChanges.entity")
    EntityModelCheckBoxEditor commitChanges;

    @Inject
    public HostBondPopupView(EventBus eventBus, ApplicationResources resources, final ApplicationConstants constants) {
        super(eventBus, resources);

        bondEditor = new ListModelListBoxEditor<Object>(new NullSafeRenderer<Object>() {
            @Override
            protected String renderNullSafe(Object object) {
                return ((VdsNetworkInterface) object).getName();
            }

        });
        networkEditor = new ListModelListBoxEditor<Object>(new NullSafeRenderer<Object>() {
            @Override
            protected String renderNullSafe(Object object) {
                return ((Network) object).getname();
            }

        });
        bondingModeEditor = new ListModelListBoxEditor<Object>(new NullSafeRenderer<Object>() {
            @SuppressWarnings("unchecked")
            @Override
            protected String renderNullSafe(Object object) {
                KeyValuePairCompat<String, EntityModel> pair = (KeyValuePairCompat<String, EntityModel>) object;
                String key = pair.getKey();
                if ("custom".equals(key)) { //$NON-NLS-1$
                    return constants.customHostPopup() + ":"; //$NON-NLS-1$
                }
                EntityModel value = pair.getValue();
                return (String) value.getEntity();
            }
        });
        bootProtocol = new EnumRadioEditor<NetworkBootProtocol>(NetworkBootProtocol.class, eventBus);

        checkConnectivity = new EntityModelCheckBoxEditor(Align.RIGHT);
        commitChanges = new EntityModelCheckBoxEditor(Align.RIGHT);

        initWidget(ViewUiBinder.uiBinder.createAndBindUi(this));

        bondEditor.setLabel(constants.bondNameHostPopup() + ":"); //$NON-NLS-1$
        networkEditor.setLabel(constants.networkHostPopup() + ":"); //$NON-NLS-1$
        bondingModeEditor.setLabel(constants.bondingModeHostPopup() + ":"); //$NON-NLS-1$
        customEditor.setLabel(constants.customModeHostPopup() + ":"); //$NON-NLS-1$
        bootProtocolLabel.setLabel(constants.bootProtocolHostPopup() + ":"); //$NON-NLS-1$
        bootProtocolLabel.asEditor().getSubEditor().setValue("   "); //$NON-NLS-1$
        address.setLabel(constants.ipHostPopup() + ":"); //$NON-NLS-1$
        subnet.setLabel(constants.subnetMaskHostPopup() + ":"); //$NON-NLS-1$
        gateway.setLabel(constants.defaultGwHostPopup() + ":"); //$NON-NLS-1$
        checkConnectivity.setLabel(constants.checkConHostPopup() + ":"); //$NON-NLS-1$
        info.setHTML(constants.changesTempHostPopup());
        commitChanges.setLabel(constants.saveNetConfigHostPopup());

        Driver.driver.initialize(this);
    }

    @Override
    public void edit(final HostBondInterfaceModel object) {
        Driver.driver.edit(object);
        if (!object.getBootProtocolAvailable()) {
            bootProtocol.asWidget().setVisible(false);
            bootProtocolLabel.setVisible(false);
        }
        bootProtocol.setEnabled(NetworkBootProtocol.None, object.getNoneBootProtocolAvailable());
        updateBondOptions(object.getBondingOptions());

        object.getPropertyChangedEvent().addListener(new IEventListener() {
            @Override
            public void eventRaised(Event ev, Object sender, EventArgs args) {
                HostBondInterfaceModel model = (HostBondInterfaceModel) sender;
                String propertyName = ((PropertyChangedEventArgs) args).PropertyName;
                if ("NoneBootProtocolAvailable".equals(propertyName)) { //$NON-NLS-1$
                    bootProtocol.setEnabled(NetworkBootProtocol.None, model.getNoneBootProtocolAvailable());
                }
                else if ("Message".equals(propertyName)) { //$NON-NLS-1$
                    message.setText(model.getMessage());
                }
            }
        });

        object.getBondingOptions().getSelectedItemChangedEvent().addListener(new IEventListener() {
            @Override
            public void eventRaised(Event ev, Object sender, EventArgs args) {
                ListModel list = (ListModel) sender;
                updateBondOptions(list);
            }
        });

        customEditor.asValueBox().addValueChangeHandler(new ValueChangeHandler<Object>() {
            @SuppressWarnings("unchecked")
            @Override
            public void onValueChange(ValueChangeEvent<Object> event) {
                for (Object item : object.getBondingOptions().getItems()) {
                    KeyValuePairCompat<String, EntityModel> pair = (KeyValuePairCompat<String, EntityModel>) item;
                    if ("custom".equals(pair.getKey())) { //$NON-NLS-1$
                        pair.getValue().setEntity(event.getValue());
                    }
                }
            }
        });

        bondingModeEditor.setVisible(true);
        bondingModeEditor.asWidget().setVisible(true);

        if (object.isCompactMode()) {
            // hide widgets
            info.setVisible(false);
            message.setVisible(false);
            checkConnectivity.setVisible(false);
            commitChanges.setVisible(false);
            // resize
            layoutPanel.remove(infoPanel);
            layoutPanel.setWidgetSize(mainPanel, 300);
            asPopupPanel().setPixelSize(400, 400);
        }

    }

    @Override
    public HostBondInterfaceModel flush() {
        return Driver.driver.flush();
    }

    @Override
    public void focusInput() {
        networkEditor.setFocus(true);
    }

    @Override
    public void setMessage(String message) {
    }

    private void updateBondOptions(ListModel list) {
        @SuppressWarnings("unchecked")
        KeyValuePairCompat<String, EntityModel> pair =
                (KeyValuePairCompat<String, EntityModel>) list.getSelectedItem();
        if ("custom".equals(pair.getKey())) { //$NON-NLS-1$
            customEditor.setVisible(true);
            Object entity = pair.getValue().getEntity();
            customEditor.asEditor().getSubEditor().setValue(entity == null ? "" : entity); //$NON-NLS-1$
        } else {
            customEditor.setVisible(false);
        }
    }

}


text:
/**
 * The expression parser of math.js has support for letting functions
 * parse and evaluate arguments themselves, instead of calling them with
 * evaluated arguments.
 *
 * By adding a property `raw` with value true to a function, the function
 * will be invoked with unevaluated arguments, allowing the function
 * to process the arguments in a customized way.
 */
const { create, all } = require('../..')
const math = create(all)

/**
 * Calculate the numeric integration of a function
 * @param {Function} f
 * @param {number} start
 * @param {number} end
 * @param {number} [step=0.01]
 */
function integrate (f, start, end, step) {
  let total = 0
  step = step || 0.01
  for (let x = start; x < end; x += step) {
    total += f(x + step / 2) * step
  }
  return total
}

/**
 * A transformation for the integrate function. This transformation will be
 * invoked when the function is used via the expression parser of math.js.
 *
 * Syntax:
 *
 *     integrate(integrand, variable, start, end)
 *     integrate(integrand, variable, start, end, step)
 *
 * Usage:
 *
 *     math.evaluate('integrate(2*x, x, 0, 2)')
 *     math.evaluate('integrate(2*x, x, 0, 2, 0.01)')
 *
 * @param {Array.<math.Node>} args
 *            Expects the following arguments: [f, x, start, end, step]
 * @param {Object} math
 * @param {Object} [scope]
 */
integrate.transform = function (args, math, scope) {
  // determine the variable name
  if (!args[1].isSymbolNode) {
    throw new Error('Second argument must be a symbol')
  }
  const variable = args[1].name

  // evaluate start, end, and step
  const start = args[2].compile().evaluate(scope)
  const end = args[3].compile().evaluate(scope)
  const step = args[4] && args[4].compile().evaluate(scope) // step is optional

  // create a new scope, linked to the provided scope. We use this new scope
  // to apply the variable.
  const fnScope = Object.create(scope)

  // construct a function which evaluates the first parameter f after applying
  // a value for parameter x.
  const fnCode = args[0].compile()
  const f = function (x) {
    fnScope[variable] = x
    return fnCode.evaluate(fnScope)
  }

  // execute the integration
  return integrate(f, start, end, step)
}

// mark the transform function with a "rawArgs" property, so it will be called
// with uncompiled, unevaluated arguments.
integrate.transform.rawArgs = true

// import the function into math.js. Raw functions must be imported in the
// math namespace, they can't be used via `evaluate(scope)`.
math.import({
  integrate: integrate
})

// use the function in JavaScript
function f (x) {
  return math.pow(x, 0.5)
}
console.log(math.integrate(f, 0, 1)) // outputs 0.6667254718034714

// use the function via the expression parser
console.log(math.evaluate('integrate(x^0.5, x, 0, 1)')) // outputs 0.6667254718034714

// use the function via the expression parser (2)
const scope = {}
math.evaluate('f(x) = 2 * x', scope)
console.log(math.evaluate('integrate(f(x), x, 0, 2)', scope)) // outputs 4.000000000000003


text:
package boofcv.alg.distort.radtan;

import boofcv.alg.distort.TransformThenPixel_F64;
import boofcv.alg.geo.PerspectiveOps;
import georegression.geometry.GeometryMath_F64;
import georegression.struct.point.Point2D_F64;
import org.ejml.data.DenseMatrix64F;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @author Peter Abeles
 */
public class TestRemoveRadialPtoN_F64 {

	@Test
	public void checkAgainstAdd() {
		checkAgainstAdd(0,0);
		checkAgainstAdd(0.1,-0.05);
	}

	public void checkAgainstAdd( double t1 , double t2 ) {
		double fx = 600;
		double fy = 500;
		double skew = 2;
		double xc = 300;
		double yc = 350;

		double radial[]= new double[]{0.12,-0.13};

		Point2D_F64 point = new Point2D_F64();

		double undistX = 19.5;
		double undistY = 200.1;

		AddRadialPtoN_F64 p_to_n = new AddRadialPtoN_F64().setK(fx, fy, skew, xc, yc).setDistortion(radial,t1,t2);
		new TransformThenPixel_F64(p_to_n).set(fx, fy, skew, xc, yc).compute(undistX, undistY, point);

		double distX = point.x;
		double distY = point.y;

		RemoveRadialPtoN_F64 alg = new RemoveRadialPtoN_F64().setK(fx,fy,skew,xc,yc).setDistortion(radial,t1,t2);

		alg.compute(distX, distY, point);

		/// go from calibrated coordinates to pixel
		DenseMatrix64F K = PerspectiveOps.calibrationMatrix(fx, fy, skew, xc, yc);

		GeometryMath_F64.mult(K,point,point);

		assertEquals(undistX,point.x,1e-4);
		assertEquals(undistY,point.y,1e-4);
	}
}


text:
package com.lanxing.service.test;

import com.lanxing.model.Student;
import com.lanxing.service.StudentService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * Created by lanxing on 16-3-1.
 */

@RunWith(SpringJUnit4ClassRunner.class)   //相当于继承了SpringJUnit4ClassRunner
@ContextConfiguration(locations = {"classpath:spring.xml", "classpath:spring-mybatis.xml"})
public class StudentServiceTest {
    private StudentService studentService;

    public StudentService getStudentService() {
        return studentService;
    }

    @Autowired
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }

    @Test
    public void findAllStudents(){
        List<Student> stus = studentService.findAllStudents();
        for (Student stu:stus) {
            System.out.println(stu);
        }
    }
}


text:
Description
===========

Cookbook to install gpg, set up root's GPG trustdb in /root/.gnupg,
and install and mark trusted all the "well known" GPG public keys from
a named data bag.

Requirements
============

gnupg2    (installed from package)
gpgme gem (specified by the chef_gem resource)

Attributes
==========

See `attributes/default.rb` for default values.

`node['gpg']['keys_data_bag']`

     -- set the name of the data bag containing PGP keys to be
        installed and trusted.

Usage
=====

Having set up your keys in the appropriate data bag, include the
gpg::default recipe on the relevant nodes' run_lists.

Data Bag Format
===============

This cookbook will set up a gpg keyring that contains and trusts the
keys you make available as data bag items. The format of those items
should be:

    {
      "id":"...",          // the key ID
      "fingerprint":"...", // the full PGP fingerprint of the key
      "public_key":"..."   // the key material
    }

The key material should be the ASCII-armoured public key material,
between identifiers of the form:

    -----BEGIN PGP PUBLIC KEY BLOCK-----
    -----END PGP PUBLIC KEY BLOCK-----

Licence and Author
==================

Author:: Chris Andrews (<candrews@venda.com>)

Copyright 2011-2012 Venda Ltd

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.


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2020] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package Bio::EnsEMBL::DataFile;

use strict;
use warnings;

use base qw/Bio::EnsEMBL::Storable/;

use Bio::EnsEMBL::ApiVersion;
use Bio::EnsEMBL::Utils::Argument qw/rearrange/;
use Bio::EnsEMBL::Utils::Exception qw/throw warning/;
use Bio::EnsEMBL::Utils::Scalar qw/:assert/;
use Bio::EnsEMBL::Utils::URI qw/is_uri/;
use File::Spec;

=head2 new

  Arg [-ADAPTOR]      : Bio::EnsEMBL::DBSQL::DataFileAdaptor
  Arg [-DBID]         : Integer $dbID
  Arg [-COORD_SYSTEM] : Bio::EnsEMBL::CoordSystem $coord_system
  Arg [-ANALYSIS]     : Bio::EnsEMBL::Analysis $analysis
  Arg [-NAME]         : String $name
  Arg [-VERSION_LOCK] : Boolean $version_lock
  Arg [-ABSOLUTE]     : Boolean $absolute
  Arg [-URL]          : String $url
  Arg [-FILE_TYPE]    : String $file_type
  Example			      : Bio::EnsEMBL::DataFile->new();
  Description	      : Returns a new instance of this object
  Returntype 	      : Bio::EnsEMBL::DataFile
  Exceptions 	      : Thrown if data is not as expected

=cut

sub new {
  my ($class, @args) = @_;
  my $self = $class->SUPER::new(@args);
  my ($coord_system, $analysis, $name, $version_lock, $absolute, $url, $file_type) =
    rearrange([qw/coord_system analysis name version_lock absolute url file_type/], @args);

  $self->coord_system($coord_system);
  $self->analysis($analysis);
  $self->name($name);
  $self->version_lock($version_lock);
  $self->absolute($absolute);
  $self->url($url);
  $self->file_type($file_type);

  return $self;
}

=head2 get_ExternalAdaptor

  Arg[1]     	: Scalar; (optional) base path. Uses defaults if not given
  Arg[2]        : Scalar; (optional) file type
  Example       : my $ea = $df->get_ExternalAdaptor('/base/path');
  Description	: Delegates to the parent adaptor to retrieve the external
                  adaptor for this data type
  Returntype 	: Adaptor; will be an adaptor that can read the given data file
  Exceptions 	: Thrown if there is no attached adaptor.

=cut

sub get_ExternalAdaptor {
  my ($self, $base_path, $requested_type) = @_;
  my $adaptor = $self->adaptor();
  throw "No DataFileAdaptor found in this object. Cannot request ExternalAdaptor" if ! $adaptor;
  return $adaptor->DataFile_to_adaptor($self, $base_path, $requested_type);
}

=head2 path

  Arg[1]      : Scalar base of the path to use. Can be ignored if the instance
                already represents a canonical path
  Example     : my $f = $df->path();
  Description : Used to generate the path to the file resource. Can return a
                path to the file or a URL but it is up to the using code to
                know how to interprate the different returned forms.

                If the data file url is canonical then this is just returned.
                If not then a path is generated of the form
                B</base/path/production_name/coord_system_version/[software_version]/db_group/name.ext>

  Returntype  : Scalar the absolute path/url to the given resource
  Exceptions  : Thrown if the linked Coordinate System lacks a version and the
                current database also lacks a default version
  Caller      : public

=cut

sub path {
  my ($self, $base) = @_;
  my $all_paths = $self->get_all_paths($base);
  return $all_paths->[0];
}

sub get_all_paths {
  my ($self, $base) = @_;

  return [$self->url()] if $self->absolute();

  my @all_paths;

  $base = $self->adaptor()->get_base_path($base) if ! $base;

  my $production_name = $self->adaptor()->db()->get_MetaContainer()->get_production_name();
  my $cs_version = $self->coord_system()->version();
  if(! $cs_version) {
    my ($highest_cs) = @{$self->adaptor()->db()->get_CoordSystemAdaptor()->fetch_all()};
    $cs_version = $highest_cs->version();
  }
  if(!$cs_version) {
    my $name = $self->name();
    throw "The file '${name}' in species '${$production_name} is attached to a CoordinateSystem lacking a version and has no default assembly. Please fix";
  }

  my @portions;
  push(@portions, $production_name);
  push(@portions, $cs_version);
  push(@portions, software_version()) if $self->version_lock();
  push(@portions, $self->adaptor()->db()->group());

  #Targets are the files to generate
  my @targets;
  #If URL is populated we assume we need to add this onto the end but removing the /
  if($self->url()) {
    my @split = split(/\//, $self->url());
    push(@targets, [@split]);
  }
  else {
    my $extensions = $self->adaptor()->DataFile_to_extensions($self);
    foreach my $ext (@{$extensions}) {
      my $filename = sprintf(q{%s.%s}, $self->name(), $ext);
      push(@targets, [$filename]);
    }
  }

  my $is_uri = is_uri($base);
  foreach my $t (@targets) {
    my $path;
    if($is_uri) {
      $path = join(q{/}, $base, @portions, @{$t});
    }
    else {
      $path = File::Spec->catfile($base, @portions, @{$t});
    }
    push(@all_paths, $path);
  }
  return \@all_paths;
}

=head2 coord_system

  Arg[1]      : Bio::EnsEMBL::CoordSystem Optional setter
  Description : Mutator for the coord system field. All files are linked to one
  Returntype  : Bio::EnsEMBL::CoordSystem
  Exceptions  : Thrown if not of the expected type

=cut

sub coord_system {
  my ($self, $coord_system) = @_;
  if(defined $coord_system) {
    assert_ref($coord_system, 'Bio::EnsEMBL::CoordSystem', 'coord_system');
  	$self->{'coord_system'} = $coord_system;
  }
  return $self->{'coord_system'};
}

=head2 analysis

  Arg[1]      : Bio::EnsEMBL::Analysis Optional setter
  Description : Mutator for the analysis field. All files are linked to one
  Returntype  : Bio::EnsEMBL::Analysis
  Exceptions  : Thrown if not of the expected type

=cut

sub analysis {
  my ($self, $analysis) = @_;
  if(defined $analysis) {
    assert_ref($analysis, 'Bio::EnsEMBL::Analysis', 'analysis');
  	$self->{'analysis'} = $analysis;
  }
  return $self->{'analysis'};
}

=head2 name

  Arg[1]      : String Optional setter
  Description : Mutator for the name of the file. Can be used in file location
                generation
  Returntype  : String

=cut

sub name {
  my ($self, $name) = @_;
  if(defined $name) {
  	$self->{'name'} = $name;
  }
  return $self->{'name'};
}

=head2 version_lock

  Arg[1]      : Boolean Optional setter
  Description : Boolean indicating if the file is linked to the version of the
                database it was found in.
  Returntype  : Boolean

=cut

sub version_lock {
  my ($self, $version_lock) = @_;
  if(defined $version_lock) {
    assert_boolean($version_lock, 'version_lock');
    $self->{'version_lock'} = $version_lock;
  }
  return $self->{'version_lock'};
}

=head2 absolute

  Arg[1]      : Boolean Optional setter
  Description : Indicates if the URL of this file is an absolute one i.e.
                should be used verbatim or not.
  Returntype  : Boolean

=cut

sub absolute {
  my ($self, $absolute) = @_;
  if(defined $absolute) {
    assert_boolean($absolute, 'absolute');
  	$self->{'absolute'} = $absolute;
  }
  return $self->{'absolute'};
}

=head2 url

  Arg[1]      : String Optional setter
  Description : Location of the file. Can be optional and if set means once
                we are in an automatic location use this value to locate
                the file.
  Returntype  : String

=cut

sub url {
  my ($self, $url) = @_;
  $self->{'url'} = $url if defined $url;
  return $self->{'url'};
}

=head2 file_type

  Arg[1]      : String Optional setter
  Description : The type of file we are working with. Can be used to generate
                a file name.
  Returntype  : String

=cut

sub file_type {
  my ($self, $file_type) = @_;
  $self->{'file_type'} = $file_type if defined $file_type;
  return $self->{'file_type'};
}

#=head2 files
#
#  Args       	:
#  Example			: my $files = @{$df->files()};
#  Description	: Returns all the file names we expect to cover for a flat file
#  Returntype 	: type return_description
#  Exceptions 	:
#  Caller     	: caller
#  Status     	: status
#
#=cut
#
#
#sub files {
#  my ($self) = @_;
#
#}

1;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="generator" content="AsciiDoc 8.2.5" />

<title>git-for-each-ref(1)</title>

git-for-each-ref(1) Manual Page

NAME

git-for-each-ref -
   Output information on each ref

SYNOPSIS

git for-each-ref [--count=<count>] [--shell|--perl|--python|--tcl]
                   [--sort=<key>]* [--format=<format>] [<pattern>…]

DESCRIPTION

Iterate over all refs that match <tt><pattern></tt> and show them
according to the given <tt><format></tt>, after sorting them according
to the given set of <tt><key></tt>.  If <tt><count></tt> is given, stop after
showing that many refs.  The interpolated values in <tt><format></tt>
can optionally be quoted as string literals in the specified
host language allowing their direct evaluation in that language.

OPTIONS

<count>

        By default the command shows all refs that match
        <tt><pattern></tt>.  This option makes it stop after showing
        that many refs.

<key>

        A field name to sort on.  Prefix <tt>-</tt> to sort in
        descending order of the value.  When unspecified,
        <tt>refname</tt> is used.  You may use the --sort=<key> option
        multiple times, in which case the last key becomes the primary
        key.

<format>

        A string that interpolates <tt>%(fieldname)</tt> from the
        object pointed at by a ref being shown.  If <tt>fieldname</tt>
        is prefixed with an asterisk (<tt>*</tt>) and the ref points
        at a tag object, the value for the field in the object
        tag refers is used.  When unspecified, defaults to
        <tt>%(objectname) SPC %(objecttype) TAB %(refname)</tt>.
        It also interpolates <tt>%%</tt> to <tt>%</tt>, and <tt>%xx</tt> where <tt>xx</tt>
        are hex digits interpolates to character with hex code
        <tt>xx</tt>; for example <tt>%00</tt> interpolates to <tt>\0</tt> (NUL),
        <tt>%09</tt> to <tt>\t</tt> (TAB) and <tt>%0a</tt> to <tt>\n</tt> (LF).

<pattern>…

        If one or more patterns are given, only refs are shown that
        match against at least one pattern, either using fnmatch(3) or
        literally, in the latter case matching completely or from the
        beginning up to a slash.

--shell

--perl

--python

--tcl

        If given, strings that substitute <tt>%(fieldname)</tt>
        placeholders are quoted as string literals suitable for
        the specified host language.  This is meant to produce
        a scriptlet that can directly be `eval`ed.

FIELD NAMES

Various values from structured fields in referenced objects can
be used to interpolate into the resulting output, or as sort
keys.

For all objects, the following names can be used:

refname

        The name of the ref (the part after $GIT_DIR/).
        For a non-ambiguous short name of the ref append <tt>:short</tt>.
        The option core.warnAmbiguousRefs is used to select the strict
        abbreviation mode.

objecttype

        The type of the object (<tt>blob</tt>, <tt>tree</tt>, <tt>commit</tt>, <tt>tag</tt>).

objectsize

        The size of the object (the same as git cat-file -s reports).

objectname

        The object name (aka SHA-1).
        For a non-ambiguous abbreviation of the object name append <tt>:short</tt>.

upstream

        The name of a local ref which can be considered “upstream”
        from the displayed ref. Respects <tt>:short</tt> in the same way as
        <tt>refname</tt> above.

In addition to the above, for commit and tag objects, the header
field names (<tt>tree</tt>, <tt>parent</tt>, <tt>object</tt>, <tt>type</tt>, and <tt>tag</tt>) can
be used to specify the value in the header field.

Fields that have name-email-date tuple as its value (<tt>author</tt>,
<tt>committer</tt>, and <tt>tagger</tt>) can be suffixed with <tt>name</tt>, <tt>email</tt>,
and <tt>date</tt> to extract the named component.

The first line of the message in a commit and tag object is
<tt>subject</tt>, the remaining lines are <tt>body</tt>.  The whole message
is <tt>contents</tt>.

For sorting purposes, fields with numeric values sort in numeric
order (<tt>objectsize</tt>, <tt>authordate</tt>, <tt>committerdate</tt>, <tt>taggerdate</tt>).
All other fields are used to sort in their byte-value order.

In any case, a field name that refers to a field inapplicable to
the object referred by the ref does not cause an error.  It
returns an empty string instead.

As a special case for the date-type fields, you may specify a format for
the date by adding one of <tt>:default</tt>, <tt>:relative</tt>, <tt>:short</tt>, <tt>:local</tt>,
<tt>:iso8601</tt> or <tt>:rfc2822</tt> to the end of the fieldname; e.g.
<tt>%(taggerdate:relative)</tt>.

EXAMPLES

An example directly producing formatted text.  Show the most recent
3 tagged commits::

<tt>#!/bin/sh

git for-each-ref --count=3 --sort='-*authordate' \
--format='From: %(*authorname) %(*authoremail)
Subject: %(*subject)
Date: %(*authordate)
Ref: %(*refname)

%(*body)
' 'refs/tags'</tt>

A simple example showing the use of shell eval on the output,
demonstrating the use of --shell.  List the prefixes of all heads::

<tt>#!/bin/sh

git for-each-ref --shell --format="ref=%(refname)" refs/heads | \
while read entry
do
        eval "$entry"
        echo `dirname $ref`
done</tt>

A bit more elaborate report on tags, demonstrating that the format
may be an entire script::

<tt>#!/bin/sh

fmt='
        r=%(refname)
        t=%(*objecttype)
        T=${r#refs/tags/}

        o=%(*objectname)
        n=%(*authorname)
        e=%(*authoremail)
        s=%(*subject)
        d=%(*authordate)
        b=%(*body)

        kind=Tag
        if test "z$t" = z
        then
                # could be a lightweight tag
                t=%(objecttype)
                kind="Lightweight tag"
                o=%(objectname)
                n=%(authorname)
                e=%(authoremail)
                s=%(subject)
                d=%(authordate)
                b=%(body)
        fi
        echo "$kind $T points at a $t object $o"
        if test "z$t" = zcommit
        then
                echo "The commit was authored by $n $e
at $d, and titled

    $s

Its message reads as:
"
                echo "$b" | sed -e "s/^/    /"
                echo
        fi
'

eval=`git for-each-ref --shell --format="$fmt" \
        --sort='*objecttype' \
        --sort=-taggerdate \
        refs/tags`
eval "$eval"</tt>

Last updated 2010-09-18 23:56:43 UTC


text:
package com.amazonaws.services.waf.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * The response to a GetXssMatchSet request.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetXssMatchSetResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * Information about the XssMatchSet that you specified in the GetXssMatchSet request. For more
     * information, see the following topics:
     *

     *

     *

     *

     * XssMatchSet: Contains Name, XssMatchSetId, and an array of
     * XssMatchTuple objects
     *

     *

     *

     *

     * XssMatchTuple: Each XssMatchTuple object contains FieldToMatch and
     * TextTransformation
     *

     *

     *

     *

     * FieldToMatch: Contains Data and Type
     *

     *

     *

     */
    private XssMatchSet xssMatchSet;

    /**
     *

     * Information about the XssMatchSet that you specified in the GetXssMatchSet request. For more
     * information, see the following topics:
     *

     *

     *

     *

     * XssMatchSet: Contains Name, XssMatchSetId, and an array of
     * XssMatchTuple objects
     *

     *

     *

     *

     * XssMatchTuple: Each XssMatchTuple object contains FieldToMatch and
     * TextTransformation
     *

     *

     *

     *

     * FieldToMatch: Contains Data and Type
     *

     *

     *

     *
     * @param xssMatchSet
     *        Information about the XssMatchSet that you specified in the GetXssMatchSet request.
     *        For more information, see the following topics:

     *

     *

     *

     *        XssMatchSet: Contains Name, XssMatchSetId, and an array of
     *        XssMatchTuple objects
     *

     *

     *

     *

     *        XssMatchTuple: Each XssMatchTuple object contains FieldToMatch and
     *        TextTransformation
     *

     *

     *

     *

     *        FieldToMatch: Contains Data and Type
     *

     *

     */

    public void setXssMatchSet(XssMatchSet xssMatchSet) {
        this.xssMatchSet = xssMatchSet;
    }

    /**
     *

     * Information about the XssMatchSet that you specified in the GetXssMatchSet request. For more
     * information, see the following topics:
     *

     *

     *

     *

     * XssMatchSet: Contains Name, XssMatchSetId, and an array of
     * XssMatchTuple objects
     *

     *

     *

     *

     * XssMatchTuple: Each XssMatchTuple object contains FieldToMatch and
     * TextTransformation
     *

     *

     *

     *

     * FieldToMatch: Contains Data and Type
     *

     *

     *

     *
     * @return Information about the XssMatchSet that you specified in the GetXssMatchSet request.
     *         For more information, see the following topics:

     *

     *

     *

     *         XssMatchSet: Contains Name, XssMatchSetId, and an array of
     *         XssMatchTuple objects
     *

     *

     *

     *

     *         XssMatchTuple: Each XssMatchTuple object contains FieldToMatch and
     *         TextTransformation
     *

     *

     *

     *

     *         FieldToMatch: Contains Data and Type
     *

     *

     */

    public XssMatchSet getXssMatchSet() {
        return this.xssMatchSet;
    }

    /**
     *

     * Information about the XssMatchSet that you specified in the GetXssMatchSet request. For more
     * information, see the following topics:
     *

     *

     *

     *

     * XssMatchSet: Contains Name, XssMatchSetId, and an array of
     * XssMatchTuple objects
     *

     *

     *

     *

     * XssMatchTuple: Each XssMatchTuple object contains FieldToMatch and
     * TextTransformation
     *

     *

     *

     *

     * FieldToMatch: Contains Data and Type
     *

     *

     *

     *
     * @param xssMatchSet
     *        Information about the XssMatchSet that you specified in the GetXssMatchSet request.
     *        For more information, see the following topics:

     *

     *

     *

     *        XssMatchSet: Contains Name, XssMatchSetId, and an array of
     *        XssMatchTuple objects
     *

     *

     *

     *

     *        XssMatchTuple: Each XssMatchTuple object contains FieldToMatch and
     *        TextTransformation
     *

     *

     *

     *

     *        FieldToMatch: Contains Data and Type
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetXssMatchSetResult withXssMatchSet(XssMatchSet xssMatchSet) {
        setXssMatchSet(xssMatchSet);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getXssMatchSet() != null)
            sb.append("XssMatchSet: ").append(getXssMatchSet());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GetXssMatchSetResult == false)
            return false;
        GetXssMatchSetResult other = (GetXssMatchSetResult) obj;
        if (other.getXssMatchSet() == null ^ this.getXssMatchSet() == null)
            return false;
        if (other.getXssMatchSet() != null && other.getXssMatchSet().equals(this.getXssMatchSet()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getXssMatchSet() == null) ? 0 : getXssMatchSet().hashCode());
        return hashCode;
    }

    @Override
    public GetXssMatchSetResult clone() {
        try {
            return (GetXssMatchSetResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}