text:
package org.elasticsearch.count.query;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.count.CountResponse;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.*;
import org.elasticsearch.index.query.CommonTermsQueryBuilder.Operator;
import org.elasticsearch.index.query.MatchQueryBuilder.Type;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Test;

import java.io.IOException;

import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.FilterBuilders.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*;
import static org.hamcrest.Matchers.*;

public class SimpleQueryTests extends ElasticsearchIntegrationTest {

    @Test
    public void passQueryAsStringTest() throws Exception {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));

        client().prepareIndex("test", "type1", "1").setSource("field1", "value1_1", "field2", "value2_1").setRefresh(true).get();

        CountResponse countResponse = client().prepareCount().setSource(new BytesArray("{ \"query\" : { \"term\" : { \"field1\" : \"value1_1\" }}}").array()).get();
        assertHitCount(countResponse, 1l);
    }

    @Test
    public void testIndexOptions() throws Exception {
        assertAcked(prepareCreate("test")
                .addMapping("type1", "field1", "type=string,index_options=docs")
                .setSettings("index.number_of_shards", 1));

        client().prepareIndex("test", "type1", "1").setSource("field1", "quick brown fox", "field2", "quick brown fox").get();
        client().prepareIndex("test", "type1", "2").setSource("field1", "quick lazy huge brown fox", "field2", "quick lazy huge brown fox").setRefresh(true).get();

        CountResponse countResponse = client().prepareCount().setQuery(QueryBuilders.matchQuery("field2", "quick brown").type(Type.PHRASE).slop(0)).get();
        assertHitCount(countResponse, 1l);
        try {
            client().prepareCount().setQuery(QueryBuilders.matchQuery("field1", "quick brown").type(Type.PHRASE).slop(0)).get();
        } catch (SearchPhaseExecutionException e) {
            assertTrue("wrong exception message " + e.getMessage(), e.getMessage().endsWith("IllegalStateException[field \"field1\" was indexed without position data; cannot run PhraseQuery (term=quick)]; }"));
        }
    }

    @Test
    public void testCommonTermsQuery() throws Exception {
        assertAcked(prepareCreate("test")
                .addMapping("type1", "field1", "type=string,analyzer=whitespace")
                .setSettings(SETTING_NUMBER_OF_SHARDS, 1));

        indexRandom(true,
                client().prepareIndex("test", "type1", "3").setSource("field1", "quick lazy huge brown pidgin", "field2", "the quick lazy huge brown fox jumps over the tree"),
                client().prepareIndex("test", "type1", "1").setSource("field1", "the quick brown fox"),
                client().prepareIndex("test", "type1", "2").setSource("field1", "the quick lazy huge brown fox jumps over the tree") );

        CountResponse countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the quick brown").cutoffFrequency(3).lowFreqOperator(Operator.OR)).get();
        assertHitCount(countResponse, 3l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the quick brown").cutoffFrequency(3).lowFreqOperator(Operator.AND)).get();
        assertHitCount(countResponse, 2l);

        // Default
        countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the quick brown").cutoffFrequency(3)).get();
        assertHitCount(countResponse, 3l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the huge fox").lowFreqMinimumShouldMatch("2")).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the lazy fox brown").cutoffFrequency(1).highFreqMinimumShouldMatch("3")).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the lazy fox brown").cutoffFrequency(1).highFreqMinimumShouldMatch("4")).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setSource(new BytesArray("{ \"query\" : { \"common\" : { \"field1\" : { \"query\" : \"the lazy fox brown\", \"cutoff_frequency\" : 1, \"minimum_should_match\" : { \"high_freq\" : 4 } } } } }").array()).get();
        assertHitCount(countResponse, 1l);

        // Default
        countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the lazy fox brown").cutoffFrequency(1)).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the quick brown").cutoffFrequency(3).analyzer("standard")).get();
        assertHitCount(countResponse, 3l);
        // standard drops "the" since its a stopword

        // try the same with match query
        countResponse = client().prepareCount().setQuery(QueryBuilders.matchQuery("field1", "the quick brown").cutoffFrequency(3).operator(MatchQueryBuilder.Operator.AND)).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.matchQuery("field1", "the quick brown").cutoffFrequency(3).operator(MatchQueryBuilder.Operator.OR)).get();
        assertHitCount(countResponse, 3l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.matchQuery("field1", "the quick brown").cutoffFrequency(3).operator(MatchQueryBuilder.Operator.AND).analyzer("stop")).get();
        assertHitCount(countResponse, 3l);
        // standard drops "the" since its a stopword

        // try the same with multi match query
        countResponse = client().prepareCount().setQuery(QueryBuilders.multiMatchQuery("the quick brown", "field1", "field2").cutoffFrequency(3).operator(MatchQueryBuilder.Operator.AND)).get();
        assertHitCount(countResponse, 3l);
    }

    @Test
    public void queryStringAnalyzedWildcard() throws Exception {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));

        client().prepareIndex("test", "type1", "1").setSource("field1", "value_1", "field2", "value_2").get();
        refresh();

        CountResponse countResponse = client().prepareCount().setQuery(queryString("value*").analyzeWildcard(true)).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(queryString("*ue*").analyzeWildcard(true)).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(queryString("*ue_1").analyzeWildcard(true)).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(queryString("val*e_1").analyzeWildcard(true)).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(queryString("v?l*e?1").analyzeWildcard(true)).get();
        assertHitCount(countResponse, 1l);
    }

    @Test
    public void testLowercaseExpandedTerms() {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));

        client().prepareIndex("test", "type1", "1").setSource("field1", "value_1", "field2", "value_2").get();
        refresh();

        CountResponse countResponse = client().prepareCount().setQuery(queryString("VALUE_3~1").lowercaseExpandedTerms(true)).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount().setQuery(queryString("VALUE_3~1").lowercaseExpandedTerms(false)).get();
        assertHitCount(countResponse, 0l);
        countResponse = client().prepareCount().setQuery(queryString("ValUE_*").lowercaseExpandedTerms(true)).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount().setQuery(queryString("vAl*E_1")).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount().setQuery(queryString("[VALUE_1 TO VALUE_3]")).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount().setQuery(queryString("[VALUE_1 TO VALUE_3]").lowercaseExpandedTerms(false)).get();
        assertHitCount(countResponse, 0l);
    }

    @Test
    public void testDateRangeInQueryString() {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));

        String aMonthAgo = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).minusMonths(1));
        String aMonthFromNow = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).plusMonths(1));

        client().prepareIndex("test", "type", "1").setSource("past", aMonthAgo, "future", aMonthFromNow).get();
        refresh();

        CountResponse countResponse = client().prepareCount().setQuery(queryString("past:[now-2M/d TO now/d]")).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(queryString("future:[now/d TO now+2M/d]").lowercaseExpandedTerms(false)).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(queryString("future:[now/D TO now+2M/d]").lowercaseExpandedTerms(false)).get();
        //D is an unsupported unit in date math
        assertThat(countResponse.getSuccessfulShards(), equalTo(0));
        assertThat(countResponse.getFailedShards(), equalTo(1));
        assertThat(countResponse.getShardFailures().length, equalTo(1));
        assertThat(countResponse.getShardFailures()[0].reason(), allOf(containsString("Failed to parse"), containsString("unit [D] not supported for date math")));
    }

    @Test
    public void typeFilterTypeIndexedTests() throws Exception {
        typeFilterTests("not_analyzed");
    }

    @Test
    public void typeFilterTypeNotIndexedTests() throws Exception {
        typeFilterTests("no");
    }

    private void typeFilterTests(String index) throws Exception {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1)
                .addMapping("type1", jsonBuilder().startObject().startObject("type1")
                        .startObject("_type").field("index", index).endObject()
                        .endObject().endObject())
                .addMapping("type2", jsonBuilder().startObject().startObject("type2")
                        .startObject("_type").field("index", index).endObject()
                        .endObject().endObject()));
        indexRandom(true, client().prepareIndex("test", "type1", "1").setSource("field1", "value1"),
                client().prepareIndex("test", "type2", "1").setSource("field1", "value1"),
                client().prepareIndex("test", "type1", "2").setSource("field1", "value1"),
                client().prepareIndex("test", "type2", "2").setSource("field1", "value1"),
                client().prepareIndex("test", "type2", "3").setSource("field1", "value1"));

        assertHitCount(client().prepareCount().setQuery(filteredQuery(matchAllQuery(), typeFilter("type1"))).get(), 2l);
        assertHitCount(client().prepareCount().setQuery(filteredQuery(matchAllQuery(), typeFilter("type2"))).get(), 3l);

        assertHitCount(client().prepareCount().setTypes("type1").setQuery(matchAllQuery()).get(), 2l);
        assertHitCount(client().prepareCount().setTypes("type2").setQuery(matchAllQuery()).get(), 3l);

        assertHitCount(client().prepareCount().setTypes("type1", "type2").setQuery(matchAllQuery()).get(), 5l);
    }

    @Test
    public void idsFilterTestsIdIndexed() throws Exception {
        idsFilterTests("not_analyzed");
    }

    @Test
    public void idsFilterTestsIdNotIndexed() throws Exception {
        idsFilterTests("no");
    }

    private void idsFilterTests(String index) throws Exception {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1)
                .addMapping("type1", jsonBuilder().startObject().startObject("type1")
                        .startObject("_id").field("index", index).endObject()
                        .endObject().endObject()));

        indexRandom(true, client().prepareIndex("test", "type1", "1").setSource("field1", "value1"),
                client().prepareIndex("test", "type1", "2").setSource("field1", "value2"),
                client().prepareIndex("test", "type1", "3").setSource("field1", "value3"));

        CountResponse countResponse = client().prepareCount().setQuery(constantScoreQuery(idsFilter("type1").ids("1", "3"))).get();
        assertHitCount(countResponse, 2l);

        // no type
        countResponse = client().prepareCount().setQuery(constantScoreQuery(idsFilter().ids("1", "3"))).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(idsQuery("type1").ids("1", "3")).get();
        assertHitCount(countResponse, 2l);

        // no type
        countResponse = client().prepareCount().setQuery(idsQuery().ids("1", "3")).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(idsQuery("type1").ids("7", "10")).get();
        assertHitCount(countResponse, 0l);

        // repeat..., with terms
        countResponse = client().prepareCount().setTypes("type1").setQuery(constantScoreQuery(termsFilter("_id", "1", "3"))).get();
        assertHitCount(countResponse, 2l);
    }

    @Test
    public void testLimitFilter() throws Exception {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));

        indexRandom(true, client().prepareIndex("test", "type1", "1").setSource("field1", "value1_1"),
                client().prepareIndex("test", "type1", "2").setSource("field1", "value1_2"),
                client().prepareIndex("test", "type1", "3").setSource("field2", "value2_3"),
                client().prepareIndex("test", "type1", "4").setSource("field3", "value3_4"));

        CountResponse countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), limitFilter(2))).get();
        assertHitCount(countResponse, 2l);
    }

    @Test
    public void filterExistsMissingTests() throws Exception {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));

        indexRandom(true,
                client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject().startObject("obj1").field("obj1_val", "1").endObject().field("x1", "x_1").field("field1", "value1_1").field("field2", "value2_1").endObject()),
                client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject().startObject("obj1").field("obj1_val", "1").endObject().field("x2", "x_2").field("field1", "value1_2").endObject()),
                client().prepareIndex("test", "type1", "3").setSource(jsonBuilder().startObject().startObject("obj2").field("obj2_val", "1").endObject().field("y1", "y_1").field("field2", "value2_3").endObject()),
                client().prepareIndex("test", "type1", "4").setSource(jsonBuilder().startObject().startObject("obj2").field("obj2_val", "1").endObject().field("y2", "y_2").field("field3", "value3_4").endObject()));

        CountResponse countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("field1"))).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(constantScoreQuery(existsFilter("field1"))).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(queryString("_exists_:field1")).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("field2"))).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("field3"))).get();
        assertHitCount(countResponse, 1l);

        // wildcard check
        countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("x*"))).get();
        assertHitCount(countResponse, 2l);

        // object check
        countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("obj1"))).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("field1"))).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("field1"))).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(constantScoreQuery(missingFilter("field1"))).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(queryString("_missing_:field1")).get();
        assertHitCount(countResponse, 2l);

        // wildcard check
        countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("x*"))).get();
        assertHitCount(countResponse, 2l);

        // object check
        countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("obj1"))).get();
        assertHitCount(countResponse, 2l);
    }

    @Test
    public void passQueryAsJSONStringTest() throws Exception {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));

        client().prepareIndex("test", "type1", "1").setSource("field1", "value1_1", "field2", "value2_1").setRefresh(true).get();

        WrapperQueryBuilder wrapper = new WrapperQueryBuilder("{ \"term\" : { \"field1\" : \"value1_1\" } }");
        assertHitCount(client().prepareCount().setQuery(wrapper).get(), 1l);

        BoolQueryBuilder bool = boolQuery().must(wrapper).must(new TermQueryBuilder("field2", "value2_1"));
        assertHitCount(client().prepareCount().setQuery(bool).get(), 1l);
    }

    @Test
    public void testFiltersWithCustomCacheKey() throws Exception {
        createIndex("test");
        ensureGreen();
        client().prepareIndex("test", "type1", "1").setSource("field1", "value1").get();
        refresh();

        CountResponse countResponse = client().prepareCount("test").setQuery(constantScoreQuery(termsFilter("field1", "value1").cacheKey("test1"))).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount("test").setQuery(constantScoreQuery(termsFilter("field1", "value1").cacheKey("test1"))).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount("test").setQuery(constantScoreQuery(termsFilter("field1", "value1"))).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount("test").setQuery(constantScoreQuery(termsFilter("field1", "value1"))).get();
        assertHitCount(countResponse, 1l);
    }

    @Test
    public void testMatchQueryNumeric() throws Exception {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));

        client().prepareIndex("test", "type1", "1").setSource("long", 1l, "double", 1.0d).get();
        client().prepareIndex("test", "type1", "2").setSource("long", 2l, "double", 2.0d).get();
        client().prepareIndex("test", "type1", "3").setSource("long", 3l, "double", 3.0d).get();
        refresh();
        CountResponse countResponse = client().prepareCount().setQuery(matchQuery("long", "1")).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(matchQuery("double", "2")).get();
        assertHitCount(countResponse, 1l);
    }

    @Test
    public void testMultiMatchQuery() throws Exception {

        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));

        client().prepareIndex("test", "type1", "1").setSource("field1", "value1", "field2", "value4", "field3", "value3").get();
        client().prepareIndex("test", "type1", "2").setSource("field1", "value2", "field2", "value5", "field3", "value2").get();
        client().prepareIndex("test", "type1", "3").setSource("field1", "value3", "field2", "value6", "field3", "value1").get();
        refresh();

        MultiMatchQueryBuilder builder = QueryBuilders.multiMatchQuery("value1 value2 value4", "field1", "field2");
        CountResponse countResponse = client().prepareCount().setQuery(builder).get();
        assertHitCount(countResponse, 2l);

        refresh();
        builder = QueryBuilders.multiMatchQuery("value1", "field1", "field2")
                .operator(MatchQueryBuilder.Operator.AND); // Operator only applies on terms inside a field! Fields are always OR-ed together.
        countResponse = client().prepareCount().setQuery(builder).get();
        assertHitCount(countResponse, 1l);

        refresh();
        builder = QueryBuilders.multiMatchQuery("value1", "field1", "field3^1.5")
                .operator(MatchQueryBuilder.Operator.AND); // Operator only applies on terms inside a field! Fields are always OR-ed together.
        countResponse = client().prepareCount().setQuery(builder).get();
        assertHitCount(countResponse, 2l);

        refresh();
        builder = QueryBuilders.multiMatchQuery("value1").field("field1").field("field3", 1.5f)
                .operator(MatchQueryBuilder.Operator.AND); // Operator only applies on terms inside a field! Fields are always OR-ed together.
        countResponse = client().prepareCount().setQuery(builder).get();
        assertHitCount(countResponse, 2l);

        // Test lenient
        client().prepareIndex("test", "type1", "3").setSource("field1", "value7", "field2", "value8", "field4", 5).get();
        refresh();

        builder = QueryBuilders.multiMatchQuery("value1", "field1", "field2", "field4");
        builder.lenient(true);
        countResponse = client().prepareCount().setQuery(builder).get();
        assertHitCount(countResponse, 1l);
    }

    @Test
    public void testMatchQueryZeroTermsQuery() {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1)
            .addMapping("type1", "field1", "type=string,analyzer=classic", "field2", "type=string,analyzer=classic"));
        client().prepareIndex("test", "type1", "1").setSource("field1", "value1").get();
        client().prepareIndex("test", "type1", "2").setSource("field1", "value2").get();
        refresh();

        BoolQueryBuilder boolQuery = boolQuery()
                .must(matchQuery("field1", "a").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.NONE))
                .must(matchQuery("field1", "value1").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.NONE));
        CountResponse countResponse = client().prepareCount().setQuery(boolQuery).get();
        assertHitCount(countResponse, 0l);

        boolQuery = boolQuery()
                .must(matchQuery("field1", "a").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.ALL))
                .must(matchQuery("field1", "value1").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.ALL));
        countResponse = client().prepareCount().setQuery(boolQuery).get();
        assertHitCount(countResponse, 1l);

        boolQuery = boolQuery().must(matchQuery("field1", "a").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.ALL));
        countResponse = client().prepareCount().setQuery(boolQuery).get();
        assertHitCount(countResponse, 2l);
    }

    @Test
    public void testMultiMatchQueryZeroTermsQuery() {
        assertAcked(client().admin().indices().prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1)
                .addMapping("type1", "field1", "type=string,analyzer=classic", "field2", "type=string,analyzer=classic"));
        client().prepareIndex("test", "type1", "1").setSource("field1", "value1", "field2", "value2").get();
        client().prepareIndex("test", "type1", "2").setSource("field1", "value3", "field2", "value4").get();
        refresh();

        BoolQueryBuilder boolQuery = boolQuery()
                .must(multiMatchQuery("a", "field1", "field2").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.NONE))
                .must(multiMatchQuery("value1", "field1", "field2").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.NONE)); // Fields are ORed together
        CountResponse countResponse = client().prepareCount().setQuery(boolQuery).get();
        assertHitCount(countResponse, 0l);

        boolQuery = boolQuery()
                .must(multiMatchQuery("a", "field1", "field2").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.ALL))
                .must(multiMatchQuery("value4", "field1", "field2").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.ALL));
        countResponse = client().prepareCount().setQuery(boolQuery).get();
        assertHitCount(countResponse, 1l);

        boolQuery = boolQuery().must(multiMatchQuery("a", "field1").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.ALL));
        countResponse = client().prepareCount().setQuery(boolQuery).get();
        assertHitCount(countResponse, 2l);
    }

    @Test
    public void testMultiMatchQueryMinShouldMatch() {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));
        client().prepareIndex("test", "type1", "1").setSource("field1", new String[]{"value1", "value2", "value3"}).get();
        client().prepareIndex("test", "type1", "2").setSource("field2", "value1").get();
        refresh();

        MultiMatchQueryBuilder multiMatchQuery = multiMatchQuery("value1 value2 foo", "field1", "field2");

        multiMatchQuery.useDisMax(true);
        multiMatchQuery.minimumShouldMatch("70%");
        CountResponse countResponse = client().prepareCount().setQuery(multiMatchQuery).get();
        assertHitCount(countResponse, 1l);

        multiMatchQuery.minimumShouldMatch("30%");
        countResponse = client().prepareCount().setQuery(multiMatchQuery).get();
        assertHitCount(countResponse, 2l);

        multiMatchQuery.useDisMax(false);
        multiMatchQuery.minimumShouldMatch("70%");
        countResponse = client().prepareCount().setQuery(multiMatchQuery).get();
        assertHitCount(countResponse, 1l);

        multiMatchQuery.minimumShouldMatch("30%");
        countResponse = client().prepareCount().setQuery(multiMatchQuery).get();
        assertHitCount(countResponse, 2l);

        multiMatchQuery = multiMatchQuery("value1 value2 bar", "field1");
        multiMatchQuery.minimumShouldMatch("100%");
        countResponse = client().prepareCount().setQuery(multiMatchQuery).get();
        assertHitCount(countResponse, 0l);

        multiMatchQuery.minimumShouldMatch("70%");
        countResponse = client().prepareCount().setQuery(multiMatchQuery).get();
        assertHitCount(countResponse, 1l);
    }

    @Test
    public void testFuzzyQueryString() {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));
        client().prepareIndex("test", "type1", "1").setSource("str", "kimchy", "date", "2012-02-01", "num", 12).get();
        client().prepareIndex("test", "type1", "2").setSource("str", "shay", "date", "2012-02-05", "num", 20).get();
        refresh();

        CountResponse countResponse = client().prepareCount().setQuery(queryString("str:kimcy~1")).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(queryString("num:11~1")).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(queryString("date:2012-02-02~1d")).get();
        assertHitCount(countResponse, 1l);
    }

    @Test
    public void testSpecialRangeSyntaxInQueryString() {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));
        client().prepareIndex("test", "type1", "1").setSource("str", "kimchy", "date", "2012-02-01", "num", 12).get();
        client().prepareIndex("test", "type1", "2").setSource("str", "shay", "date", "2012-02-05", "num", 20).get();
        refresh();

        CountResponse countResponse = client().prepareCount().setQuery(queryString("num:>19")).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(queryString("num:>20")).get();
        assertHitCount(countResponse, 0l);

        countResponse = client().prepareCount().setQuery(queryString("num:>=20")).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(queryString("num:>11")).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(queryString("num:<20")).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(queryString("num:<=20")).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(queryString("+num:>11 +num:<20")).get();
        assertHitCount(countResponse, 1l);
    }

    @Test
    public void testEmptyTermsFilter() throws Exception {
        assertAcked(prepareCreate("test").addMapping("type", "terms", "type=string"));
        ensureGreen();
        client().prepareIndex("test", "type", "1").setSource("term", "1").get();
        client().prepareIndex("test", "type", "2").setSource("term", "2").get();
        client().prepareIndex("test", "type", "3").setSource("term", "3").get();
        client().prepareIndex("test", "type", "4").setSource("term", "4").get();
        refresh();
        CountResponse countResponse = client().prepareCount("test")
                .setQuery(filteredQuery(matchAllQuery(), termsFilter("term", new String[0]))).get();
        assertHitCount(countResponse, 0l);

        countResponse = client().prepareCount("test")
                .setQuery(filteredQuery(matchAllQuery(), idsFilter())).get();
        assertHitCount(countResponse, 0l);
    }

    @Test
    public void testTermsLookupFilter() throws Exception {
        assertAcked(prepareCreate("lookup").addMapping("type", "terms", "type=string", "other", "type=string"));
        assertAcked(prepareCreate("lookup2").addMapping("type",
                jsonBuilder().startObject().startObject("type").startObject("properties")
                        .startObject("arr").startObject("properties").startObject("term").field("type", "string")
                        .endObject().endObject().endObject().endObject().endObject().endObject()));
        assertAcked(prepareCreate("test").addMapping("type", "term", "type=string"));
        ensureGreen();

        indexRandom(true, client().prepareIndex("lookup", "type", "1").setSource("terms", new String[]{"1", "3"}),
                client().prepareIndex("lookup", "type", "2").setSource("terms", new String[]{"2"}),
                client().prepareIndex("lookup", "type", "3").setSource("terms", new String[]{"2", "4"}),
                client().prepareIndex("lookup", "type", "4").setSource("other", "value"),
                client().prepareIndex("lookup2", "type", "1").setSource(XContentFactory.jsonBuilder().startObject()
                        .startArray("arr")
                        .startObject().field("term", "1").endObject()
                        .startObject().field("term", "3").endObject()
                        .endArray()
                        .endObject()),
                client().prepareIndex("lookup2", "type", "2").setSource(XContentFactory.jsonBuilder().startObject()
                        .startArray("arr")
                        .startObject().field("term", "2").endObject()
                        .endArray()
                        .endObject()),
                client().prepareIndex("lookup2", "type", "3").setSource(XContentFactory.jsonBuilder().startObject()
                        .startArray("arr")
                        .startObject().field("term", "2").endObject()
                        .startObject().field("term", "4").endObject()
                        .endArray()
                        .endObject()),
                client().prepareIndex("test", "type", "1").setSource("term", "1"),
                client().prepareIndex("test", "type", "2").setSource("term", "2"),
                client().prepareIndex("test", "type", "3").setSource("term", "3"),
                client().prepareIndex("test", "type", "4").setSource("term", "4"));

        CountResponse countResponse = client().prepareCount("test")
                .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms"))).get();
        assertHitCount(countResponse, 2l);

        // same as above, just on the _id...
        countResponse = client().prepareCount("test")
                .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("_id").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms"))).get();
        assertHitCount(countResponse, 2l);

        // another search with same parameters...
        countResponse = client().prepareCount("test")
                .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms"))).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount("test")
                .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("2").lookupPath("terms"))).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount("test")
                .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("3").lookupPath("terms"))
                ).get();
        assertNoFailures(countResponse);
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount("test")
                .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("4").lookupPath("terms"))).get();
        assertHitCount(countResponse, 0l);

        countResponse = client().prepareCount("test")
                .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup2").lookupType("type").lookupId("1").lookupPath("arr.term"))).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount("test")
                .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup2").lookupType("type").lookupId("2").lookupPath("arr.term"))).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount("test")
                .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup2").lookupType("type").lookupId("3").lookupPath("arr.term"))).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount("test")
                .setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("not_exists").lookupIndex("lookup2").lookupType("type").lookupId("3").lookupPath("arr.term"))).get();
        assertHitCount(countResponse, 0l);
    }

    @Test
    public void testBasicFilterById() throws Exception {
        createIndex("test");
        ensureGreen();

        client().prepareIndex("test", "type1", "1").setSource("field1", "value1").get();
        client().prepareIndex("test", "type2", "2").setSource("field1", "value2").get();
        refresh();

        CountResponse countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter("type1", "type2").ids("1", "2"))).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter().ids("1", "2"))).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter("type1").ids("1", "2"))).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter().ids("1"))).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter(null).ids("1"))).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter("type1", "type2", "type3").ids("1", "2", "3", "4"))).get();
        assertHitCount(countResponse, 2l);
    }

    @Test
    public void testBasicQueryById() throws Exception {
        createIndex("test");
        ensureGreen();

        client().prepareIndex("test", "type1", "1").setSource("field1", "value1").get();
        client().prepareIndex("test", "type2", "2").setSource("field1", "value2").get();
        refresh();

        CountResponse countResponse = client().prepareCount().setQuery(QueryBuilders.idsQuery("type1", "type2").ids("1", "2")).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.idsQuery().ids("1")).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.idsQuery().ids("1", "2")).get();
        assertHitCount(countResponse, 2l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.idsQuery("type1").ids("1", "2")).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.idsQuery().ids("1")).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.idsQuery(null).ids("1")).get();
        assertHitCount(countResponse, 1l);

        countResponse = client().prepareCount().setQuery(QueryBuilders.idsQuery("type1", "type2", "type3").ids("1", "2", "3", "4")).get();
        assertHitCount(countResponse, 2l);
    }

    @Test
    public void testNumericTermsAndRanges() throws Exception {
        assertAcked(client().admin().indices().prepareCreate("test")
                .setSettings(SETTING_NUMBER_OF_SHARDS, 1)
                .addMapping("type1",
                        "num_byte", "type=byte", "num_short", "type=short",
                        "num_integer", "type=integer", "num_long", "type=long",
                        "num_float", "type=float", "num_double", "type=double"));
        ensureGreen();

        client().prepareIndex("test", "type1", "1").setSource("num_byte", 1, "num_short", 1, "num_integer", 1,
                "num_long", 1, "num_float", 1, "num_double", 1).get();

        client().prepareIndex("test", "type1", "2").setSource("num_byte", 2, "num_short", 2, "num_integer", 2,
                "num_long", 2, "num_float", 2, "num_double", 2).get();

        client().prepareIndex("test", "type1", "17").setSource("num_byte", 17, "num_short", 17, "num_integer", 17,
                "num_long", 17, "num_float", 17, "num_double", 17).get();
        refresh();

        CountResponse countResponse;
        logger.info("--> term query on 1");
        countResponse = client().prepareCount("test").setQuery(termQuery("num_byte", 1)).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(termQuery("num_short", 1)).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(termQuery("num_integer", 1)).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(termQuery("num_long", 1)).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(termQuery("num_float", 1)).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(termQuery("num_double", 1)).get();
        assertHitCount(countResponse, 1l);

        logger.info("--> terms query on 1");
        countResponse = client().prepareCount("test").setQuery(termsQuery("num_byte", new int[]{1})).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(termsQuery("num_short", new int[]{1})).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(termsQuery("num_integer", new int[]{1})).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(termsQuery("num_long", new int[]{1})).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(termsQuery("num_float", new double[]{1})).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(termsQuery("num_double", new double[]{1})).get();
        assertHitCount(countResponse, 1l);

        logger.info("--> term filter on 1");
        countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_byte", 1))).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_short", 1))).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_integer", 1))).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_long", 1))).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_float", 1))).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_double", 1))).get();
        assertHitCount(countResponse, 1l);

        logger.info("--> terms filter on 1");
        countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_byte", new int[]{1}))).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_short", new int[]{1}))).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_integer", new int[]{1}))).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_long", new int[]{1}))).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_float", new int[]{1}))).get();
        assertHitCount(countResponse, 1l);
        countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_double", new int[]{1}))).get();
        assertHitCount(countResponse, 1l);
    }

    @Test // see #2994
    public void testSimpleSpan() throws ElasticsearchException, IOException {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1, SETTING_NUMBER_OF_REPLICAS, 0));
        ensureGreen();

        client().prepareIndex("test", "test", "1").setSource("description", "foo other anything bar").get();
        client().prepareIndex("test", "test", "2").setSource("description", "foo other anything").get();
        client().prepareIndex("test", "test", "3").setSource("description", "foo other").get();
        client().prepareIndex("test", "test", "4").setSource("description", "foo").get();
        refresh();

        CountResponse response = client().prepareCount("test")
                .setQuery(QueryBuilders.spanOrQuery().clause(QueryBuilders.spanTermQuery("description", "bar"))).get();
        assertHitCount(response, 1l);
        response = client().prepareCount("test")
                .setQuery(QueryBuilders.spanOrQuery().clause(QueryBuilders.spanTermQuery("test.description", "bar"))).get();
        assertHitCount(response, 1l);

        response = client().prepareCount("test").setQuery(
                QueryBuilders.spanNearQuery()
                        .clause(QueryBuilders.spanTermQuery("description", "foo"))
                        .clause(QueryBuilders.spanTermQuery("test.description", "other"))
                        .slop(3)).get();
        assertHitCount(response, 3l);
    }
}


