text:
package net.ripe.db.whois.api.freetext;

import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import net.ripe.db.whois.api.AbstractRestClientTest;
import net.ripe.db.whois.api.httpserver.Audience;
import net.ripe.db.whois.common.IntegrationTest;
import net.ripe.db.whois.common.rpsl.RpslObject;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.util.NamedList;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.StringReader;
import java.util.List;
import java.util.Map;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

@Category(IntegrationTest.class)
public class FreeTextSearchTestIntegration extends AbstractRestClientTest {
    private static final Audience AUDIENCE = Audience.PUBLIC;

    @Autowired FreeTextIndex freeTextIndex;

    @Before
    public void setUp() throws Exception {
        freeTextIndex.rebuild();
    }

    @Test
    public void search_no_params() throws Exception {
        try {
            query("");
            fail();
        } catch (UniformInterfaceException e) {
            assertThat(e.getResponse().getStatus(), is(ClientResponse.Status.BAD_REQUEST.getStatusCode()));
            // @TODO http error responses are currently being looked at
            //assertThat(e.getResponse().getEntity(String.class), containsString("No query parameter."));
        }
    }

    @Test
    public void search_empty_query_param() throws Exception {
        try {
            query("q=");
            fail();
        } catch (UniformInterfaceException e) {
            assertThat(e.getResponse().getStatus(), is(ClientResponse.Status.BAD_REQUEST.getStatusCode()));
            // @TODO http error responses are currently being looked at
            //assertThat(e.getResponse().getEntity(String.class), containsString("Invalid query"));
        }
    }

    @Test
    public void search_single_result() throws Exception {
        databaseHelper.addObject(RpslObject.parse("" +
                "mntner: DEV-MNT\n" +
                "source: RIPE"));

        freeTextIndex.update();

        final String searchResult = query("q=DEV-MNT");

        final NamedList<Object> namedList = new XMLResponseParser().processResponse(new StringReader(searchResult));
        final QueryResponse queryResponse = new QueryResponse();
        queryResponse.setResponse(namedList);
        assertThat(queryResponse.getStatus(), is(0));
        assertThat(queryResponse.getResults().getNumFound(), is(1L));

        final SolrDocument solrDocument = queryResponse.getResults().get(0);
        solrDocument.addField("primary-key", "1");
        solrDocument.addField("object-type", "mntner");
        solrDocument.addField("lookup-key", "DEV-MNT");
        solrDocument.addField("mntner", "DEV-MNT");
        assertThat(solrDocument.getFirstValue("primary-key").toString(), is("1"));
        assertThat(solrDocument.getFirstValue("object-type").toString(), is("mntner"));
        assertThat(solrDocument.getFirstValue("lookup-key").toString(), is("DEV-MNT"));
        assertThat(solrDocument.getFirstValue("mntner").toString(), is("DEV-MNT"));
    }

    @Test
    public void search_multiple_results_with_highlighting() throws Exception {
        databaseHelper.addObject(RpslObject.parse("" +
                "mntner: DEV1-MNT\n" +
                "remarks: Some remark\n" +
                "source: RIPE"));

        databaseHelper.addObject(RpslObject.parse("" +
                "mntner: DEV2-MNT\n" +
                "remarks: Second remark\n" +
                "source: RIPE"));

        databaseHelper.addObject(RpslObject.parse("" +
                "mntner: DEV3-MNT\n" +
                "remarks: Other remark\n" +
                "source: RIPE"));

        databaseHelper.addObject(RpslObject.parse("" +
                "mntner: DEV4-MNT\n" +
                "source: RIPE"));

        freeTextIndex.rebuild();

        final String searchResult = query("q=remark&hl=true");

        final NamedList<Object> namedList = new XMLResponseParser().processResponse(new StringReader(searchResult));
        final QueryResponse queryResponse = new QueryResponse();
        queryResponse.setResponse(namedList);
        assertThat(queryResponse.getStatus(), is(0));
        assertThat(queryResponse.getResults().getNumFound(), is(3L));

        final Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
        assertThat(highlighting.keySet(), hasSize(3));
        final Map<String, List<String>> map = highlighting.get("1");
        assertThat(map.keySet(), contains("remarks"));
    }

    @Test
    public void search_multiple_results_with_facet() throws Exception {
        databaseHelper.addObject(RpslObject.parse("" +
                "mntner: DEV1-MNT\n" +
                "remarks: Some remark\n" +
                "source: RIPE"));

        databaseHelper.addObject(RpslObject.parse("" +
                "person: First Last\n" +
                "nic-hdl: AA1-RIPE\n" +
                "remarks: Some remark\n" +
                "source: RIPE"));

        freeTextIndex.rebuild();

        final String searchResult = query("q=remark&facet=true");

        final NamedList<Object> namedList = new XMLResponseParser().processResponse(new StringReader(searchResult));
        final QueryResponse queryResponse = new QueryResponse();
        queryResponse.setResponse(namedList);
        assertThat(queryResponse.getStatus(), is(0));
        assertThat(queryResponse.getResults().getNumFound(), is(2L));

        final List<FacetField> facets = queryResponse.getFacetFields();
        assertThat(facets.size(), is(1));
        final FacetField facet = facets.get(0);
        assertThat(facet.getName(), is("object-type"));
        assertThat(facet.getValueCount(), is(2));
        assertThat(facet.getValues().toString(), containsString("mntner (1)"));
        assertThat(facet.getValues().toString(), containsString("person (1)"));
    }

    @Test
    public void no_exact_match_for_highlighting() {
        databaseHelper.addObject(RpslObject.parse("" +
                "mntner:  AARD-MNT\n" +
                "source: RIPE"));

        databaseHelper.addObject(RpslObject.parse("" +
                "domain:          198.76.217.in-addr.arpa\n" +
                "descr:           T.E.S.T. Ltd\n" +
                "nserver:         ns.foo.ua\n" +
                "nserver:         ns2.foo.ua\n" +
                "changed:         bar@foo.ua 20120911\n" +
                "notify:          bar@foo.ua\n" +
                "source:          RIPE\n" +
                "mnt-by:          AARD-MNT"));

        freeTextIndex.update();

        final String searchResult = query("q=test&hl=true");
        final NamedList<Object> namedList = new XMLResponseParser().processResponse(new StringReader(searchResult));
        final QueryResponse queryResponse = new QueryResponse();
        queryResponse.setResponse(namedList);
        assertThat(queryResponse.getStatus(), is(0));
        assertThat(queryResponse.getResults().getNumFound(), is(1L));

        final Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
        assertThat(highlighting.keySet(), contains("2"));
        final Map<String, List<String>> map = highlighting.get("2");
        assertThat(map.keySet(), contains("descr"));
        assertThat(map.get("descr"), contains("<b>T.E.S.T</b>. Ltd"));
    }

    @Test
    public void search_no_match() throws Exception {
        databaseHelper.addObject(RpslObject.parse("" +
                "mntner: DEV-MNT\n" +
                "source: RIPE"));

        freeTextIndex.update();

        final String searchResult = query("q=10.0.0.0");
        final NamedList<Object> namedList = new XMLResponseParser().processResponse(new StringReader(searchResult));
        final QueryResponse queryResponse = new QueryResponse();
        queryResponse.setResponse(namedList);
        assertThat(queryResponse.getStatus(), is(0));
        assertThat(queryResponse.getResults().getNumFound(), is(0L));
    }

    @Test
    public void search_word_match_subword_case_change() throws Exception {
        databaseHelper.addObject(RpslObject.parse("" +
                "person: John McDonald\n" +
                "nic-hdl: AA1-RIPE\n" +
                "source: RIPE"));

        freeTextIndex.rebuild();

        final String searchResult = query("q=donald");

        final NamedList<Object> namedList = new XMLResponseParser().processResponse(new StringReader(searchResult));
        final QueryResponse queryResponse = new QueryResponse();
        queryResponse.setResponse(namedList);
        assertThat(queryResponse.getStatus(), is(0));
        assertThat(queryResponse.getResults().getNumFound(), is(1L));
    }

    @Test
    public void search_word_match_subword_dash_separator() throws Exception {
        databaseHelper.addObject(RpslObject.parse("" +
                "mntner:  MNT-TESTUA\n" +
                "source: RIPE"));

        freeTextIndex.rebuild();

        final String searchResult = query("q=TESTUA");

        final NamedList<Object> namedList = new XMLResponseParser().processResponse(new StringReader(searchResult));
        final QueryResponse queryResponse = new QueryResponse();
        queryResponse.setResponse(namedList);
        assertThat(queryResponse.getStatus(), is(0));
        assertThat(queryResponse.getResults().getNumFound(), is(1L));
    }

    @Test
    public void search_word_match_original() throws Exception {
        databaseHelper.addObject(RpslObject.parse("" +
                "person: John McDonald1\n" +
                "nic-hdl: AA1-RIPE\n" +
                "source: RIPE"));

        freeTextIndex.rebuild();

        final String searchResult = query("q=mcdonald1");

        final NamedList<Object> namedList = new XMLResponseParser().processResponse(new StringReader(searchResult));
        final QueryResponse queryResponse = new QueryResponse();
        queryResponse.setResponse(namedList);
        assertThat(queryResponse.getStatus(), is(0));
        assertThat(queryResponse.getResults().getNumFound(), is(1L));
    }

    @Test
    public void search_word_with_matching_object_type() throws Exception {
        databaseHelper.addObject(RpslObject.parse("" +
                "person: John McDonald\n" +
                "nic-hdl: AA1-RIPE\n" +
                "source: RIPE"));

        freeTextIndex.rebuild();

        final String searchResult = query("q=mcdonald+AND+object-type%3Aperson");

        final NamedList<Object> namedList = new XMLResponseParser().processResponse(new StringReader(searchResult));
        final QueryResponse queryResponse = new QueryResponse();
        queryResponse.setResponse(namedList);
        assertThat(queryResponse.getStatus(), is(0));
        assertThat(queryResponse.getResults().getNumFound(), is(1L));
    }

    @Test
    public void search_word_with_non_matching_object_type() throws Exception {
        databaseHelper.addObject(RpslObject.parse("" +
                "person: John McDonald\n" +
                "nic-hdl: AA1-RIPE\n" +
                "source: RIPE"));

        freeTextIndex.rebuild();

        final String searchResult = query("q=mcdonald+AND+object-type%3Ainetnum");

        final NamedList<Object> namedList = new XMLResponseParser().processResponse(new StringReader(searchResult));
        final QueryResponse queryResponse = new QueryResponse();
        queryResponse.setResponse(namedList);
        assertThat(queryResponse.getStatus(), is(0));
        assertThat(queryResponse.getResults().getNumFound(), is(0L));
    }

    @Test
    public void search_by_attribute_and_object_type() {
        databaseHelper.addObject(RpslObject.parse("" +
                "person: John McDonald\n" +
                "nic-hdl: AA1-RIPE\n" +
                "source: RIPE"));

        freeTextIndex.rebuild();

        final String searchResult = query("q=(nic-hdl:(AA1-RIPE))+AND+(object-type:person)");

        final NamedList<Object> namedList = new XMLResponseParser().processResponse(new StringReader(searchResult));
        final QueryResponse queryResponse = new QueryResponse();
        queryResponse.setResponse(namedList);
        assertThat(queryResponse.getStatus(), is(0));
        assertThat(queryResponse.getResults().getNumFound(), is(1L));
    }

