text:
package org.p7h.storm.wordcount.utils;

/**
 * Constants used in this project.
 *
 * @author - Prashanth Babu
 */
public final class Constants {
	public static final String TOPOLOGY_NAME = "WordCount";
	public static final String CONFIG_PROPERTIES_FILE = "config.properties";
	public static final String OAUTH_ACCESS_TOKEN = "OAUTH_ACCESS_TOKEN";
	public static final String OAUTH_ACCESS_TOKEN_SECRET = "OAUTH_ACCESS_TOKEN_SECRET";
	public static final String OAUTH_CONSUMER_KEY = "OAUTH_CONSUMER_KEY";
	public static final String OAUTH_CONSUMER_SECRET = "OAUTH_CONSUMER_SECRET";
}

redpajama_set_name: RedPajamaGithub


text:
const DrawCard = require('../../drawcard.js');

class ToTheRoseBanner extends DrawCard {
    setupCardAbilities(ability) {
        this.action({
            title: 'Remove character from game',
            cost: ability.costs.kneelFactionCard(),
            target: {
                cardCondition: card => card.location === 'play area' && card.controller === this.controller &&
                    card !== this && card.isFaction('tyrell') && card.getType() === 'character'
            },
            handler: context => {
                this.lastingEffect(ability => ({
                    until: {
                        onPhaseStarted: () => true
                    },
                    match: context.target,
                    targetLocation: ['play area', 'out of game'],
                    effect: ability.effects.removeFromGame()
                }));
                this.game.addMessage('{0} uses {1} and kneels their faction card to remove {2} from the game',
                    this.controller, this, context.target);
            }
        });
    }
}

ToTheRoseBanner.code = '17141';

module.exports = ToTheRoseBanner;


text:
package common

import (
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/mitchellh/multistep"
)

const (
	privateIP = "10.0.0.1"
	publicIP  = "192.168.1.1"
	publicDNS = "public.dns.test"
)

func TestSSHHost(t *testing.T) {
	origSshHostSleepDuration := sshHostSleepDuration
	defer func() { sshHostSleepDuration = origSshHostSleepDuration }()
	sshHostSleepDuration = 0

	var cases = []struct {
		allowTries int
		vpcId      string
		private    bool

		ok       bool
		wantHost string
	}{
		{1, "", false, true, publicDNS},
		{1, "", true, true, privateIP},
		{1, "vpc-id", false, true, publicIP},
		{1, "vpc-id", true, true, privateIP},
		{2, "", false, true, publicDNS},
		{2, "", true, true, privateIP},
		{2, "vpc-id", false, true, publicIP},
		{2, "vpc-id", true, true, privateIP},
		{3, "", false, false, ""},
		{3, "", true, false, ""},
		{3, "vpc-id", false, false, ""},
		{3, "vpc-id", true, false, ""},
	}

	for _, c := range cases {
		testSSHHost(t, c.allowTries, c.vpcId, c.private, c.ok, c.wantHost)
	}
}

func testSSHHost(t *testing.T, allowTries int, vpcId string, private, ok bool, wantHost string) {
	t.Logf("allowTries=%d vpcId=%s private=%t ok=%t wantHost=%q", allowTries, vpcId, private, ok, wantHost)

	e := &fakeEC2Describer{
		allowTries: allowTries,
		vpcId:      vpcId,
		privateIP:  privateIP,
		publicIP:   publicIP,
		publicDNS:  publicDNS,
	}

	f := SSHHost(e, private)
	st := &multistep.BasicStateBag{}
	st.Put("instance", &ec2.Instance{
		InstanceId: aws.String("instance-id"),
	})

	host, err := f(st)

	if e.tries > allowTries {
		t.Fatalf("got %d ec2 DescribeInstances tries, want %d", e.tries, allowTries)
	}

	switch {
	case ok && err != nil:
		t.Fatalf("expected no error, got %+v", err)
	case !ok && err == nil:
		t.Fatalf("expected error, got none and host %s", host)
	}

	if host != wantHost {
		t.Fatalf("got host %s, want %s", host, wantHost)
	}
}

type fakeEC2Describer struct {
	allowTries int
	tries      int

	vpcId                          string
	privateIP, publicIP, publicDNS string
}

func (d *fakeEC2Describer) DescribeInstances(in *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error) {
	d.tries++

	instance := &ec2.Instance{
		InstanceId: aws.String("instance-id"),
	}

	if d.vpcId != "" {
		instance.VpcId = aws.String(d.vpcId)
	}

	if d.tries >= d.allowTries {
		instance.PublicIpAddress = aws.String(d.publicIP)
		instance.PrivateIpAddress = aws.String(d.privateIP)
		instance.PublicDnsName = aws.String(d.publicDNS)
	}

	out := &ec2.DescribeInstancesOutput{
		Reservations: []*ec2.Reservation{
			{
				Instances: []*ec2.Instance{instance},
			},
		},
	}

	return out, nil
}


text:
package ua.luxoft.study.datastructures.list;

import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public abstract class AbstractListTest {
    private List list;
    private static final Object OBJECT_STUB = new Object();

    protected abstract List determineList();

    @Before
    public void setUpList() {
        list = determineList();
    }

    @Test
    public void testMethodSizeShouldReturnSize3() {
        list.add(OBJECT_STUB);
        list.add(OBJECT_STUB);
        list.add(OBJECT_STUB);

        assertThat(list.size(), is(3));
    }

    @Test
    public void testMethodAddWithoutIndexShouldReturnSize3ShouldReturn3ElementsWhichWeAdd() {
        list.add(10);
        list.add(20);
        list.add(30);

        assertThat(list.size(), is(3));
        assertThat(list.get(0), CoreMatchers.<Object>is(10));
        assertThat(list.get(1), CoreMatchers.<Object>is(20));
        assertThat(list.get(2), CoreMatchers.<Object>is(30));

    }

    @Test
    public void testMethodAddWithIndexShouldReturnSize4ShouldReturn4ElementsInOrder10_aa_20_30() {
        list.add(10);
        list.add(20);
        list.add(30);

        assertThat(list.size(), is(3));
        assertThat(list.get(0), CoreMatchers.<Object>is(10));
        assertThat(list.get(1), CoreMatchers.<Object>is(20));
        assertThat(list.get(2), CoreMatchers.<Object>is(30));

        list.add("aa", 1);

        assertThat(list.size(), is(4));
        assertThat(list.get(0), CoreMatchers.<Object>is(10));
        assertThat(list.get(1), CoreMatchers.<Object>is("aa"));
        assertThat(list.get(2), CoreMatchers.<Object>is(20));
        assertThat(list.get(3), CoreMatchers.<Object>is(30));
    }

    @Test
    public void testMethodAddAllShouldReturnSize7ShouldReturn7ElementsInOrder10_20_30_40_50_60_70() {
        List list1 = new ArrayList();
        list1.add(40);
        list1.add(50);

        List list2 = new LinkedList();
        list2.add(60);
        list2.add(70);

        list.add(10);
        list.add(20);
        list.add(30);
        assertThat(list.size(), is(3));

        list.addAll(list1);
        list.addAll(list2);

        assertThat(list.get(0), CoreMatchers.<Object>is(10));
        assertThat(list.get(1), CoreMatchers.<Object>is(20));
        assertThat(list.get(2), CoreMatchers.<Object>is(30));
        assertThat(list.get(3), CoreMatchers.<Object>is(40));
        assertThat(list.get(4), CoreMatchers.<Object>is(50));
        assertThat(list.get(5), CoreMatchers.<Object>is(60));
        assertThat(list.get(6), CoreMatchers.<Object>is(70));
        assertThat(list.size(), CoreMatchers.<Object>is(7));
    }

    @Test
    public void testMethodSetShouldReturnNegativeValueAndPositiveValue() {
        int positiveValue = 1;
        int negativeValue = -1;

        list.add(positiveValue);
        list.set(negativeValue, 0);
        assertThat(list.get(0), CoreMatchers.<Object>is(negativeValue));

        list.set(positiveValue, 0);
        assertThat(list.get(0), CoreMatchers.<Object>is(positiveValue));
    }

    @Test
    public void testMethodGetShouldReturn3ElementsInOrder10_20_30AfterRemoveShouldReturn3ElementsInOrder10_20() {
        list.add(10);
        list.add(20);
        list.add(30);

        assertThat(list.get(0), CoreMatchers.<Object>is(10));
        assertThat(list.get(1), CoreMatchers.<Object>is(20));
        assertThat(list.get(2), CoreMatchers.<Object>is(30));

        list.remove(0);

        assertThat(list.get(0), CoreMatchers.<Object>is(20));
        assertThat(list.get(1), CoreMatchers.<Object>is(30));
    }

    @Test
    public void testMethodRemoveShouldReturnSize2ShouldReturn2ElementsInOrder10_30() {
        list.add(10);
        list.add(20);
        list.add(30);

        assertThat(list.size(), is(3));
        assertThat(list.get(0), CoreMatchers.<Object>is(10));
        assertThat(list.get(1), CoreMatchers.<Object>is(20));
        assertThat(list.get(2), CoreMatchers.<Object>is(30));

        list.remove(1);

        assertThat(list.size(), is(2));
        assertThat(list.get(0), CoreMatchers.<Object>is(10));
        assertThat(list.get(1), CoreMatchers.<Object>is(30));
    }

    @Test
    public void testMethodIndexOfShouldReturnIndex0And1() {
        list.add(10);
        list.add(30);
        list.add(30);

        assertThat(list.indexOf(10), is(0));
        assertThat(list.indexOf(30), is(1));
    }

    @Test
    public void testLastIndexOfShouldReturnIndex0And2() {
        list.add(10);
        list.add(30);
        list.add(30);

        assertThat(list.lastIndexOf(10), is(0));
        assertThat(list.lastIndexOf(30), is(2));
    }

    @Test
    public void testMethodContainsShouldReturnBooleanInOrderTrue_False_False_True() {
        list.add(10);
        list.add(20);
        list.add(30);
        assertThat(list.contains(20), is(true));
        assertThat(list.contains(69), is(false));
        assertThat(list.contains(null), is(false));

        list.add(null);
        assertThat(list.contains(null), is(true));
    }

    @Test
    public void testMethodClearShouldReturnSize0() {
        list.add(OBJECT_STUB);
        list.add(OBJECT_STUB);
        list.add(OBJECT_STUB);

        assertThat(list.size(), is(3));

        list.clear();
        assertThat(list.size(), is(0));

        list.add(OBJECT_STUB);
        assertThat(list.size(), is(1));
    }

    @Test
    public void testMethodEqualsShouldReturnTrueWhenCompareWithSelfFirstAndThirdListReturnFalseOtherwise() {
        List list1 = new ArrayList();
        list1.add(10);
        list1.add(null);
        list1.add(30);

        List list2 = new ArrayList();
        list2.add(10);
        list2.add(null);
        list2.add(20);

        List list3 = new LinkedList();
        list3.add(10);
        list3.add(null);
        list3.add(30);

        List list4 = new LinkedList();
        list4.add(10);
        list4.add(null);
        list4.add(30);
        list4.add(30);

        list.add(10);
        list.add(null);
        list.add(30);

        assertThat(list, is(list));
        assertThat(list, is(list1));
        assertThat(list, is(list3));
        assertThat(list.equals(list2), is(false));
        assertThat(list.equals(list4), is(false));
    }

    @Test
    public void testMethodToStringShouldReturnTrueWhenCompareExpectedAndActualString() {
        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);

        String expected = "List: {10, 20, 30, 40}";
        String actual = list.toString();
        assertThat(actual, is(expected));
    }

    @Test
    public void testMethodIteratorHasNextShouldReturnDoubleTrueAndThenFalse() {
        list.add(OBJECT_STUB);
        list.add(OBJECT_STUB);
        Iterator iterator = list.iterator();
        assertThat(iterator.hasNext(), is(true));
        iterator.next();
        assertThat(iterator.hasNext(), is(true));
        iterator.next();
        assertThat(iterator.hasNext(), is(false));
    }

    @Test
    public void testMethodIteratorNextShouldReturnElementFromFirstToThird() {
        list.add(10);
        list.add(20);
        list.add(30);
        Iterator iterator = list.iterator();
        assertThat(iterator.next(), CoreMatchers.<Object>is(10));
        assertThat(iterator.next(), CoreMatchers.<Object>is(20));
        assertThat(iterator.next(), CoreMatchers.<Object>is(30));
    }

    @Test
    public void testMethodIteratorRemoveShouldDecreaseSizeByTwoLeaveOnlyLastElement() {
        list.add(10);
        list.add(20);
        list.add(30);
        Iterator iterator = list.iterator();
        iterator.next();
        iterator.remove();

        assertThat(list.size(), is(2));
        assertThat(list.get(0), CoreMatchers.<Object>is(20));

        iterator.next();
        iterator.remove();

        assertThat(list.size(), is(1));
        assertThat(list.get(0), CoreMatchers.<Object>is(30));
    }

    @Test(expected = IllegalStateException.class)
    public void testMethodIteratorRemoveShouldThrowIllegalStateException() {
        list.add(OBJECT_STUB);
        list.add(OBJECT_STUB);
        list.add(OBJECT_STUB);
        Iterator iterator = list.iterator();
        iterator.next();

        iterator.remove();
        iterator.remove();

    }

    @Test(expected = IllegalStateException.class)
    public void testMethodIteratorNextShouldThrowIllegalStateException() {
        list.iterator().next();
    }

    @Test(expected = IndexOutOfBoundsException.class)
    public void testMethodRemoveShouldThrowIndexOutOfBoundsException() {
        list.add(OBJECT_STUB);
        list.add(OBJECT_STUB);
        list.add(OBJECT_STUB);

        list.remove(5);
    }

    @Test(expected = IndexOutOfBoundsException.class)
    public void testMethodAddWithIndexShouldThrowIndexOutOfBoundsException() {
        list.add(OBJECT_STUB);
        list.add(OBJECT_STUB);

        list.add(OBJECT_STUB, 8);
    }

    @Test(expected = IndexOutOfBoundsException.class)
    public void testMethodGetShouldThrowIndexOutOfBoundsException() {
        list.add(OBJECT_STUB);
        list.add(OBJECT_STUB);
        list.add(OBJECT_STUB);

        list.get(5);
    }
}