text:
class SubCommand(type):
    """
    This metaclass implements an entry point based on a standard
    command-subcommand in which any method belonging to a particular
    superclass that implements it and it starts with "do".

    The class methods that start with "do" will serve as command and by
    decorators and arg option subcommands can be implemented and pass data to
    these subcommands to be processed.

    Example:::

        class CommandTool(object):
            __metaclass__ = Subcommand
            name = "CommandTool"
            description = "A desc for CommandTool"
            epilog = "An epilog for CommandTool"

    :returns: object - A class implementing subcommands pattern.
    """

    def __new__(cls, classname, bases, classdict):
        """
        Class creation.

        Get all methods starting with "do" and put them available as commands.
        """

        # Default subcommands
        subcmds = {}

        for name, func in classdict.items():
            # If method starts with 'do_' is a command.
            if name.startswith('do_'):
                name = name[3:]
                subcmd = {
                    'name': name,
                    'func': func,
                    'options': []
                }
                # Get subcommand custom arguments
                if hasattr(func, 'options'):
                    subcmd['options'] = func.options
                subcmds[name] = subcmd

        classdict['_argparse_subcmds'] = subcmds
        return type.__new__(cls, classname, bases, classdict)

redpajama_set_name: RedPajamaGithub


text:
require "lpad/version"
require "lpad/device/base"