    @Test
    public void search_hyphenated_complete_word() throws Exception {
        databaseHelper.addObject(RpslObject.parse("" +
                "mntner:  TESTUA-MNT\n" +
                "source: RIPE"));
        databaseHelper.addObject(RpslObject.parse("" +
                "mntner:  NINJA-MNT\n" +
                "source: RIPE"));
        freeTextIndex.rebuild();

        final String searchResult = query("q=NINJA-MNT");

        final NamedList<Object> namedList = new XMLResponseParser().processResponse(new StringReader(searchResult));
        final QueryResponse queryResponse = new QueryResponse();
        queryResponse.setResponse(namedList);
        assertThat(queryResponse.getStatus(), is(0));
        assertThat(queryResponse.getResults().getNumFound(), is(1L));
    }

    @Test
    public void search_hyphenated_partial_word() throws Exception {
        databaseHelper.addObject(RpslObject.parse("" +
                "mntner:  TESTUA-MNT\n" +
                "source: RIPE"));
        databaseHelper.addObject(RpslObject.parse("" +
                "mntner:  NINJA-MNT\n" +
                "source: RIPE"));
        freeTextIndex.rebuild();

        final String searchResult = query("q=NINJA");

        final NamedList<Object> namedList = new XMLResponseParser().processResponse(new StringReader(searchResult));
        final QueryResponse queryResponse = new QueryResponse();
        queryResponse.setResponse(namedList);
        assertThat(queryResponse.getStatus(), is(0));
        assertThat(queryResponse.getResults().getNumFound(), is(1L));
    }

    @Test
    public void search_match_all_terms() throws Exception {
        databaseHelper.addObject(RpslObject.parse("" +
                "person: John McDonald\n" +
                "nic-hdl: JM1-RIPE\n" +
                "source: RIPE"));
        databaseHelper.addObject(RpslObject.parse("" +
                "person: Kate McDonald\n" +
                "nic-hdl: KM1-RIPE\n" +
                "source: RIPE"));

        freeTextIndex.rebuild();

        final String searchResult = query("q=John+McDonald");

        final NamedList<Object> namedList = new XMLResponseParser().processResponse(new StringReader(searchResult));
        final QueryResponse queryResponse = new QueryResponse();
        queryResponse.setResponse(namedList);
        assertThat(queryResponse.getStatus(), is(0));
        assertThat(queryResponse.getResults().getNumFound(), is(1L));
    }

    @Test
    public void search_for_deleted_object() {
        final RpslObject object = RpslObject.parse("" +
                "person: John McDonald\n" +
                "nic-hdl: JM1-RIPE\n" +
                "source: RIPE");
        databaseHelper.addObject(object);
        freeTextIndex.rebuild();

        assertThat(query("q=JM1-RIPE"), containsString("numFound=\"1\""));

        databaseHelper.removeObject(object);
        freeTextIndex.scheduledUpdate();

        assertThat(query("q=JM1-RIPE"), containsString("numFound=\"0\""));
    }

    @Test
    public void search_with_forward_slash() {
        databaseHelper.addObject(RpslObject.parse(
                "inet6num: 2a00:1f78::fffe/48\n" +
                        "netname: RIPE-NCC\n" +
                        "descr: some description\n" +
                        "source: TEST"));
        freeTextIndex.rebuild();

        assertThat(query("q=2a00%5C%3A1f78%5C%3A%5C%3Afffe%2F48"), containsString("numFound=\"1\""));
        assertThat(query("q=212.166.64.0%2F19"), containsString("numFound=\"0\""));
    }

    @Test
    public void nullpointerbug() {
        assertThat(query("q=%28http%5C%3A%2F%2Fvv.uka.ru%29"), containsString("numFound=\"0\""));
    }

    @Test
    public void search_inetnum() throws Exception {
        databaseHelper.addObject(
               "inetnum:        193.0.0.0 - 193.0.0.255\n" +
               "netname:        RIPE-NCC\n" +
               "source:         RIPE");

        freeTextIndex.rebuild();

        assertThat(query("q=193.0.0.0"), containsString("numFound=\"1\""));
        assertThat(query("q=193.0.0.255"), containsString("numFound=\"1\""));
        assertThat(query("q=193%2E0%2E0%2E255"), containsString("numFound=\"1\""));
        assertThat(query("q=%28193%2E0%2E0%2E255%29"), containsString("numFound=\"1\""));
        assertThat(query("q=193"), containsString("numFound=\"1\""));
        assertThat(query("q=193.0"), containsString("numFound=\"1\""));
        assertThat(query("q=193.0.0"), containsString("numFound=\"1\""));
        assertThat(query("q=ripe-ncc"), containsString("numFound=\"1\""));
        assertThat(query("q=ripe"), containsString("numFound=\"1\""));
        assertThat(query("q=ncc"), containsString("numFound=\"1\""));
        assertThat(query("q=ripencc"), containsString("numFound=\"1\""));
    }

    @Test
    public void search_inetnum_with_prefix_length() throws Exception {
        databaseHelper.addObject("" +
                "inetnum:        10.0.0.0/24\n" +
                "netname:        RIPE-NCC\n" +
                "source:         RIPE");
        freeTextIndex.rebuild();

        assertThat(query("q=10.0.0.0/24"), containsString("numFound=\"1\""));
    }

    @Test
    public void search_inetnum_multiple_matches() throws Exception {
        databaseHelper.addObject(
               "inetnum:        193.0.0.0 - 193.0.0.255\n" +
               "netname:        RIPE-NCC\n" +
               "source:         RIPE");
        databaseHelper.addObject(
                "inetnum:        193.1.0.0 - 193.1.0.255\n" +
                        "netname:        RIPE-NCC\n" +
                        "source:         RIPE");

        freeTextIndex.rebuild();

        assertThat(query("q=193.0.0.0"), containsString("numFound=\"1\""));
        assertThat(query("q=193.1.0.0"), containsString("numFound=\"1\""));
        assertThat(query("q=193"), containsString("numFound=\"2\""));
    }

    @Test
    public void search_inet6num() throws Exception {
        databaseHelper.addObject(
                "inet6num: 2001:0638:0501::/48\n" +
                "netname: RIPE-NCC\n" +
                "source: RIPE\n");

        freeTextIndex.rebuild();

        assertThat(query("q=%282001%29"), containsString("numFound=\"1\""));
        assertThat(query("q=%282001%5C%3A0638%29"), containsString("numFound=\"1\""));
        assertThat(query("q=%282001%5C%3A0638%5C%3A0501%29"), containsString("numFound=\"1\""));
        assertThat(query("q=%282001%5C%3A0638%5C%3A0501%5C%3A%5C%3A%2F48%29"), containsString("numFound=\"1\""));
        assertThat(query("q=2001"), containsString("numFound=\"1\""));
        assertThat(query("q=2001%5C%3A0638"), containsString("numFound=\"1\""));
        assertThat(query("q=2001%5C%3A0638%5C%3A0501"), containsString("numFound=\"1\""));
        assertThat(query("q=2001%5C%3A0638%5C%3A0501%5C%3A%5C%3A%2F48"), containsString("numFound=\"1\""));
    }

    @Test
    public void search_inet6num_double_colons() throws Exception {
        databaseHelper.addObject(
                "inet6num: 2a00:1f78::fffe/48\n" +
                "netname: RIPE-NCC\n" +
                "source: RIPE\n");

        freeTextIndex.rebuild();

        assertThat(query("q=2a00"), containsString("numFound=\"1\""));
        assertThat(query("q=2a00%5C%3A1f78"), containsString("numFound=\"1\""));       // need to escape single colon (used as separator by lucene)
        assertThat(query("q=2a00%5C%3A1f78%5C%3A%5C%3Afffe%2F48"), containsString("numFound=\"1\""));

    }

    @Test
    public void search_inet6num_multiple_matches() throws Exception {
        databaseHelper.addObject(
                "inet6num: 2a00:1f78:7a2b:2001::/64\n" +
                "netname: RIPE-NCC\n" +
                "source: RIPE\n");
        databaseHelper.addObject(
                "inet6num: 2a00:1f11:7777:2a98::/64\n" +
                        "netname: RIPE-NCC\n" +
                        "source: RIPE\n");

        freeTextIndex.rebuild();

        assertThat(query("q=2a00"), containsString("numFound=\"2\""));
    }

    @Test
    public void search_filter_comma_when_indexing() throws Exception {
        databaseHelper.addObject(RpslObject.parse(
                "mntner: OWNER-MNT\n" +
                "source: RIPE"));
        databaseHelper.addObject(RpslObject.parse(
                "organisation: ORG-TOS1-TEST\n" +
                "org-name:     Company, Ltd\n" +
                "org-type:     OTHER\n" +
                "descr:        test org\n" +
                "address:      street 1\n" +
                "e-mail:       org1@test.com\n" +
                "mnt-ref:      OWNER-MNT\n" +
                "mnt-by:       OWNER-MNT\n" +
                "changed:      dbtest@ripe.net 20120505\n" +
                "source:       RIPE\n"));
        freeTextIndex.rebuild();

        assertThat(query("q=Company"), containsString("numFound=\"1\""));
    }

    @Test
    public void search_filter_comma_on_query_term() throws Exception {
        databaseHelper.addObject(RpslObject.parse(
                "mntner: OWNER-MNT\n" +
                "source: RIPE"));
        databaseHelper.addObject(RpslObject.parse(
                "organisation: ORG-TOS1-TEST\n" +
                "org-name:     Company Ltd\n" +
                "org-type:     OTHER\n" +
                "descr:        test org\n" +
                "address:      street 1\n" +
                "e-mail:       org1@test.com\n" +
                "mnt-ref:      OWNER-MNT\n" +
                "mnt-by:       OWNER-MNT\n" +
                "changed:      dbtest@ripe.net 20120505\n" +
                "source:       RIPE\n"));
        freeTextIndex.rebuild();

        assertThat(query("q=company,"), containsString("numFound=\"1\""));
    }

    @Test
    public void search_filter_quotes_when_indexing() {
        databaseHelper.addObject(RpslObject.parse(
                "mntner: OWNER-MNT\n" +
                "source: RIPE"));
        databaseHelper.addObject(RpslObject.parse(
                "organisation: ORG-TOS1-TEST\n" +
                "org-name:     \"Company\" Ltd\n" +
                "org-type:     OTHER\n" +
                "descr:        test org\n" +
                "address:      street 1\n" +
                "e-mail:       org1@test.com\n" +
                "mnt-ref:      OWNER-MNT\n" +
                "mnt-by:       OWNER-MNT\n" +
                "changed:      dbtest@ripe.net 20120505\n" +
                "source:       RIPE\n"));
        freeTextIndex.rebuild();

        assertThat(query("q=company"), containsString("numFound=\"1\""));
    }

    @Test
    public void search_multiple_matches_but_only_one_result() throws Exception {
        databaseHelper.addObject(RpslObject.parse(
                "mntner: OWNER-MNT\n" +
                "source: RIPE"));
        databaseHelper.addObject(RpslObject.parse(
                "organisation: ORG-TOS1-TEST\n" +
                "org-name:     ORG-TOS1-TEST\n" +
                "org-type:     OTHER\n" +
                "descr:        ORG-TOS1-TEST\n" +
                "address:      street 1\n" +
                "e-mail:       org1@test.com\n" +
                "mnt-ref:      OWNER-MNT\n" +
                "mnt-by:       OWNER-MNT\n" +
                "changed:      dbtest@ripe.net 20120505\n" +
                "source:       RIPE\n"));
        freeTextIndex.rebuild();

        assertThat(query("q=ORG-TOS1-TEST"), containsString("numFound=\"1\""));
    }