text:
package org.zaproxy.addon.encoder.processors.predefined;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;

import org.junit.jupiter.api.Test;
import org.zaproxy.addon.encoder.processors.EncodeDecodeResult;

public class UnicodeEncoderUnitTest extends ProcessorTests<UnicodeEncoder> {

    @Override
    protected UnicodeEncoder createProcessor() {
        return UnicodeEncoder.getSingleton();
    }

    @Test
    void shouldEncodeWithoutError() throws Exception {
        // Given / When
        EncodeDecodeResult result = processor.process("<script>alert('✅')</script>");
        // Then
        assertThat(result.hasError(), is(equalTo(false)));
        assertThat(
                result.getResult(),
                is(
                        equalTo(
                                "%u003c%u0073%u0063%u0072%u0069%u0070%u0074%u003e%u0061%u006c%u0065%u0072%u0074%u0028%u0027%u2705%u0027%u0029%u003c%u002f%u0073%u0063%u0072%u0069%u0070%u0074%u003e")));
    }

    @Test
    void shouldEncodeMultilineInput() throws Exception {
        // Given / When
        EncodeDecodeResult result = processor.process("some multiline\ncontent");
        // Then
        assertThat(result.hasError(), is(equalTo(false)));
        assertThat(
                result.getResult(),
                is(
                        equalTo(
                                "%u0073%u006f%u006d%u0065%u0020%u006d%u0075%u006c%u0074%u0069%u006c%u0069%u006e%u0065%u000a%u0063%u006f%u006e%u0074%u0065%u006e%u0074")));
    }
}


text:
import unittest
from zope.testing.cleanup import cleanUp