module Lpad
end


text:
class AcDbDatabase;
class AcDbStub;
class AcRxClass;

class AcDbObjectId
{
public:
    AcDbObjectId();
    AcDbObjectId(const AcDbStub*);

    static const   AcDbObjectId  kNull;         // see definition below

    bool           isNull() const;
    void           setNull();

    Adesk::IntDbId     asOldId     () const;
    AcDbObjectId&  setFromOldId(Adesk::IntDbId oldId);
#if (defined(_WIN64) || defined(_AC64)) && defined(_ADESK_WINDOWS_)
  private:
    // catch attempts to store the id in and set it from a 32-bit long
    AcDbObjectId&  setFromOldId(long);  // private and unimplemented
  public:
    // need this overload to allow passing of unsigned 64-bit
    inline AcDbObjectId&  setFromOldId(Adesk::UIntPtr nUnsignedId)
    {
        const Adesk::IntDbId nSignedId =
                        static_cast<Adesk::IntDbId>(nUnsignedId);
        return this->setFromOldId(nSignedId);
    }
#endif

/// <summary>
/// Checks, in a safe way (using an exception handler), whether this AcDbObjectId is valid.
/// Valid ids are non-null and map to a non-null AcDbHandle (and to an AcDbObject) in an
/// existing AcDbDatabase.
/// </summary>
/// <returns>True if the id is valid, false otherwise.
/// </returns>
/// <remarks>Even though an id is valid, the AcDbObject it refers to may fail to open.
///          This method may have performance overhead if called in a tight loop.
/// </remarks>
///
    ACDBCORE2D_PORT bool isValid() const;

/// <summary>
/// Checks, in a safe way (using an exception handler), whether this AcDbObjectId
/// is "well behaved".
/// Well-behaved ids may be null, valid or "stale", or they may be a garbage value
/// which happens to fail gracefully (without crashing) when operated on.
/// </summary>
/// <returns>True if this id is well-behaved, false otherwise.
/// </returns>
/// <remarks>It is safe to call functions like acdbOpenObject() and methods like
///          objectClass(), database() and handle() on any well-behaved id.
///          Non-well-behaved ids, however, can cause crashes in these functions.
///          "Stale" ids are those which were once valid but whose owning
///          AcDbDatabase has been destroyed, making them now invalid
///          This method may have performance overhead if called in a tight loop.
/// </remarks>
///
    ACDBCORE2D_PORT bool isWellBehaved() const;