    @Test
    public void search_match_partial_email_address() throws Exception {
        databaseHelper.addObject(RpslObject.parse(
                "mntner: OWNER-MNT\n" +
                "source: RIPE"));
        databaseHelper.addObject(RpslObject.parse(
                "organisation: ORG-TOS1-TEST\n" +
                "org-name:     ORG-TOS1-TEST\n" +
                "org-type:     OTHER\n" +
                "descr:        ORG-TOS1-TEST\n" +
                "address:      street 1\n" +
                "e-mail:       org1@test.com\n" +
                "mnt-ref:      OWNER-MNT\n" +
                "mnt-by:       OWNER-MNT\n" +
                "changed:      dbtest@ripe.net 20120505\n" +
                "source:       RIPE\n"));
        freeTextIndex.rebuild();

        assertThat(query("q=test.com"), containsString("numFound=\"1\""));
    }

    private String query(final String queryString) {
        return client
                .resource(String.format("http://localhost:%s/search?%s", getPort(AUDIENCE), queryString))
                .get(String.class);
    }
}


text:
Extraterm Extension API
=======================

This module holds the TypeScript definitions of the Extraterm extension API and is published as a packge up on npmjs.com.

https://github.com/sedwards2009/extraterm

Publishing API package
----------------------

When this API changes it needs to be published.

Steps:
* Bump the package version inside `package.json`.
* Commit that change.
* Run `yarn publish` to publish and have the password for npmjs ready.
* Done.

Publishing API reference docs
-----------------------------

Do this on `master` branch.

* In this folder run `yarn run build-docs`
* Commit the changes in <root>/docs/extension_api/* also keep an eye open for new files.

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Gets a list of country codes
 *
 * @package modx
 * @subpackage processors.system.country
 */
class modCountryGetListProcessor extends modProcessor {
    public function checkPermissions() {
        return $this->modx->hasPermission('countries');
    }

    public function process() {
        $countryList = $this->getCountryList();
        if (empty($countryList)) return $this->failure();

        $countries = array();
        foreach ($countryList as $country) {
            $countries[] = array(
                'value' => $country,
            );
        }

        return $this->outputArray($countries);
    }

    public function getCountryList() {
        $_country_lang = array();
        include $this->modx->getOption('core_path').'lexicon/country/en.inc.php';
        if ($this->modx->getOption('manager_language') != 'en' && file_exists($this->modx->getOption('core_path').'lexicon/country/'.$this->modx->getOption('manager_language').'.inc.php')) {
            include_once $this->modx->getOption('core_path').'lexicon/country/'.$this->modx->getOption('manager_language').'.inc.php';
        }
        asort($_country_lang);
        return $_country_lang;
    }
}
return 'modCountryGetListProcessor';


text:
<?php

namespace Symfony\Bridge\PsrHttpMessage;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Creates Symfony Request and Response instances from PSR-7 ones.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
interface HttpFoundationFactoryInterface
{
    /**
     * Creates a Symfony Request instance from a PSR-7 one.
     *
     * @return Request
     */
    public function createRequest(ServerRequestInterface $psrRequest, bool $streamed = false);

    /**
     * Creates a Symfony Response instance from a PSR-7 one.
     *
     * @return Response
     */
    public function createResponse(ResponseInterface $psrResponse, bool $streamed = false);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MixedPhones
{
    class MixedPhones
    {
        static void Main()
        {
            var phoneBook = new SortedDictionary<string, long>();
            string text = Console.ReadLine();
            while (text != "Over")
            {
                string[] tokens = text.Split(new[] { " : " }, StringSplitOptions.RemoveEmptyEntries);
                var first = tokens[0];
                var second = tokens[1];
                long number = 0;

                if (long.TryParse(first, out number))
                {
                    var key = second;
                    var value = number;
                    phoneBook[key] = number;
                }
                else
                {
                    var key = first;
                    var value = long.Parse(second);
                    phoneBook[first] = value;
                }

                text = Console.ReadLine();
            }

            foreach (var phone in phoneBook)
            {
                Console.WriteLine("{0} -> {1}", phone.Key, phone.Value);
            }
        }
    }
}


text:
@interface CDASpace ()

@property (nonatomic) NSString* name;

@end

#pragma mark -

@implementation CDASpace

+(NSString *)CDAType {
    return @"Space";
}

#pragma mark -

-(id)initWithDictionary:(NSDictionary *)dictionary client:(CDAClient*)client {
    self = [super initWithDictionary:dictionary client:client];
    if (self) {
        self.defaultLocale = @"en-US";
        self.locales = dictionary[@"locales"];
        self.name = dictionary[@"name"];

        for (NSDictionary* locale in self.locales) {
            if ([locale[@"default"] boolValue] && locale[@"code"]) {
                NSString* code = locale[@"code"];
                self.defaultLocale = code;
            }
        }
    }
    return self;
}

-(NSArray *)localeCodes {
    return [self.locales valueForKey:@"code"] ?: @[ self.defaultLocale ];
}

@end


text:
/**
 */

package petstore.implementation;

import petstore.StorageAccountProperties;
import com.microsoft.azure.Resource;

/**
 * The storage account.
 */
public class StorageAccountInner extends Resource {
    /**
     * The properties property.
     */
    private StorageAccountProperties properties;

    /**
     * Get the properties value.
     *
     * @return the properties value
     */
    public StorageAccountProperties properties() {
        return this.properties;
    }

    /**
     * Set the properties value.
     *
     * @param properties the properties value to set
     * @return the StorageAccountInner object itself.
     */
    public StorageAccountInner withProperties(StorageAccountProperties properties) {
        this.properties = properties;
        return this;
    }

}


text:
class Admin::Teams::ApplicationController < Admin::ApplicationController

  private