class SolrIndexTests(unittest.TestCase):

    def setUp(self):
        cleanUp()

    def tearDown(self):
        cleanUp()

    def _getTargetClass(self):
        from alm.solrindex.index import SolrIndex
        return SolrIndex

    def _makeOne(self, id, solr_uri_static=''):
        obj = self._getTargetClass()(id, solr_uri_static)
        return obj

    def _registerConnectionManager(self):
        from alm.solrindex.interfaces import ISolrConnectionManager
        from alm.solrindex.interfaces import ISolrIndex
        from zope.component import getGlobalSiteManager
        getGlobalSiteManager().registerAdapter(
            DummyConnectionManager, (ISolrIndex,), ISolrConnectionManager)

    def test_verifyImplements(self):
        from zope.interface.verify import verifyClass
        from alm.solrindex.interfaces import ISolrIndex
        verifyClass(ISolrIndex, self._getTargetClass())

    def test_verifyProvides(self):
        from zope.interface.verify import verifyObject
        from alm.solrindex.interfaces import ISolrIndex
        self._registerConnectionManager()
        obj = self._makeOne('id', 'someuri')
        verifyObject(ISolrIndex, obj)

    def test_connection_manager(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        cm = index.connection_manager
        cm2 = index.connection_manager
        self.assert_(cm is cm2)
        self.assert_(cm.index is index)

    def test_getIndexSourceNames(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        self.assertEqual(index.getIndexSourceNames(), ['f1', 'f2'])

    def test_getEntryForObject(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        cm = index.connection_manager
        cm.connection.results = [[{'docid': 2}]]
        entry = index.getEntryForObject(2)
        self.assertEqual(entry, {'docid': 2})
        self.assertEqual(cm.connection.queries,
            [{'q': 'docid:"2"', 'fields': '*'}])

    def test_index_object(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        cm = index.connection_manager
        self.assertFalse(cm.changed)
        index.index_object(2, DummyIndexableObject())
        self.assertTrue(cm.changed)
        self.assertEqual(cm.connection.added,
            [{'f1': ['a'], 'f2': ['b'], 'docid': 2}])

    def test_unindex_object(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        cm = index.connection_manager
        self.assertFalse(cm.changed)
        index.unindex_object(2)
        self.assertTrue(cm.changed)
        self.assertEqual(cm.connection.deleted, [2])

    def test__apply_index_basic(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        cm = index.connection_manager
        request = {'f1': 'somequery'}
        cm.connection.results = [[{'docid': 5}]]
        result, queried = index._apply_index(request)
        self.assertEqual(queried, ['f1'])
        self.assertEqual(dict(result.items()), {5: 0})
        self.assertFalse(cm.changed)
        self.assertEqual(cm.connection.queries, [
            {'q': "f1:somequery", 'fields': 'docid'}])

    def test__apply_index_with_scores(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        cm = index.connection_manager
        request = {'f1': 'somequery'}
        cm.connection.results = [[{'docid': 5, 'score': 0.25}]]
        result, queried = index._apply_index(request)
        self.assertEqual(queried, ['f1'])
        self.assertEqual(dict(result.items()), {5: 250})
        self.assertFalse(cm.changed)
        self.assertEqual(cm.connection.queries, [
            {'q': "f1:somequery", 'fields': 'docid'}])

    def test__apply_index_no_matching_fields(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        cm = index.connection_manager
        request = {'f99': 'somequery'}
        res = index._apply_index(request)
        self.assertEqual(res, None)

    def test__apply_index_extra_solr_params(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        cm = index.connection_manager
        request = {
            'f1': 'somequery',
            'solr_params': {'q': 'stuff', 'spellcheck': 'true'},
            }
        cm.connection.results = [[{'docid': 5}]]
        result, queried = index._apply_index(request)
        self.assertEqual(queried, ['f1'])
        self.assertEqual(dict(result.items()), {5: 0})
        self.assertFalse(cm.changed)
        self.assertEqual(cm.connection.queries, [{
            'q': 'stuff f1:somequery',
            'fields': 'docid',
            'spellcheck': 'true',
            }])

    def test__apply_index_dismax_no_q(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        cm = index.connection_manager
        request = {
            'solr_params': {'defType': 'dismax'},
            }
        cm.connection.results = [[{'docid': 5}]]
        result, queried = index._apply_index(request)
        self.assertFalse(cm.changed)
        self.assertEqual(cm.connection.queries, [{
                'q': '',
                'fields': 'docid',
                'defType': 'dismax',
                'q.alt': '*:*',
                }])

    def test__apply_index_dismax(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        cm = index.connection_manager
        request = {
            'f1': 'somequery',
            'solr_params': {'q': 'stuff', 'defType': 'dismax'},
            }
        cm.connection.results = [[{'docid': 5}]]
        result, queried = index._apply_index(request)
        self.assertEqual(queried, ['f1'])
        self.assertEqual(dict(result.items()), {5: 0})
        self.assertFalse(cm.changed)
        self.assertEqual(cm.connection.queries, [{
            'q': 'stuff f1:somequery',
            'fields': 'docid',
            'defType': 'dismax',
            }])

    def test__apply_index_with_callback(self):
        self._registerConnectionManager()
        index = self._makeOne('solr', 'someuri')
        cm = index.connection_manager
        responses = []
        request = {
            'f1': 'somequery',
            'solr_callback': responses.append,
            }
        cm.connection.results = [[{'docid': 5}]]
        result, queried = index._apply_index(request)
        self.assertEqual(queried, ['f1'])
        self.assertEqual(dict(result.items()), {5: 0})
        self.assertFalse(cm.changed)
        self.assertEqual(cm.connection.queries, [
            {'q': 'f1:somequery', 'fields': 'docid'}])
        self.assertEqual(responses, [[{'docid': 5}]])

    def test__apply_index_with_unicode(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        cm = index.connection_manager
        request = {'f1': u'\xfcber'}
        cm.connection.results = [[{'docid': 5}]]
        result, queried = index._apply_index(request)
        self.assertEqual(queried, ['f1'])
        self.assertEqual(dict(result.items()), {5: 0})
        self.assertFalse(cm.changed)
        self.assertEqual(cm.connection.queries, [
            {'q': 'f1:\xc3\xbcber', 'fields': 'docid'}])

    def test__apply_index_with_highlighting(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        cm = index.connection_manager
        f2 = cm.schema.fields[1]
        request = {'f1': 'someuri',
                   'solr_params': {'highlight': [f2.name]}}
        cm.connection.results = [[{'docid': 5}]]
        f2.stored = True
        result, queried = index._apply_index(request)
        self.assertEqual(queried, ['f1'])
        self.assertEqual(dict(result.items()), {5: 0})
        self.assertFalse(cm.changed)
        self.assertEqual(cm.connection.queries, [
            {'q': 'f1:someuri', 'fields': 'docid', 'highlight': [f2.name]}])

    def test_indexSize(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        cm = index.connection_manager
        cm.connection.results = [DummySolrResult(4)]
        count = index.indexSize()
        self.assertEqual(count, 4)
        self.assertFalse(cm.changed)

    def test_clear(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        cm = index.connection_manager
        self.assertFalse(cm.changed)
        index.clear()
        self.assertTrue(cm.changed)
        self.assertEqual(cm.connection.delete_queries, ['*:*'])

    def test_change_solr_uri(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        cm1 = index.connection_manager
        index.solr_uri_static = 'otheruri'
        cm2 = index.connection_manager
        self.assertFalse(cm1 is cm2)

    def test_get_solr_connection_from_zodb(self):
        self._registerConnectionManager()
        index = self._makeOne('id', 'someuri')
        index._p_oid = '8byteoid'
        index._p_jar = zodbc = DummyZODBConnection()
        cm = index.connection_manager
        self.assertEqual(len(zodbc.foreign_connections), 1)
        self.assert_(zodbc.foreign_connections['8byteoid'] is cm)

    def test_get_static_solr_uri(self):
        index = self._makeOne('id', 'someuri')
        self.assertEqual(index.solr_uri, 'someuri')

    def test_get_solr_uri_from_environment(self):
        import os
        index = self._makeOne('id')
        index.solr_uri_env_var = 'TEST_SOLR_URI'
        os.environ['TEST_SOLR_URI'] = 'some-uri-from-env'
        try:
            self.assertEqual(index.solr_uri, 'some-uri-from-env')
        finally:
            del os.environ['TEST_SOLR_URI']

    def test_get_bw_compat_solr_uri(self):
        index = self._makeOne('id', '')
        index.__dict__['solr_uri'] = 'bw-compat-uri'
        self.assertEqual(index.solr_uri, 'bw-compat-uri')

    def test_no_solr_uri_specified(self):
        index = self._makeOne('id', '')
        self.assertRaises(ValueError, getattr, index, 'solr_uri')

class SolrConnectionManagerTests(unittest.TestCase):

    def setUp(self):
        cleanUp()

    def tearDown(self):
        cleanUp()

    def _getTargetClass(self):
        from alm.solrindex.index import SolrConnectionManager
        return SolrConnectionManager

    def _makeOne(self, uri=''):
        class DummySolrIndex:
            solr_uri = uri
        obj = self._getTargetClass()(DummySolrIndex(), DummySolrConnection)
        return obj

    def test_verifyImplements(self):
        from zope.interface.verify import verifyClass
        from alm.solrindex.interfaces import ISolrConnectionManager
        verifyClass(ISolrConnectionManager, self._getTargetClass())

    def test_verifyProvides(self):
        from zope.interface.verify import verifyObject
        from alm.solrindex.interfaces import ISolrConnectionManager
        obj = self._makeOne()
        verifyObject(ISolrConnectionManager, obj)

    def test_get_connection(self):
        obj = self._makeOne()
        c = obj.connection
        self.assert_(c is not None)
        self.assert_(obj.connection is c)

    def test_set_changed(self):
        obj = self._makeOne()
        self.assertFalse(obj._joined)
        obj.set_changed()
        self.assertTrue(obj._joined)

    def test_abort(self):
        obj = self._makeOne()
        obj.abort(None)
        self.assertFalse(obj._joined)
        self.assertEqual(obj._connection, None)

    def test_commit(self):
        obj = self._makeOne()
        obj.set_changed()
        obj.tpc_vote(None)
        obj.tpc_finish(None)
        self.assertFalse(obj._joined)
        self.assertEqual(obj._connection.commits, 1)

    def test_commit_after_abort(self):
        obj = self._makeOne()
        obj.abort(None)
        obj.set_changed()
        obj.tpc_vote(None)
        obj.tpc_finish(None)
        self.assertFalse(obj._joined)
        self.assertEqual(obj._connection.commits, 1)

class DummyZODBConnection:
    def register(self, obj):
        pass

class DummyConnectionManager:
    def __init__(self, index):
        self.index = index
        self.schema = DummySchema()
        self.connection = DummySolrConnection()
        self.changed = False
        self.solr_uri = 'someuri'

    def set_changed(self):
        self.changed = True

class DummySolrConnection:
    def __init__(self, uri=None):
        self.uri = uri
        self.queries = []
        self.results = []
        self.added = []
        self.deleted = []
        self.delete_queries = []
        self.commits = 0

    def query(self, **args):
        self.queries.append(args)
        return self.results.pop(0)

    def add(self, **args):
        self.added.append(args)

    def delete(self, id):
        self.deleted.append(id)

    def delete_query(self, q):
        self.delete_queries.append(q)

    def close(self):
        pass

    def commit(self):
        self.commits += 1

class DummySchema:
    uniqueKey = 'docid'

    def __init__(self):
        self.fields = []
        for name in ('f1', 'f2'):
            self.fields.append(DummyField(name))

class DummyField:
    def __init__(self, name):
        self.name = name
        self.stored = False
        self.handler = DummyFieldHandler()
        self.type = 'dummy'

class DummyFieldHandler:
    def parse_query(self, field, field_query):
        return {'q': '%s:%s' % (field.name, field_query)}

    def convert(self, value):
        return [value]

class DummySolrResult:
    def __init__(self, numFound):
        self.numFound = numFound

class DummyIndexableObject:
    f1 = 'a'

    def f2(self):
        return 'b'


text:
package com.example.plugin;

import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import java.text.DecimalFormat;
import java.util.Optional;

public class ExamplePlugin extends JavaPlugin {

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage("Only players may execute this command");
            return true;
        }

        Player player = (Player) sender;
        Optional<String> id = FactionsTopApi.getId(player);
        Optional<Integer> rank = id.flatMap(FactionsTopApi::getRank);
        Optional<Double> worth = id.flatMap(FactionsTopApi::getWorth).map(FactionsTopApi.Worth::getTotal);

        if (!rank.isPresent() || !worth.isPresent()) {
            sender.sendMessage("Your faction is currently not ranked");
            return true;
        }

        DecimalFormat df = new DecimalFormat("$#,###.##");
        sender.sendMessage(String.format("Your faction is ranked #%d with %s", rank.get(), df.format(worth.get())));
        return true;
    }
}


text:
package ssh

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"code.google.com/p/gosshold/ssh/terminal"
)

func ExampleListen() {
	// An SSH server is represented by a ServerConfig, which holds
	// certificate details and handles authentication of ServerConns.
	config := &ServerConfig{
		PasswordCallback: func(conn *ServerConn, user, pass string) bool {
			return user == "testuser" && pass == "tiger"
		},
	}

	privateBytes, err := ioutil.ReadFile("id_rsa")
	if err != nil {
		panic("Failed to load private key")
	}

	private, err := ParsePrivateKey(privateBytes)
	if err != nil {
		panic("Failed to parse private key")
	}

	config.AddHostKey(private)

	// Once a ServerConfig has been configured, connections can be
	// accepted.
	listener, err := Listen("tcp", "0.0.0.0:2022", config)
	if err != nil {
		panic("failed to listen for connection")
	}
	sConn, err := listener.Accept()
	if err != nil {
		panic("failed to accept incoming connection")
	}
	if err := sConn.Handshake(); err != nil {
		panic("failed to handshake")
	}

	// A ServerConn multiplexes several channels, which must
	// themselves be Accepted.
	for {
		// Accept reads from the connection, demultiplexes packets
		// to their corresponding channels and returns when a new
		// channel request is seen. Some goroutine must always be
		// calling Accept; otherwise no messages will be forwarded
		// to the channels.
		channel, err := sConn.Accept()
		if err != nil {
			panic("error from Accept")
		}

		// Channels have a type, depending on the application level
		// protocol intended. In the case of a shell, the type is
		// "session" and ServerShell may be used to present a simple
		// terminal interface.
		if channel.ChannelType() != "session" {
			channel.Reject(UnknownChannelType, "unknown channel type")
			continue
		}
		channel.Accept()

		term := terminal.NewTerminal(channel, "> ")
		serverTerm := &ServerTerminal{
			Term:    term,
			Channel: channel,
		}
		go func() {
			defer channel.Close()
			for {
				line, err := serverTerm.ReadLine()
				if err != nil {
					break
				}
				fmt.Println(line)
			}
		}()
	}
}

func ExampleDial() {
	// An SSH client is represented with a ClientConn. Currently only
	// the "password" authentication method is supported.
	//
	// To authenticate with the remote server you must pass at least one
	// implementation of ClientAuth via the Auth field in ClientConfig.
	config := &ClientConfig{
		User: "username",
		Auth: []ClientAuth{
			// ClientAuthPassword wraps a ClientPassword implementation
			// in a type that implements ClientAuth.
			ClientAuthPassword(password("yourpassword")),
		},
	}
	client, err := Dial("tcp", "yourserver.com:22", config)
	if err != nil {
		panic("Failed to dial: " + err.Error())
	}

	// Each ClientConn can support multiple interactive sessions,
	// represented by a Session.
	session, err := client.NewSession()
	if err != nil {
		panic("Failed to create session: " + err.Error())
	}
	defer session.Close()

	// Once a Session is created, you can execute a single command on
	// the remote side using the Run method.
	var b bytes.Buffer
	session.Stdout = &b
	if err := session.Run("/usr/bin/whoami"); err != nil {
		panic("Failed to run: " + err.Error())
	}
	fmt.Println(b.String())
}

func ExampleClientConn_Listen() {
	config := &ClientConfig{
		User: "username",
		Auth: []ClientAuth{
			ClientAuthPassword(password("password")),
		},
	}
	// Dial your ssh server.
	conn, err := Dial("tcp", "localhost:22", config)
	if err != nil {
		log.Fatalf("unable to connect: %s", err)
	}
	defer conn.Close()

	// Request the remote side to open port 8080 on all interfaces.
	l, err := conn.Listen("tcp", "0.0.0.0:8080")
	if err != nil {
		log.Fatalf("unable to register tcp forward: %v", err)
	}
	defer l.Close()

	// Serve HTTP with your SSH server acting as a reverse proxy.
	http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(resp, "Hello world!\n")
	}))
}

func ExampleSession_RequestPty() {
	// Create client config
	config := &ClientConfig{
		User: "username",
		Auth: []ClientAuth{
			ClientAuthPassword(password("password")),
		},
	}
	// Connect to ssh server
	conn, err := Dial("tcp", "localhost:22", config)
	if err != nil {
		log.Fatalf("unable to connect: %s", err)
	}
	defer conn.Close()
	// Create a session
	session, err := conn.NewSession()
	if err != nil {
		log.Fatalf("unable to create session: %s", err)
	}
	defer session.Close()
	// Set up terminal modes
	modes := TerminalModes{
		ECHO:          0,     // disable echoing
		TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
		TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
	}
	// Request pseudo terminal
	if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
		log.Fatalf("request for pseudo terminal failed: %s", err)
	}
	// Start remote shell
	if err := session.Shell(); err != nil {
		log.Fatalf("failed to start shell: %s", err)
	}
}


text:
require_relative "../../../../base"

describe "VagrantPlugins::GuestBSD::Cap::InsertPublicKey" do
  let(:caps) do
    VagrantPlugins::GuestBSD::Plugin
      .components
      .guest_capabilities[:bsd]
  end

  let(:machine) { double("machine") }
  let(:comm) { VagrantTests::DummyCommunicator::Communicator.new(machine) }

  before do
    allow(machine).to receive(:communicate).and_return(comm)
  end

  after do
    comm.verify_expectations!
  end

  describe ".insert_public_key" do
    let(:cap) { caps.get(:insert_public_key) }

    it "inserts the public key" do
      cap.insert_public_key(machine, "ssh-rsa ...")
      expect(comm.received_commands[0]).to match(/mkdir -p ~\/.ssh/)
      expect(comm.received_commands[0]).to match(/chmod 0700 ~\/.ssh/)
      expect(comm.received_commands[0]).to match(/cat '\/tmp\/vagrant-(.+)' >> ~\/.ssh\/authorized_keys/)
      expect(comm.received_commands[0]).to match(/chmod 0600 ~\/.ssh\/authorized_keys/)
    end
  end
end


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschränkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using Squidex.Domain.Apps.Core.Rules;
using Squidex.Infrastructure.EventSourcing;

namespace Squidex.Domain.Apps.Events.Rules
{
    [EventType(nameof(RuleCreated))]
    public sealed class RuleCreated : RuleEvent
    {
        public RuleTrigger Trigger { get; set; }

        public RuleAction Action { get; set; }
    }
}


text:
namespace blink {

class ClientHintsPreferencesTest : public ::testing::Test {
};

TEST_F(ClientHintsPreferencesTest, Basic)
{
    struct TestCase {
        const char* headerValue;
        bool expectationResourceWidth;
        bool expectationDPR;
        bool expectationViewportWidth;
    } cases[] = {
        {"width, dpr, viewportWidth", true, true, false},
        {"WiDtH, dPr,     viewport-width", true, true, true},
        {"WIDTH, DPR, VIWEPROT-Width", true, true, false},
        {"VIewporT-Width, wutwut, width", true, false, true},
        {"dprw", false, false, false},
        {"DPRW", false, false, false},
    };

    for (const auto& testCase : cases) {
        ClientHintsPreferences preferences;
        const char* value = testCase.headerValue;

        handleAcceptClientHintsHeader(value, preferences, nullptr);
        EXPECT_EQ(testCase.expectationResourceWidth, preferences.shouldSendResourceWidth());
        EXPECT_EQ(testCase.expectationDPR, preferences.shouldSendDPR());
        EXPECT_EQ(testCase.expectationViewportWidth, preferences.shouldSendViewportWidth());
    }
}

} // namespace blink


text:
<!-- Generated by //third_party/blink/web_tests/bluetooth/generate.py -->
<!DOCTYPE html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/resources/testdriver.js"></script>
<script src="/resources/testdriver-vendor.js"></script>
<script src="/bluetooth/resources/bluetooth-test.js"></script>
<script src="/bluetooth/resources/bluetooth-fake-devices.js"></script>
<script src="/common/gc.js"></script>
<script>
'use strict';
bluetooth_test(() => {
  let promise;
  return setBluetoothFakeAdapter('DisconnectingHealthThermometerAdapter')
    .then(() => requestDeviceWithTrustedClick({
      filters: [{services: ['health_thermometer']}]}))
    .then(device => device.gatt.connect())
    .then(gattServer => gattServer.getPrimaryService('health_thermometer'))
    .then(service => service.getCharacteristic('measurement_interval'))
    .then(characteristic => {
      return assert_promise_rejects_with_message(
        characteristic.getDescriptor('invalid-name'),
          new DOMException(
              'Failed to execute \'getDescriptor\' on ' +
                  '\'BluetoothRemoteGATTCharacteristic\': Invalid Descriptor name: ' +
                  '\'invalid-name\'. ' +
                  'It must be a valid UUID alias (e.g. 0x1234), ' +
                  'UUID (lowercase hex characters e.g. ' +
                  '\'00001234-0000-1000-8000-00805f9b34fb\'), ' +
                  'or recognized standard name from ' +
                  'https://www.bluetooth.com/specifications/gatt/descriptors' +
                  ' e.g. \'gatt.characteristic_presentation_format\'.',
              'TypeError'));

    })
}, 'Test to ensure getDescriptor throws when called with an invalid name.');

</script>


text:
import { BaseComponent, Config } from '../../frameworks/core/index';
import {  ElementRef, OnInit, ViewChild, forwardRef } from "@angular/core";
import "rxjs/add/operator/catch";
import "rxjs/add/observable/throw";
import "rxjs/add/observable/empty";
import { Router } from '@angular/router';
// import { ActivatedRoute, Params } from '@angular/router';
// import { WindowNative }  from '../../../../../shared/core/services/window-native.service';
import { GlobalService }  from '../../frameworks/itn/services/singles/global.service';
import { LoginService }  from '../../frameworks/itn/services/login.service';
import { AppUser }        from '../../frameworks/itn/services/singles/app-user.service';
import { ItnUtilsService }       from '../../frameworks/itn/utils/itn.utils';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

const noop = () => {
};

export const CUSTOM_LOGIN_CONTROL_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => LoginComponent),
  multi: true
};

@BaseComponent({
  selector: 'fresh-login',
  templateUrl: './app/components/login/login.component.html',
  providers: [ CUSTOM_LOGIN_CONTROL_VALUE_ACCESSOR ],  // WindowNative,
  styleUrls: ["./app/components/login/login-common.css", "./app/components/login/login.css" ],
})

export class LoginComponent {  // implements ControlValueAccessor
  public userEmail: string = '';
  public userPswd: string = '';
  public newName: string = '';

  isLoggingIn: boolean = true;
  loginFailed: boolean = false;

  @ViewChild("userIdRef") userIdRef: ElementRef;
  @ViewChild("userPswdRef") userPswdRef: ElementRef;

  constructor(private appUser: AppUser,
    private router: Router,
    private loginService: LoginService,
    private itnUtils: ItnUtilsService)  //  public windowNative: WindowNative
    {
    }

  doLogin(form: any): void {
//  var idx;
//  var roles;

    if (!this.itnUtils.isValidEmail(this.userEmail)) {
      alert("Enter a valid email address.");
      return;
    }
    this.appUser.userid = this.userEmail;
    this.appUser.pswd = this.userPswd;

//    console.log('***** userid: ' + this.userEmail);
//    console.log('*** password: '+ this.userPswd);

    this.loginService.doLoginSequence(this.appUser.userid, this.appUser.pswd)
        .subscribe(
            (itnResponse) => {
              let look = this.appUser.token;
              console.log("Token: " + this.appUser.token);
              this.router.navigate(["/home"]);
    },
      error => {
        this.itnUtils.itnLog("Error caught in login.component.doLoginSequence *******" + error);
        console.error(error);
      }
    );

/*
      .catch(function (error) {
      // In our each() callback above fails, OR db.open() fails due to any reason,
      // including our ajax call failed, this operation will fail and we will get
      // the error here!
      _self.itnUtils.itnLog("Error caught in login.component.doLoginSequence *******" + error);
      console.error(error);
    });
*/

      /*

      if (((form.username.$invalid || form.password) && !sharedService.isFirstTime) || ((form.username.$invalid || form.password.$invalid || form.password.$invalid) && sharedService.isFirstTime)) {
//    $broadcast('show-errors-check-validity');
  } else {
    inspectionService.doLoginSequence(angular.lowercase(form.username), form.password).then(function(itnResponse) {  // angular.lowercase(form.username)
      if (itnResponse) {

      }
    }

        //set user
        //process user preferences for UI
        processUserProfile();

        // here, we are authenticating and give the user
        principal.authenticate({
          name: appUser.user,
          roles: appUser.auth
        });

      }
*/
    }

  forgotPassword() {

  }

  handleError( error ) {
    console.warn( "Caught an error in the stream." );
    console.log( error );
  }
}


text:
<?php

return [
    // Components
    'components' => [
        'status' => [
            1 => 'Operativo',
            2 => 'Problemi sulle prestazioni',
            3 => 'Disservizio parziale',
            4 => 'Interruzione del servizio',
        ],
    ],

    // Incidents
    'incidents' => [
        'none'          => 'Nothing to report',
        'past'          => 'Past Incidents',
        'previous_week' => 'Previous Week',
        'next_week'     => 'Next Week',
        'none'          => 'Nothing to report',
        'scheduled'     => 'Manutenzione programmata',
        'scheduled_at'  => ', programmata il :timestamp',
        'status'        => [
            0 => 'Programmata', // TODO: Hopefully remove this.
            1 => 'Analisi',
            2 => 'Identificato',
            3 => 'Osservazione',
            4 => 'Risolto',
        ],
    ],

    // Service Status
    'service' => [
        'good'  => '[0,1] System operational|[2,Inf] All systems are operational',
        'bad'   => '[0,1] The system is currently experiencing issues|[2,Inf] Some systems are experiencing issues',
        'major' => '[0,1] The service experiencing a major outage|[2,Inf] Some systems are experiencing a major outage',
    ],

    'api' => [
        'regenerate' => 'Rigenera API Key',
        'revoke'     => 'Revoca API Key',
    ],

    // Metrics
    'metrics' => [
        'filter' => [
            'last_hour' => 'Last Hour',
            'hourly'    => 'Last 12 Hours',
            'weekly'    => 'Week',
            'monthly'   => 'Month',
        ],
    ],

    // Subscriber
    'subscriber' => [
        'subscribe' => 'Subscribe to get the most recent updates',
        'button'    => 'Iscriviti',
        'email'     => [
            'subscribe'          => 'Iscriviti agli aggiornamenti via email.',
            'subscribed'         => 'Ti sei appena iscritto agli aggiornamenti email, controlla la tua casella per confermare la sottoscrizione',
            'verified'           => 'La tua iscrizione è stata confermata. Grazie!',
            'unsubscribe'        => 'Unsubscribe from email updates.',
            'unsubscribed'       => 'La tua iscrizione è stata rimossa.',
            'failure'            => 'Qualcosa è andato storto con l\'iscrizione.',
            'already-subscribed' => 'Cannot subscribe :email because they\'re already subscribed.',
            'verify'             => [
                'text'           => "Conferma la sottoscrizione email per gli aggiornamento di stato su :app_name \n:link\nGrazie, :app_name",
                'html-preheader' => 'Conferma la sottoscrizione email per gli aggiornamento di stato su :app_name',
                'html'           => '
Please confirm your email subscription to :app_name status updates.

:link

Thank you, :app_name
',
            ],
            'maintenance' => [
                'text'           => "Una nuova manutenzione programmata è stata inserita su :app_name.\nGrazie, :app_name",
                'html-preheader' => 'Una nuova manutenzione programmata è stata inserita su :app_name.',
                'html'           => '
New maintenance has been scheduled on :app_name.
',
            ],
            'incident' => [
                'text'           => "Un nuovo incidente è stato segnalato su :app_name.\nGrazie, :app_name",
                'html-preheader' => 'Un nuovo incidente è stato segnalato su :app_name.',
                'html'           => '
Un nuovo incidente è stato segnalato su :app_name.

Grazie, :app_name
',
            ],
            'component' => [
                'subject'        => 'Component Status Update',
                'text'           => 'The component :component_name has seen a status change. The component is now at :component_human_status.\nThank you, :app_name',
                'html-preheader' => 'Component Update from :app_name',
                'html'           => '
The component :component_name has seen a status change. The component is now at :component_human_status.

Thank you, :app_name
',
                'tooltip-title'  => 'Subscribe to notifications for :component_name.',
            ],
        ],
    ],

    'users' => [
        'email' => [
            'invite' => [
                'text'           => "You have been invited to the team :app_name status page, to sign up follow the next link.\n:link\nThank you, :app_name",
                'html-preheader' => 'You have been invited to the team :app_name.',
                'html'           => '
You have been invited to the team :app_name status page, to sign up follow the next link.

:link

Thank you, :app_name
',
            ],
        ],
    ],

    'signup' => [
        'title'    => 'Sign Up',
        'username' => 'Nome Utente',
        'email'    => 'Email',
        'password' => 'Password',
        'success'  => 'Your account has been created.',
        'failure'  => 'Something went wrong with the signup.',
    ],

    'system' => [
        'update' => 'There is a newer version of Cachet available. You can learn how to update here!',
    ],

    // Modal
    'modal' => [
        'close'     => 'Close',
        'subscribe' => [
            'title'  => 'Subscribe to component updates?',
            'body'   => 'Enter your email address to subscribe to updates for this component. If you\'re already subscribed, you\'ll receive emails for this component too.',
            'button' => 'Iscriviti',
        ],
    ],

    // Other
    'powered_by'      => ':app Status Page is powered by Cachet.',
    'about_this_site' => 'About This Site',
    'rss-feed'        => 'RSS',
    'atom-feed'       => 'Atom',
    'feed'            => 'Status Feed',

];


text:
@interface  Activity:NSObject
@property (nonatomic,copy)NSString *activityId;
@property (nonatomic,copy)NSString *picUrl;
@property (nonatomic,copy)NSString *title;
@property (nonatomic,copy)NSString *publisher;
@property (nonatomic,copy)NSString *place;
@property (nonatomic,copy)NSString *date;
@property (nonatomic,copy)NSString *price;
@property (nonatomic,copy)NSString *tel;

@property (nonatomic,copy)NSNumber *NSNumprice;

@property (nonatomic,copy)NSString *myActivityOrderId;

//@property (nonatomic,copy)NSString *price;

@end


text:
package com.intel.analytics.bigdl.example.textclassification

import java.io.File
import java.util

import com.intel.analytics.bigdl._
import com.intel.analytics.bigdl.dataset._
import com.intel.analytics.bigdl.example.textclassification.SimpleTokenizer._
import com.intel.analytics.bigdl.nn.{ClassNLLCriterion, _}
import com.intel.analytics.bigdl.optim._
import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.utils.{Engine, T}
import org.apache.log4j.{Level => Levle4j, Logger => Logger4j}
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.slf4j.{Logger, LoggerFactory}
import scopt.OptionParser

import scala.collection.mutable.{ArrayBuffer, Map => MMap}
import scala.io.Source
import scala.language.existentials

  /**
 * This example use a (pre-trained GloVe embedding) to convert word to vector,
 * and uses it to train a text classification model on the 20 Newsgroup dataset
 * with 20 different categories. This model can achieve around 90% accuracy after
 * 2 epochs training.
 */
class TextClassifier(param: TextClassificationParams) {
  val log: Logger = LoggerFactory.getLogger(this.getClass)
  val gloveDir = s"${param.baseDir}/glove.6B/"
  val textDataDir = s"${param.baseDir}/20_newsgroup/"
  var classNum = -1

  /**
   * Load the pre-trained word2Vec
   * @return A map from word to vector
   */
  private def buildWord2Vec(word2Meta: Map[String, WordMeta]): Map[Float, Array[Float]] = {
    log.info("Indexing word vectors.")
    val preWord2Vec = MMap[Float, Array[Float]]()
    val filename = s"$gloveDir/glove.6B.100d.txt"
    for (line <- Source.fromFile(filename, "ISO-8859-1").getLines) {
      val values = line.split(" ")
      val word = values(0)
      if (word2Meta.contains(word)) {
        val coefs = values.slice(1, values.length).map(_.toFloat)
        preWord2Vec.put(word2Meta(word).index.toFloat, coefs)
      }
    }
    log.info(s"Found ${preWord2Vec.size} word vectors.")
    preWord2Vec.toMap
  }

  /**
   * Load the training data from the given baseDir
   * @return An array of sample
   */
  private def loadRawData(): ArrayBuffer[(String, Float)] = {
    val texts = ArrayBuffer[String]()
    val labels = ArrayBuffer[Float]()
    // category is a string name, label is it's index
    val categoryToLabel = new util.HashMap[String, Int]()
    val categoryPathList = new File(textDataDir).listFiles().filter(_.isDirectory).toList.sorted

    categoryPathList.foreach { categoryPath =>
      val label_id = categoryToLabel.size() + 1 // one-base index
      categoryToLabel.put(categoryPath.getName(), label_id)
      val textFiles = categoryPath.listFiles()
        .filter(_.isFile).filter(_.getName.forall(Character.isDigit(_))).sorted
      textFiles.foreach { file =>
        val source = Source.fromFile(file, "ISO-8859-1")
        val text = try source.getLines().toList.mkString("\n") finally source.close()
        texts.append(text)
        labels.append(label_id)
      }
    }
    this.classNum = labels.toSet.size
    log.info(s"Found ${texts.length} texts.")
    log.info(s"Found ${classNum} classes")
    texts.zip(labels)
  }

  /**
   * Go through the whole data set to gather some meta info for the tokens.
   * Tokens would be discarded if the frequency ranking is less then maxWordsNum
   */
  def analyzeTexts(dataRdd: RDD[(String, Float)])
  : (Map[String, WordMeta], Map[Float, Array[Float]]) = {
    // Remove the top 10 words roughly, you might want to fine tuning this.
    val frequencies = dataRdd.flatMap{case (text: String, label: Float) =>
      SimpleTokenizer.toTokens(text)
    }.map(word => (word, 1)).reduceByKey(_ + _)
      .sortBy(- _._2).collect().slice(10, param.maxWordsNum)

    val indexes = Range(1, frequencies.length)
    val word2Meta = frequencies.zip(indexes).map{item =>
      (item._1._1, WordMeta(item._1._2, item._2))}.toMap
    (word2Meta, buildWord2Vec(word2Meta))
  }

  // TODO: Replace SpatialConv and SpatialMaxPolling with 1D implementation
  def buildModel(classNum: Int): Sequential[Float] = {
    val model = Sequential[Float]()

    model.add(Reshape(Array(param.embeddingDim, 1, param.maxSequenceLength)))

    model.add(SpatialConvolution(param.embeddingDim, 128, 5, 1))
    model.add(ReLU())

    model.add(SpatialMaxPooling(5, 1, 5, 1))

    model.add(SpatialConvolution(128, 128, 5, 1))
    model.add(ReLU())

    model.add(SpatialMaxPooling(5, 1, 5, 1))

    model.add(SpatialConvolution(128, 128, 5, 1))
    model.add(ReLU())

    model.add(SpatialMaxPooling(35, 1, 35, 1))

    model.add(Reshape(Array(128)))
    model.add(Linear(128, 100))
    model.add(Linear(100, classNum))
    model.add(LogSoftMax())
    model
  }

  def train(): Unit = {
    val sc = new SparkContext(
      Engine.init(param.nodeNum, param.coreNum, true).get
        .setAppName("Text classification")
        .set("spark.akka.frameSize", 64.toString)
        .set("spark.task.maxFailures", "1"))
    val sequenceLen = param.maxSequenceLength
    val embeddingDim = param.embeddingDim
    val trainingSplit = param.trainingSplit

    // For large dataset, you might want to get such RDD[(String, Float)] from HDFS
    val dataRdd = sc.parallelize(loadRawData(), param.partitionNum)
    val (word2Meta, word2Vec) = analyzeTexts(dataRdd)
    val word2MetaBC = sc.broadcast(word2Meta)
    val word2VecBC = sc.broadcast(word2Vec)
    val vectorizedRdd = dataRdd
        .map {case (text, label) => (toTokens(text, word2MetaBC.value), label)}
        .map {case (tokens, label) => (shaping(tokens, sequenceLen), label)}
        .map {case (tokens, label) => (vectorization(
          tokens, embeddingDim, word2VecBC.value), label)}
    val sampleRDD = vectorizedRdd.map {case (input: Array[Array[Float]], label: Float) =>
          Sample(
            featureTensor = Tensor(input.flatten, Array(sequenceLen, embeddingDim))
              .transpose(1, 2).contiguous(),
            labelTensor = Tensor(Array(label), Array(1)))
        }

    val Array(trainingRDD, valRDD) = sampleRDD.randomSplit(
      Array(trainingSplit, 1 - trainingSplit))

    val optimizer = Optimizer(
      model = buildModel(classNum),
      sampleRDD = trainingRDD,
      criterion = new ClassNLLCriterion[Float](),
      batchSize = param.batchSize
    )
    val state = T("learningRate" -> 0.01, "learningRateDecay" -> 0.0002)
    optimizer
      .setState(state)
      .setOptimMethod(new Adagrad())
      .setValidation(Trigger.everyEpoch, valRDD, Array(new Top1Accuracy[Float]), param.batchSize)
      .setEndWhen(Trigger.maxEpoch(2))
      .optimize()
    sc.stop()
  }
}

/**
 * @param baseDir The root directory which containing the training and embedding data
 * @param maxSequenceLength number of the tokens
 * @param maxWordsNum maximum word to be included
 * @param trainingSplit percentage of the training data
 * @param batchSize size of the mini-batch
 * @param embeddingDim size of the embedding vector
 * @param coreNum same idea of spark core
 * @param nodeNum size of the cluster
 */
case class TextClassificationParams(baseDir: String = "./",
  maxSequenceLength: Int = 1000,
  maxWordsNum: Int = 20000,
  trainingSplit: Double = 0.8,
  batchSize: Int = 128,
  embeddingDim: Int = 100,
  coreNum: Int = 4,
  nodeNum: Int = 1,
  partitionNum: Int = 4)

object TextClassifier {
  val log: Logger = LoggerFactory.getLogger(this.getClass)
  Logger4j.getLogger("org").setLevel(Levle4j.ERROR)
  Logger4j.getLogger("akka").setLevel(Levle4j.ERROR)
  Logger4j.getLogger("breeze").setLevel(Levle4j.ERROR)
  Logger4j.getLogger("com.intel.analytics.bigdl.optim").setLevel(Levle4j.INFO)

  def main(args: Array[String]): Unit = {
    val localParser = new OptionParser[TextClassificationParams]("BigDL Example") {
      opt[String]('b', "baseDir")
        .required()
        .text("Base dir containing the training and word2Vec data")
        .action((x, c) => c.copy(baseDir = x))
      opt[String]('o', "coreNum")
        .text("core number")
        .action((x, c) => c.copy(coreNum = x.toInt))
      opt[String]('n', "nodeNum")
        .text("nodeNumber")
        .action((x, c) => c.copy(nodeNum = x.toInt))
      opt[String]('p', "partitionNum")
        .text("you may want to tune the partitionNum if run into spark mode")
        .action((x, c) => c.copy(partitionNum = x.toInt))
      opt[String]('s', "maxSequenceLength")
        .text("maxSequenceLength")
        .action((x, c) => c.copy(maxSequenceLength = x.toInt))
      opt[String]('w', "maxWordsNum")
        .text("maxWordsNum")
        .action((x, c) => c.copy(maxWordsNum = x.toInt))
      opt[String]('l', "trainingSplit")
        .text("trainingSplit")
        .action((x, c) => c.copy(trainingSplit = x.toDouble))
      opt[String]('z', "batchSize")
        .text("batchSize")
        .action((x, c) => c.copy(batchSize = x.toInt))
    }

    localParser.parse(args, TextClassificationParams()).map { param =>
      log.info(s"Current parameters: $param")
      val textClassification = new TextClassifier(param)
      textClassification.train()
    }
  }
}


text:
Yinject
=======

JavaScript Dependency Injection


text:
package com.cloudant.sync.internal.replication;

import static org.hamcrest.CoreMatchers.hasItems;

import com.cloudant.sync.internal.mazha.DocumentRevs;
import com.cloudant.sync.documentstore.DocumentRevision;
import com.cloudant.sync.internal.documentstore.DocumentRevsUtils;
import com.cloudant.sync.internal.util.JSONUtils;
import com.cloudant.sync.util.TestUtils;

import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class DocumentRevsUtilsTest {

    @Test
    public void test_load_data_from_file() throws IOException {
        DocumentRevs documentRevs = getDocumentRevsFromFile(TestUtils.loadFixture
                ("fixture/document_revs_with_everything.json"));
        Assert.assertNotNull(documentRevs);
        Assert.assertEquals("cdb1a2fec33d146fe07a44ea823bf3ae", documentRevs.getId());
        Assert.assertEquals("4-47d7102726fc89914431cb217ab7bace", documentRevs.getRev());
        Assert.assertEquals(4, documentRevs.getRevisions().getStart());
        Assert.assertEquals(4, documentRevs.getRevisions().getIds().size());
        Assert.assertThat(documentRevs.getOthers().keySet(), hasItems("title", "album"));
    }

    @Test(expected = IllegalArgumentException.class)
    public void createRevisionIdHistory_null_exception() {
        DocumentRevsUtils.createRevisionIdHistory(null);
    }

    @Test
    public void createRevisionIdHistory_historyWithFourIds() throws IOException {
        DocumentRevs documentRevs = getDocumentRevsFromFile(TestUtils.loadFixture("fixture/document_revs_with_everything.json"));
        List<String> revisions = DocumentRevsUtils.createRevisionIdHistory(documentRevs);
        Assert.assertEquals(4, revisions.size());
        Assert.assertEquals("1-421ff3d58df47ea6c5e83ca65efb2fa9", revisions.get(0));
        Assert.assertEquals("2-74e0572530e3b4cd4776616d2f591a96", revisions.get(1));
        Assert.assertEquals("3-d8e1fb8127d8dd732d9ae46a6c38ae3c", revisions.get(2));
        Assert.assertEquals("4-47d7102726fc89914431cb217ab7bace", revisions.get(3));
    }

    @Test
    public void createRevisionIdHistory_onlyOneRevision() throws IOException {
        DocumentRevs documentRevs = getDocumentRevsFromFile(TestUtils.loadFixture("fixture/document_revs_only_one_revision.json"));
        List<String> revisions = DocumentRevsUtils.createRevisionIdHistory(documentRevs);
        Assert.assertEquals(1, revisions.size());
        Assert.assertEquals("1-47d7102726fc89914431cb217ab7bace", revisions.get(0));
    }

    private DocumentRevs getDocumentRevsFromFile(File file) throws IOException {
        byte[] data = FileUtils.readFileToByteArray(file);
        return JSONUtils.deserialize(data, DocumentRevs.class);
    }

    @Test
    public void createDocument() throws Exception {

        DocumentRevs documentRevs = getDocumentRevsFromFile(TestUtils.loadFixture("fixture/document_revs_with_everything.json"));
        DocumentRevision documentRevision = DocumentRevsUtils.createDocument(documentRevs);

        Assert.assertEquals("cdb1a2fec33d146fe07a44ea823bf3ae", documentRevision.getId());
        Assert.assertEquals("4-47d7102726fc89914431cb217ab7bace", documentRevision.getRevision());

        Map<String, Object> body = documentRevision.getBody().asMap();
        Assert.assertEquals(2, body.size());
        Assert.assertThat(body.keySet(), hasItems("title", "album"));
        Assert.assertEquals("A Flush Of Blood To My Head", body.get("album"));
        Assert.assertEquals("Trouble Two", body.get("title"));
    }

    @Test(expected = IllegalArgumentException.class)
    public void createDocument_null_exception() {
        DocumentRevsUtils.createDocument(null);
    }

    @Test
    public void createDocument_deletedDocument_documentMarkedAsDeleted() throws Exception {
        DocumentRevs documentRevs = getDocumentRevsFromFile(TestUtils.loadFixture("fixture/document_revs_deleted.json"));
        DocumentRevision documentRevision = DocumentRevsUtils.createDocument(documentRevs);

        Assert.assertTrue(documentRevision.isDeleted());
    }
}


text:
<?php

namespace Tonic;

/**
 * A Tonic application
 */
class Application
{
    /**
     * The base of the URI of all resources in this Tonic Application.
     * It should usually match the value of Apache's mod_rewrite RewriteBase.
     */
    public $baseUri = '';

    /**
     * Application configuration options
     */
    private $options = array();

    /**
     * Metadata of the loaded resources
     */
    private $resources = array();

    public function __construct($options = array())
    {
        if (isset($options['baseUri'])) {
            $this->baseUri = $options['baseUri'];
        } elseif (isset($_SERVER['DOCUMENT_URI'])) {
            $this->baseUri = dirname($_SERVER['DOCUMENT_URI']);
        }
        $this->options = $options;

        // load resource metadata passed in via options array
        if (isset($options['resources']) && is_array($options['resources'])) {
            $this->resources = $options['resources'];
        }

        $cache = isset($options['cache']) ? $options['cache'] : NULL;
        if ($cache && $cache->isCached()) { // if we've been given a annotation cache, use it
            $this->resources = $cache->load();
        } else { // otherwise load from loaded resource files
            if (isset($options['load'])) { // load given resource class files
                $this->loadResourceFiles($options['load']);
            }
            $this->loadResourceMetadata();
            if ($cache) { // save metadata into annotation cache
                $cache->save($this->resources);
            }
        }

        // set any URI-space mount points we've been given
        if (isset($options['mount']) && is_array($options['mount'])) {
            foreach ($options['mount'] as $namespaceName => $uriSpace) {
                $this->mount($namespaceName, $uriSpace);
            }
        }
    }

    /**
     * Include PHP files containing resources in the given filename globs
     * @paramstr[] $filenames Array of filename globs
     */
    private function loadResourceFiles($filenames)
    {
        if (!is_array($filenames)) {
            $filenames = array($filenames);
        }

        foreach ($filenames as $glob) {
            $globs = glob(str_replace('[', '[[]', $glob));
            if ($globs) {
                foreach ($globs as $filename) {
                    require_once $filename;
                }
            }
        }
    }

    /**
     * Load the metadata for all loaded resource classes
     * @param str $uriSpace Optional URI-space to mount the resources into
     */
    private function loadResourceMetadata($uriSpace = NULL)
    {
        foreach (get_declared_classes() as $className) {
            if (
                !isset($this->resources[$className]) &&
                is_subclass_of($className, 'Tonic\Resource')
            ) {
                $resource = $this->readResourceAnnotations($className);
                if (isset($resource['uri'])) {
                    foreach ($resource['uri'] as $k => $uri) {
                        if ($uriSpace) {
                            $resource['uri'][$k][0] = $uriSpace . $resource['uri'][$k][0];
                        }
                        $resource['uri'][$k][0] = $this->baseUri . $resource['uri'][$k][0];
                    }
                    $resource['methods'] = $this->readMethodAnnotations($className);
                    $this->resources[$className] = $resource;
                }
            }
        }
    }

    /**
     * Add a namespace to a specific URI-space
     *
     * @param str $namespaceName
     * @param str $uriSpace
     */
    public function mount($namespaceName, $uriSpace)
    {
        foreach ($this->resources as $className => $metadata) {
            if ($metadata['namespace'][0] == $namespaceName) {
                if (isset($metadata['uri'])) {
                    foreach ($metadata['uri'] as $index => $uri) {
                        $this->resources[$className]['uri'][$index][0] = $uriSpace.$uri[0];
                    }
                }
            }
        }
    }

    /**
     * Get the URL for the given resource class
     *
     * @param  str   $className
     * @param  str[] $params
     * @return str
     */
    public function uri($className, $params = array())
    {
        if (is_object($className)) {
            $className = get_class($className);
        }
        if (isset($this->resources[$className])) {
            if ($params && !is_array($params)) {
                $params = array($params);
            }
            foreach ($this->resources[$className]['uri'] as $uri) {
                if (count($params) == count($uri) - 1) {
                    $parts = explode('([^/]+)', $uri[0]);
                    $path = '';
                    foreach ($parts as $key => $part) {
                        $path .= $part;
                        if (isset($params[$key])) {
                            $path .= $params[$key];
                        }
                    }

                    return $this->baseUri.$path;
                }
            }
        }
    }

    /**
     * Given the request data and the loaded resource metadata, pick the best matching
     * resource to handle the request based on URI and priority.
     *
     * @param  Request  $request
     * @return Resource
     */
    public function getResource($request = NULL)
    {
        $matchedResource = NULL;
        if (!$request) {
            $request= new Request();
        }
        foreach ($this->resources as $className => $resourceMetadata) {
            if (isset($resourceMetadata['uri'])) {
                if (!is_array($resourceMetadata['uri'])) {
                    $resourceMetadata['uri'] = array($resourceMetadata['uri']);
                }
                foreach ($resourceMetadata['uri'] as $uri) {
                    if (!is_array($uri)) {
                        $uri = array($uri);
                    }
                    $uriRegex = '|^'.$uri[0].'$|';
                    if (!isset($resourceMetadata['priority'])) {
                        $resourceMetadata['priority'] = 1;
                    }
                    if (!isset($resourceMetadata['class'])) {
                        $resourceMetadata['class'] = $className;
                    }
                    if (
                        ($matchedResource == NULL || $matchedResource[0]['priority'] < $resourceMetadata['priority'])
                    &&
                        preg_match($uriRegex, $request->uri, $params)
                    ) {
                        array_shift($params);
                        if (count($uri) > 1) { // has params within URI
                            array_shift($uri);
                            foreach ($uri as $key => $name) {
                                $params[$name] = $params[$key];
                            }
                        }
                        $matchedResource = array($resourceMetadata, $params);
                    }
                }
            }
        }
        if ($matchedResource) {
            if (isset($matchedResource[0]['filename']) && is_readable($matchedResource[0]['filename'])) {
                require_once($matchedResource[0]['filename']);
            }
            $request->params = $matchedResource[1];

            return new $matchedResource[0]['class']($this, $request, $matchedResource[1]);
        } else {
            throw new NotFoundException(sprintf('Resource matching URI "%s" not found', $request->uri));
        }
    }

    /**
     * Get the already loaded resource annotation metadata
     * @param  Tonic/Resource $resource
     * @return str[]
     */
    public function getResourceMetadata($resource)
    {
        if (is_object($resource)) {
            $className = get_class($resource);
        } else {
            $className = $resource;
        }

        return isset($this->resources[$className]) ? $this->resources[$className] : NULL;
    }

    /**
     * Read the annotation metadata for the given class
     * @return str[] Annotation metadata
     */
    private function readResourceAnnotations($className)
    {
        $metadata = array();

        // get data from reflector
        $classReflector = new \ReflectionClass($className);

        $metadata['class'] = '\\'.$classReflector->getName();
        $metadata['namespace'] = array($classReflector->getNamespaceName());
        $metadata['filename'] = $classReflector->getFileName();
        $metadata['priority'] = array(1);

        // get data from docComment
        $docComment = $this->parseDocComment($classReflector->getDocComment());

        if (isset($docComment['@uri'])) {
            foreach ($docComment['@uri'] as $uri) {
                $metadata['uri'][] = $this->uriTemplateToRegex($uri);
            }
        }
        if (isset($docComment['@namespace'])) $metadata['namespace'] = $docComment['@namespace'][0];
        if (isset($docComment['@priority'])) $metadata['priority'] = $docComment['@priority'][0];

        return $metadata;
    }

    /**
     * Turn a URL template into a regular expression
     * @param  str[] $uri URL template
     * @return str[] Regular expression and parameter names
     */
    private function uriTemplateToRegex($uri)
    {
        preg_match_all('#((?<!\?):[^/]+|{[^0-9][^}]*}|\(.+?\))#', $uri[0], $params, PREG_PATTERN_ORDER);
        $return = $uri;
        if (isset($params[1])) {
            foreach ($params[1] as $index => $param) {
                if (substr($param, 0, 1) == ':') {
                    $return[] = substr($param, 1);
                } elseif (substr($param, 0, 1) == '{' && substr($param, -1, 1) == '}') {
                    $return[] = substr($param, 1, -1);
                } else {
                    $return[] = $index;
                }
            }
        }

        $return[0] = preg_replace('#((?<!\?):[^(/]+|{[^0-9][^}]*})#', '([^/]+)', $return[0]);

        return $return;
    }

    private function mergeMetadata($array1, $array2)
    {
        foreach ($array2 as $method => $metadata) {
            foreach ($metadata as $annotation => $values) {
                foreach ($values as $value) {
                    if (isset($array1[$method][$annotation])) {
                        if (!in_array($value, $array1[$method][$annotation])) {
                            $array1[$method][$annotation][] = $value;
                        }
                    } else {
                        $array1[$method][$annotation] = array($value);
                    }
                }
            }
        }

        return $array1;
    }

    private function readMethodAnnotations($className, $targetClass = null)
    {
        if (isset($this->resources[$className]) && isset($this->resources[$className]['methods'])) {
            return $this->resources[$className]['methods'];
        }

        if (!$targetClass) {
            $targetClass = $className;
        }

        $metadata = array();

        $methodNames = get_class_methods($className);
        $methodNames[] = 'setup';
        foreach ($methodNames as $methodName) {
            if (method_exists($className, $methodName)) {

                $methodReflector = new \ReflectionMethod($className, $methodName);
                if (($methodReflector->isPublic() || $methodName == 'setup') && $methodReflector->getDeclaringClass()->name != 'Tonic\Resource') {

                    $methodMetadata = array();

                    $docComment = $this->parseDocComment($methodReflector->getDocComment());

                    foreach ($docComment as $annotationName => $value) {
                        $annotationMethodName = substr($annotationName, 1);
                        if (method_exists($targetClass, $annotationMethodName)) {
                            foreach ($value as $v) {
                                $methodMetadata[$annotationMethodName][] = $v;
                            }
                        }
                    }
                    $metadata[$methodReflector->getName()] = $methodMetadata;
                }
            }
        }

        // recurse through parent classes and merge in parent class metadata
        $classReflector = new \ReflectionClass($className);
        $parentReflector = $classReflector->getParentClass();
        if ($parentReflector) {
            $metadata = $this->mergeMetadata($this->readMethodAnnotations($parentReflector->name, $targetClass), $metadata);
        }
        $interfaces = $classReflector->getInterfaceNames();
        foreach ($interfaces as $interface) {
            $metadata = $this->mergeMetadata($this->readMethodAnnotations($interface, $targetClass), $metadata);
        }

        return $metadata;
    }

    /**
     * Parse annotations out of a doc comment
     * @param  str   $comment Doc comment to parse
     * @return str[]
     */
    private function parseDocComment($comment)
    {
        $data = array();
        preg_match_all('/^\s*\*[*\s]*(@.+)$/m', $comment, $items);
        if ($items && isset($items[1])) {
            foreach ($items[1] as $item) {
                preg_match_all('/"[^"]+"|[^\s]+/', $item, $parts);
                $key = array_shift($parts[0]);
                array_walk($parts[0], create_function('&$v', '$v = trim($v, \'"\');'));
                $data[$key][] = $parts[0];
            }
        }

        return $data;
    }

    public function __toString()
    {
        $baseUri = $this->baseUri;

        if (isset($this->options['load']) && is_array($this->options['load'])) {
            $loadPath = join(', ', $this->options['load']);
        } else $loadPath = '';

        $mount = array();
        if (isset($this->options['mount']) && is_array($this->options['mount'])) {
            foreach ($this->options['mount'] as $namespaceName => $uriSpace) {
                $mount[] = $namespaceName.'="'.$uriSpace.'"';
            }
        }
        $mount = join(', ', $mount);

        $cache = isset($this->options['cache']) ? $this->options['cache'] : NULL;

        $resources = array();
        foreach ($this->resources as $resource) {
            $uri = array();
            foreach ($resource['uri'] as $u) {
                $uri[] = $u[0];
            }
            $uri = join(', ', $uri);
            $r = $resource['class'].' '.$uri.' '.join(', ', $resource['priority']);
            foreach ($resource['methods'] as $methodName => $method) {
                $r .= "\n\t\t".$methodName;
                foreach ($method as $itemName => $items) {
                    foreach ($items as $item) {
                        $r .= ' '.$itemName;
                        if ($item) {
                            $r .= '="'.join(', ', $item).'"';
                        }
                    }
                }
            }
            $resources[] = $r;
        }
        $resources = join("\n\t", $resources);

        return <<<EOF
=================
Tonic\Application
=================
Base URI: $baseUri
Load path: $loadPath
Mount points: $mount
Annotation cache: $cache
Loaded resources:
\t$resources

EOF;
    }

}


text:
class ConditionIsBack < ConditionSimple
  def match?(card)
    card.back?
  end

  def to_s
    "is:back"
  end
end


text:
'use strict';

import React, {Component, PropTypes} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    TouchableOpacity,
    TextInput
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

class ToolBar extends Component {
    constructor(props)
    {
        super(props);
    }

    static propTypes = {
        title: PropTypes.string, //中间的标题
        leftOnClick: PropTypes.func, //左边按钮的监听
        rightOnClick: PropTypes.func//右边按钮的监听
    };

    render()
    {
        return (
            <View style={styles.container}>
                <TouchableOpacity onPress={this.props.leftOnClick}>
                    <Icon name="ios-menu" size={30} color='#303030'/>
                </TouchableOpacity>

                <Text style={styles.textCenter}>{this.props.title}</Text>

                <TouchableOpacity onPress={this.props.rightOnClick}>
                    <Icon name="ios-contact" size={30} color='#303030'/>
                </TouchableOpacity>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        paddingLeft: 15,
        paddingRight: 15,
        flexDirection: 'row',
        alignItems: 'center',
    },
    textCenter: {
        flex: 1,
        fontFamily: 'FZQingKeBenYueSongS-R-GB',
        textAlign: 'center',
        fontSize: 25
    },
});

export default ToolBar;


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic

    ''' <summary>
    ''' Binder used for attributes
    ''' </summary>
    Friend NotInheritable Class AttributeBinder
        Inherits Binder

        ''' <summary> Root syntax node </summary>
        Private ReadOnly _root As VisualBasicSyntaxNode

        Public Sub New(containingBinder As Binder, tree As SyntaxTree, Optional node As VisualBasicSyntaxNode = Nothing)
            MyBase.New(containingBinder, tree)

            _root = node
        End Sub

        ''' <summary> Field or property declaration statement syntax node </summary>
        Friend ReadOnly Property Root As VisualBasicSyntaxNode
            Get
                Return _root
            End Get
        End Property

        ''' <summary>
        ''' Some nodes have special binder's for their contents
        ''' </summary>
        Public Overrides Function GetBinder(node As VisualBasicSyntaxNode) As Binder
            Return Nothing
        End Function

        Friend Overrides ReadOnly Property IsDefaultInstancePropertyAllowed As Boolean
            Get
                Return False
            End Get
        End Property
    End Class

End Namespace


text:
#include <iostream>

#define BOOST_SPIRIT_DEBUG

#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_error_handling.hpp>
#include <boost/spirit/include/classic_iterator.hpp>
#include <boost/spirit/include/classic_symbols.hpp>
#include <boost/spirit/include/classic_utility.hpp>

using namespace BOOST_SPIRIT_CLASSIC_NS;

template <typename Rule>
struct SetRest
{
    SetRest(Rule& the_rule)
    : m_the_rule(the_rule)
    {
    }

    void operator()(Rule* new_rule) const
    {
        m_the_rule = *new_rule;
    }

private:

    Rule& m_the_rule;
};

struct nabialek_trick : public grammar<nabialek_trick>
{
    template <typename ScannerT>
    struct definition
    {
        typedef rule<ScannerT> rule_t;

        rule_t name;
        rule_t line;
        rule_t rest;
        rule_t main;
        rule_t one;
        rule_t two;

        symbols<rule_t*> continuations;

        definition(nabialek_trick const& self)
        {
            name = lexeme_d[repeat_p(1,20)[alnum_p | '_']];

            one = name;
            two = name >> ',' >> name;

            continuations.add
                ("one", &one)
                ("two", &two)
                ;

            line = continuations[SetRest<rule_t>(rest)] >> rest;
            main = *line;

            BOOST_SPIRIT_DEBUG_RULE(name);
            BOOST_SPIRIT_DEBUG_RULE(line);
            BOOST_SPIRIT_DEBUG_RULE(rest);
            BOOST_SPIRIT_DEBUG_RULE(main);
            BOOST_SPIRIT_DEBUG_RULE(one);
            BOOST_SPIRIT_DEBUG_RULE(two);
        }

        rule_t const&
        start() const
        {
            return main;
        }
    };
};

int
main()
{
    nabialek_trick g;
    parse("one only\none again\ntwo first,second", g, space_p);
    return 0;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/SESSendRawEmailResponse.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/SESSendRawEmailResponse</TokenIdentifier>
			<Abstract type="html">Send Raw Email Result</Abstract>
			<DeclaredIn>SESSendRawEmailResponse.h</DeclaredIn>

			<NodeRef refid="754"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/SESSendRawEmailResponse/setException:</TokenIdentifier>
			<Abstract type="html">If an exception was thrown, this will return the exception.</Abstract>
			<DeclaredIn>SESSendRawEmailResponse.h</DeclaredIn>

			<Declaration>- (void)setException:(AmazonServiceException *)theException</Declaration>

			<Anchor>//api/name/setException:</Anchor>
            <NodeRef refid="754"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/SESSendRawEmailResponse/init</TokenIdentifier>
			<Abstract type="html">Default constructor for a new  object.  Callers should use the
property methods to initialize this object after creating it.</Abstract>
			<DeclaredIn>SESSendRawEmailResponse.h</DeclaredIn>

			<Declaration>- (id)init</Declaration>

			<Anchor>//api/name/init</Anchor>
            <NodeRef refid="754"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/SESSendRawEmailResponse/setMessageId:</TokenIdentifier>
			<Abstract type="html">The unique message identifier returned from the
SendRawEmail action.</Abstract>
			<DeclaredIn>SESSendRawEmailResponse.h</DeclaredIn>

			<Declaration>@property (nonatomic, retain) NSString *messageId</Declaration>

			<Anchor>//api/name/messageId</Anchor>
            <NodeRef refid="754"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/SESSendRawEmailResponse/messageId</TokenIdentifier>
			<Abstract type="html">The unique message identifier returned from the
SendRawEmail action.</Abstract>
			<DeclaredIn>SESSendRawEmailResponse.h</DeclaredIn>

			<Declaration>@property (nonatomic, retain) NSString *messageId</Declaration>

			<Anchor>//api/name/messageId</Anchor>
            <NodeRef refid="754"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/SESSendRawEmailResponse/messageId</TokenIdentifier>
			<Abstract type="html">The unique message identifier returned from the
SendRawEmail action.</Abstract>
			<DeclaredIn>SESSendRawEmailResponse.h</DeclaredIn>

			<Declaration>@property (nonatomic, retain) NSString *messageId</Declaration>

			<Anchor>//api/name/messageId</Anchor>
            <NodeRef refid="754"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/SESSendRawEmailResponse/description</TokenIdentifier>
			<Abstract type="html">Returns a string representation of this object; useful for testing and
debugging.</Abstract>
			<DeclaredIn>SESSendRawEmailResponse.h</DeclaredIn>

			<Declaration>- (NSString *)description</Declaration>

			<ReturnValue><Abstract type="html">A string representation of this object.</Abstract></ReturnValue>
			<Anchor>//api/name/description</Anchor>
            <NodeRef refid="754"/>
		</Token>

	</File>
</Tokens>


text:
#ifndef __CLKDEV__H_
#define __CLKDEV__H_

#include <linux/bootmem.h>
#include <linux/mm.h>
#include <linux/slab.h>

#include <asm/clock.h>

static inline struct clk_lookup_alloc *__clkdev_alloc(size_t size)
{
	if (!slab_is_available())
		return alloc_bootmem_low_pages(size);
	else
		return kzalloc(size, GFP_KERNEL);
}

#ifndef CONFIG_COMMON_CLK
#define __clk_put(clk)
#define __clk_get(clk) ({ 1; })
#endif

#endif /* __CLKDEV_H__ */


text:
GeolocationInfoBarDelegateAndroid::GeolocationInfoBarDelegateAndroid(
    const GURL& requesting_frame,
    bool user_gesture,
    Profile* profile,
    const PermissionSetCallback& callback)
    : PermissionInfoBarDelegate(requesting_frame,
                                content::PermissionType::GEOLOCATION,
                                CONTENT_SETTINGS_TYPE_GEOLOCATION,
                                user_gesture,
                                profile,
                                callback) {}

GeolocationInfoBarDelegateAndroid::~GeolocationInfoBarDelegateAndroid() {}

infobars::InfoBarDelegate::InfoBarIdentifier
GeolocationInfoBarDelegateAndroid::GetIdentifier() const {
  return GEOLOCATION_INFOBAR_DELEGATE_ANDROID;
}

int GeolocationInfoBarDelegateAndroid::GetIconId() const {
  return IDR_ANDROID_INFOBAR_GEOLOCATION;
}

int GeolocationInfoBarDelegateAndroid::GetMessageResourceId() const {
  return IDS_GEOLOCATION_INFOBAR_QUESTION;
}


text:
**include_sort** is a Lua-based order-explicit inclusion sorter for pedants.

## License

include_sort carries the MIT license, which can be found in the `LICENSE` file.


text:
#ifndef PCL_STEREO_STEREO_GRABER_H_
#define PCL_STEREO_STEREO_GRABER_H_

#include <pcl/io/grabber.h>
#include <pcl/common/time_trigger.h>
#include <pcl/conversions.h>
#include <pcl/stereo/stereo_matching.h>

namespace pcl
{
  /** \brief Base class for Stereo file grabber.
    * \ingroup io
    */
  class PCL_EXPORTS StereoGrabberBase : public Grabber
  {
    public:
      /** \brief Constructor taking just one Stereo pair.
        * \param[in] pair_files the name of the the stereo (left + right) images.
        * \param[in] frames_per_second frames per second. If 0, start() functions like a trigger, publishing the next pair in the list.
        * \param[in] repeat whether to play files in an endless loop or not.
        */
      StereoGrabberBase (const std::pair<std::string, std::string>& pair_files, float frames_per_second, bool repeat);

      /** \brief Constructor taking a list of paths to Stereo pair files, that are played in the order they appear in the list.
        * \param[in] files vector of paths to stereo (left+right) images.
        * \param[in] frames_per_second frames per second. If 0, start() functions like a trigger, publishing the next pair in the list.
        * \param[in] repeat whether to play files in an endless loop or not.
        */
      StereoGrabberBase (const std::vector<std::pair<std::string, std::string> >& files, float frames_per_second, bool repeat);

      /** \brief Copy constructor.
        * \param[in] src the Stereo Grabber base object to copy into this
        */
      StereoGrabberBase (const StereoGrabberBase &src) : Grabber (), impl_ ()
      {
        *this = src;
      }

      /** \brief Copy operator.
        * \param[in] src the Stereo Grabber base object to copy into this
        */
      StereoGrabberBase&
      operator = (const StereoGrabberBase &src)
      {
        impl_ = src.impl_;
        return (*this);
      }

      /** \brief Virtual destructor. */
      virtual ~StereoGrabberBase () throw ();

      /** \brief Starts playing the list of Stereo images if frames_per_second is > 0. Otherwise it works as a trigger: publishes only the next pair in the list. */
      virtual void
      start ();

      /** \brief Stops playing the list of Stereo images if frames_per_second is > 0. Otherwise the method has no effect. */
      virtual void
      stop ();

      /** \brief Triggers a callback with new data */
      virtual void
      trigger ();

      /** \brief whether the grabber is started (publishing) or not.
        * \return true only if publishing.
        */
      virtual bool
      isRunning () const;

      /** \return The name of the grabber */
      virtual std::string
      getName () const;

      /** \brief Rewinds to the first pair of files in the list.*/
      virtual void
      rewind ();

      /** \brief Returns the frames_per_second. 0 if grabber is trigger-based */
      virtual float
      getFramesPerSecond () const;

      /** \brief Returns whether the repeat flag is on */
      bool
      isRepeatOn () const;

    private:
      virtual void
      publish (const pcl::PCLPointCloud2& blob, const Eigen::Vector4f& origin, const Eigen::Quaternionf& orientation) const = 0;

      // to separate and hide the implementation from interface: PIMPL
      struct StereoGrabberImpl;
      StereoGrabberImpl* impl_;
  };

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  template <typename T> class PointCloud;
  template <typename PointT> class StereoGrabber : public StereoGrabberBase
  {
    public:
      StereoGrabber (const std::pair<std::string, std::string> & pair_files, float frames_per_second = 0, bool repeat = false);
      StereoGrabber (const std::vector<std::pair<std::string, std::string> >& files, float frames_per_second = 0, bool repeat = false);
    protected:
      virtual void
      publish (const pcl::PCLPointCloud2& blob, const Eigen::Vector4f& origin, const Eigen::Quaternionf& orientation) const;

      boost::signals2::signal<void (const boost::shared_ptr<const pcl::PointCloud<PointT> >&)>* signal_;
  };

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  template<typename PointT>
  StereoGrabber<PointT>::StereoGrabber (const std::pair<std::string, std::string>& pair_files, float frames_per_second, bool repeat)
    : StereoGrabberBase (pair_files, frames_per_second, repeat)
  {
    signal_ = createSignal<void (const boost::shared_ptr<const pcl::PointCloud<PointT> >&)>();
  }

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  template<typename PointT>
  StereoGrabber<PointT>::StereoGrabber (const std::vector<std::pair<std::string, std::string> >& files, float frames_per_second, bool repeat)
    : StereoGrabberBase (files, frames_per_second, repeat), signal_ ()
  {
    signal_ = createSignal<void (const boost::shared_ptr<const pcl::PointCloud<PointT> >&)>();
  }

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  template<typename PointT> void
  StereoGrabber<PointT>::publish (const pcl::PCLPointCloud2& blob, const Eigen::Vector4f& origin, const Eigen::Quaternionf& orientation) const
  {
    typename pcl::PointCloud<PointT>::Ptr cloud (new pcl::PointCloud<PointT> ());
    pcl::fromPCLPointCloud2 (blob, *cloud);
    cloud->sensor_origin_ = origin;
    cloud->sensor_orientation_ = orientation;

    signal_->operator () (cloud);
  }
}
#endif