    AcDbObjectId&  operator =  (const AcDbObjectId&);
    AcDbObjectId&  operator =  (const AcDbStub*);

    bool           operator <  (const AcDbObjectId&) const;
    bool           operator >  (const AcDbObjectId&) const;
    bool           operator >= (const AcDbObjectId&) const;
    bool           operator <= (const AcDbObjectId&) const;
    bool           operator == (const AcDbObjectId&) const;
    bool           operator != (const AcDbObjectId&) const;

    bool           operator <  (const AcDbStub*) const;
    bool           operator >  (const AcDbStub*) const;
    bool           operator >= (const AcDbStub*) const;
    bool           operator <= (const AcDbStub*) const;
    bool           operator == (const AcDbStub*) const;
    bool           operator != (const AcDbStub*) const;

    operator       AcDbStub*   () const;

    AcDbDatabase* database() const;
    AcDbDatabase* originalDatabase() const;

/// <summary>
/// Change this id's value to the host id value, if this id is currently being
/// redirected (forwarded) from an xref database to one in the host database.
/// Otherwise, do nothing.
/// </summary>
/// <returns>True if the id was redirected, otherwise false.
/// </returns>
/// <remarks>Only ids of symbol table records can be redirected
/// </remarks>
///
    ACDBCORE2D_PORT bool convertToRedirectedId();