  def user_team
    @team = UserTeam.find_by_path(params[:team_id])
  end
end


text:
<?php

namespace AppBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use AppBundle\Entity\Movie;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;

class LoadMovieData extends AbstractFixture implements OrderedFixtureInterface
{
    public function load(ObjectManager $manager)
    {
        $m1 = new Movie();
        $m1
            ->setName("Interstellar")
            ->setCover('interstellar.jpg')
            ->setDescription("Byt ludzkości na Ziemi dobiega końca wskutek zmian klimatycznych. Grupa naukowców odkrywa tunel czasoprzestrzenny, który umożliwia poszukiwanie nowego domu.")
            ->setActores("Matthew McConaughey	jako:	Cooper
Anne Hathaway	jako:	Brand")
            ->setPrice(15.99)
            ->addCategory($this->getReference('category-sci-fi'));

        $manager->persist($m1);

        $m2 = new Movie();
        $m2
            ->setName("Jak wytresować smoka")
            ->setCover('smok.jpg')
            ->setDescription("Chuderlawy Wiking przewróci porządek w wiosce, kiedy zamiast zabić w ramach inicjacji jakiegoś smoka, zaprzyjaźni się z najgroźniejszym z nich.")
            ->setActores("Dubbing:
Mateusz Damięcki	jako:	Czkawka
Julia Kamińska	jako:	Astrid")
            ->setPrice(19.00)
            ->addCategory($this->getReference('category-animacja'))
            ->addCategory($this->getReference('category-przygodowy'))
            ->addCategory($this->getReference('category-fantasy'));

        $manager->persist($m2);

        $manager->flush();

        $m3 = new Movie();
        $m3
            ->setName("Jak wytresować smoka 2")
            ->setCover('smok2.jpg')
            ->setDescription("Pięć lat po zjednoczeniu rasy smoków oraz ludzi Czkawka i Szczerbatek stają do obrony wyspy Berk przed niebezpiecznymi dzikimi bestiami, a także tajemniczym Smoczym Jeźdźcem.")
            ->setActores("Dubbing:
Mateusz Damięcki	jako:	Czkawka
Julia Kamińska	jako:	Astrid")
            ->setPrice(19.00)
            ->addCategory($this->getReference('category-animacja'))
            ->addCategory($this->getReference('category-przygodowy'))
            ->addCategory($this->getReference('category-fantasy'));

        $manager->persist($m3);

        $manager->flush();
    }

    public function getOrder()
    {
        return 3;
    }
}


text:
Imports System.Runtime.InteropServices

Public Class Form1

    Private Sub OnGetWhereUsedForAutomationUsingKeyProperties_Click(sender As Object, e As EventArgs) Handles OnGetWhereUsedForAutomationUsingKeyProperties.Click
        Dim objSEApplication As SolidEdgeFramework.Application = Nothing
        Dim objTCE As SolidEdgeFramework.SolidEdgeTCE = Nothing
        Dim majorVersion As Object = Nothing
        Dim completeVersion As Object = Nothing
        Dim UserName As String
        Dim Password As String
        Dim Group As String
        Dim Role As String
        Dim URL As String
        Dim bTeamCenterMode As Boolean

        Dim MFKAttributes(2, 1) As Object
        MFKAttributes(0, 0) = "item_id"
        MFKAttributes(0, 1) = "001411"
        MFKAttributes(1, 0) = "object_type"
        MFKAttributes(1, 1) = "MFK9Item12"
        MFKAttributes(2, 0) = "mfk9attribute1"
        MFKAttributes(2, 1) = "hhhh"

        Dim FileItemRevID As String = "B"
        Dim ItemTypeMFK As Object
        ItemTypeMFK = "MFK9Item12"
        Dim FileDataSetName As String = "001411-BE144.asm"
        Dim Listoffiles As Object = Nothing

        Try
            objSEApplication = Marshal.GetActiveObject("SolidEdge.Application")
            objSEApplication.DisplayAlerts = False

            objTCE = objSEApplication.SolidEdgeTCE
            Call objTCE.GetTeamCenterMode(bTeamCenterMode)
            If bTeamCenterMode = False Then
                objTCE.SetTeamCenterMode(True)
            End If

            'Specify Server Credentials
            UserName = "abc"
            Password = "abc"
            Group = ""
            Role = ""
            URL = "http://Servername:8085/tc"

            Call objTCE.ValidateLogin(UserName, Password, Group, Role, URL)
            objTCE.OnGetWhereUsedForAutomationUsingKeyProperties(MFKAttributes, FileItemRevID, ItemTypeMFK, FileDataSetName, Listoffiles)

        Catch ex As Exception
            MsgBox(ex.ToString)
            Clipboard.SetText(ex.ToString)
        End Try
    End Sub
End Class


text:
module TimeCard
  class Developer
    attr_accessor :name

    def initialize(name, schedule = nil)
      default_schedule = {
          1 => OpenStruct.new(start_time: '08:00', end_time: '19:30'),
          2 => OpenStruct.new(start_time: '08:00', end_time: '19:30'),
          3 => OpenStruct.new(start_time: '08:00', end_time: '19:30'),
          4 => OpenStruct.new(start_time: '08:00', end_time: '19:30'),
          5 => OpenStruct.new(start_time: '08:00', end_time: '19:30')
      }
      @schedule = schedule || default_schedule
      @name = name
    end

    def work_days(start_date, end_date)
      days_worked = []
      (start_date..end_date).each do |day|
        workday = schedule_on_day(day)
        days_worked.push workday unless workday.nil?
      end
      days_worked
    end

    def schedule_on_day(day)
      if @schedule[day.wday]
        schedule_start_time = Time.parse("#{day.to_date} #{@schedule[day.wday].start_time}")
        schedule_end_time = Time.parse("#{day.to_date} #{@schedule[day.wday].end_time}")
        OpenStruct.new(start_time: schedule_start_time, end_time: schedule_end_time)
      end
    end

    def min_worked_during_segment(workday, start_time, end_time = nil)
      end_time ||= workday.end_time
      time_worked = 0
      unless start_time > workday.end_time || end_time < workday.start_time || start_time > end_time
        start_work = [workday.start_time, start_time].max
        end_work = [workday.end_time, end_time].min
        time_worked = end_work - start_work
      end
      (time_worked/60.0).to_i
    end
  end
end


text:
class LocationManager
{
	@STAMP(flows={@Flow(from="$LOCATION",to="@return")})
	private Location getLocation()
	{
		return new Location((String) null);
	}

	private void registerListener(final android.location.LocationListener listener)
	{
		edu.stanford.stamp.harness.ApplicationDriver.getInstance().
			registerCallback(new edu.stanford.stamp.harness.Callback(){
					public void run() {
						listener.onLocationChanged(getLocation());
					}
				});
	}

	@STAMP(flows={@Flow(from="$FINE_LOCATION",to="!INTENT")})
        public  void requestLocationUpdates(java.lang.String provider, long minTime, float minDistance, android.app.PendingIntent intent) {

	}

	public  void requestLocationUpdates(java.lang.String provider, long minTime, float minDistance, android.location.LocationListener listener)
	{
		registerListener(listener);
	}

	public  void requestLocationUpdates(java.lang.String provider, long minTime, float minDistance, android.location.LocationListener listener, android.os.Looper looper)
	{
		registerListener(listener);
	}

	public  void requestLocationUpdates(long minTime, float minDistance, android.location.Criteria criteria, android.location.LocationListener listener, android.os.Looper looper)
	{
		registerListener(listener);
	}

        @STAMP(flows={@Flow(from="$FINE_LOCATION",to="!INTENT")})
        public  void requestLocationUpdates(long minTime, float minDistance, android.location.Criteria criteria, android.app.PendingIntent intent) {
	}

	public  void requestSingleUpdate(java.lang.String provider, android.location.LocationListener listener, android.os.Looper looper)
	{
		registerListener(listener);
	}

	public  void requestSingleUpdate(android.location.Criteria criteria, android.location.LocationListener listener, android.os.Looper looper)
	{
		registerListener(listener);
	}

	@STAMP(flows={@Flow(from="$FINE_LOCATION",to="!INTENT")})
	public  void requestSingleUpdate(java.lang.String provider, android.app.PendingIntent intent) {
	}

	@STAMP(flows={@Flow(from="$FINE_LOCATION",to="!INTENT")})
	public  void requestSingleUpdate(android.location.Criteria criteria, android.app.PendingIntent intent) {
	}

	public  android.location.Location getLastKnownLocation(java.lang.String provider)
	{
		return getLocation();
	}

	private static LocationManager locationManager = new LocationManager();
	public static LocationManager getInstance()
	{
		return locationManager;
	}

        @STAMP(flows={@Flow(from="$FINE_LOCATION",to="!INTENT")})
        public  void addProximityAlert(double latitude, double longitude, float radius, long expiration, android.app.PendingIntent intent) {
	}

	@STAMP(flows={@Flow(from="$FINE_LOCATION.nmea",to="@return")})
	private String getNmea()
	{
		return new String();
	}

        public  boolean addNmeaListener(final android.location.GpsStatus.NmeaListener listener) {
		edu.stanford.stamp.harness.ApplicationDriver.getInstance().
			registerCallback(new edu.stanford.stamp.harness.Callback(){
					public void run() {
					    listener.onNmeaReceived(0,getNmea());
					}
				});
		return true;
	}

}


text:
package org.hamcrest.text.pattern.internal.naming;

import java.util.HashMap;
import java.util.Map;

public class GroupNamespace {
    private final GroupNamespace parent;
    private final Map<String, GroupNamespace> bindings = new HashMap<String, GroupNamespace>();
    private final IndexSequence nextGroupIndex;
    private final int groupIndex;

    private GroupNamespace(GroupNamespace parent, IndexSequence nextGroupIndex) {
        this.parent = parent;
        this.nextGroupIndex = nextGroupIndex;
        this.groupIndex = nextGroupIndex.next();
    }

    public GroupNamespace() {
        this(null, new IndexSequence());
    }

    public int toIndex() {
        return groupIndex;
    }

    public GroupNamespace create(String name) {
        if (bindings.containsKey(name)) {
            throw new IllegalArgumentException("duplicate name '" + name + "'");
        }

        GroupNamespace child = new GroupNamespace(this, nextGroupIndex);
        bindings.put(name, child);
        return child;
    }

    public int resolve(String pathAsString) {
        return resolve(Path.parse(pathAsString));
    }

    public int resolve(Path path) {
        return environmentContaining(path.head()).resolveInternally(path.tail());
    }

    public int resolveInternally(Path path) {
        if (path.size() == 0) {
            return groupIndex;
        } else if (bindings.containsKey(path.head())) {
            return bindings.get(path.head()).resolveInternally(path.tail());
        } else {
            throw new IllegalArgumentException("name '" + path.head() + "' not bound");
        }
    }

    private GroupNamespace environmentContaining(String name) {
        if (bindings.containsKey(name)) {
            return bindings.get(name);
        } else if (parent != null) {
            return parent.environmentContaining(name);
        } else {
            throw new IllegalArgumentException("name '" + name + "' not bound");
        }
    }
}


text:
using UnityEngine;
using UnityEditor;
using UNEB;

public class OutputTexture2D : Node
{
    private Texture2D texPreview;

    NodeInput inputNoise;

    private int _texRes = 100;
    public int Resolution
    {
        get { return _texRes; }
        set { _texRes = Mathf.Clamp(value, 10, 300); }
    }

    public override void Init()
    {
        inputNoise = AddInput();
        inputNoise.name = "Input Noise";

        texPreview = new Texture2D(200, 200);

        FitKnobs();
        bodyRect.height += 245;
        bodyRect.width = 210f;
    }

    public override void OnBodyGUI()
    {
        EditorGUI.BeginChangeCheck();
        Resolution = EditorGUILayout.IntField("Resolution", Resolution);

        GUILayout.Box(texPreview, GUILayout.Width(texPreview.width), GUILayout.Height(texPreview.height));

        if (GUILayout.Button("Update")) {
            UpdateTexture();
        }

        if (EditorGUI.EndChangeCheck()) {
            UpdateTexture();
        }
    }

    public void UpdateTexture()
    {
        if (!inputNoise.HasOutputConnected()) {
            return;
        }

        var noise = inputNoise.Outputs[0].GetValue<LibNoise.Generator.Perlin>();

        for (int x = 0; x < texPreview.width; ++x) {
            for (int y = 0; y < texPreview.height; ++y) {

                var point = new Vector3(x, y, 0f) / _texRes;
                float value = (float)noise.GetValue(point);

                value = Mathf.Clamp01((value + 1) / 2f);
                Color color = Color.HSVToRGB(value, 1f, 1f);

                texPreview.SetPixel(x, y, color);
            }
        }

        texPreview.Apply();
    }
}


text:
package aci

import (
	"bytes"
	"fmt"
	"strconv"
)

func rnBridgeDomain(bd string) string {
	return "BD-" + bd
}

func dnBridgeDomain(tenant, bd string) string {
	return rnTenant(tenant) + "/" + rnBridgeDomain(bd)
}

func rnSubnet(subnet string) string {
	return "subnet-[" + subnet + "]"
}

func dnSubnet(tenant, bd, subnet string) string {
	return dnBridgeDomain(tenant, bd) + "/" + rnSubnet(subnet)
}

// BridgeDomainAdd creates a new bridge domain in a tenant.
func (c *Client) BridgeDomainAdd(tenant, bd, descr string) error {

	me := "BridgeDomainAdd"

	rn := rnBridgeDomain(bd)

	dn := dnBridgeDomain(tenant, bd)

	api := "/api/node/mo/uni/" + dn + ".json"

	url := c.getURL(api)

	j := fmt.Sprintf(`{"fvBD":{"attributes":{"dn":"uni/%s","name":"%s","descr":"%s","rn":"%s","status":"created"}}}`,
		dn, bd, descr, rn)

	c.debugf("%s: url=%s json=%s", me, url, j)

	body, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))
	if errPost != nil {
		return fmt.Errorf("%s: %v", me, errPost)
	}

	c.debugf("%s: reply: %s", me, string(body))

	return parseJSONError(body)
}

// BridgeDomainDel deletes an existing bridge domain from a tenant.
func (c *Client) BridgeDomainDel(tenant, bd string) error {

	me := "BridgeDomainDel"

	rnT := rnTenant(tenant)

	dn := dnBridgeDomain(tenant, bd)

	api := "/api/node/mo/uni/" + rnT + ".json"

	url := c.getURL(api)

	j := fmt.Sprintf(`{"fvTenant":{"attributes":{"dn":"uni/%s","status":"modified"},"children":[{"fvBD":{"attributes":{"dn":"uni/%s","status":"deleted"}}}]}}`,
		rnT, dn)

	c.debugf("%s: url=%s json=%s", me, url, j)

	body, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))
	if errPost != nil {
		return fmt.Errorf("%s: %v", me, errPost)
	}

	c.debugf("%s: reply: %s", me, string(body))

	return parseJSONError(body)
}

// BridgeDomainList retrieves the list of bridge domains from a tenant.
func (c *Client) BridgeDomainList(tenant string) ([]map[string]interface{}, error) {

	me := "BridgeDomainList"

	key := "fvBD"

	t := rnTenant(tenant)

	api := "/api/node/mo/uni/" + t + ".json?query-target=children&target-subtree-class=" + key

	url := c.getURL(api)

	c.debugf("%s: url=%s", me, url)

	body, errGet := c.get(url)
	if errGet != nil {
		return nil, fmt.Errorf("%s: %v", me, errGet)
	}

	c.debugf("%s: reply: %s", me, string(body))

	return jsonImdataAttributes(c, body, key, me)
}

// BridgeDomainVrfSet defines the VRF for a bridge domain.
func (c *Client) BridgeDomainVrfSet(tenant, bd, vrf string) error {

	me := "BridgeDomainVrfSet"

	dn := dnBridgeDomain(tenant, bd)

	api := "/api/node/mo/uni/" + dn + "/rsctx.json"

	url := c.getURL(api)

	j := fmt.Sprintf(`{"fvRsCtx":{"attributes":{"tnFvCtxName":"%s"}}}`,
		vrf)

	c.debugf("%s: url=%s json=%s", me, url, j)

	body, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))
	if errPost != nil {
		return fmt.Errorf("%s: %v", me, errPost)
	}

	c.debugf("%s: reply: %s", me, string(body))

	return parseJSONError(body)
}

// BridgeDomainVrfGet retrieves the VRF for a bridge domain.
func (c *Client) BridgeDomainVrfGet(tenant, bd string) (string, error) {

	me := "BridgeDomainVrfGet"

	key := "fvRsCtx"

	dn := dnBridgeDomain(tenant, bd)

	api := "/api/node/mo/uni/" + dn + ".json?query-target=children&target-subtree-class=" + key

	url := c.getURL(api)

	c.debugf("%s: url=%s", me, url)

	body, errGet := c.get(url)
	if errGet != nil {
		return "", fmt.Errorf("%s: %v", me, errGet)
	}

	c.debugf("%s: reply: %s", me, string(body))

	attrs, errAttr := jsonImdataAttributes(c, body, key, me)
	if errAttr != nil {
		return "", fmt.Errorf("%s: %v", me, errAttr)
	}

	if len(attrs) < 1 {
		return "", fmt.Errorf("%s: empty list of VRFs", me)
	}

	attr := attrs[0]
	v, found := attr["tnFvCtxName"]
	if !found {
		return "", fmt.Errorf("%s: VRF not found", me)
	}

	vrf, isStr := v.(string)
	if !isStr {
		return "", fmt.Errorf("%s: VRF is not a string", me)
	}

	if vrf == "" {
		return "", fmt.Errorf("%s: empty VRF name", me)
	}

	return vrf, nil
}