    bool          isErased() const;
    bool          isEffectivelyErased() const;
    bool          isResident() const;
    bool          objectLeftOnDisk() const;
    AcDbHandle    handle() const;
    AcDbHandle    nonForwardedHandle() const;

    AcRxClass*    objectClass() const;

protected:
    AcDbStub*  mId;
};

class AcDbHardOwnershipId : public AcDbObjectId
{
public:
    AcDbHardOwnershipId();
    AcDbHardOwnershipId(const AcDbObjectId&);
    AcDbHardOwnershipId(const AcDbStub*);

    AcDbHardOwnershipId& operator =(const AcDbHardOwnershipId&);
    AcDbHardOwnershipId& operator =(const AcDbObjectId&);
    AcDbHardOwnershipId& operator =(const AcDbStub*);

    bool           operator != (const AcDbObjectId&) const;
    bool           operator != (const AcDbStub*) const;
    bool           operator == (const AcDbObjectId&) const;
    bool           operator == (const AcDbStub*) const;

    operator AcDbStub* () const;
};

class AcDbSoftOwnershipId : public AcDbObjectId
{
public:
    AcDbSoftOwnershipId();
    AcDbSoftOwnershipId(const AcDbObjectId&);
    AcDbSoftOwnershipId(const AcDbStub*);

    AcDbSoftOwnershipId& operator =(const AcDbSoftOwnershipId&);
    AcDbSoftOwnershipId& operator =(const AcDbObjectId&);
    AcDbSoftOwnershipId& operator =(const AcDbStub*);
    bool           operator != (const AcDbObjectId&) const;
    bool           operator != (const AcDbStub*) const;
    bool           operator == (const AcDbObjectId&) const;
    bool           operator == (const AcDbStub*) const;

    operator AcDbStub* () const;
};

class AcDbHardPointerId : public AcDbObjectId
{
public:
    AcDbHardPointerId();
    AcDbHardPointerId(const AcDbObjectId&);
    AcDbHardPointerId(const AcDbStub*);

    AcDbHardPointerId& operator =(const AcDbHardPointerId&);
    AcDbHardPointerId& operator =(const AcDbObjectId&);
    AcDbHardPointerId& operator =(const AcDbStub*);
    bool           operator != (const AcDbObjectId&) const;
    bool           operator != (const AcDbStub*) const;
    bool           operator == (const AcDbObjectId&) const;
    bool           operator == (const AcDbStub*) const;

    operator AcDbStub* () const;
};

class AcDbSoftPointerId : public AcDbObjectId
{
public:
    AcDbSoftPointerId();
    AcDbSoftPointerId(const AcDbObjectId&);
    AcDbSoftPointerId(const AcDbStub*);

    AcDbSoftPointerId& operator =(const AcDbSoftPointerId&);
    AcDbSoftPointerId& operator =(const AcDbObjectId&);
    AcDbSoftPointerId& operator =(const AcDbStub*);
    bool           operator != (const AcDbObjectId&) const;
    bool           operator != (const AcDbStub*) const;
    bool           operator == (const AcDbObjectId&) const;
    bool           operator == (const AcDbStub*) const;

    operator AcDbStub* () const;
};

#pragma pack(pop)

//////////////////// AcDbObjectId inlines ////////////////////

__declspec(selectany) const AcDbObjectId  AcDbObjectId::kNull;

inline
AcDbObjectId::AcDbObjectId()
{ mId = nullptr; }

//inline
//AcDbObjectId::AcDbObjectId(const AcDbObjectId& id)
//{ mId = id.mId; }

inline
AcDbObjectId::AcDbObjectId(const AcDbStub* pStub)
{ mId = const_cast<AcDbStub*>(pStub); }

inline bool
AcDbObjectId::isNull() const
{ return mId == nullptr; }

inline void
AcDbObjectId::setNull()
{ mId = nullptr; }

inline
Adesk::IntDbId AcDbObjectId::asOldId() const
{
    return reinterpret_cast<Adesk::IntDbId>(this->mId);
}

inline
AcDbObjectId& AcDbObjectId::setFromOldId(Adesk::IntDbId oldId)
{
    this->mId = reinterpret_cast<AcDbStub*>(oldId);
    return *this;
}

inline
AcDbObjectId& AcDbObjectId::operator = (const AcDbObjectId& id)
{ mId = id.mId; return *this; }

inline
AcDbObjectId& AcDbObjectId::operator = (const AcDbStub* pStub)
{ mId = const_cast<AcDbStub*>(pStub); return *this; }

inline
AcDbObjectId::operator AcDbStub* () const
{ return mId; }

inline bool AcDbObjectId::operator < (const AcDbObjectId& id) const
{ return mId < id.mId; }

inline bool AcDbObjectId::operator > (const AcDbObjectId& id) const
{ return mId > id.mId; }

inline bool AcDbObjectId::operator <= (const AcDbObjectId& id) const
{ return mId <= id.mId; }

inline bool AcDbObjectId::operator >= (const AcDbObjectId& id) const
{ return mId >= id.mId; }

inline bool AcDbObjectId::operator == (const AcDbObjectId& id) const
{ return mId == id.mId; }

inline bool AcDbObjectId::operator != (const AcDbObjectId& id) const
{ return mId != id.mId; }

inline bool AcDbObjectId::operator < (const AcDbStub* pStub) const
{ return mId < pStub; }

inline bool AcDbObjectId::operator > (const AcDbStub* pStub) const
{ return mId > pStub; }

inline bool AcDbObjectId::operator <= (const AcDbStub* pStub) const
{ return mId <= pStub; }

inline bool AcDbObjectId::operator >= (const AcDbStub* pStub) const
{ return mId >= pStub; }

inline bool AcDbObjectId::operator == (const AcDbStub* pStub) const
{ return mId == pStub; }

inline bool AcDbObjectId::operator != (const AcDbStub* pStub) const
{ return mId != pStub; }

//////////////////// AcDbHardOwnershipId inlines ////////////////////

inline
AcDbHardOwnershipId::AcDbHardOwnershipId() {}

inline
AcDbHardOwnershipId::AcDbHardOwnershipId(const AcDbObjectId& id)
  : AcDbObjectId(id) {}

inline
AcDbHardOwnershipId::AcDbHardOwnershipId(const AcDbStub* pStub)
  : AcDbObjectId(pStub) {}

inline
AcDbHardOwnershipId& AcDbHardOwnershipId::operator  = (
    const AcDbHardOwnershipId& id)
{ AcDbObjectId::operator=(id); return *this; }

inline
AcDbHardOwnershipId& AcDbHardOwnershipId::operator = (const AcDbObjectId& id)
{ AcDbObjectId::operator=(id); return *this; }

inline
AcDbHardOwnershipId& AcDbHardOwnershipId::operator = (const AcDbStub* pStub)
{ mId = const_cast<AcDbStub*>(pStub); return *this; }

inline
bool AcDbHardOwnershipId::operator != (const AcDbObjectId& id) const
{ return AcDbObjectId::operator!=(id); }

inline
bool AcDbHardOwnershipId::operator != (const AcDbStub* pStub) const
{ return AcDbObjectId::operator!=(pStub); }

inline
bool AcDbHardOwnershipId::operator == (const AcDbObjectId& id) const
{ return AcDbObjectId::operator==(id); }

inline
bool AcDbHardOwnershipId::operator == (const AcDbStub* pStub) const
{ return AcDbObjectId::operator==(pStub); }

inline
AcDbHardOwnershipId::operator AcDbStub* () const
{ return mId; }

//////////////////// AcDbSoftOwnershipId inlines ////////////////////

inline
AcDbSoftOwnershipId::AcDbSoftOwnershipId() {}

inline
AcDbSoftOwnershipId::AcDbSoftOwnershipId(const AcDbObjectId& id)
  : AcDbObjectId(id) {}

inline
AcDbSoftOwnershipId::AcDbSoftOwnershipId(const AcDbStub* pStub)
  : AcDbObjectId(pStub) {}

inline
AcDbSoftOwnershipId& AcDbSoftOwnershipId::operator = (
    const AcDbSoftOwnershipId& id)
{ AcDbObjectId::operator=(id); return *this; }

inline
AcDbSoftOwnershipId& AcDbSoftOwnershipId::operator = (const AcDbObjectId& id)
{ AcDbObjectId::operator=(id); return *this; }

inline
AcDbSoftOwnershipId& AcDbSoftOwnershipId::operator = (const AcDbStub* pStub)
{ mId = const_cast<AcDbStub*>(pStub); return *this; }

inline
bool AcDbSoftOwnershipId::operator != (const AcDbObjectId& id) const
{ return AcDbObjectId::operator!=(id); }

inline
bool AcDbSoftOwnershipId::operator != (const AcDbStub* pStub) const
{ return AcDbObjectId::operator!=(pStub); }

inline
bool AcDbSoftOwnershipId::operator == (const AcDbObjectId& id) const
{ return AcDbObjectId::operator==(id); }

inline
bool AcDbSoftOwnershipId::operator == (const AcDbStub* pStub) const
{ return AcDbObjectId::operator==(pStub); }

inline
AcDbSoftOwnershipId::operator AcDbStub* () const
{ return mId; }

//////////////////// AcDbHardPointerId inlines ////////////////////

inline
AcDbHardPointerId::AcDbHardPointerId() {}

inline
AcDbHardPointerId::AcDbHardPointerId(const AcDbObjectId& id)
  : AcDbObjectId(id) {}

inline
AcDbHardPointerId::AcDbHardPointerId(const AcDbStub* pStub)
  : AcDbObjectId(pStub) {}

inline
AcDbHardPointerId& AcDbHardPointerId::operator = (
    const AcDbHardPointerId& id)
{ AcDbObjectId::operator=(id); return *this; }

inline
AcDbHardPointerId& AcDbHardPointerId::operator = (const AcDbObjectId& id)
{ AcDbObjectId::operator=(id); return *this; }

inline
AcDbHardPointerId& AcDbHardPointerId::operator = (const AcDbStub* pStub)
{ mId = const_cast<AcDbStub*>(pStub); return *this; }

inline
bool AcDbHardPointerId::operator != (const AcDbObjectId& id) const
{ return AcDbObjectId::operator!=(id); }

inline
bool AcDbHardPointerId::operator != (const AcDbStub* pStub) const
{ return AcDbObjectId::operator!=(pStub); }

inline
bool AcDbHardPointerId::operator == (const AcDbObjectId& id) const
{ return AcDbObjectId::operator==(id); }

inline
bool AcDbHardPointerId::operator == (const AcDbStub* pStub) const
{ return AcDbObjectId::operator==(pStub); }

inline
AcDbHardPointerId::operator AcDbStub* () const
{ return mId; }

//////////////////// AcDbSoftPointerId inlines ////////////////////

inline
AcDbSoftPointerId::AcDbSoftPointerId() {}

inline
AcDbSoftPointerId::AcDbSoftPointerId(const AcDbObjectId& id)
  : AcDbObjectId(id) {}

inline
AcDbSoftPointerId::AcDbSoftPointerId(const AcDbStub* pStub)
  : AcDbObjectId(pStub) {}

inline
AcDbSoftPointerId& AcDbSoftPointerId::operator = (const AcDbSoftPointerId& id)
{ AcDbObjectId::operator=(id); return *this; }

inline
AcDbSoftPointerId& AcDbSoftPointerId::operator = (const AcDbObjectId& id)
{ AcDbObjectId::operator=(id); return *this; }

inline
AcDbSoftPointerId& AcDbSoftPointerId::operator = (const AcDbStub* pStub)
{ mId = const_cast<AcDbStub*>(pStub); return *this; }

inline
bool AcDbSoftPointerId::operator != (const AcDbObjectId& id) const
{ return AcDbObjectId::operator!=(id); }

inline
bool AcDbSoftPointerId::operator != (const AcDbStub* pStub) const
{ return AcDbObjectId::operator!=(pStub); }

inline
bool AcDbSoftPointerId::operator == (const AcDbObjectId& id) const
{ return AcDbObjectId::operator==(id); }

inline
bool AcDbSoftPointerId::operator == (const AcDbStub* pStub) const
{ return AcDbObjectId::operator==(pStub); }

inline
AcDbSoftPointerId::operator AcDbStub* () const
{ return mId; }

#define ADSK_ACDBOBJECTID_DEFINED
#include "acarrayhelper.h"

#endif


text:
{% load static from staticfiles %}
{% load markup %}
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>{{ app_name }} {{ flatpage.title }}</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta name="description" content="">
		<meta name="author" content="Stefano Tranquillini">
		<meta name="keywords" content="">

		<link rel="icon"
		type="image/png"
		href="{% static "img/icon.png" %}">
		<link href="{% static "css/bootstrap.css" %}" rel="stylesheet">
		<link rel="stylesheet" href="{% static "css/font-awesome.css" %}">
		<link rel="stylesheet" href="{% static "css/style.css" %}">

		{%block script_head %}

		{% endblock %}

		{% block navabar %}

					{{ app_name }}

					{% if user.is_authenticated %}

						{% load flatpages %}
						{% get_flatpages as flatpages %}
						{% for page in flatpages %}

							{{ page.title }}

						{% endfor %}

					{% endif %}

		{% endblock %}

				{% if messages %}
				{% for message in messages %}

					<button type="button" class="close" data-dismiss="alert">
						×
					</button>

{{message.tags}}

					{{ message }}

				{% endfor %}
				{% endif %}
				{%block container %}
				{{ flatpage.content|markdown	 }}
				{% endblock %}

				<button class="close" data-dismiss="modal">
					×
				</button>

				<button class="btn btn-success" data-dismiss="modal">
					ok
				</button>

		{%block script_footer %}

		{% endblock %}
		{% include 'footer.html' %}


text:
import pytest
from swagip import app

@pytest.fixture(scope='module')
def client():
    client = app.test_client()
    return client


text:
=head1 NAME

VCP::Newlines - Newline, ^Z, and NULL handling in VCP

=head1 DESCRIPTION

Newlines can be a bear to debug, since most display programs hide the
difference between C<\r\n>, C<\r>, and C<\n> from you.

VCP copes with newlines thusly:

=over

=item 1.

When reading/writing repositories (Cvs, Perforce, etc), it lets them sweat
the details.

=item 2.

RevML text (non-binary) files always use single newline "\n" endings internally
for both content and patches.  Due to XML handling, any "\r\n" or "\r"
sequences that sneak in to an XML file get converted to "\n" anyway.

=item 3.

RevML binary files use an escape like <char code="0x0d"/> to encode carriage
returns and other character codes illegal in XML texts.

=item 4.

L<VCP::Source::revml|VCP::Source::revml> can be asked to convert "\n" to "\r\n"
on the fly in text files.  It never does this by default because most
modern-day editors do the right thing (C<notepad.exe> is *not* modern day :).

=item 5.

L<VCP::Dest::revml|VCP::Dest::revml> always converts "\r\n" and "\r" in to "\n"
for consistancy's sake, so the RevML file extracted on a Windows machine should
be identical (or at least more nearly so) to one extracted on a Unix machine.
The metadata might differ a bit, of course, but at least the content won't.

=back

Embedded Control-Z characters C<^Z> (ASCII 26) are passed through, as are
embedded NULLs.  Both the diff and patch code are ^Z and NULL clean as well
(unlike many).

C<vcp> treats all files as binary files and uses it's own C<\r\n> conversion
routines specifically to be able to pass C<^Z> through unmolested, since not
passing things through can mess up both end users with loitering C<^Z>
characters and C<vcp>'s checksums.

If you think you have issues like these, see the document
L<VCP::Maintenance|VCP::Maintenance> for some options and tools that can help
when debugging.

=cut


text:
module Rack
  module Handler
    class David
      def self.run(app, options={})
        g = Celluloid::SupervisionGroup.run!

        g.supervise_as(:server, ::David::Server, app, options)
        g.supervise_as(:gc, ::David::GarbageCollector)

        unless options[:Observe] == 'false'
          g.supervise_as(:observe, ::David::Observe)
        end

        begin
          Celluloid::Actor[:server].run
        rescue Interrupt
          Celluloid.logger.info 'Terminated'
          Celluloid.logger = nil
          g.terminate
        end
      end

      def self.valid_options
        host, port = AppConfig::DEFAULT_OPTIONS.values_at(:Host, :Port)

        {
          'Block=BOOLEAN'     => 'Support for blockwise transfer (default: true)',
          'CBOR=BOOLEAN'      => 'Transparent JSON/CBOR conversion (default: false)',
          'DefaultFormat=F'   => 'Content-Type if CoAP accept option on request is undefined',
          'Host=HOST'         => "Hostname to listen on (default: #{host})",
          'Log=LOG'           => 'Change logging (debug|none)',
          'Multicast=BOOLEAN' => 'Multicast support (default: true)',
          'Observe=BOOLEAN'   => 'Observe support (default: true)',
          'Port=PORT'         => "Port to listen on (default: #{port})"
        }
      end
    end

    register(:david, David)
  end
end


text:
import re
from bookmarks.cmdparse import bk_urlencode

OLD_EXT_ID = "mytools.BookmarksMenu"
OLD_COMMAND = "mytools:BookmarskMenu"

OLD_BOOKMARKS_LIB = "BookmarksMenu"
OLD_SHELLCOMMANDS_MODULE = "ShellCommands"