// BridgeDomainSubnetAdd creates a new subnet in a bridge domain.
func (c *Client) BridgeDomainSubnetAdd(tenant, bd, subnet, descr string) error {

	me := "BridgeDomainSubnetAdd"

	rnSN := rnSubnet(subnet)

	dnSN := dnSubnet(tenant, bd, subnet)

	api := "/api/node/mo/uni/" + dnSN + ".json"

	url := c.getURL(api)

	j := fmt.Sprintf(`{"fvSubnet":{"attributes":{"dn":"uni/%s","ip":"%s","descr":"%s","rn":"%s","status":"created"}}}`,
		dnSN, subnet, descr, rnSN)

	c.debugf("%s: url=%s json=%s", me, url, j)

	body, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))
	if errPost != nil {
		return fmt.Errorf("%s: %v", me, errPost)
	}

	c.debugf("%s: reply: %s", me, string(body))

	return parseJSONError(body)
}

// BridgeDomainSubnetDel deletes an existing subnet from a bridge domain.
func (c *Client) BridgeDomainSubnetDel(tenant, bd, subnet string) error {

	me := "BridgeDomainSubnetDel"

	dnBD := dnBridgeDomain(tenant, bd)

	dnSN := dnSubnet(tenant, bd, subnet)

	api := "/api/node/mo/uni/" + dnBD + ".json"

	url := c.getURL(api)

	j := fmt.Sprintf(`{"fvBD":{"attributes":{"dn":"uni/%s","status":"modified"},"children":[{"fvSubnet":{"attributes":{"dn":"uni/%s","status":"deleted"}}}]}}`,
		dnBD, dnSN)

	c.debugf("%s: url=%s json=%s", me, url, j)

	body, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))
	if errPost != nil {
		return fmt.Errorf("%s: %v", me, errPost)
	}

	c.debugf("%s: reply: %s", me, string(body))

	return parseJSONError(body)
}

// BridgeDomainSubnetList retrieves the list of subnets from a bridge domain.
func (c *Client) BridgeDomainSubnetList(tenant, bd string) ([]map[string]interface{}, error) {

	me := "BridgeDomainSubnetList"

	key := "fvSubnet"

	dnBD := dnBridgeDomain(tenant, bd)

	api := "/api/node/mo/uni/" + dnBD + ".json?query-target=children&target-subtree-class=" + key

	url := c.getURL(api)

	c.debugf("%s: url=%s", me, url)

	body, errGet := c.get(url)
	if errGet != nil {
		return nil, fmt.Errorf("%s: %v", me, errGet)
	}

	c.debugf("%s: reply: %s", me, string(body))

	return jsonImdataAttributes(c, body, key, me)
}

// BridgeDomainSubnetGet retrieves specific subnet from a bridge domain.
func (c *Client) BridgeDomainSubnetGet(tenant, bd, subnet string) ([]map[string]interface{}, error) {

	me := "BridgeDomainSubnetGet"

	key := "fvSubnet"

	dnSN := dnSubnet(tenant, bd, subnet)

	api := "/api/node/mo/uni/" + dnSN + ".json"

	url := c.getURL(api)

	c.debugf("%s: url=%s", me, url)

	body, errGet := c.get(url)
	if errGet != nil {
		return nil, fmt.Errorf("%s: %v", me, errGet)
	}

	c.debugf("%s: reply: %s", me, string(body))

	return jsonImdataAttributes(c, body, key, me)
}

// BridgeDomainSubnetScopeSet defines the scope for a bridge domain subnet.
func (c *Client) BridgeDomainSubnetScopeSet(tenant, bd, subnet, scope string) error {

	me := "BridgeDomainSubnetScopeSet"

	dnSN := dnSubnet(tenant, bd, subnet)

	api := "/api/node/mo/uni/" + dnSN + ".json"

	url := c.getURL(api)

	j := fmt.Sprintf(`{"fvSubnet":{"attributes":{"dn":"uni/%s","scope":"%s"}}}`,
		dnSN, scope)

	c.debugf("%s: url=%s json=%s", me, url, j)

	body, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))
	if errPost != nil {
		return fmt.Errorf("%s: %v", me, errPost)
	}

	c.debugf("%s: reply: %s", me, string(body))

	return parseJSONError(body)
}

// BridgeDomainSubnetScopeGet retrieves the scope from a bridge domain subnet.
func (c *Client) BridgeDomainSubnetScopeGet(tenant, bd, subnet string) (string, error) {

	me := "BridgeDomainSubnetScopeGet"

	list, errSubnet := c.BridgeDomainSubnetGet(tenant, bd, subnet)
	if errSubnet != nil {
		return "", fmt.Errorf("%s: %v", me, errSubnet)
	}

	if len(list) < 1 {
		return "", fmt.Errorf("%s: empty list of subnets", me)
	}

	attrs := list[0]
	s, found := attrs["scope"]
	if !found {
		return "", fmt.Errorf("%s: scope not found", me)
	}

	scope, isStr := s.(string)
	if !isStr {
		return "", fmt.Errorf("%s: scope is not a string", me)
	}

	return scope, nil
}

// BridgeDomainSetUnicastRouting sets or clears the "Enable unicast routing" flag
func (c *Client) BridgeDomainSetUnicastRouting(tenant, bd string, enabled bool) error {
	me := "BdSetUnicastRouting"
	dn := dnBridgeDomain(tenant, bd)
	api := "/api/node/mo/uni/" + dn + ".json"
	j := fmt.Sprintf(`{"fvBD":{"attributes":{"dn":"uni/%s", "unicastRoute":"%s"}}}`, dn, strconv.FormatBool(enabled))
	url := c.getURL(api)
	c.debugf("%s: url=%s json=%s", me, url, j)
	body, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))
	if errPost != nil {
		return fmt.Errorf("%s: %v", me, errPost)
	}

	c.debugf("%s: reply: %s", me, string(body))

	return parseJSONError(body)
}


text:
namespace muduo
{

///
/// Time stamp in UTC, in microseconds resolution.
///
/// This class is immutable.
/// It's recommended to pass it by value, since it's passed in register on x64.
///
class Timestamp : public muduo::copyable,
                  public boost::equality_comparable<Timestamp>,
                  public boost::less_than_comparable<Timestamp>
{
 public:
  ///
  /// Constucts an invalid Timestamp.
  ///
  Timestamp()
    : microSecondsSinceEpoch_(0)
  {
  }

  ///
  /// Constucts a Timestamp at specific time
  ///
  /// @param microSecondsSinceEpoch
  explicit Timestamp(int64_t microSecondsSinceEpochArg)
    : microSecondsSinceEpoch_(microSecondsSinceEpochArg)
  {
  }

  void swap(Timestamp& that)
  {
    std::swap(microSecondsSinceEpoch_, that.microSecondsSinceEpoch_);
  }

  // default copy/assignment/dtor are Okay

  string toString() const;
  string toFormattedString(bool showMicroseconds = true) const;

  bool valid() const { return microSecondsSinceEpoch_ > 0; }

  // for internal usage.
  int64_t microSecondsSinceEpoch() const { return microSecondsSinceEpoch_; }
  time_t secondsSinceEpoch() const
  { return static_cast<time_t>(microSecondsSinceEpoch_ / kMicroSecondsPerSecond); }

  ///
  /// Get time of now.
  ///
  static Timestamp now();
  static Timestamp invalid()
  {
    return Timestamp();
  }

  static Timestamp fromUnixTime(time_t t)
  {
    return fromUnixTime(t, 0);
  }

  static Timestamp fromUnixTime(time_t t, int microseconds)
  {
    return Timestamp(static_cast<int64_t>(t) * kMicroSecondsPerSecond + microseconds);
  }

  static const int kMicroSecondsPerSecond = 1000 * 1000;

 private:
  int64_t microSecondsSinceEpoch_;
};

inline bool operator<(Timestamp lhs, Timestamp rhs)
{
  return lhs.microSecondsSinceEpoch() < rhs.microSecondsSinceEpoch();
}

inline bool operator==(Timestamp lhs, Timestamp rhs)
{
  return lhs.microSecondsSinceEpoch() == rhs.microSecondsSinceEpoch();
}

///
/// Gets time difference of two timestamps, result in seconds.
///
/// @param high, low
/// @return (high-low) in seconds
/// @c double has 52-bit precision, enough for one-microsecond
/// resolution for next 100 years.
inline double timeDifference(Timestamp high, Timestamp low)
{
  int64_t diff = high.microSecondsSinceEpoch() - low.microSecondsSinceEpoch();
  return static_cast<double>(diff) / Timestamp::kMicroSecondsPerSecond;
}

///
/// Add @c seconds to given timestamp.
///
/// @return timestamp+seconds as Timestamp
///
inline Timestamp addTime(Timestamp timestamp, double seconds)
{
  int64_t delta = static_cast<int64_t>(seconds * Timestamp::kMicroSecondsPerSecond);
  return Timestamp(timestamp.microSecondsSinceEpoch() + delta);
}

}  // namespace muduo

#endif  // MUDUO_BASE_TIMESTAMP_H


text:
package rmq

type BatchConsumer interface {
	Consume(batch Deliveries)
}


text:
title: PhoneGap Community Roundup – August 2012
date: 2012-09-06 00:00:00 Z
tags:
- Event
- Community
author: Steve Gill
---