OLD_MACRO_MODULE = OLD_BOOKMARKS_LIB + "." + OLD_SHELLCOMMANDS_MODULE

OLD_MACRO_SHELL = "ShellOpenFile"
OLD_MACRO_EXECUTE = "ExecuteCommand"
OLD_MACRO_OPEN = "OpenWithSpecifiedDirectory"
OLD_MACRO_SAVEAS = "SaveAsWithSpecifiedDirectory"

OLD_ADDTHIS = "mytools_BookmarksMenu.Module4.AddCurrentDocument"
OLD_EDIT = "mytools_BookmarksMenu.Module1.Main"

from bookmarks.bookmark import Separator, Item, Container
from bookmarks.command import BookmarksCommands

class Migration(object):
    """ Migrate from older bookmarks menu. """

    SUB_EXP = re.compile("Sub ([^\n]*)$(.*?)^End Sub", re.I + re.M + re.S)
    TWO_ARGS_EXP = re.compile("\"(.*?)\", \"(.*?)\"")
    ONE_ARG_EXP = re.compile("\"(.*?)\"")

    def __init__(self, ctx):
        self.ctx = ctx

    def create_service(self, name, args=None):
        if args:
            return self.ctx.getServiceManager().\
                createInstanceWithArgumentsAndContext(name, args, self.ctx)
        else:
            return self.ctx.getServiceManager().\
                createInstanceWithContext(name, self.ctx)

    def check(self):
        """ To find older bookmarks in the menu. """
        self.config_supplier = self.create_service(
            "com.sun.star.ui.ModuleUIConfigurationManagerSupplier")
        manager = self.config_supplier.getUIConfigurationManager(
            "com.sun.star.text.TextDocument")
        self.menu_settings = manager.getSettings(
            "private:resource/menubar/menubar", False)

        self.container = self.find_bookmarks(self.menu_settings)
        return not self.container is None

    def migrate(self):
        """ Starting to migrate and generate items. """
        self.macro = None
        self.macros = None
        self.commands = BookmarksCommands()
        self.load_macro()
        self.parse_macro()
        items = self.convert_item(self.container)
        return items

    def find_bookmarks(self, settings):
        """ Find older bookmarks top menu. """
        for i in range(self.menu_settings.getCount()):
            item = self.menu_settings.getByIndex(i)
            command, label, type, container = self.read_item(item)
            if command == OLD_COMMAND:
                return item

    def read_item(self, item):
        """ Get velue from menu item. """
        label = ""
        command = ""
        container = None
        type = None
        for value in item:
            if value.Name == "CommandURL":
                command = value.Value
            elif value.Name == "ItemDescriptorContainer":
                container = value.Value
            elif value.Name == "Label":
                label = value.Value
            elif value.Name == "Type":
                type = value.Value
            #else:
            #   print(value.Name)
            #print(value.Name)
        return command, label, type, container

    def load_macro(self):
        """ Load old bookmarks macro generated automatically. """
        lib = self.get_macro_lib()
        if lib:
            if lib.hasByName(OLD_SHELLCOMMANDS_MODULE):
                self.macro = lib.getByName(OLD_SHELLCOMMANDS_MODULE)

    def get_macro_lib(self):
        """ Load macro source from application library. """
        libs = self.create_service(
            "com.sun.star.script.ApplicationScriptLibraryContainer")
        if libs.hasByName(OLD_BOOKMARKS_LIB):
            libs.loadLibrary(OLD_BOOKMARKS_LIB)
            return libs.getByName(OLD_BOOKMARKS_LIB)
        return None

    def parse_macro(self):
        """ Split macro in each subroutine. """
        if self.macro:
            macros = {}
            for m in self.SUB_EXP.finditer(self.macro):
                if m:
                    macros[m.group(1)] = m.group(2)
            self.macros = macros

    def convert_item(self, item):
        """ Convert entry to bookmarks item in new format. """
        command, label, type, container = self.read_item(item)
        if container:
            command, label, type, container = self.read_item(item)
            c = Container(label, "")
            children = c.children
            for i in range(container.getCount()):
                _child = self.convert_item(container.getByIndex(i))
                if _child:
                    children.append(_child)
            return c
        elif type == 0:
            try:
                return Item(label, "", self.convert_command(command))
            except:
                return None
        else:
            return Separator()

    def convert_command(self, command):
        """ Convert old command to new format. """
        if command.startswith(BookmarksCommands.PROTOCOL_SCRIPT):
            # check ShellCommands
            return self.convert_macro(command)

        elif command.startswith(BookmarksCommands.PROTOCOL_MACRO):
            return command

        elif command.startswith(".uno"):
            if command.startswith(".uno:Open"):
                parts = command.split("?", 1)
                if len(parts) == 2:
                    queries = [i.split("=") for i in parts[1].split("&")]
                    d = {}
                    d["type"] = "document"
                    for key, value in queries:
                        if key == self.commands.QUERY_NAME_URL:
                            d["path"] = value
                    return self.commands.generate_command(d)

            elif command.find("?") >= 0:
                parts = command.split("?", 1)
                if len(parts) == 2:
                    queries = [i.split("=") for i in parts[1].split("&")]
                    q = bk_urlencode(dict(queries))
                    return parts[0] + q
            return command

    def convert_macro(self, command):
        """ Convert macro entry with data from macros. """
        parts = command.split(":", 1)
        if len(parts) == 2:
            parts = parts[1].split("?", 1)
            if len(parts) == 2:
                path = parts[0]
                if path in (OLD_ADDTHIS, OLD_EDIT):
                    raise Exception("This item is ignored: %s" % command)
                elif path.startswith(OLD_MACRO_MODULE):
                    _path = path[len(OLD_MACRO_MODULE)+1:]
                    try:
                        return self.generate_command_from_macro(
                                            _path, self.macros[_path])
                    except:
                        pass
        return command

    def generate_command_from_macro(self, path, macro):
        """ Generate command from type and its macro. """
        if path.startswith(OLD_MACRO_SHELL):
            path, args = self.get_arguments_pair(OLD_MACRO_SHELL, macro)
            d = {"type": "something", "flag": "file"}
            d["path"] = path
            return self.commands.generate_command(d)

        elif path.startswith(OLD_MACRO_EXECUTE):
            prog, args = self.get_arguments_pair(OLD_MACRO_EXECUTE, macro)
            if prog in ("xdg-open", "open", "kfmclient openURL", "explorer.exe"):
                d = {"type": "something", "flag": "folder"}
                d["path"] = args
            else:
                d = {"type": "program"}
                d["path"] = prog
                d["arguments"] = args
            return self.commands.generate_command(d)

        elif path.startswith(OLD_MACRO_OPEN):
            path = self.get_argument(OLD_MACRO_OPEN, macro)
            d = {"type": "special", "flag": "open_from_folder"}
            d["path"] = path
            return self.commands.generate_command(d)

        elif path.startswith(OLD_MACRO_SAVEAS):
            path = self.get_argument(OLD_MACRO_SAVEAS, macro)
            d = {"type": "special", "flag": "saveas_into_folder"}
            d["path"] = path
            return self.commands.generate_command(d)

    def get_arguments_pair(self, name, macro):
        """ Get arguments from macro. """
        index = macro.find(name)
        if index >= 0:
            found = macro[index+len(name):]
            m = self.TWO_ARGS_EXP.search(found)
            if m:
                return m.group(1), m.group(2)
        return "", ""

    def get_argument(self, name, macro):
        """ Get an argument from macro. """
        index = macro.find(name)
        if index >= 0:
            found = macro[index+len(name):]
            m = self.ONE_ARG_EXP.search(found)
            if m:
                return m.group(1)
        return ""


text:
FOUNDATION_EXPORT double Pods_EnsemblesTestingTestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_EnsemblesTestingTestsVersionString[];


text:
FROM java:openjdk-8-jdk

MAINTAINER chgeuer <chgeuer@microsoft.com>

ENV SCALA_VERSION 2.11
ENV SCALA_VERSION_LONG 2.11.7
ENV HADOOP_VERSION 2.7.0
ENV HADOOP_VERSION_SHORT 27
ENV FLINK_VERSION 1.2.0
ENV FLINK_ROOT_DIR /opt/flink

RUN apt-get -y upgrade && apt-get -y update && \
    apt-get -y install gnupg apt-transport-https rsync && \
    curl --get --url http://www.scala-lang.org/files/archive/scala-${SCALA_VERSION_LONG}.deb --output scala-${SCALA_VERSION_LONG}.deb && \
    dpkg -i scala-${SCALA_VERSION_LONG}.deb && \
    rm -f scala-${SCALA_VERSION_LONG}.deb && \
    echo "deb https://dl.bintray.com/sbt/debian /" | tee -a /etc/apt/sources.list.d/sbt.list && \
    apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2EE0EA64E40A89B84B2DF73499E82A75642AC823 && \
    apt-get -y update && \
    ln -s $JAVA_HOME/lib $JAVA_HOME/conf && \
    apt-get install sbt && \
    apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* && \
    echo                                                           && \
    echo                                                           && \
    echo                                                           && \
    echo                                                           && \
    mkdir -p /opt && \
    cd /opt && \
    curl --get --url http://www.us.apache.org/dist/hadoop/common/hadoop-${HADOOP_VERSION}/hadoop-${HADOOP_VERSION}.tar.gz --output hadoop.tgz && \
    mkdir -p hadoop-${HADOOP_VERSION} && \
    tar xvfz hadoop.tgz -C hadoop-${HADOOP_VERSION} && \
    rm hadoop.tgz && \
    ln -s hadoop-${HADOOP_VERSION} hadoop && \
    echo Hadoop ${HADOOP_VERSION} native libraries installed in /opt/hadoop && \
    echo                                                           && \
    echo                                                           && \
    echo                                                           && \
    echo                                                           && \
    cd /opt && \
    curl --get --url http://www.us.apache.org/dist/flink/flink-${FLINK_VERSION}/flink-${FLINK_VERSION}-bin-hadoop${HADOOP_VERSION_SHORT}-scala_${SCALA_VERSION}.tgz --output flink.tgz && \
    tar xvfz flink.tgz -C /opt && \
    rm flink.tgz && \
    ln -s /opt/flink-${FLINK_VERSION} ${FLINK_ROOT_DIR} && \
    echo Flink ${FLINK_VERSION} installed in ${FLINK_ROOT_DIR}

ADD log4j.properties logback.xml ${FLINK_ROOT_DIR}/conf/
ADD start-common.sh start-worker.sh start-master.sh ${FLINK_ROOT_DIR}/bin/
ADD flink-conf.yaml ${FLINK_ROOT_DIR}/conf/flink-conf.yaml

ENV PATH $PATH:${FLINK_ROOT_DIR}/bin


text:
package com.sharksharding.sql.dialect.mysql.ast;

public interface MySqlIndexHint extends MySqlHint {
    public static enum Option {
        JOIN("JOIN"),
        ORDER_BY("ORDER BY"),
        GROUP_BY("GROUP BY")
        ;

        public final String name;

        Option(String name) {
            this.name = name;
        }
    }
}


text:
<?php

namespace Estrutura\Service;

class HtmlHelper{
    public static function botaoLink($url, $icone, $attributos=[], $title='Alterar'){
        $attributos = self::arrayToString($attributos);

        $botao = '
                     <button title="'. $title .'" type="button" class="btn btn-default">

                     </button>
                  ';

        return $botao;
    }

    public static function botaoNovo($url, $title='Novo'){
        $attributos = ['class'=>'btn-novo btn-xs', 'id'=>'botaonovo'];
        return self::botaoLink($url, 'glyphicon glyphicon-remove-sign', $attributos, $title);
    }

    public static function botaoExcluir($url, $title='Excluir'){
        $attributos = ['class'=>'btn-excluir btn-xs', 'id'=>'botaoexcluir'];
        return self::botaoLink($url, 'glyphicon glyphicon-remove-sign', $attributos, $title);
    }

    public static function botaoAlterar($url, $title='Modificar'){
        $attributos = ['class'=>'btn-alterar btn-xs', 'id'=>'botaoalterar'];
        return self::botaoLink($url, 'glyphicon glyphicon-edit', $attributos, $title);
    }

    public static function botaoDesativar($url, $title='Desativar', $icone_bootstrap = 'glyphicon glyphicon-off', $id = 'botaodesativar'){
        $attributos = ['class'=>'btn-desativar btn-xs', 'id'=>$id];
        return self::botaoLink($url, $icone_bootstrap, $attributos, $title);
    }

    public static function botaoAlterarCustomizado($url, $title='Modificar'){
        $attributos = ['class'=>'btn-alterar btn-xs btn-alterar-customizado', 'id'=>'botaomodificar'];
        return self::botaoLink($url, 'glyphicon glyphicon-user', $attributos, $title);
    }

    public static function botaoDownload($url, $title='Ação', $id = 'botaoacao', $icone_bootstrap = 'glyphicon glyphicon-screenshot', $classe = 'btn btn-default'){
        $attributos = ['class'=>$classe, 'id'=>$id];
        #$attributos = ['class'=>'btn-alterar btn-xs btn-alterar-customizado', 'id'=>$id];
        return self::botaoLink($url, $icone_bootstrap, $attributos, $title, " target='_blank'");
    }
    private static function arrayToString($array){
        $string = '';
        foreach($array as $chave => $item){
            $string .= "{$chave}='{$item}' ";
        }
        return $string;
    }
}


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

package org.camunda.bpm.engine.impl.dmn.cmd;

import java.io.InputStream;
import java.io.Serializable;
import java.util.concurrent.Callable;
import org.camunda.bpm.engine.impl.cmd.GetDeploymentResourceCmd;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.repository.DecisionDefinition;

/**
 * Gives access to a deployed decision diagram, e.g., a PNG image, through a stream of bytes.
 */
public class GetDeploymentDecisionDiagramCmd implements Command<InputStream>, Serializable {

  private static final long serialVersionUID = 1L;

  protected String decisionDefinitionId;

  public GetDeploymentDecisionDiagramCmd(String decisionDefinitionId) {
    this.decisionDefinitionId = decisionDefinitionId;
  }

  public InputStream execute(final CommandContext commandContext) {
    DecisionDefinition decisionDefinition = new GetDeploymentDecisionDefinitionCmd(decisionDefinitionId).execute(commandContext);

    final String deploymentId = decisionDefinition.getDeploymentId();
    final String resourceName = decisionDefinition.getDiagramResourceName();

    if (resourceName != null ) {
      return commandContext.runWithoutAuthorization(new Callable<InputStream>() {
        public InputStream call() throws Exception {
          return new GetDeploymentResourceCmd(deploymentId, resourceName).execute(commandContext);
        }
      });
    }
    else {
      return null;
    }
  }

}


text:
describe 'API Spec' do
  subject do
    Class.new(Grape::API) do
      params do
        optional :root, default: ''
      end
      get '/posts' do
        status 200
        root = params[:root]
        root = false if params[:root] == 'false'
        root = nil if params[:root] == ''
        if root.nil?
          present Post.all.entity.to_json
        else
          present Post.all.entity(root: root).to_json
        end
      end
    end
  end

  def app
    subject
  end

  it 'check getting one object entity without root' do
    create(:post)
    get '/posts', root: 'false'
    expect(last_response.status).to eq(200)
    expect(JSON.parse(last_response.body)).to eq([{"title"=>"Some title"}])
  end
  it 'check getting one object entity with changed root' do
    create(:post)
    get '/posts', root: 'postik'
    expect(last_response.status).to eq(200)
    expect(JSON.parse(last_response.body)).to eq({"postik"=>[{"title"=>"Some title"}]})
  end
  it 'check getting one object entity' do
    create(:post)
    get '/posts'
    expect(last_response.status).to eq(200)
    expect(JSON.parse(last_response.body)).to eq({"posts"=>[{"title"=>"Some title"}]})
  end
  it 'check getting relation entity with changed root' do
    3.times { create(:post) }
    get '/posts', root: 'postes'
    expect(last_response.status).to eq(200)
    expect(JSON.parse(last_response.body)).to eq({"postes"=>[{"title"=>"Some title"}, {"title"=>"Some title"}, {"title"=>"Some title"}]})
  end

end


text:
require 'spec_helper'

describe ChunkyPNG::Canvas::Masking do

  subject { reference_canvas('clock') }

  before(:all) do
    @theme_color      = ChunkyPNG::Color('#e10f7a')
    @new_color        = ChunkyPNG::Color('#ff0000')
    @background_color = ChunkyPNG::Color('white')
  end

  describe '#change_theme_color!' do
    it "should change the theme color correctly" do
      subject.change_theme_color!(@theme_color, @new_color)
      subject.should == reference_canvas('clock_updated')
    end
  end

  describe '#extract_mask' do
    it "should create the correct base and mask image" do
      base, mask = subject.extract_mask(@theme_color, @background_color)
      base.should == reference_canvas('clock_base')
      mask.should == reference_canvas('clock_mask')
    end

    it "should create a mask image with only one opaque color" do
      base, mask = subject.extract_mask(@theme_color, @background_color)
      mask.palette.opaque_palette.size.should == 1
    end
  end

  describe '#change_mask_color!' do
    before { @mask = reference_canvas('clock_mask') }

    it "should replace the mask color correctly" do
      @mask.change_mask_color!(@new_color)
      @mask.should == reference_canvas('clock_mask_updated')
    end

    it "should still only have one opaque color" do
      @mask.change_mask_color!(@new_color)
      @mask.palette.opaque_palette.size.should == 1
    end

    it "should raise an exception when the mask image has more than once color" do
      not_a_mask = reference_canvas('operations')
      lambda { not_a_mask.change_mask_color!(@new_color) }.should raise_error(ChunkyPNG::ExpectationFailed)
    end
  end
end