A few months ago we started the [PhoneGap Community Release Notes](https://phonegap.com/2012/05/18/phonegap-community-release-notes/). Thank you to everyone who contributed. If you're organizing a PhoneGap event, speaking on PhoneGap or writing a blog post, please add it to the release notes on [Github](https://github.com/phonegap/phonegap-community).

We'll be posting the round up from each month and below is the roundup for the month of August.

## EVENTS

- August 6-7, [Riacon](http://www.riacon.com/), Andrew Trice
- August 16, [Developing Enterprise Android Applications with PhoneGap](http://www.meetup.com/DC-Droids/events/74741212/), Andrew Trice
- August 30, [SF PhoneGap Meetup](http://www.meetup.com/PhoneGap-SF/events/76053352/)

## ARTICLES

- [11 Upcoming Changes for Cordova iOS 2.1.0](http://shazronatadobe.wordpress.com/2012/08/28/10-upcoming-changes-for-cordova-ios-2-1-0/), Shazron Abdullah
- [New PhoneGap API Explorer available on the App Store](http://http://coenraets.org/blog/2012/08/new-phonegap-api-explorer-available-on-the-app-store), Christophe Coenraets
- [Create "onboard" PhoneGap apk with AIDE (FR)](http://k33g.github.com/2012/08/16/APK-ONBOARD.html)
- [PhoneGap Build adds Hydration](http://www.raymondcamden.com/index.cfm/2012/8/23/PhoneGap-Build-adds-Hydration), [Raymond Camden](http://twitter.com/cfjedimaster)
- [Transcript From Open Session on PhoneGap/Cordova](http://www.tricedesigns.com/2012/08/28/transcript-from-open-session-on-phonegapcordova/), Andy Trice
- [PhoneGap Day US Videos](https://phonegap.com/blog/2012/08/28/pgday-intro-video/), Steve Gill
- [SponsorPay Integrates PhoneGap Plugin](https://phonegap.com/blog/2012/08/23/sponsorpay/), Sponsor Pay
- [Enterprise Android Apps With PhoneGap](http://www.tricedesigns.com/2012/08/17/enterprise-android-apps-w-phonegap/), Andy Trice
- [Introducing PhoneGap Emulation](https://phonegap.com/blog/2012/08/10/introducing-phonegap-emulation/), Michael Brooks
- [Appliness features PhoneGap](https://phonegap.com/blog/2012/08/02/appliness-august/), Steve Gill


text:
"""
The :mod:`sklearn.exceptions` module includes all custom warnings and error
classes used across scikit-learn.
"""

__all__ = ['NotFittedError',
           'ChangedBehaviorWarning',
           'ConvergenceWarning',
           'DataConversionWarning',
           'DataDimensionalityWarning',
           'EfficiencyWarning',
           'FitFailedWarning',
           'NonBLASDotWarning',
           'UndefinedMetricWarning']

class NotFittedError(ValueError, AttributeError):
    """Exception class to raise if estimator is used before fitting.

    This class inherits from both ValueError and AttributeError to help with
    exception handling and backward compatibility.

    Examples
    --------
    >>> from sklearn.svm import LinearSVC
    >>> from sklearn.exceptions import NotFittedError
    >>> try:
    ...     LinearSVC().predict([[1, 2], [2, 3], [3, 4]])
    ... except NotFittedError as e:
    ...     print(repr(e))
    ...                        # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
    NotFittedError('This LinearSVC instance is not fitted yet',)

    .. versionchanged:: 0.18
       Moved from sklearn.utils.validation.
    """

class ChangedBehaviorWarning(UserWarning):
    """Warning class used to notify the user of any change in the behavior.

    .. versionchanged:: 0.18
       Moved from sklearn.base.
    """

class ConvergenceWarning(UserWarning):
    """Custom warning to capture convergence problems

    .. versionchanged:: 0.18
       Moved from sklearn.utils.
    """

class DataConversionWarning(UserWarning):
    """Warning used to notify implicit data conversions happening in the code.

    This warning occurs when some input data needs to be converted or
    interpreted in a way that may not match the user's expectations.

    For example, this warning may occur when the user
        - passes an integer array to a function which expects float input and
          will convert the input
        - requests a non-copying operation, but a copy is required to meet the
          implementation's data-type expectations;
        - passes an input whose shape can be interpreted ambiguously.

    .. versionchanged:: 0.18
       Moved from sklearn.utils.validation.
    """

class DataDimensionalityWarning(UserWarning):
    """Custom warning to notify potential issues with data dimensionality.

    For example, in random projection, this warning is raised when the
    number of components, which quantifies the dimensionality of the target
    projection space, is higher than the number of features, which quantifies
    the dimensionality of the original source space, to imply that the
    dimensionality of the problem will not be reduced.

    .. versionchanged:: 0.18
       Moved from sklearn.utils.
    """

class EfficiencyWarning(UserWarning):
    """Warning used to notify the user of inefficient computation.

    This warning notifies the user that the efficiency may not be optimal due
    to some reason which may be included as a part of the warning message.
    This may be subclassed into a more specific Warning class.

    .. versionadded:: 0.18
    """

class FitFailedWarning(RuntimeWarning):
    """Warning class used if there is an error while fitting the estimator.

    This Warning is used in meta estimators GridSearchCV and RandomizedSearchCV
    and the cross-validation helper function cross_val_score to warn when there
    is an error while fitting the estimator.

    Examples
    --------
    >>> from sklearn.model_selection import GridSearchCV
    >>> from sklearn.svm import LinearSVC
    >>> from sklearn.exceptions import FitFailedWarning
    >>> import warnings
    >>> warnings.simplefilter('always', FitFailedWarning)
    >>> gs = GridSearchCV(LinearSVC(), {'C': [-1, -2]}, error_score=0)
    >>> X, y = [[1, 2], [3, 4], [5, 6], [7, 8], [8, 9]], [0, 0, 0, 1, 1]
    >>> with warnings.catch_warnings(record=True) as w:
    ...     try:
    ...         gs.fit(X, y)   # This will raise a ValueError since C is < 0
    ...     except ValueError:
    ...         pass
    ...     print(repr(w[-1].message))
    ... # doctest: +NORMALIZE_WHITESPACE
    FitFailedWarning("Classifier fit failed. The score on this train-test
    partition for these parameters will be set to 0.000000. Details:
    \\nValueError('Penalty term must be positive; got (C=-2)',)",)

    .. versionchanged:: 0.18
       Moved from sklearn.cross_validation.
    """

class NonBLASDotWarning(EfficiencyWarning):
    """Warning used when the dot operation does not use BLAS.

    This warning is used to notify the user that BLAS was not used for dot
    operation and hence the efficiency may be affected.

    .. versionchanged:: 0.18
       Moved from sklearn.utils.validation, extends EfficiencyWarning.
    """

class UndefinedMetricWarning(UserWarning):
    """Warning used when the metric is invalid

    .. versionchanged:: 0.18
       Moved from sklearn.base.
    """


text:
package net.docusign.api_3_0;

import java.math.BigDecimal;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 *
Java class for TabStatus complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="TabStatus">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="TabType" type="{http://www.docusign.net/API/3.0}TabTypeCode"/>
 *         <element name="Status" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="XPosition" type="{http://www.w3.org/2001/XMLSchema}double"/>
 *         <element name="YPosition" type="{http://www.w3.org/2001/XMLSchema}double"/>
 *         <element name="Signed" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
 *         <element name="TabLabel" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="TabName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="TabValue" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="DocumentID" type="{http://www.w3.org/2001/XMLSchema}positiveInteger" minOccurs="0"/>
 *         <element name="PageNumber" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" minOccurs="0"/>
 *         <element name="OriginalValue" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="ValidationPattern" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="RoleName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="ListValues" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="ListSelectedValue" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="ScaleValue" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
 *         <element name="CustomTabType" type="{http://www.docusign.net/API/3.0}CustomTabType" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TabStatus", propOrder = {
    "tabType",
    "status",
    "xPosition",
    "yPosition",
    "signed",
    "tabLabel",
    "tabName",
    "tabValue",
    "documentID",
    "pageNumber",
    "originalValue",
    "validationPattern",
    "roleName",
    "listValues",
    "listSelectedValue",
    "scaleValue",
    "customTabType"
})
public class TabStatus {

    @XmlElement(name = "TabType", required = true)
    protected TabTypeCode tabType;
    @XmlElement(name = "Status")
    protected String status;
    @XmlElement(name = "XPosition")
    protected double xPosition;
    @XmlElement(name = "YPosition")
    protected double yPosition;
    @XmlElement(name = "Signed")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar signed;
    @XmlElement(name = "TabLabel")
    protected String tabLabel;
    @XmlElement(name = "TabName")
    protected String tabName;
    @XmlElement(name = "TabValue")
    protected String tabValue;
    @XmlElement(name = "DocumentID")
    @XmlSchemaType(name = "positiveInteger")
    protected BigInteger documentID;
    @XmlElement(name = "PageNumber")
    @XmlSchemaType(name = "nonNegativeInteger")
    protected BigInteger pageNumber;
    @XmlElement(name = "OriginalValue")
    protected String originalValue;
    @XmlElement(name = "ValidationPattern")
    protected String validationPattern;
    @XmlElement(name = "RoleName")
    protected String roleName;
    @XmlElement(name = "ListValues")
    protected String listValues;
    @XmlElement(name = "ListSelectedValue")
    protected String listSelectedValue;
    @XmlElement(name = "ScaleValue")
    protected BigDecimal scaleValue;
    @XmlElement(name = "CustomTabType")
    protected CustomTabType customTabType;

    /**
     * Gets the value of the tabType property.
     *
     * @return
     *     possible object is
     *     {@link TabTypeCode }
     *
     */
    public TabTypeCode getTabType() {
        return tabType;
    }

    /**
     * Sets the value of the tabType property.
     *
     * @param value
     *     allowed object is
     *     {@link TabTypeCode }
     *
     */
    public void setTabType(TabTypeCode value) {
        this.tabType = value;
    }

    /**
     * Gets the value of the status property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getStatus() {
        return status;
    }

    /**
     * Sets the value of the status property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setStatus(String value) {
        this.status = value;
    }

    /**
     * Gets the value of the xPosition property.
     *
     */
    public double getXPosition() {
        return xPosition;
    }

    /**
     * Sets the value of the xPosition property.
     *
     */
    public void setXPosition(double value) {
        this.xPosition = value;
    }

    /**
     * Gets the value of the yPosition property.
     *
     */
    public double getYPosition() {
        return yPosition;
    }

    /**
     * Sets the value of the yPosition property.
     *
     */
    public void setYPosition(double value) {
        this.yPosition = value;
    }

    /**
     * Gets the value of the signed property.
     *
     * @return
     *     possible object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public XMLGregorianCalendar getSigned() {
        return signed;
    }

    /**
     * Sets the value of the signed property.
     *
     * @param value
     *     allowed object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public void setSigned(XMLGregorianCalendar value) {
        this.signed = value;
    }

    /**
     * Gets the value of the tabLabel property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getTabLabel() {
        return tabLabel;
    }

    /**
     * Sets the value of the tabLabel property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setTabLabel(String value) {
        this.tabLabel = value;
    }

    /**
     * Gets the value of the tabName property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getTabName() {
        return tabName;
    }

    /**
     * Sets the value of the tabName property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setTabName(String value) {
        this.tabName = value;
    }

    /**
     * Gets the value of the tabValue property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getTabValue() {
        return tabValue;
    }

    /**
     * Sets the value of the tabValue property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setTabValue(String value) {
        this.tabValue = value;
    }

    /**
     * Gets the value of the documentID property.
     *
     * @return
     *     possible object is
     *     {@link BigInteger }
     *
     */
    public BigInteger getDocumentID() {
        return documentID;
    }

    /**
     * Sets the value of the documentID property.
     *
     * @param value
     *     allowed object is
     *     {@link BigInteger }
     *
     */
    public void setDocumentID(BigInteger value) {
        this.documentID = value;
    }

    /**
     * Gets the value of the pageNumber property.
     *
     * @return
     *     possible object is
     *     {@link BigInteger }
     *
     */
    public BigInteger getPageNumber() {
        return pageNumber;
    }

    /**
     * Sets the value of the pageNumber property.
     *
     * @param value
     *     allowed object is
     *     {@link BigInteger }
     *
     */
    public void setPageNumber(BigInteger value) {
        this.pageNumber = value;
    }

    /**
     * Gets the value of the originalValue property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getOriginalValue() {
        return originalValue;
    }

    /**
     * Sets the value of the originalValue property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setOriginalValue(String value) {
        this.originalValue = value;
    }

    /**
     * Gets the value of the validationPattern property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getValidationPattern() {
        return validationPattern;
    }

    /**
     * Sets the value of the validationPattern property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setValidationPattern(String value) {
        this.validationPattern = value;
    }

    /**
     * Gets the value of the roleName property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getRoleName() {
        return roleName;
    }

    /**
     * Sets the value of the roleName property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setRoleName(String value) {
        this.roleName = value;
    }

    /**
     * Gets the value of the listValues property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getListValues() {
        return listValues;
    }

    /**
     * Sets the value of the listValues property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setListValues(String value) {
        this.listValues = value;
    }

    /**
     * Gets the value of the listSelectedValue property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getListSelectedValue() {
        return listSelectedValue;
    }

    /**
     * Sets the value of the listSelectedValue property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setListSelectedValue(String value) {
        this.listSelectedValue = value;
    }

    /**
     * Gets the value of the scaleValue property.
     *
     * @return
     *     possible object is
     *     {@link BigDecimal }
     *
     */
    public BigDecimal getScaleValue() {
        return scaleValue;
    }

    /**
     * Sets the value of the scaleValue property.
     *
     * @param value
     *     allowed object is
     *     {@link BigDecimal }
     *
     */
    public void setScaleValue(BigDecimal value) {
        this.scaleValue = value;
    }

    /**
     * Gets the value of the customTabType property.
     *
     * @return
     *     possible object is
     *     {@link CustomTabType }
     *
     */
    public CustomTabType getCustomTabType() {
        return customTabType;
    }

    /**
     * Sets the value of the customTabType property.
     *
     * @param value
     *     allowed object is
     *     {@link CustomTabType }
     *
     */
    public void setCustomTabType(CustomTabType value) {
        this.customTabType = value;
    }

}


text:
/**
 * Internal dependencies
 */
import API from 'googlesitekit-api';
import { MODULES_ADSENSE } from './constants';
import {
	createTestRegistry,
	subscribeUntil,
	unsubscribeFromAll,
} from '../../../../../tests/js/utils';
import { getAdSenseMockResponse } from '../util/data-mock';

describe( 'modules/adsense report', () => {
	let registry;

	beforeAll( () => {
		API.setUsingCache( false );
	} );

	beforeEach( () => {
		registry = createTestRegistry();
	} );

	afterAll( () => {
		API.setUsingCache( true );
	} );

	afterEach( () => {
		unsubscribeFromAll( registry );
	} );

	describe( 'actions', () => {} );

	describe( 'selectors', () => {
		describe( 'getReport', () => {
			const options = {
				startDate: '2021-07-01',
				endDate: '2021-07-28',
				metrics: [ 'IMPRESSIONS' ],
				dimensions: [ 'DATE' ],
			};

			it( 'uses a resolver to make a network request', async () => {
				const report = getAdSenseMockResponse( options );

				fetchMock.getOnce(
					/^\/google-site-kit\/v1\/modules\/adsense\/data\/report/,
					{ body: report }
				);

				expect(
					registry.select( MODULES_ADSENSE ).getReport( options )
				).toBeUndefined();
				await subscribeUntil(
					registry,
					() =>
						registry
							.select( MODULES_ADSENSE )
							.getReport( options ) !== undefined
				);

				expect(
					registry.select( MODULES_ADSENSE ).getReport( options )
				).toEqual( report );
				expect( fetchMock ).toHaveFetchedTimes( 1 );
			} );

			it( 'does not make a network request if report for given options is already present', async () => {
				const report = getAdSenseMockResponse( options );

				// Load data into this store so there are matches for the data we're about to select,
				// even though the selector hasn't fulfilled yet.
				registry
					.dispatch( MODULES_ADSENSE )
					.receiveGetReport( report, { options } );

				const initialReport = registry
					.select( MODULES_ADSENSE )
					.getReport( options );
				await subscribeUntil( registry, () =>
					registry
						.select( MODULES_ADSENSE )
						.hasFinishedResolution( 'getReport', [ options ] )
				);

				expect( fetchMock ).not.toHaveFetched();
				expect( initialReport ).toEqual( report );
			} );

			it( 'dispatches an error if the request fails', async () => {
				const response = {
					code: 'internal_server_error',
					message: 'Internal server error',
					data: { status: 500 },
				};
				fetchMock.getOnce(
					/^\/google-site-kit\/v1\/modules\/adsense\/data\/report/,
					{ body: response, status: 500 }
				);

				registry.select( MODULES_ADSENSE ).getReport( options );
				await subscribeUntil(
					registry,
					() =>
						registry
							.select( MODULES_ADSENSE )
							.isFetchingGetReport( options ) === false
				);

				expect( fetchMock ).toHaveFetchedTimes( 1 );

				const report = registry
					.select( MODULES_ADSENSE )
					.getReport( options );
				expect( report ).toEqual( undefined );
				expect( console ).toHaveErrored();
			} );
		} );
	} );
} );


text:
var initialized = false;
var key_battery = 0;
var key_date_format = 1;
var options = {};

function fixedEncodeURIComponent(str)
{
	return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}

function buildURL()
{
	var url = 'http://josephkpalazzolo.com/pebblefaces/toothless_configurable.html?';
	if (options['battery-indicator'])
		url += fixedEncodeURIComponent("battery-indicator") + '=' + fixedEncodeURIComponent(options['battery-indicator']) + '&';
	if (options['date-format'])
		url +=fixedEncodeURIComponent("date-format") + '=' + fixedEncodeURIComponent(options['date-format']);
	return url;
}

Pebble.addEventListener("ready", function() {
  	console.log("ready called!");
  	initialized = true;
});

Pebble.addEventListener("showConfiguration", function() {
  	console.log("showing configuration");
	var battery = localStorage.getItem(key_battery);
	var date_format = localStorage.getItem(key_date_format);
	options['battery-indicator'] = battery;
	options['date-format'] = date_format;
	var url = buildURL();
  	Pebble.openURL(url);
});

Pebble.addEventListener("webviewclosed", function(e) {
  	console.log("configuration closed");
  	// webview closed
  	//Using primitive JSON validity and non-empty check
	options = JSON.parse(decodeURIComponent(e.response));
  	if (options['battery-indicator'] && options['date-format'] && e.response.length > 5) {
		var battery;
		if (options['battery-indicator'] == 'on')
			battery = 1;
		else
			battery = 0;
		var dateConfig;
		if (options['date-format'] == 'a')
			{
				dateConfig = 1;
				console.log("Date format a");
			}
		else
			dateConfig = 0;
		var dictionary = {
			"KEY_BATTERY": battery,
			"KEY_DATE_FORMAT": dateConfig
		};
		Pebble.sendAppMessage(dictionary,
							 function(e) {
								 console.log("Sent app message");
							 },
							 function(e) {
								 console.log("Failed to send app message");
							 });
    	console.log("Options = " + JSON.stringify(options));
		localStorage.setItem(key_battery, options['battery-indicator']);
		localStorage.setItem(key_date_format, options['date-format']);
  	} else {
    	console.log("Canceled");
  	}
});


text:
import { StoreProvider, Type, Injectable, InjectableId, Dependency } from './types';
import { Reflector } from './reflector';
import { InjectionToken } from './injection-token';

export class Store {
  public static providers: StoreProvider[] = [];

  /**
   * Get provider id
   *
   * @static
   * @param {Injectable} injectable
   * @returns {InjectableId}
   */
  public static providerId(injectable: Injectable): InjectableId {
    if (!injectable) {
      return null;
    }

    if (typeof injectable === 'string' || injectable instanceof InjectionToken) {
      return injectable;
    }

    return Reflector.getId(injectable);
  }

  /**
   * Register provider
   *
   * @internal
   * @static
   * @param {Type} provider
   * @param {InjectableId} useId
   */
  public static provider(type: Type, args?: { injectable?, optional?, index? }): Type {
    let provider: StoreProvider = this.findProvider(type);

    if (provider === undefined) {
      provider = this.createProvider(type);
    }

    if (args === undefined) {
      Reflector.paramTypes(type)
        .forEach((param: Injectable, index: number) => {
          if (!provider.deps[index] || !provider.deps[index].id) {
            provider.deps[index] = { id: this.providerId(param) };
          }
        });

      return type;
    }

    const dep: Dependency = provider.deps[args.index] || { id: null };

    provider.deps[args.index] = {
      id: args.injectable ? this.providerId(args.injectable) : dep.id,
      optional: args.optional || dep.optional
    };

    return type;
  }

  /**
   * Find stored provider
   *
   * @internal
   * @static
   * @param {Injectable} injectable
   *
   * @returns {StoreProvider}
   */
  public static findProvider(injectable: Injectable): StoreProvider {
    const id: InjectableId = this.providerId(injectable);

    return this.providers.find((provider: StoreProvider) => provider.id === id);
  }

  /**
   * Replace stored provider wiht new provider
   *
   * @static
   * @param {Injectable} injectable
   * @param {StoreProvider} provider
   */
  public static replaceProvider(injectable: Injectable, provider: StoreProvider): void {
    const storeProvider: StoreProvider = this.findProvider(injectable);
    const index: number = this.providers.indexOf(storeProvider);

    if (index !== -1) {
      this.providers[index] = provider;
    } else {
      this.providers.push(provider);
    }
  }

  /**
   * Create and store provider
   *
   * @internal
   * @static
   * @param {Injectable} injectable
   *
   * @returns {StoreProvider}
   */
  private static createProvider(type: Type): StoreProvider {
    const id: InjectableId = Reflector.setId(type);
    const storeProvider: StoreProvider = { id, type, deps: [] };

    this.providers.push(storeProvider);

    return storeProvider;
  }

}


text:
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;

public class NodeSidePanel
{
    protected NodeTestWindow parentWindow;
    protected Vector2 scrollPosition;

    #region cache values

    protected Rect contentRect;
    protected Rect labelRect;
    protected Rect backgroundRect;
    protected Rect itemRect;

    #endregion

    public event System.Action<int> IndexSelected;

    private const float BorderSize = 5f;

    public NodeSidePanel (NodeTestWindow parentWindow)
    {
        this.parentWindow = parentWindow;
    }

    public void Draw (Rect contentRect)
    {
        //TODO add filter

        this.contentRect = contentRect;
        this.labelRect = GetLabelRect ();
        this.backgroundRect = GetBackgroundRect ();

        Rect viewRect = GetCompleteViewRect ();

        //this.scrollPosition = GUI.BeginScrollView (contentRect, this.scrollPosition, viewRect);

        // header
        EditorGUI.LabelField (this.labelRect, "Nodes:");

        // boxBackground
        EditorGUI.DrawRect (this.backgroundRect, Color.white);

        // list
        this.itemRect = GetItemRect ();
        for (int i = 0; i < this.parentWindow.Windows.Count; ++i)
        {
            EditorGUI.DrawRect (this.itemRect, Color.yellow);
            if (GUI.Button (this.itemRect, new GUIContent (this.parentWindow.Windows [i].Name)))
            {
                Debug.Log ("Pressed index " + i);
            }

            this.itemRect.y += EditorGUIUtility.singleLineHeight;
        }

        //GUI.EndScrollView ();
    }

    public void SelectIndex (int index)
    {
        //TODO search for hitlist when filter is implemented
        //TODO implement scrollPositon
    }

    private float GetHeight ()
    {
        // header

        // content

        return 0f;
    }

    private Rect GetCompleteViewRect ()
    {
        return new Rect ();

    }

    private Rect GetLabelRect ()
    {
        return new Rect (
            this.contentRect.x + BorderSize,
            this.contentRect.y + BorderSize,
            this.contentRect.width,
            EditorGUIUtility.singleLineHeight);
    }

    private Rect GetBackgroundRect ()
    {
        return new Rect (
            this.labelRect.x,
            this.labelRect.y + EditorGUIUtility.singleLineHeight,
            this.contentRect.width - (BorderSize * 2),
            (this.parentWindow.Windows.Count * EditorGUIUtility.singleLineHeight) + (2f * BorderSize));
    }

    private Rect GetItemRect ()
    {
        Rect result = backgroundRect;
        result.y += BorderSize;
        result.height = EditorGUIUtility.singleLineHeight;
        result.x += BorderSize;
        result.width -= BorderSize * 2f;

        return result;
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoInfo
{
	/// <summary>
	/// A Demo header.
	/// </summary>
	public class DemoHeader
    {
        const int MAX_OSPATH = 260;

	    public string Filestamp { get; private set; }		// Should be HL2DEMO
		public int Protocol { get; private set; }		// Should be DEMO_PROTOCOL (4)

		[Obsolete("This was a typo. Use NetworkProtocol instead")]
		public int NetworkProtocal {
			get {
				return NetworkProtocol;
			}
		}

        public int NetworkProtocol { get; private set; }				// Should be PROTOCOL_VERSION

        public string ServerName { get; private set; }		            // Name of server
        public string ClientName { get; private set; }		            // Name of client who recorded the game
        public string MapName { get; private set; }			        // Name of map
        public string GameDirectory { get; private set; }	            // Name of game directory (com_gamedir)
        public float PlaybackTime { get; private set; }				// Time of track
        public int PlaybackTicks { get; private set; }				// # of ticks in track
        public int PlaybackFrames { get; private set; }			// # of frames in track
        public int SignonLength { get; private set; }				// length of sigondata in bytes

        public static DemoHeader ParseFrom(IBitStream reader)
        {
            return new DemoHeader() {
                Filestamp = reader.ReadCString(8),
                Protocol = reader.ReadSignedInt(32),
				NetworkProtocol = reader.ReadSignedInt(32),
                ServerName = reader.ReadCString(MAX_OSPATH),

                ClientName = reader.ReadCString(MAX_OSPATH),
                MapName = reader.ReadCString(MAX_OSPATH),
                GameDirectory = reader.ReadCString(MAX_OSPATH),
				PlaybackTime = reader.ReadFloat(),

				PlaybackTicks = reader.ReadSignedInt(32),
				PlaybackFrames = reader.ReadSignedInt(32),
				SignonLength = reader.ReadSignedInt(32),
            };
        }
    }

	/// <summary>
	/// And Source-Engine Vector.
	/// </summary>
	public class Vector
    {
        public float X { get; set; }
        public float Y { get; set; }
        public float Z { get; set; }

		public double Angle2D
		{
			get
			{
				return Math.Atan2(this.Y, this.X);
			}
		}

		public double Absolute
		{
			get
			{
				return Math.Sqrt(AbsoluteSquared);
			}
		}

		public double AbsoluteSquared
		{
			get
			{
				return this.X * this.X + this.Y * this.Y + this.Z * this.Z;
			}
		}

        public static Vector Parse(IBitStream reader)
        {
            return new Vector
            {
                X = reader.ReadFloat(),
				Y = reader.ReadFloat(),
				Z = reader.ReadFloat(),
            };
        }

		public Vector()
		{

		}

		public Vector(float x, float y, float z)
		{
			this.X = x;
			this.Y = y;
			this.Z = z;
		}

		/// <summary>
		/// Copy this instance. So if you want to permanently store the position of a player at a point in time,
		/// COPY it.
		/// </summary>
		public Vector Copy()
		{
			return new Vector(X,Y,Z);
		}

		public static Vector operator + (Vector a, Vector b)
		{
			return new Vector() {X = a.X + b.X, Y = a.Y + b.Y, Z = a.Z + b.Z };
		}

		public static Vector operator - (Vector a, Vector b)
		{
			return new Vector() {X = a.X - b.X, Y = a.Y - b.Y, Z = a.Z - b.Z };
		}

        public override string ToString()
        {
            return "{X: " + X + ", Y: " + Y + ", Z: " + Z + " }";
        }
    }

	/// <summary>
	/// And Angle in the Source-Engine. Looks pretty much like a vector.
	/// </summary>
	class QAngle
    {
        public float X { get; private set; }
        public float Y { get; private set; }
        public float Z { get; private set; }

		public static QAngle Parse(IBitStream reader)
        {
            return new QAngle
            {
				X = reader.ReadFloat(),
				Y = reader.ReadFloat(),
				Z = reader.ReadFloat(),
            };
        }
    }

	/// <summary>
	/// A split.
	/// </summary>
	class Split
    {
        const int FDEMO_NORMAL = 0, FDEMO_USE_ORIGIN2 = 1, FDEMO_USE_ANGLES2 = 2, FDEMO_NOINTERP = 4;

        public int Flags { get; private set; }
        public Vector viewOrigin { get; private set; }
        public QAngle viewAngles { get; private set; }
        public QAngle localViewAngles { get; private set; }

        public Vector viewOrigin2 { get; private set; }
        public QAngle viewAngles2 { get; private set; }
        public QAngle localViewAngles2 { get; private set; }

        public Vector ViewOrigin { get { return (Flags & FDEMO_USE_ORIGIN2) != 0 ? viewOrigin2 : viewOrigin;  }}

        public QAngle ViewAngles { get { return (Flags & FDEMO_USE_ANGLES2) != 0 ? viewAngles2 : viewAngles;   }}

        public QAngle LocalViewAngles { get { return (Flags & FDEMO_USE_ANGLES2) != 0 ? localViewAngles2 : localViewAngles; }}

        public static Split Parse(IBitStream reader)
        {
            return new Split
            {
                Flags = reader.ReadSignedInt(32),
                viewOrigin = Vector.Parse(reader),
                viewAngles = QAngle.Parse(reader),
                localViewAngles = QAngle.Parse(reader),

                viewOrigin2 = Vector.Parse(reader),
                viewAngles2 = QAngle.Parse(reader),
                localViewAngles2 = QAngle.Parse(reader),
            };
        }
    }

	class CommandInfo
    {
        public Split[] u { get; private set; }

        public static CommandInfo Parse(IBitStream reader)
        {
            return new CommandInfo
            {
                u = new Split[2] { Split.Parse(reader), Split.Parse(reader) }
            };
        }
    }

	/// <summary>
	/// A playerinfo, based on playerinfo_t by Volvo.
	/// </summary>
    public class PlayerInfo
    {
	    /// version for future compatibility
	    public long Version { get; set; }

	    // network xuid
        public long XUID { get; set; }

	    // scoreboard information
        public string Name { get; set; } //MAX_PLAYER_NAME_LENGTH=128

	    // local server user ID, unique while server is running
        public int UserID { get; set; }

	    // global unique player identifer
        public string GUID { get; set; } //33bytes

	    // friends identification number
        public int FriendsID { get; set; }
	    // friends name
        public string FriendsName { get; set; } //128

	    // true, if player is a bot controlled by game.dll
        public bool IsFakePlayer { get; set; }

	    // true if player is the HLTV proxy
        public bool IsHLTV { get; set; }

        // custom files CRC for this player
        public int customFiles0 { get; set; }
        public int customFiles1 { get; set; }
        public int customFiles2 { get; set; }
        public int customFiles3 { get; set; }

        byte filesDownloaded { get; set; }

	    // this counter increases each time the server downloaded a new file
        byte FilesDownloaded { get; set; }

		internal PlayerInfo()
		{
		}

		internal PlayerInfo(BinaryReader reader)
        {
            Version = reader.ReadInt64SwapEndian();
            XUID = reader.ReadInt64SwapEndian();
            Name = reader.ReadCString(128);
            UserID = reader.ReadInt32SwapEndian();
            GUID = reader.ReadCString(33);
            FriendsID = reader.ReadInt32SwapEndian();
            FriendsName = reader.ReadCString(128);

            IsFakePlayer = reader.ReadBoolean();
            IsHLTV = reader.ReadBoolean();

            customFiles0 = reader.ReadInt32();
            customFiles1 = reader.ReadInt32();
            customFiles2 = reader.ReadInt32();
            customFiles3 = reader.ReadInt32();

            filesDownloaded = reader.ReadByte();
        }

        public static PlayerInfo ParseFrom(BinaryReader reader)
        {
            return new PlayerInfo(reader);
        }

        public static int SizeOf { get { return 8 + 8 + 128 + 4 + 3 + 4 + 1 + 1 + 4 * 8 + 1; } }
    }

	/// <summary>
	/// This contains information about Collideables (specific edicts), mostly used for bombsites.
	/// </summary>
	class BoundingBoxInformation
	{
		public int Index { get; private set; }
		public Vector Min { get; set; }
		public Vector Max { get; set; }

		public BoundingBoxInformation (int index)
		{
			this.Index = index;
		}

		/// <summary>
		/// Checks wheter a point lies within the BoundingBox.
		/// </summary>
		/// <param name="point">The point to check</param>
		public bool Contains(Vector point)
		{
			return point.X >= Min.X && point.X <= Max.X &&
				point.Y >= Min.Y && point.Y <= Max.Y &&
				point.Z >= Min.Z && point.Z <= Max.Z;
		}
	}

	/// <summary>
	/// The demo-commands as given by Valve.
	/// </summary>
    enum DemoCommand
    {

        /// <summary>
        /// it's a startup message, process as fast as possible
        /// </summary>
	    Signon	= 1,
        /// <summary>
        // it's a normal network packet that we stored off
        /// </summary>
	    Packet,

        /// <summary>
        /// sync client clock to demo tick
        /// </summary>
	    Synctick,

	    /// <summary>
        /// Console Command
	    /// </summary>
	    ConsoleCommand,

        /// <summary>
        /// user input command
        /// </summary>
	    UserCommand,

	    /// <summary>
        ///  network data tables
	    /// </summary>
	    DataTables,

        /// <summary>
        /// end of time.
        /// </summary>
	    Stop,

	    /// <summary>
        /// a blob of binary data understood by a callback function
	    /// </summary>
	    CustomData,

	    StringTables,

	    /// <summary>
	    /// Last Command
	    /// </summary>
	    LastCommand	= StringTables,

         /// <summary>
	    /// First Command
	    /// </summary>
	    FirstCommand	= Signon
    };

	public enum RoundEndReason
	{
		/// <summary>
		/// Target Successfully Bombed!
		/// </summary>
		TargetBombed = 1,
		/// <summary>
		/// The VIP has escaped.
		/// </summary>
		VIPEscaped,
		/// <summary>
		/// VIP has been assassinated
		/// </summary>
		VIPKilled,
		/// <summary>
		/// The terrorists have escaped
		/// </summary>
		TerroristsEscaped,

		/// <summary>
		/// The CTs have prevented most of the terrorists from escaping!
		/// </summary>
		CTStoppedEscape,
		/// <summary>
		/// Escaping terrorists have all been neutralized
		/// </summary>
		TerroristsStopped,
		/// <summary>
		/// The bomb has been defused!
		/// </summary>
		BombDefused,
		/// <summary>
		/// Counter-Terrorists Win!
		/// </summary>
		CTWin,
		/// <summary>
		/// Terrorists Win!
		/// </summary>
		TerroristWin,
		/// <summary>
		/// Round Draw!
		/// </summary>
		Draw,
		/// <summary>
		/// All Hostages have been rescued
		/// </summary>
		HostagesRescued,
		/// <summary>
		/// Target has been saved!
		/// </summary>
		TargetSaved,
		/// <summary>
		/// Hostages have not been rescued!
		/// </summary>
		HostagesNotRescued,
		/// <summary>
		/// Terrorists have not escaped!
		/// </summary>
		TerroristsNotEscaped,
		/// <summary>
		/// VIP has not escaped!
		/// </summary>
		VIPNotEscaped,
		/// <summary>
		/// Game Commencing!
		/// </summary>
		GameStart,
		/// <summary>
		/// Terrorists Surrender
		/// </summary>
		TerroristsSurrender,
		/// <summary>
		/// CTs Surrender
		/// </summary>
		CTSurrender
	};

	public enum RoundMVPReason
	{
		MostEliminations = 1,
		BombPlanted,
		BombDefused
	};

	public enum Hitgroup
	{
		Generic = 0,
		Head = 1,
		Chest = 2,
		Stomach = 3,
		LeftArm = 4,
		RightArm = 5,
		LeftLeg = 6,
		RightLeg = 7,
		Gear = 10,
	};

}