text:
package org.elasticsearch.join.query;

import org.apache.lucene.search.join.ScoreMode;
import org.apache.lucene.util.ArrayUtil;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.InnerHitBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.MockScriptPlugin;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.extractValue;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.index.query.QueryBuilders.nestedQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO;
import static org.elasticsearch.join.query.JoinQueryBuilders.hasChildQuery;
import static org.elasticsearch.join.query.JoinQueryBuilders.hasParentQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHit;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHits;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.hasId;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;

public class InnerHitsIT extends ParentChildTestCase {

    @Override
    protected Collection<Class<? extends Plugin>> nodePlugins() {
        ArrayList<Class<? extends Plugin>> plugins = new ArrayList<>(super.nodePlugins());
        plugins.add(CustomScriptPlugin.class);
        return plugins;
    }

    public static class CustomScriptPlugin extends MockScriptPlugin {
        @Override
        protected Map<String, Function<Map<String, Object>, Object>> pluginScripts() {
            return Collections.singletonMap("5", script -> "5");
        }
    }

    public void testSimpleParentChild() throws Exception {
        if (legacy()) {
            assertAcked(prepareCreate("articles")
                .addMapping("article", "title", "type=text")
                .addMapping("comment", "_parent", "type=article", "message", "type=text,fielddata=true")
            );
        } else {
            assertAcked(prepareCreate("articles")
                .addMapping("doc", jsonBuilder().startObject().startObject("doc").startObject("properties")
                    .startObject("join_field")
                        .field("type", "join")
                        .startObject("relations")
                            .field("article", "comment")
                        .endObject()
                    .endObject()
                    .startObject("title")
                        .field("type", "text")
                    .endObject()
                    .startObject("message")
                        .field("type", "text")
                        .field("fielddata", true)
                    .endObject()
                    .endObject().endObject().endObject()
                ));
        }

        List<IndexRequestBuilder> requests = new ArrayList<>();
        requests.add(createIndexRequest("articles", "article", "p1", null, "title", "quick brown fox"));
        requests.add(createIndexRequest("articles", "comment", "c1", "p1", "message", "fox eat quick"));
        requests.add(createIndexRequest("articles", "comment", "c2", "p1", "message", "fox ate rabbit x y z"));
        requests.add(createIndexRequest("articles", "comment", "c3", "p1", "message", "rabbit got away"));
        requests.add(createIndexRequest("articles", "article", "p2", null, "title", "big gray elephant"));
        requests.add(createIndexRequest("articles", "comment", "c4", "p2", "message", "elephant captured"));
        requests.add(createIndexRequest("articles", "comment", "c5", "p2", "message", "mice squashed by elephant x"));
        requests.add(createIndexRequest("articles", "comment", "c6", "p2", "message", "elephant scared by mice x y"));
        indexRandom(true, requests);

        SearchResponse response = client().prepareSearch("articles")
            .setQuery(hasChildQuery("comment", matchQuery("message", "fox"), ScoreMode.None)
                .innerHit(new InnerHitBuilder()))
            .get();
        assertNoFailures(response);
        assertHitCount(response, 1);
        assertSearchHit(response, 1, hasId("p1"));
        assertThat(response.getHits().getAt(0).getShard(), notNullValue());

        assertThat(response.getHits().getAt(0).getInnerHits().size(), equalTo(1));
        SearchHits innerHits = response.getHits().getAt(0).getInnerHits().get("comment");
        assertThat(innerHits.getTotalHits(), equalTo(2L));

        assertThat(innerHits.getAt(0).getId(), equalTo("c1"));
        assertThat(innerHits.getAt(0).getType(), equalTo(legacy() ? "comment" : "doc"));
        assertThat(innerHits.getAt(1).getId(), equalTo("c2"));
        assertThat(innerHits.getAt(1).getType(), equalTo(legacy() ? "comment" : "doc"));

        final boolean seqNoAndTerm = randomBoolean();
        response = client().prepareSearch("articles")
            .setQuery(hasChildQuery("comment", matchQuery("message", "elephant"), ScoreMode.None)
                .innerHit(new InnerHitBuilder().setSeqNoAndPrimaryTerm(seqNoAndTerm)))
            .get();
        assertNoFailures(response);
        assertHitCount(response, 1);
        assertSearchHit(response, 1, hasId("p2"));

        assertThat(response.getHits().getAt(0).getInnerHits().size(), equalTo(1));
        innerHits = response.getHits().getAt(0).getInnerHits().get("comment");
        assertThat(innerHits.getTotalHits(), equalTo(3L));

        assertThat(innerHits.getAt(0).getId(), equalTo("c4"));
        assertThat(innerHits.getAt(0).getType(), equalTo(legacy() ? "comment" : "doc"));
        assertThat(innerHits.getAt(1).getId(), equalTo("c5"));
        assertThat(innerHits.getAt(1).getType(), equalTo(legacy() ? "comment" : "doc"));
        assertThat(innerHits.getAt(2).getId(), equalTo("c6"));
        assertThat(innerHits.getAt(2).getType(), equalTo(legacy() ? "comment" : "doc"));

        if (seqNoAndTerm) {
            assertThat(innerHits.getAt(0).getPrimaryTerm(), equalTo(1L));
            assertThat(innerHits.getAt(1).getPrimaryTerm(), equalTo(1L));
            assertThat(innerHits.getAt(2).getPrimaryTerm(), equalTo(1L));
            assertThat(innerHits.getAt(0).getSeqNo(), greaterThanOrEqualTo(0L));
            assertThat(innerHits.getAt(1).getSeqNo(), greaterThanOrEqualTo(0L));
            assertThat(innerHits.getAt(2).getSeqNo(), greaterThanOrEqualTo(0L));
        } else {
            assertThat(innerHits.getAt(0).getPrimaryTerm(), equalTo(UNASSIGNED_PRIMARY_TERM));
            assertThat(innerHits.getAt(1).getPrimaryTerm(), equalTo(UNASSIGNED_PRIMARY_TERM));
            assertThat(innerHits.getAt(2).getPrimaryTerm(), equalTo(UNASSIGNED_PRIMARY_TERM));
            assertThat(innerHits.getAt(0).getSeqNo(), equalTo(UNASSIGNED_SEQ_NO));
            assertThat(innerHits.getAt(1).getSeqNo(), equalTo(UNASSIGNED_SEQ_NO));
            assertThat(innerHits.getAt(2).getSeqNo(), equalTo(UNASSIGNED_SEQ_NO));
        }

        response = client().prepareSearch("articles")
            .setQuery(
                hasChildQuery("comment", matchQuery("message", "fox"), ScoreMode.None).innerHit(
                    new InnerHitBuilder()
                        .addDocValueField("message")
                        .setHighlightBuilder(new HighlightBuilder().field("message"))
                        .setExplain(true).setSize(1)
                        .addScriptField("script", new Script(ScriptType.INLINE, MockScriptEngine.NAME, "5",
                            Collections.emptyMap())))
            ).get();
        assertNoFailures(response);
        innerHits = response.getHits().getAt(0).getInnerHits().get("comment");
        assertThat(innerHits.getHits().length, equalTo(1));
        assertThat(innerHits.getAt(0).getHighlightFields().get("message").getFragments()[0].string(), equalTo("fox eat quick"));
        assertThat(innerHits.getAt(0).getExplanation().toString(), containsString("weight(message:fox"));
        assertThat(innerHits.getAt(0).getFields().get("message").getValue().toString(), equalTo("eat"));
        assertThat(innerHits.getAt(0).getFields().get("script").getValue().toString(), equalTo("5"));
    }

    public void testRandomParentChild() throws Exception {
        if (legacy()) {
            assertAcked(prepareCreate("idx")
                .addMapping("parent")
                .addMapping("child1", "_parent", "type=parent")
                .addMapping("child2", "_parent", "type=parent")
            );
        } else {
            assertAcked(prepareCreate("idx")
                .addMapping("doc", jsonBuilder().startObject().startObject("doc").startObject("properties")
                    .startObject("join_field")
                        .field("type", "join")
                        .startObject("relations")
                            .field("parent", new String[] {"child1", "child2"})
                        .endObject()
                    .endObject()
                    .endObject().endObject().endObject()
                ));
        }
        int numDocs = scaledRandomIntBetween(5, 50);
        List<IndexRequestBuilder> requestBuilders = new ArrayList<>();

        int child1 = 0;
        int child2 = 0;
        int[] child1InnerObjects = new int[numDocs];
        int[] child2InnerObjects = new int[numDocs];
        for (int parent = 0; parent < numDocs; parent++) {
            String parentId = String.format(Locale.ENGLISH, "p_%03d", parent);
            requestBuilders.add(createIndexRequest("idx", "parent", parentId, null));

            int numChildDocs = child1InnerObjects[parent] = scaledRandomIntBetween(1, numDocs);
            int limit = child1 + numChildDocs;
            for (; child1 < limit; child1++) {
                requestBuilders.add(createIndexRequest("idx", "child1", String.format(Locale.ENGLISH, "c1_%04d", child1), parentId));
            }
            numChildDocs = child2InnerObjects[parent] = scaledRandomIntBetween(1, numDocs);
            limit = child2 + numChildDocs;
            for (; child2 < limit; child2++) {
                requestBuilders.add(createIndexRequest("idx", "child2", String.format(Locale.ENGLISH, "c2_%04d", child2), parentId));
            }
        }
        indexRandom(true, requestBuilders);

        int size = randomIntBetween(0, numDocs);
        BoolQueryBuilder boolQuery = new BoolQueryBuilder();
        boolQuery.should(constantScoreQuery(hasChildQuery("child1", matchAllQuery(), ScoreMode.None)
            .innerHit(new InnerHitBuilder().setName("a")
                .addSort(new FieldSortBuilder("_uid").order(SortOrder.ASC)).setSize(size))));
        boolQuery.should(constantScoreQuery(hasChildQuery("child2", matchAllQuery(), ScoreMode.None)
            .innerHit(new InnerHitBuilder().setName("b")
                .addSort(new FieldSortBuilder("_uid").order(SortOrder.ASC)).setSize(size))));
        SearchResponse searchResponse = client().prepareSearch("idx")
            .setSize(numDocs)
            .addSort("_uid", SortOrder.ASC)
            .setQuery(boolQuery)
            .get();

        assertNoFailures(searchResponse);
        assertHitCount(searchResponse, numDocs);
        assertThat(searchResponse.getHits().getHits().length, equalTo(numDocs));

        int offset1 = 0;
        int offset2 = 0;
        for (int parent = 0; parent < numDocs; parent++) {
            SearchHit searchHit = searchResponse.getHits().getAt(parent);
            assertThat(searchHit.getType(), equalTo(legacy() ? "parent" : "doc"));
            assertThat(searchHit.getId(), equalTo(String.format(Locale.ENGLISH, "p_%03d", parent)));
            assertThat(searchHit.getShard(), notNullValue());

            SearchHits inner = searchHit.getInnerHits().get("a");
            assertThat(inner.getTotalHits(), equalTo((long) child1InnerObjects[parent]));
            for (int child = 0; child < child1InnerObjects[parent] && child < size; child++) {
                SearchHit innerHit =  inner.getAt(child);
                assertThat(innerHit.getType(), equalTo(legacy() ? "child1" : "doc"));
                String childId = String.format(Locale.ENGLISH, "c1_%04d", offset1 + child);
                assertThat(innerHit.getId(), equalTo(childId));
                assertThat(innerHit.getNestedIdentity(), nullValue());
            }
            offset1 += child1InnerObjects[parent];

            inner = searchHit.getInnerHits().get("b");
            assertThat(inner.getTotalHits(), equalTo((long) child2InnerObjects[parent]));
            for (int child = 0; child < child2InnerObjects[parent] && child < size; child++) {
                SearchHit innerHit = inner.getAt(child);
                assertThat(innerHit.getType(), equalTo(legacy() ? "child2" : "doc"));
                String childId = String.format(Locale.ENGLISH, "c2_%04d", offset2 + child);
                assertThat(innerHit.getId(), equalTo(childId));
                assertThat(innerHit.getNestedIdentity(), nullValue());
            }
            offset2 += child2InnerObjects[parent];
        }
    }

    public void testInnerHitsOnHasParent() throws Exception {
        if (legacy()) {
            assertAcked(prepareCreate("stack")
                .addMapping("question", "body", "type=text")
                .addMapping("answer", "_parent", "type=question", "body", "type=text")
            );
        } else {
            assertAcked(prepareCreate("stack")
                .addMapping("doc", addFieldMappings(buildParentJoinFieldMappingFromSimplifiedDef("join_field", true, "question", "answer"),
                    "body", "text")));
        }
        List<IndexRequestBuilder> requests = new ArrayList<>();
        requests.add(createIndexRequest("stack", "question", "1", null, "body", "I'm using HTTPS + Basic authentication "
            + "to protect a resource. How can I throttle authentication attempts to protect against brute force attacks?"));
        requests.add(createIndexRequest("stack", "answer", "3", "1", "body", "install fail2ban and enable rules for apache"));
        requests.add(createIndexRequest("stack", "question", "2", null, "body",
            "I have firewall rules set up and also denyhosts installed.\\ndo I also need to install fail2ban?"));
        requests.add(createIndexRequest("stack", "answer", "4", "2", "body",
            "Denyhosts protects only ssh; Fail2Ban protects all daemons."));
        indexRandom(true, requests);

        SearchResponse response = client().prepareSearch("stack")
            .addSort("_uid", SortOrder.ASC)
            .setQuery(
                boolQuery()
                    .must(matchQuery("body", "fail2ban"))
                    .must(hasParentQuery("question", matchAllQuery(), false).innerHit(new InnerHitBuilder()))
            ).get();
        assertNoFailures(response);
        assertHitCount(response, 2);

        SearchHit searchHit = response.getHits().getAt(0);
        assertThat(searchHit.getId(), equalTo("3"));
        assertThat(searchHit.getType(), equalTo(legacy() ? "answer" : "doc"));
        assertThat(searchHit.getInnerHits().get("question").getTotalHits(), equalTo(1L));
        assertThat(searchHit.getInnerHits().get("question").getAt(0).getType(), equalTo(legacy() ? "question" : "doc"));
        assertThat(searchHit.getInnerHits().get("question").getAt(0).getId(), equalTo("1"));

        searchHit = response.getHits().getAt(1);
        assertThat(searchHit.getId(), equalTo("4"));
        assertThat(searchHit.getType(), equalTo(legacy() ? "answer" : "doc"));
        assertThat(searchHit.getInnerHits().get("question").getTotalHits(), equalTo(1L));
        assertThat(searchHit.getInnerHits().get("question").getAt(0).getType(), equalTo(legacy() ? "question" : "doc"));
        assertThat(searchHit.getInnerHits().get("question").getAt(0).getId(), equalTo("2"));
    }

    public void testParentChildMultipleLayers() throws Exception {
        if (legacy()) {
            assertAcked(prepareCreate("articles")
                .addMapping("article", "title", "type=text")
                .addMapping("comment", "_parent", "type=article", "message", "type=text")
                .addMapping("remark", "_parent", "type=comment", "message", "type=text")
            );
        } else {
            assertAcked(prepareCreate("articles")
                .addMapping("doc",
                    addFieldMappings(buildParentJoinFieldMappingFromSimplifiedDef("join_field", true,
                        "article", "comment", "comment", "remark"), "title", "text", "message", "text")));
        }

        List<IndexRequestBuilder> requests = new ArrayList<>();
        requests.add(createIndexRequest("articles", "article", "1", null, "title", "quick brown fox"));
        requests.add(createIndexRequest("articles", "comment", "3", "1", "message", "fox eat quick"));
        requests.add(createIndexRequest("articles", "remark", "5", "3", "message", "good").setRouting("1"));
        requests.add(createIndexRequest("articles", "article", "2", null, "title", "big gray elephant"));
        requests.add(createIndexRequest("articles", "comment", "4", "2", "message", "elephant captured"));
        requests.add(createIndexRequest("articles", "remark", "6", "4", "message", "bad").setRouting("2"));
        indexRandom(true, requests);

        SearchResponse response = client().prepareSearch("articles")
            .setQuery(hasChildQuery("comment",
                hasChildQuery("remark", matchQuery("message", "good"), ScoreMode.None).innerHit(new InnerHitBuilder()),
                ScoreMode.None).innerHit(new InnerHitBuilder()))
            .get();

        assertNoFailures(response);
        assertHitCount(response, 1);
        assertSearchHit(response, 1, hasId("1"));

        assertThat(response.getHits().getAt(0).getInnerHits().size(), equalTo(1));
        SearchHits innerHits = response.getHits().getAt(0).getInnerHits().get("comment");
        assertThat(innerHits.getTotalHits(), equalTo(1L));
        assertThat(innerHits.getAt(0).getId(), equalTo("3"));
        assertThat(innerHits.getAt(0).getType(), equalTo(legacy() ? "comment" : "doc"));

        innerHits = innerHits.getAt(0).getInnerHits().get("remark");
        assertThat(innerHits.getTotalHits(), equalTo(1L));
        assertThat(innerHits.getAt(0).getId(), equalTo("5"));
        assertThat(innerHits.getAt(0).getType(), equalTo(legacy() ? "remark" : "doc"));

        response = client().prepareSearch("articles")
            .setQuery(hasChildQuery("comment",
                hasChildQuery("remark", matchQuery("message", "bad"), ScoreMode.None).innerHit(new InnerHitBuilder()),
                ScoreMode.None).innerHit(new InnerHitBuilder()))
            .get();

        assertNoFailures(response);
        assertHitCount(response, 1);
        assertSearchHit(response, 1, hasId("2"));

        assertThat(response.getHits().getAt(0).getInnerHits().size(), equalTo(1));
        innerHits = response.getHits().getAt(0).getInnerHits().get("comment");
        assertThat(innerHits.getTotalHits(), equalTo(1L));
        assertThat(innerHits.getAt(0).getId(), equalTo("4"));
        assertThat(innerHits.getAt(0).getType(), equalTo(legacy() ? "comment" : "doc"));

        innerHits = innerHits.getAt(0).getInnerHits().get("remark");
        assertThat(innerHits.getTotalHits(), equalTo(1L));
        assertThat(innerHits.getAt(0).getId(), equalTo("6"));
        assertThat(innerHits.getAt(0).getType(), equalTo(legacy() ? "remark" : "doc"));
    }

    public void testRoyals() throws Exception {
        if (legacy()) {
            assertAcked(
                prepareCreate("royals")
                    .addMapping("king")
                    .addMapping("prince", "_parent", "type=king")
                    .addMapping("duke", "_parent", "type=prince")
                    .addMapping("earl", "_parent", "type=duke")
                    .addMapping("baron", "_parent", "type=earl")
            );
        } else {
            assertAcked(prepareCreate("royals")
                .addMapping("doc", buildParentJoinFieldMappingFromSimplifiedDef("join_field", true,
                    "king", "prince", "prince", "duke", "duke", "earl", "earl", "baron")));
        }

        List<IndexRequestBuilder> requests = new ArrayList<>();
        requests.add(createIndexRequest("royals", "king", "king", null));
        requests.add(createIndexRequest("royals", "prince", "prince", "king"));
        requests.add(createIndexRequest("royals", "duke", "duke", "prince").setRouting("king"));
        requests.add(createIndexRequest("royals", "earl", "earl1", "duke").setRouting("king"));
        requests.add(createIndexRequest("royals", "earl", "earl2", "duke").setRouting("king"));
        requests.add(createIndexRequest("royals", "earl", "earl3", "duke").setRouting("king"));
        requests.add(createIndexRequest("royals", "earl", "earl4", "duke").setRouting("king"));
        requests.add(createIndexRequest("royals", "baron", "baron1", "earl1").setRouting("king"));
        requests.add(createIndexRequest("royals", "baron", "baron2", "earl2").setRouting("king"));
        requests.add(createIndexRequest("royals", "baron", "baron3", "earl3").setRouting("king"));
        requests.add(createIndexRequest("royals", "baron", "baron4", "earl4").setRouting("king"));
        indexRandom(true, requests);

        SearchResponse response = client().prepareSearch("royals")
            .setQuery(boolQuery()
                .filter(hasParentQuery("prince",
                    hasParentQuery("king", matchAllQuery(), false).innerHit(new InnerHitBuilder().setName("kings")),
                    false).innerHit(new InnerHitBuilder().setName("princes"))
                )
                .filter(hasChildQuery("earl",
                    hasChildQuery("baron", matchAllQuery(), ScoreMode.None)
                        .innerHit(new InnerHitBuilder().setName("barons")),
                    ScoreMode.None).innerHit(new InnerHitBuilder()
                    .addSort(SortBuilders.fieldSort("_uid").order(SortOrder.ASC))
                    .setName("earls")
                    .setSize(4))
                )
            ).get();
        assertHitCount(response, 1);
        assertThat(response.getHits().getAt(0).getId(), equalTo("duke"));

        SearchHits innerHits = response.getHits().getAt(0).getInnerHits().get("earls");
        assertThat(innerHits.getTotalHits(), equalTo(4L));
        assertThat(innerHits.getAt(0).getId(), equalTo("earl1"));
        assertThat(innerHits.getAt(1).getId(), equalTo("earl2"));
        assertThat(innerHits.getAt(2).getId(), equalTo("earl3"));
        assertThat(innerHits.getAt(3).getId(), equalTo("earl4"));

        SearchHits innerInnerHits = innerHits.getAt(0).getInnerHits().get("barons");
        assertThat(innerInnerHits.getTotalHits(), equalTo(1L));
        assertThat(innerInnerHits.getAt(0).getId(), equalTo("baron1"));

        innerInnerHits = innerHits.getAt(1).getInnerHits().get("barons");
        assertThat(innerInnerHits.getTotalHits(), equalTo(1L));
        assertThat(innerInnerHits.getAt(0).getId(), equalTo("baron2"));

        innerInnerHits = innerHits.getAt(2).getInnerHits().get("barons");
        assertThat(innerInnerHits.getTotalHits(), equalTo(1L));
        assertThat(innerInnerHits.getAt(0).getId(), equalTo("baron3"));

        innerInnerHits = innerHits.getAt(3).getInnerHits().get("barons");
        assertThat(innerInnerHits.getTotalHits(), equalTo(1L));
        assertThat(innerInnerHits.getAt(0).getId(), equalTo("baron4"));

        innerHits = response.getHits().getAt(0).getInnerHits().get("princes");
        assertThat(innerHits.getTotalHits(), equalTo(1L));
        assertThat(innerHits.getAt(0).getId(), equalTo("prince"));

        innerInnerHits = innerHits.getAt(0).getInnerHits().get("kings");
        assertThat(innerInnerHits.getTotalHits(), equalTo(1L));
        assertThat(innerInnerHits.getAt(0).getId(), equalTo("king"));
    }

    public void testMatchesQueriesParentChildInnerHits() throws Exception {
        if (legacy()) {
            assertAcked(prepareCreate("index")
                .addMapping("child", "_parent", "type=parent"));
        } else {
            assertAcked(prepareCreate("index")
                .addMapping("doc", buildParentJoinFieldMappingFromSimplifiedDef("join_field", true, "parent", "child")));
        }
        List<IndexRequestBuilder> requests = new ArrayList<>();
        requests.add(createIndexRequest("index", "parent", "1", null));
        requests.add(createIndexRequest("index", "child", "3", "1", "field", "value1"));
        requests.add(createIndexRequest("index", "child", "4", "1", "field", "value2"));
        requests.add(createIndexRequest("index", "parent", "2", null));
        requests.add(createIndexRequest("index", "child", "5", "2", "field", "value1"));
        indexRandom(true, requests);

        SearchResponse response = client().prepareSearch("index")
            .setQuery(hasChildQuery("child", matchQuery("field", "value1").queryName("_name1"), ScoreMode.None)
                .innerHit(new InnerHitBuilder()))
            .addSort("_uid", SortOrder.ASC)
            .get();
        assertHitCount(response, 2);
        assertThat(response.getHits().getAt(0).getId(), equalTo("1"));
        assertThat(response.getHits().getAt(0).getInnerHits().get("child").getTotalHits(), equalTo(1L));
        assertThat(response.getHits().getAt(0).getInnerHits().get("child").getAt(0).getMatchedQueries().length, equalTo(1));
        assertThat(response.getHits().getAt(0).getInnerHits().get("child").getAt(0).getMatchedQueries()[0], equalTo("_name1"));

        assertThat(response.getHits().getAt(1).getId(), equalTo("2"));
        assertThat(response.getHits().getAt(1).getInnerHits().get("child").getTotalHits(), equalTo(1L));
        assertThat(response.getHits().getAt(1).getInnerHits().get("child").getAt(0).getMatchedQueries().length, equalTo(1));
        assertThat(response.getHits().getAt(1).getInnerHits().get("child").getAt(0).getMatchedQueries()[0], equalTo("_name1"));

        QueryBuilder query = hasChildQuery("child", matchQuery("field", "value2").queryName("_name2"), ScoreMode.None)
            .innerHit(new InnerHitBuilder());
        response = client().prepareSearch("index")
            .setQuery(query)
            .addSort("_uid", SortOrder.ASC)
            .get();
        assertHitCount(response, 1);
        assertThat(response.getHits().getAt(0).getId(), equalTo("1"));
        assertThat(response.getHits().getAt(0).getInnerHits().get("child").getTotalHits(), equalTo(1L));
        assertThat(response.getHits().getAt(0).getInnerHits().get("child").getAt(0).getMatchedQueries().length, equalTo(1));
        assertThat(response.getHits().getAt(0).getInnerHits().get("child").getAt(0).getMatchedQueries()[0], equalTo("_name2"));
    }

    public void testUseMaxDocInsteadOfSize() throws Exception {
        if (legacy()) {
            assertAcked(prepareCreate("index1").addMapping("child", "_parent", "type=parent"));
        } else {
            assertAcked(prepareCreate("index1")
                .addMapping("doc", buildParentJoinFieldMappingFromSimplifiedDef("join_field", true, "parent", "child")));
        }
        client().admin().indices().prepareUpdateSettings("index1")
            .setSettings(Collections.singletonMap(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey(), ArrayUtil.MAX_ARRAY_LENGTH))
            .get();
        List<IndexRequestBuilder> requests = new ArrayList<>();
        requests.add(createIndexRequest("index1", "parent", "1", null));
        requests.add(createIndexRequest("index1", "child", "2", "1", "field", "value1"));
        indexRandom(true, requests);

        QueryBuilder query = hasChildQuery("child", matchQuery("field", "value1"), ScoreMode.None)
            .innerHit(new InnerHitBuilder().setSize(ArrayUtil.MAX_ARRAY_LENGTH - 1));
        SearchResponse response = client().prepareSearch("index1")
            .setQuery(query)
            .get();
        assertNoFailures(response);
        assertHitCount(response, 1);
    }

    public void testNestedInnerHitWrappedInParentChildInnerhit() throws Exception {
        if (legacy()) {
            assertAcked(prepareCreate("test")
                .addMapping("child_type", "_parent", "type=parent_type", "nested_type", "type=nested"));
        } else {
            assertAcked(prepareCreate("test")
                .addMapping("doc", addFieldMappings(buildParentJoinFieldMappingFromSimplifiedDef("join_field", true,
                    "parent_type", "child_type"), "nested_type", "nested")));
        }
        createIndexRequest("test", "parent_type", "1", null, "key", "value").get();
        createIndexRequest("test", "child_type", "2", "1", "nested_type", Collections.singletonMap("key", "value")).get();
        refresh();
        SearchResponse response = client().prepareSearch("test")
            .setQuery(boolQuery().must(matchQuery("key", "value"))
                .should(hasChildQuery("child_type", nestedQuery("nested_type", matchAllQuery(), ScoreMode.None)
                    .innerHit(new InnerHitBuilder()), ScoreMode.None).innerHit(new InnerHitBuilder())))
            .get();
        assertHitCount(response, 1);
        SearchHit hit = response.getHits().getAt(0);
        if (legacy()) {
            assertThat(hit.getInnerHits().get("child_type").getAt(0).field("_parent").getValue(), equalTo("1"));
        } else {
            String parentId = (String) extractValue("join_field.parent", hit.getInnerHits().get("child_type").getAt(0).getSourceAsMap());
            assertThat(parentId, equalTo("1"));
        }
        assertThat(hit.getInnerHits().get("child_type").getAt(0).getInnerHits().get("nested_type").getAt(0).field("_parent"), nullValue());
    }

    public void testInnerHitsWithIgnoreUnmapped() throws Exception {
        if (legacy()) {
            assertAcked(prepareCreate("index1")
                .addMapping("parent_type", "nested_type", "type=nested")
                .addMapping("child_type", "_parent", "type=parent_type")
            );
        } else {
            assertAcked(prepareCreate("index1")
                .addMapping("doc", addFieldMappings(
                    buildParentJoinFieldMappingFromSimplifiedDef("join_field", true, "parent_type", "child_type"),
                    "nested_type", "nested"))
            );
        }
        assertAcked(prepareCreate("index2"));
        createIndexRequest("index1", "parent_type", "1", null, "nested_type", Collections.singletonMap("key", "value")).get();
        createIndexRequest("index1", "child_type", "2", "1").get();
        client().prepareIndex("index2", "type", "3").setSource("key", "value").get();
        refresh();

        SearchResponse response = client().prepareSearch("index1", "index2")
            .setQuery(boolQuery()
                .should(hasChildQuery("child_type", matchAllQuery(), ScoreMode.None).ignoreUnmapped(true)
                    .innerHit(new InnerHitBuilder().setIgnoreUnmapped(true)))
                .should(termQuery("key", "value"))
            )
            .get();
        assertNoFailures(response);
        assertHitCount(response, 2);
        assertSearchHits(response, "1", "3");
    }

    public void testTooHighResultWindow() throws Exception {
        if (legacy()) {
            assertAcked(prepareCreate("index1")
                .addMapping("parent_type", "nested_type", "type=nested")
                .addMapping("child_type", "_parent", "type=parent_type")
            );
        } else {
            assertAcked(prepareCreate("index1")
                .addMapping("doc", addFieldMappings(
                    buildParentJoinFieldMappingFromSimplifiedDef("join_field", true, "parent_type", "child_type"),
                    "nested_type", "nested"))
            );
        }
        createIndexRequest("index1", "parent_type", "1", null, "nested_type", Collections.singletonMap("key", "value")).get();
        createIndexRequest("index1", "child_type", "2", "1").get();
        refresh();

        SearchResponse response = client().prepareSearch("index1")
            .setQuery(hasChildQuery("child_type", matchAllQuery(), ScoreMode.None).ignoreUnmapped(true)
                .innerHit(new InnerHitBuilder().setFrom(50).setSize(10).setName("_name")))
            .get();
        assertNoFailures(response);
        assertHitCount(response, 1);

        Exception e = expectThrows(SearchPhaseExecutionException.class, () -> client().prepareSearch("index1")
            .setQuery(hasChildQuery("child_type", matchAllQuery(), ScoreMode.None).ignoreUnmapped(true)
                .innerHit(new InnerHitBuilder().setFrom(100).setSize(10).setName("_name")))
            .get());
        assertThat(e.getCause().getMessage(),
            containsString("the inner hit definition's [_name]'s from + size must be less than or equal to: [100] but was [110]"));
        e = expectThrows(SearchPhaseExecutionException.class, () -> client().prepareSearch("index1")
            .setQuery(hasChildQuery("child_type", matchAllQuery(), ScoreMode.None).ignoreUnmapped(true)
                .innerHit(new InnerHitBuilder().setFrom(10).setSize(100).setName("_name")))
            .get());
        assertThat(e.getCause().getMessage(),
            containsString("the inner hit definition's [_name]'s from + size must be less than or equal to: [100] but was [110]"));

        client().admin().indices().prepareUpdateSettings("index1")
            .setSettings(Collections.singletonMap(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey(), 110))
            .get();
        response = client().prepareSearch("index1")
            .setQuery(hasChildQuery("child_type", matchAllQuery(), ScoreMode.None).ignoreUnmapped(true)
                .innerHit(new InnerHitBuilder().setFrom(100).setSize(10).setName("_name")))
            .get();
        assertNoFailures(response);
        response = client().prepareSearch("index1")
            .setQuery(hasChildQuery("child_type", matchAllQuery(), ScoreMode.None).ignoreUnmapped(true)
                .innerHit(new InnerHitBuilder().setFrom(10).setSize(100).setName("_name")))
            .get();
        assertNoFailures(response);
    }
}


text:
using System.Collections.Generic;
using IocApp.CIL;

namespace IocApp.DAL
{
    public class DataAccess : IDataAccess
    {
        public AbstractEntity Get<T>(int id) where T : AbstractEntity
        {
            throw new System.NotImplementedException();
        }

        public IEnumerable<T> GetList<T>(string where) where T : AbstractEntity
        {
            throw new System.NotImplementedException();
        }

        public int Insert<T>(T item) where T : AbstractEntity
        {
            throw new System.NotImplementedException();
        }

        public IEnumerable<int> InsertMany<T>(IEnumerable<T> items) where T : AbstractEntity
        {
            throw new System.NotImplementedException();
        }

        public bool Delete<T>(int id) where T : AbstractEntity
        {
            throw new System.NotImplementedException();
        }

        public bool DeleteMany<T>(int[] ids) where T : AbstractEntity
        {
            throw new System.NotImplementedException();
        }

        public bool Update<T>(T item) where T : AbstractEntity
        {
            throw new System.NotImplementedException();
        }

        public bool UpdateMany<T>(IEnumerable<T> items) where T : AbstractEntity
        {
            throw new System.NotImplementedException();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation JGLargeNumberFormatter

#pragma mark - Properties
@synthesize thousandsAbreviation = _thousandsAbreviation;
@synthesize millionsAbreviation = _millionsAbreviation;
@synthesize billionsAbreviation = _billionsAbreviation;

-(NSString*)stringFromNumber:(NSNumber*)number
{
  if ( ! ( self.thousandsAbreviation || self.millionsAbreviation || self.billionsAbreviation ) )
  {
    return [super stringFromNumber:number];
  }

  double d = [number doubleValue];
  double absolute = fabs(d);
  if ( self.billionsAbreviation && absolute >= 1000000000 )
  {
    NSString* numberInBillion = [super stringFromNumber:[NSNumber numberWithDouble:d / 1000000000]];
    return [NSString stringWithFormat:@"%@%@", numberInBillion, self.billionsAbreviation];
  }
  if ( self.millionsAbreviation && absolute >= 1000000 )
  {
    NSString* numberInMillion = [super stringFromNumber:[NSNumber numberWithDouble:d / 1000000]];
    return [NSString stringWithFormat:@"%@%@", numberInMillion, self.millionsAbreviation];
  }
  if ( self.thousandsAbreviation && absolute >= 1000 )
  {
    NSString* numberInThousand = [super stringFromNumber:[NSNumber numberWithDouble:d / 1000]];
    return [NSString stringWithFormat:@"%@%@", numberInThousand, self.thousandsAbreviation];
  }
  return [super stringFromNumber:number];
}

@end


text:
.class public interface abstract Lde/greenrobot/dao/async/AsyncOperationListener;
.super Ljava/lang/Object;

# virtual methods
.method public abstract onAsyncOperationCompleted(Lde/greenrobot/dao/async/AsyncOperation;)V
.end method


text:
Names and trademarks

				Star Trek, Star Trek: The Animated Series, Star Trek: The Next Generation,
				Star Trek: Deep Space Nine, Star Trek: Voyager, Star Trek: Enterprise,
				and Star Trek: Discovery are all registered trademarks of CBS Corporation.
				STAPI is in no way affiliated with or endorsed by CBS. STAPI makes no claim
				to own Star Trek or any of the names related to it.

Content licensing

				STAPI uses content derived from Memory Alpha, therefore
				it is safe to assume that most of STAPI'a content is licensed under CC-BY-NC 4.0.
				For details on Memory Alpha licensing see this link.

				STAPI also uses content from Memory Beta, therefore some parts of the
				data is licensed under CC BY-SA 3.0.
				For details on Memory Beta licensing see this link.

				Trading card sets and trading cards data come from StarTrekCards.com and
				should be considered copyrighted.

				Some small parts of the content, those coming from the source code, are licensed unded MIT license.

				GitHub Octicons are licensed under MIT license.

Attribution

				For the authors of content the STAPI's data has been derived from, see Memory Alpha's and Memory Beta's
				history pages. For the authors of MIT-licensed data, see GitHub repository history.

				Machine readable attribution is not provided at the moment. Neither Creative Commons wiki,
				nor a direct contact with Creative Commons, has been able to answer a question on how exactly
				should a CC-derived work by attributed for machine-readable format. Therefore it is only attributed
				in human-readable format. If you an expert on the subject, and can provide some insights on how
				to attribute a CC-derived content in machine-readable format, please go forward and start
				a public discussion on GitHub,
				so others can join too.


text:
namespace TheXDS.MCART.Types.Base;
using System;
using TheXDS.MCART.Helpers;

/// <summary>
/// Interfaz que define un rango de valores.
/// </summary>
/// <typeparam name="T">Tipo base del rango de valores.</typeparam>
public interface IRange<T> where T : IComparable<T>
{
    /// <summary>
    /// Valor máximo del rango.
    /// </summary>
    T Maximum { get; set; }

    /// <summary>
    /// Obtiene o establece un valor que determina si el valor máximo
    /// es parte del rango.
    /// </summary>
    ///
    bool MaxInclusive { get; set; }

    /// <summary>
    /// Valor mínimo del rango.
    /// </summary>
    T Minimum { get; set; }

    /// <summary>
    /// Obtiene o establece un valor que determina si el valor mínimo
    /// es parte del rango.
    /// </summary>
    bool MinInclusive { get; set; }

    /// <summary>
    /// Determina si un <see cref="IRange{T}"/> intersecta a este.
    /// </summary>
    /// <param name="other">Rango a comprobar.</param>
    /// <returns>
    /// <see langword="true"/> si <paramref name="other"/> intersecta a
    /// este <see cref="IRange{T}"/>, <see langword="false"/> en caso
    /// contrario.
    /// </returns>
    bool Intersects(IRange<T> other) => IsWithin(other.Maximum) || IsWithin(other.Minimum);

    /// <summary>
    /// Comprueba si un valor <typeparamref name="T"/> se encuentra
    /// dentro de este <see cref="IRange{T}"/>.
    /// </summary>
    /// <param name="value">Valor a comporbar.</param>
    /// <returns>
    /// <see langword="true"/> si el valor se encuentra dentro de este
    /// <see cref="IRange{T}"/>, <see langword="false"/> en caso
    /// contrario.
    /// </returns>
    bool IsWithin(T value) => value.IsBetween(Minimum, Maximum, MinInclusive, MaxInclusive);
}


text:
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.testing;

import com.intellij.execution.DefaultExecutionResult;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.ExecutionResult;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.configurations.ParamsGroup;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.target.TargetEnvironment;
import com.intellij.execution.target.TargetEnvironmentRequest;
import com.intellij.execution.target.value.TargetEnvironmentFunctions;
import com.intellij.execution.testframework.autotest.ToggleAutoTestAction;
import com.intellij.execution.testframework.sm.SMTestRunnerConnectionUtil;
import com.intellij.execution.testframework.sm.runner.SMTestLocator;
import com.intellij.execution.testframework.sm.runner.ui.SMTRunnerConsoleView;
import com.intellij.execution.testframework.ui.BaseTestsOutputConsoleView;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.text.StringUtil;
import com.jetbrains.python.HelperPackage;
import com.jetbrains.python.PythonHelpersLocator;
import com.jetbrains.python.console.PythonDebugLanguageConsoleView;
import com.jetbrains.python.run.*;
import com.jetbrains.python.sdk.PythonSdkUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.concurrency.AsyncPromise;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

public abstract class PythonTestCommandLineStateBase<T extends AbstractPythonRunConfiguration<?>> extends PythonCommandLineState {
  protected final T myConfiguration;

  public T getConfiguration() {
    return myConfiguration;
  }

  public PythonTestCommandLineStateBase(T configuration, ExecutionEnvironment env) {
    super(configuration, env);
    myConfiguration = configuration;
    setRunWithPty(false);
  }

  @Override
  @NotNull
  protected ConsoleView createAndAttachConsole(Project project, ProcessHandler processHandler, Executor executor)
    throws ExecutionException {

    final PythonTRunnerConsoleProperties consoleProperties = createConsoleProperties(executor);

    if (isDebug()) {
      final ConsoleView testsOutputConsoleView = SMTestRunnerConnectionUtil.createConsole(PythonTRunnerConsoleProperties.FRAMEWORK_NAME,
                                                                                consoleProperties);
      final ConsoleView consoleView =
        new PythonDebugLanguageConsoleView(project, PythonSdkUtil.findSdkByPath(myConfiguration.getInterpreterPath()),
                                           testsOutputConsoleView, true);
      consoleView.attachToProcess(processHandler);
      addTracebackFilter(project, consoleView, processHandler);
      return consoleView;
    }
    final ConsoleView consoleView = SMTestRunnerConnectionUtil.createAndAttachConsole(PythonTRunnerConsoleProperties.FRAMEWORK_NAME,
                                                                                processHandler,
                                                                                consoleProperties);
    addTracebackFilter(project, consoleView, processHandler);
    return consoleView;
  }

  protected PythonTRunnerConsoleProperties createConsoleProperties(Executor executor) {
    final PythonTRunnerConsoleProperties properties = new PythonTRunnerConsoleProperties(myConfiguration, executor, true, getTestLocator());
    if (myConfiguration.isIdTestBased()) {
      properties.makeIdTestBased();
    }
    return properties;
  }

  @Nullable
  protected SMTestLocator getTestLocator() {
    return null;  // by default, the IDE will use a "file://" protocol locator
  }

  @NotNull
  @Override
  public GeneralCommandLine generateCommandLine() {
    GeneralCommandLine cmd = super.generateCommandLine();

    setWorkingDirectory(cmd);

    ParamsGroup exe_options = cmd.getParametersList().getParamsGroup(GROUP_EXE_OPTIONS);
    assert exe_options != null;
    exe_options.addParametersString(myConfiguration.getInterpreterOptions());
    addTestRunnerParameters(cmd);

    return cmd;
  }

  @Override
  protected @NotNull PythonExecution buildPythonExecution(@NotNull TargetEnvironmentRequest targetEnvironmentRequest) {
    PythonScriptExecution testScriptExecution = PythonScripts.prepareHelperScriptExecution(getRunner(), targetEnvironmentRequest);
    addBeforeParameters(testScriptExecution);
    addTestSpecsAsParameters(testScriptExecution, getTestSpecs());
    addAfterParameters(targetEnvironmentRequest, testScriptExecution);
    return testScriptExecution;
  }

  protected void setWorkingDirectory(@NotNull final GeneralCommandLine cmd) {
    String workingDirectory = myConfiguration.getWorkingDirectory();
    if (StringUtil.isEmptyOrSpaces(workingDirectory)) {
      workingDirectory = myConfiguration.getWorkingDirectorySafe();
    }
    cmd.withWorkDirectory(workingDirectory);
  }

  @Override
  public ExecutionResult execute(Executor executor, PythonProcessStarter processStarter, CommandLinePatcher... patchers)
    throws ExecutionException {
    final ProcessHandler processHandler = startProcess(processStarter, patchers);
    ConsoleView console = invokeAndWait(() -> createAndAttachConsole(myConfiguration.getProject(), processHandler, executor));

    DefaultExecutionResult executionResult =
      new DefaultExecutionResult(console, processHandler, createActions(console, processHandler));

    PyRerunFailedTestsAction rerunFailedTestsAction = new PyRerunFailedTestsAction(console);
    if (console instanceof SMTRunnerConsoleView) {
      rerunFailedTestsAction.init(((BaseTestsOutputConsoleView)console).getProperties());
      rerunFailedTestsAction.setModelProvider(() -> ((SMTRunnerConsoleView)console).getResultsViewer());
    }

    executionResult.setRestartActions(rerunFailedTestsAction, new ToggleAutoTestAction());
    return executionResult;
  }

  @Override
  public @NotNull ExecutionResult execute(Executor executor, @NotNull PythonScriptTargetedCommandLineBuilder converter)
    throws ExecutionException {
    ProcessHandler processHandler = startProcess(converter);
    ConsoleView console = invokeAndWait(() -> createAndAttachConsole(myConfiguration.getProject(), processHandler, executor));

    DefaultExecutionResult executionResult =
      new DefaultExecutionResult(console, processHandler, createActions(console, processHandler));

    PyRerunFailedTestsAction rerunFailedTestsAction = new PyRerunFailedTestsAction(console);
    if (console instanceof SMTRunnerConsoleView) {
      rerunFailedTestsAction.init(((BaseTestsOutputConsoleView)console).getProperties());
      rerunFailedTestsAction.setModelProvider(() -> ((SMTRunnerConsoleView)console).getResultsViewer());
    }

    executionResult.setRestartActions(rerunFailedTestsAction, new ToggleAutoTestAction());
    return executionResult;
  }

  protected static <T, E extends Throwable> @NotNull T invokeAndWait(ThrowableComputable<@NotNull T, E> computable) {
    AsyncPromise<T> promise = new AsyncPromise<>();
    ApplicationManager.getApplication().invokeAndWait(() -> {
      try {
        promise.setResult(computable.compute());
      }
      catch (Throwable error) {
        promise.setError(error);
      }
    });
    return Objects.requireNonNull(promise.get(), "The execution was cancelled");
  }

  /**
   * To be deprecated.
   *

   * The part of the legacy implementation based on {@link GeneralCommandLine}.
   */
  protected void addBeforeParameters(GeneralCommandLine cmd) {}

  /**
   * To be deprecated.
   *

   * The part of the legacy implementation based on {@link GeneralCommandLine}.
   */
  protected void addAfterParameters(GeneralCommandLine cmd) {}

  /**
   * To be deprecated.
   *

   * The part of the legacy implementation based on {@link GeneralCommandLine}.
   */
  protected void addTestRunnerParameters(GeneralCommandLine cmd) {
    ParamsGroup scriptParams = cmd.getParametersList().getParamsGroup(GROUP_SCRIPT);
    assert scriptParams != null;
    getRunner().addToGroup(scriptParams, cmd);
    addBeforeParameters(cmd);
    myConfiguration.addTestSpecsAsParameters(scriptParams, getTestSpecs());
    addAfterParameters(cmd);
  }

  protected void addBeforeParameters(@NotNull PythonScriptExecution testScriptExecution) {}

  /**
   * Adds test specs (like method, class, script, etc) to list of runner parameters.
   */
  protected void addTestSpecsAsParameters(@NotNull PythonScriptExecution testScriptExecution, @NotNull final List<String> testSpecs) {
    // By default we simply add them as arguments
    testSpecs.forEach(parameter -> testScriptExecution.addParameter(parameter));
  }

  protected void addAfterParameters(@NotNull TargetEnvironmentRequest targetEnvironmentRequest,
                                    @NotNull PythonScriptExecution testScriptExecution) {}

  @Override
  public void customizeEnvironmentVars(Map<String, String> envs, boolean passParentEnvs) {
    super.customizeEnvironmentVars(envs, passParentEnvs);
    envs.put("PYCHARM_HELPERS_DIR", PythonHelpersLocator.getHelperPath("pycharm"));
  }

  @Override
  public void customizePythonExecutionEnvironmentVars(@NotNull TargetEnvironmentRequest targetEnvironmentRequest,
                                                      @NotNull Map<String, Function<TargetEnvironment, String>> envs,
                                                      boolean passParentEnvs) {
    super.customizePythonExecutionEnvironmentVars(targetEnvironmentRequest, envs, passParentEnvs);
    String pycharmHelperPath = PythonHelpersLocator.getHelperPath("pycharm");
    Function<TargetEnvironment, String> targetPycharmHelpersPath =
      TargetEnvironmentFunctions.getTargetEnvironmentValueForLocalPath(targetEnvironmentRequest, pycharmHelperPath);
    envs.put("PYCHARM_HELPERS_DIR", targetPycharmHelpersPath);
  }

  protected abstract HelperPackage getRunner();

  @NotNull
  protected abstract List<String> getTestSpecs();
}


text:
module Akarui.Parser.FOL where

import qualified Data.Text as T
import Text.Parsec
import Text.Parsec.String (Parser)
import qualified Text.Parsec.Expr as Ex
import Akarui.FOL.Formula
import Akarui.FOL.FOL
import Akarui.Parser.LogicOps
import Akarui.Parser.Core
import Akarui.Parser.Numbers
import Akarui.Parser.Term as Term
import Akarui.FOL.Predicate
import Akarui.FOL.QuanT

-- | Parser for weighted first-order logic. Parses a double following by
-- a formula (or a formula followed by a double).
--
-- The /smoking/ example for Markov logic:
--
-- @
--    parseWFOL \"∀x∀y∀z Friend(x, y) ∧ Friend(y, z) ⇒ Friend(x, z) 0.7\"
--    parseWFOL \"∀x Smoking(x) ⇒ Cancer(x) 1.5\"
--    parseWFOL \"1.1 ∀x∀y Friend(x, y) ∧ Smoking(x) ⇒ Smoking(y)\"
-- @
parseWFOL :: String -> Either ParseError (FOL, Double)
parseWFOL = parse (contents parseWeighted) "<stdin>"

-- | Parser for first-order logic. The parser will read a string and output
-- an either type with (hopefully) the formula on the right.
--
-- This parser makes the assumption that variables start with a lowercase
-- character, while constants start with an uppercase character.
--
-- Some examples of valid strings for the parser:
--
-- @
--    parseFOL \"ForAll x, y PositiveInteger(y) => GreaterThan(Add(x, y), x)\"
--    parseFOL \"A.x,y: Integer(x) and PositiveInteger(y) => GreaterThan(Add(x, y), x)\"
--    parseFOL \"∀ x Add(x, 0) = x\"
-- @
parseFOL :: String -> Either ParseError FOL
parseFOL = parse (contents parseFOLAll) "<stdin>"

parseFOLAll, parseSentence, parseTop, parseBot, parseAtoms, parsePred, parsePredLike, parseIdentity, parseNIdentity, parseQuan, parseNQuan, parseNegation :: Parser FOL
parseFOLAll = try parseNQuan<|> try parseQuan <|> parseSentence

parseSentence = Ex.buildExpressionParser logicTbl parseAtoms

parseTop  = reservedOps ["True", "TRUE", "true", "T", "⊤"] >> return top

parseBot = reservedOps ["False", "FALSE", "false", "F", "⊥"] >> return bot

parseNQuan = do
  nots <- many1 parseNot
  (q, vs, a) <- parseQuanForm
  return $ foldr (\_ acc -> Not acc) (foldr (Quantifier q) a vs) nots

parseQuan = do
  (q, vs, a) <- parseQuanForm
  return $ foldr (Quantifier q) a vs

parseNegation = do
  n <- parseNot
  a <- parseAtoms
  return $ n a

parsePredLike = try parseIdentity <|> try parseNIdentity <|> parsePred

parseAtoms =
      try parsePredLike
  <|> parseNegation
  <|> parseTop
  <|> parseBot
  <|> parens parseFOLAll

parsePred = do
  args <- Term.parseFunForm
  return $ Atom $ uncurry Predicate args

parseIdentity = do
  left <- Term.parseTerm
  reservedOps ["=", "=="]
  right <- Term.parseTerm
  return $ Atom $ Predicate "Identity" [left, right]

parseNIdentity = do
  left <- Term.parseTerm
  reservedOps ["!=", "/=", "\\neq"]
  right <- Term.parseTerm
  return $ Not $ Atom $ Predicate "Identity" [left, right]

parseNot :: Parser (FOL -> FOL)
parseNot = reservedOps ["Not", "NOT", "not", "~", "!", "¬"] >> return Not

parseExists, parseForAll :: Parser QuanT
parseExists = reservedOps ["E.", "Exists", "exists", "∃"] >> return Exists
parseForAll = reservedOps ["A.", "ForAll", "Forall", "forall", "∀"] >> return ForAll

-- Parse a weight and then a first-order logic formula
parseLeftW :: Parser (FOL, Double)
parseLeftW = do
  n <- getDouble
  f <- parseFOLAll
  return (f, n)

-- Parse a first-order logic formula and then a weight
parseRightW :: Parser (FOL, Double)
parseRightW = do
  f <- parseFOLAll
  n <- getDouble
  return (f, n)

parseWeighted :: Parser (FOL, Double)
parseWeighted = try parseLeftW <|> parseRightW

parseQuanForm :: Parser (QuanT, [T.Text], FOL)
parseQuanForm = do
  q <- parseExists <|> parseForAll -- many1
  v <- commaSep identifier
  optional $ reservedOp ":"
  a <- parseFOLAll
  return (q, map T.pack v, a)


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definitions"
  xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
  xmlns:camunda="http://camunda.org/schema/1.0/bpmn"
  targetNamespace="Examples">

  <process id="helloProcess" isExecutable="true">

    <startEvent id="start" />
    <sequenceFlow id="flow1" sourceRef="start" targetRef="task" />

    <userTask id="task" name="My Task" />
    <sequenceFlow id="flow2" sourceRef="task" targetRef="print" />

    <serviceTask id="print"  camunda:expression="#{failing_expression}" />
    <sequenceFlow id="flow3" sourceRef="print" targetRef="userTask" />

    <userTask id="userTask" />
    <sequenceFlow id="flow4" sourceRef="userTask" targetRef="end" />

    <endEvent id="end" />

  </process>

</definitions>


text:
package influent.idlhelper;

import influent.idl.FL_GeoData;
import influent.idl.FL_PropertyType;
import influent.idl.FL_SingletonRange;

import java.util.Date;

public class SingletonRangeHelper {

	/**
	 * Returns the value of a singleton range, handling nulls.
	 * @param range
	 * @return
	 */
	public static Object value(Object range) {
		return range instanceof FL_SingletonRange? ((FL_SingletonRange)range).getValue() : null;
	}

	/**
	 * Class construction should really be deprecated for use
	 * of these methods when the type is known at compile time.

	 * @param value
	 * @return new singleton range
	 */
	public static FL_SingletonRange from(String value) {
		return FL_SingletonRange.newBuilder()
			.setType(FL_PropertyType.STRING)
			.setValue(value)
			.build();
	}

	/**
	 * @param value
	 * @return new singleton range
	 */
	public static FL_SingletonRange from(Boolean value) {
		return FL_SingletonRange.newBuilder()
			.setType(FL_PropertyType.BOOLEAN)
			.setValue(value)
			.build();
	}

	/**
	 * @param value
	 * @return new singleton range
	 */
	public static FL_SingletonRange from(Date value) {
		return FL_SingletonRange.newBuilder()
			.setType(FL_PropertyType.DATE)
			.setValue(value.getTime())
			.build();
	}

	/**
	 * @param value
	 * @return new singleton range
	 */
	public static FL_SingletonRange from(Integer value) {
		return FL_SingletonRange.newBuilder()
			.setType(FL_PropertyType.INTEGER)
			.setValue(value)
			.build();
	}

	/**
	 * @param value
	 * @return new singleton range
	 */
	public static FL_SingletonRange from(Long value) {
		return FL_SingletonRange.newBuilder()
			.setType(FL_PropertyType.LONG)
			.setValue(value)
			.build();
	}

	/**
	 * @param value
	 * @return new singleton range
	 */
	public static FL_SingletonRange from(Float value) {
		return FL_SingletonRange.newBuilder()
			.setType(FL_PropertyType.DOUBLE)
			.setValue(Double.valueOf(value.doubleValue()))
			.build();
	}

	/**
	 * @param value
	 * @return new singleton range
	 */
	public static FL_SingletonRange from(Double value) {
		return FL_SingletonRange.newBuilder()
			.setType(FL_PropertyType.DOUBLE)
			.setValue(value)
			.build();
	}

	/**
	 * @param value
	 * @return new singleton range
	 */
	public static FL_SingletonRange from(FL_GeoData value) {
		return FL_SingletonRange.newBuilder()
			.setType(FL_PropertyType.GEO)
			.setValue(value)
			.build();
	}

	/**
	 * @param value
	 * @return new singleton range
	 */
	public static FL_SingletonRange from(Object value, FL_PropertyType type) {
		return FL_SingletonRange.newBuilder()
			.setType(type)
			.setValue(value)
			.build();
	}

	/**
	 * Do a best guess determination of type. Note that if the value is null
	 * the property type is indeterminant and will be marked as OTHER.
	 *
	 * @param untyped value
	 * @return new typed singleton range
	 */
	public static FL_SingletonRange fromUnknown(Object value) {

		// can't type nulls, which is why this method is not preferred
		if (value == null) {
			return null;
		}

		if (value instanceof String) {
			return from((String)value);

		} else if (value instanceof Number) {
			Number number = (Number)value;

			if (number instanceof Integer) {
				return from((Integer)number);

			} else if (number instanceof Long) {
				return from((Long)number);
			}

			return from(Double.valueOf(number.doubleValue()));

		} else if (value instanceof Boolean) {
			return from((Boolean)value);

		} else if (value instanceof Date) {
			return from((Date)value);

		} else if (value instanceof FL_GeoData) {
			return from((FL_GeoData)value);
		}

		// debatable.
		return from(value.toString(), FL_PropertyType.STRING);
	}
}


text:
SwiftSkeleton
=============

## What is SwiftSkeleton?

SwiftSkeleton is a simple and barebones template that includes:
- A Singleton
- A Networking Client (with authentication)
- A JSON Parser

### Future updates include:

- CoreData saving/loading
- Locales
- A better side menu/split view controller


text:
sourceDir=$(cd "$(dirname "$0")"; pwd)"/../src"

# blkmaker
if [ ! -d "run_blkmaker" ]; then
  mkdir "run_blkmaker" && cd "run_blkmaker"
  mkdir "log_blkmaker"
  ln -s ../blkmaker .
  cp "$sourceDir"/blkmaker/blkmaker.cfg .
  cd ..
fi

# gbtmaker
if [ ! -d "run_gbtmaker" ]; then
  mkdir "run_gbtmaker" && cd "run_gbtmaker"
  mkdir "log_gbtmaker"
  ln -s ../gbtmaker .
  cp "$sourceDir"/gbtmaker/gbtmaker.cfg .
  cd ..
fi

# gwmaker
if [ ! -d "run_gwmaker" ]; then
  mkdir "run_gwmaker" && cd "run_gwmaker"
  mkdir "log_gwmaker"
  ln -s ../gwmaker .
  cp "$sourceDir"/gwmaker/gwmaker.cfg .
  cd ..
fi

# jobmaker
if [ ! -d "run_jobmaker" ]; then
  mkdir "run_jobmaker" && cd "run_jobmaker"
  mkdir "log_jobmaker"
  ln -s ../jobmaker .
  cp "$sourceDir"/jobmaker/jobmaker.cfg .
  cd ..
fi

# sharelogger
if [ ! -d "run_sharelogger" ]; then
  mkdir "run_sharelogger" && cd "run_sharelogger"
  mkdir "log_sharelogger"
  ln -s ../sharelogger .
  cp "$sourceDir"/sharelogger/sharelogger.cfg .
  cd ..
fi

# slparser
if [ ! -d "run_slparser" ]; then
  mkdir "run_slparser" && cd "run_slparser"
  mkdir "log_slparser"
  ln -s ../slparser .
  cp "$sourceDir"/slparser/slparser.cfg .
  cd ..
fi

# sserver
if [ ! -d "run_sserver" ]; then
  mkdir "run_sserver" && cd "run_sserver"
  mkdir "log_sserver"
  ln -s ../sserver .
  cp "$sourceDir"/sserver/sserver.cfg .
  cd ..
fi

# statshttpd
if [ ! -d "run_statshttpd" ]; then
  mkdir "run_statshttpd" && cd "run_statshttpd"
  mkdir "log_statshttpd"
  ln -s ../statshttpd .
  cp "$sourceDir"/statshttpd/statshttpd.cfg .
  cd ..
fi

# poolwatcher
if [ ! -d "run_poolwatcher" ]; then
  mkdir "run_poolwatcher" && cd "run_poolwatcher"
  mkdir "log_poolwatcher"
  ln -s ../poolwatcher .
  cp "$sourceDir"/poolwatcher/poolwatcher.cfg .
  cd ..
fi

# simulator
if [ ! -d "run_simulator" ]; then
  mkdir "run_simulator" && cd "run_simulator"
  mkdir "log_simulator"
  ln -s ../simulator .
  cp "$sourceDir"/simulator/simulator.cfg .
  cd ..
fi

# nmcauxmaker
if [ ! -d "run_nmcauxmaker" ]; then
  mkdir "run_nmcauxmaker" && cd "run_nmcauxmaker"
  mkdir "log_nmcauxmaker"
  ln -s ../nmcauxmaker .
  cp "$sourceDir"/nmcauxmaker/nmcauxmaker.cfg .
  cd ..
fi


text:
<?

// make sure we have at least a name - everything else is optional
if(trim($_GET['did']) == '')
{
	$notifications[] = array("warning", "Your item was not deleted because it's identifier was not specified!");
	return 0;
}

// get our item information
$result = mysqli_query($db, "select * from items where id='".$_GET['did']."';");
$item = mysqli_fetch_array($result);

// and delete it!
$result = mysqli_query($db, "delete from items where id='".$_GET['did']."';");
if($result === FALSE)
{
	$errorMessage = mysqli_error($db);
	return 0;
}

// also delete the item from any shopping lists
$result = mysqli_query($db, "delete from shoppingLists where itemID='".$_GET['did']."';");
if($result === FALSE)
{
	$errorMessage = mysqli_error($db);
	return 0;
}

// notify by email
include('actions/emailnotify.php');
emailNotify($_SESSION['name'], 'delete', $item['name']);

$notifications[] = array("success", "'" . $item['name'] . "' was deleted!");

?>


text:
title: Service Consumer
---
The agent that is using a [service](#service).


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    android:gravity="center"
    android:background="@drawable/login_fragment_background"
    tools:context="com.sevenre.trackre.parent.fragment.LoginFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/simply_track"
        android:gravity="center"
        android:layout_margin="30dp"
        android:textAllCaps="true"
        android:textColor="@color/login_title" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/simply_track_message"
        android:gravity="center"
        android:layout_marginBottom="60dp"
        android:textColor="@color/login_message" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:ems="10"
        android:hint="@string/school_code"
        android:background="@color/white"
        android:id="@+id/login_phone"
        android:padding="@dimen/padding_login_edit_text"
        android:gravity="center"
        android:layout_marginBottom="@dimen/margin_login_input_field"
        />

    <Button
        android:id="@+id/login_continue"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/continue_"
        android:textColor="@color/white"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
        style="@style/Material.Drawable.Ripple.Wave.Light"
        android:background="@color/login_forward_button"
        android:layout_marginTop="58dp" />

</LinearLayout>


text:
#ifndef CHANNEL_MANAGER_H_
#define CHANNEL_MANAGER_H_

#ifdef __cplusplus
extern "C" {
#endif

#include <linux/limits.h>
#include <sys/un.h>
#include <rte_atomic.h>
#include "channel_commands.h"

/* Maximum name length including '\0' terminator */
#define CHANNEL_MGR_MAX_NAME_LEN    64

/* Maximum number of channels to each Virtual Machine */
#define CHANNEL_MGR_MAX_CHANNELS    64

/* Hypervisor Path for libvirt(qemu/KVM) */
#define CHANNEL_MGR_DEFAULT_HV_PATH "qemu:///system"

/* File socket directory */
#define CHANNEL_MGR_SOCKET_PATH     "/tmp/powermonitor/"

#ifndef UNIX_PATH_MAX
struct sockaddr_un _sockaddr_un;
#define UNIX_PATH_MAX sizeof(_sockaddr_un.sun_path)
#endif

/* Communication Channel Status */
enum channel_status { CHANNEL_MGR_CHANNEL_DISCONNECTED = 0,
	CHANNEL_MGR_CHANNEL_CONNECTED,
	CHANNEL_MGR_CHANNEL_DISABLED,
	CHANNEL_MGR_CHANNEL_PROCESSING};

/* VM libvirt(qemu/KVM) connection status */
enum vm_status { CHANNEL_MGR_VM_INACTIVE = 0, CHANNEL_MGR_VM_ACTIVE};

/*
 *  Represents a single and exclusive VM channel that exists between a guest and
 *  the host.
 */
struct channel_info {
	char channel_path[UNIX_PATH_MAX]; /**< Path to host socket */
	volatile uint32_t status;    /**< Connection status(enum channel_status) */
	int fd;                      /**< AF_UNIX socket fd */
	unsigned channel_num;        /**< CHANNEL_MGR_SOCKET_PATH/<vm_name>.channel_num */
	void *priv_info;             /**< Pointer to private info, do not modify */
};

/* Represents a single VM instance used to return internal information about
 * a VM */
struct vm_info {
	char name[CHANNEL_MGR_MAX_NAME_LEN];          /**< VM name */
	enum vm_status status;                        /**< libvirt status */
	uint64_t pcpu_mask[CHANNEL_CMDS_MAX_CPUS];    /**< pCPU mask for each vCPU */
	unsigned num_vcpus;                           /**< number of vCPUS */
	struct channel_info channels[CHANNEL_MGR_MAX_CHANNELS]; /**< Array of channel_info */
	unsigned num_channels;                        /**< Number of channels */
};

/**
 * Initialize the Channel Manager resources and connect to the Hypervisor
 * specified in path.
 * This must be successfully called first before calling any other functions.
 * It must only be call once;
 *
 * @param path
 *  Must be a local path, e.g. qemu:///system.
 *
 * @return
 *  - 0 on success.
 *  - Negative on error.
 */
int channel_manager_init(const char *path);

/**
 * Free resources associated with the Channel Manager.
 *
 * @param path
 *  Must be a local path, e.g. qemu:///system.
 *
 * @return
 *  None
 */
void channel_manager_exit(void);

/**
 * Get the Physical CPU mask for VM lcore channel(vcpu), result is assigned to
 * core_mask.
 * It is not thread-safe.
 *
 * @param chan_info
 *  Pointer to struct channel_info
 *
 * @param vcpu
 *  The virtual CPU to query.
 *
 *
 * @return
 *  - 0 on error.
 *  - >0 on success.
 */
uint64_t get_pcpus_mask(struct channel_info *chan_info, unsigned vcpu);

/**
 * Set the Physical CPU mask for the specified vCPU.
 * It is not thread-safe.
 *
 * @param name
 *  Virtual Machine name to lookup
 *
 * @param vcpu
 *  The virtual CPU to set.
 *
 * @param core_mask
 *  The core mask of the physical CPU(s) to bind the vCPU
 *
 * @return
 *  - 0 on success.
 *  - Negative on error.
 */
int set_pcpus_mask(char *vm_name, unsigned vcpu, uint64_t core_mask);

/**
 * Set the Physical CPU for the specified vCPU.
 * It is not thread-safe.
 *
 * @param name
 *  Virtual Machine name to lookup
 *
 * @param vcpu
 *  The virtual CPU to set.
 *
 * @param core_num
 *  The core number of the physical CPU(s) to bind the vCPU
 *
 * @return
 *  - 0 on success.
 *  - Negative on error.
 */
int set_pcpu(char *vm_name, unsigned vcpu, unsigned core_num);
/**
 * Add a VM as specified by name to the Channel Manager. The name must
 * correspond to a valid libvirt domain name.
 * This is required prior to adding channels.
 * It is not thread-safe.
 *
 * @param name
 *  Virtual Machine name to lookup.
 *
 * @return
 *  - 0 on success.
 *  - Negative on error.
 */
int add_vm(const char *name);

/**
 * Remove a previously added Virtual Machine from the Channel Manager
 * It is not thread-safe.
 *
 * @param name
 *  Virtual Machine name to lookup.
 *
 * @return
 *  - 0 on success.
 *  - Negative on error.
 */
int remove_vm(const char *name);

/**
 * Add all available channels to the VM as specified by name.
 * Channels in the form of paths
 * (CHANNEL_MGR_SOCKET_PATH/<vm_name>.<channel_number>) will only be parsed.
 * It is not thread-safe.
 *
 * @param name
 *  Virtual Machine name to lookup.
 *
 * @return
 *  - N the number of channels added for the VM
 */
int add_all_channels(const char *vm_name);

/**
 * Add the channel numbers in channel_list to the domain specified by name.
 * Channels in the form of paths
 * (CHANNEL_MGR_SOCKET_PATH/<vm_name>.<channel_number>) will only be parsed.
 * It is not thread-safe.
 *
 * @param name
 *  Virtual Machine name to add channels.
 *
 * @param channel_list
 *  Pointer to list of unsigned integers, representing the channel number to add
 *  It must be allocated outside of this function.
 *
 * @param num_channels
 *  The amount of channel numbers in channel_list
 *
 * @return
 *  - N the number of channels added for the VM
 *  - 0 for error
 */
int add_channels(const char *vm_name, unsigned *channel_list,
		unsigned num_channels);

/**
 * Remove a channel definition from the channel manager. This must only be
 * called from the channel monitor thread.
 *
 * @param chan_info
 *  Pointer to a valid struct channel_info.
 *
 * @return
 *  - 0 on success.
 *  - Negative on error.
 */
int remove_channel(struct channel_info **chan_info_dptr);

/**
 * For all channels associated with a Virtual Machine name, update the
 * connection status. Valid states are CHANNEL_MGR_CHANNEL_CONNECTED or
 * CHANNEL_MGR_CHANNEL_DISABLED only.
 *
 *
 * @param name
 *  Virtual Machine name to modify all channels.
 *
 * @param status
 *  The status to set each channel
 *
 * @param num_channels
 *  The amount of channel numbers in channel_list
 *
 * @return
 *  - N the number of channels added for the VM
 *  - 0 for error
 */
int set_channel_status_all(const char *name, enum channel_status status);

/**
 * For all channels in channel_list associated with a Virtual Machine name
 * update the connection status of each.
 * Valid states are CHANNEL_MGR_CHANNEL_CONNECTED or
 * CHANNEL_MGR_CHANNEL_DISABLED only.
 * It is not thread-safe.
 *
 * @param name
 *  Virtual Machine name to add channels.
 *
 * @param channel_list
 *  Pointer to list of unsigned integers, representing the channel numbers to
 *  modify.
 *  It must be allocated outside of this function.
 *
 * @param num_channels
 *  The amount of channel numbers in channel_list
 *
 * @return
 *  - N the number of channels modified for the VM
 *  - 0 for error
 */
int set_channel_status(const char *vm_name, unsigned *channel_list,
		unsigned len_channel_list, enum channel_status status);

/**
 * Populates a pointer to struct vm_info associated with vm_name.
 *
 * @param vm_name
 *  The name of the virtual machine to lookup.
 *
 *  @param vm_info
 *   Pointer to a struct vm_info, this must be allocated prior to calling this
 *   function.
 *
 * @return
 *  - 0 on success.
 *  - Negative on error.
 */
int get_info_vm(const char *vm_name, struct vm_info *info);

#ifdef __cplusplus
}
#endif

#endif /* CHANNEL_MANAGER_H_ */


text:
<input type="checkbox" class="form-control">
	<%= teacher_title %><input type="text" class="form-control hidden title-input" value="<%= teacher_title %>">
	<%= first_name %><input type="text" class="form-control hidden fname-input" value="<%= first_name %>">
	<%= last_name %><input type="text" class="form-control hidden lname-input" value="<%= last_name %>">
	<%= date_created %>

		<button class="btn btn-success btn-sm editTeacher"> Edit</button>
		<button class="btn btn-primary btn-sm editDone hidden"> Done</button>

	<button class="btn btn-danger btn-sm deleteTeacher" href="#"> Delete</button>


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

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

import com.amazonaws.AmazonWebServiceRequest;

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

    /**
     *

     * The Amazon Resource Name (ARN) of the solution containing the training configuration information.
     *

     */
    private String solutionArn;

    /**
     *

     * The Amazon Resource Name (ARN) of the solution containing the training configuration information.
     *

     *
     * @param solutionArn
     *        The Amazon Resource Name (ARN) of the solution containing the training configuration information.
     */

    public void setSolutionArn(String solutionArn) {
        this.solutionArn = solutionArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the solution containing the training configuration information.
     *

     *
     * @return The Amazon Resource Name (ARN) of the solution containing the training configuration information.
     */

    public String getSolutionArn() {
        return this.solutionArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the solution containing the training configuration information.
     *

     *
     * @param solutionArn
     *        The Amazon Resource Name (ARN) of the solution containing the training configuration information.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateSolutionVersionRequest withSolutionArn(String solutionArn) {
        setSolutionArn(solutionArn);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getSolutionArn() != null)
            sb.append("SolutionArn: ").append(getSolutionArn());
        sb.append("}");
        return sb.toString();
    }

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

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

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

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

    @Override
    public CreateSolutionVersionRequest clone() {
        return (CreateSolutionVersionRequest) super.clone();
    }

}


text:
// <copyright file="DefaultGraphiteUdpClient.cs" company="App Metrics Contributors">
// Copyright (c) App Metrics Contributors. All rights reserved.
// </copyright>

using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using App.Metrics.Logging;

namespace App.Metrics.Reporting.Graphite.Client
{
    public class DefaultGraphiteUdpClient : IGraphiteClient
    {
        private static readonly ILog Logger = LogProvider.For<DefaultGraphiteUdpClient>();

        private static TimeSpan _backOffPeriod;
        private static long _backOffTicks;
        private static long _failureAttempts;
        private static long _failuresBeforeBackoff;
        private readonly int _sendTimeout;
        private readonly GraphiteOptions _options;

        public DefaultGraphiteUdpClient(
            GraphiteOptions options,
            ClientPolicy clientPolicy)
        {
            _options = options;
            _backOffPeriod = clientPolicy.BackoffPeriod;
            _failuresBeforeBackoff = clientPolicy.FailuresBeforeBackoff;
            _sendTimeout = clientPolicy.Timeout.Milliseconds;
            _failureAttempts = 0;
        }

        /// <inheritdoc />
        public async Task<GraphiteWriteResult> WriteAsync(string payload, CancellationToken cancellationToken = default)
        {
            if (payload == null)
            {
                return GraphiteWriteResult.SuccessResult;
            }

            if (NeedToBackoff())
            {
                return new GraphiteWriteResult(false, "Too many failures in writing to Graphite - UDP, Circuit Opened");
            }

            try
            {
                using (var client = new UdpClient { Client = { SendTimeout = _sendTimeout } })
                {
                    Logger.Trace("Opening UDP Connection for Graphite");
                    await client.Client.ConnectAsync(_options.BaseUri.Host, _options.BaseUri.Port).ConfigureAwait(false);

                    var datagram = Encoding.UTF8.GetBytes(payload);

                    await client.Client.SendAsync(new ArraySegment<byte>(datagram), SocketFlags.None).ConfigureAwait(false);

                    Logger.Trace("Successful write to Graphite - UDP");

                    return new GraphiteWriteResult(true);
                }
            }
            catch (Exception ex)
            {
                Interlocked.Increment(ref _failureAttempts);
                Logger.Error(ex, "Failed to write to Graphite - UDP");
                return new GraphiteWriteResult(false, ex.ToString());
            }
        }

        private bool NeedToBackoff()
        {
            if (Interlocked.Read(ref _failureAttempts) < _failuresBeforeBackoff)
            {
                return false;
            }

            if (Interlocked.Read(ref _backOffTicks) == 0)
            {
                Interlocked.Exchange(ref _backOffTicks, DateTime.UtcNow.Add(_backOffPeriod).Ticks);
            }

            if (DateTime.UtcNow.Ticks <= Interlocked.Read(ref _backOffTicks))
            {
                return true;
            }

            Interlocked.Exchange(ref _failureAttempts, 0);
            Interlocked.Exchange(ref _backOffTicks, 0);

            return false;
        }
    }
}


text:
/*
// This file implements a variation of the octree color quantization algorithm.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "QuantOctree.h"

typedef struct _ColorBucket{
   /* contains palette index when used for look up cube */
   uint32_t count;
   uint64_t r;
   uint64_t g;
   uint64_t b;
   uint64_t a;
} *ColorBucket;

typedef struct _ColorCube{
   unsigned int rBits, gBits, bBits, aBits;
   unsigned int rWidth, gWidth, bWidth, aWidth;
   unsigned int rOffset, gOffset, bOffset, aOffset;

   long size;
   ColorBucket buckets;
} *ColorCube;

#define MAX(a, b) (a)>(b) ? (a) : (b)

static ColorCube
new_color_cube(int r, int g, int b, int a) {
   ColorCube cube;

   cube = malloc(sizeof(struct _ColorCube));
   if (!cube) return NULL;

   cube->rBits = MAX(r, 0);
   cube->gBits = MAX(g, 0);
   cube->bBits = MAX(b, 0);
   cube->aBits = MAX(a, 0);

   /* the width of the cube for each dimension */
   cube->rWidth = 1<<cube->rBits;
   cube->gWidth = 1<<cube->gBits;
   cube->bWidth = 1<<cube->bBits;
   cube->aWidth = 1<<cube->aBits;

   /* the offsets of each color */

   cube->rOffset = cube->gBits + cube->bBits + cube->aBits;
   cube->gOffset = cube->bBits + cube->aBits;
   cube->bOffset = cube->aBits;
   cube->aOffset = 0;

   /* the number of color buckets */
   cube->size = cube->rWidth * cube->gWidth * cube->bWidth * cube->aWidth;
   cube->buckets = calloc(cube->size, sizeof(struct _ColorBucket));

   if (!cube->buckets) {
      free(cube);
      return NULL;
   }
   return cube;
}

static void
free_color_cube(ColorCube cube) {
   if (cube != NULL) {
      free(cube->buckets);
      free(cube);
   }
}

static long
color_bucket_offset_pos(const ColorCube cube,
   unsigned int r, unsigned int g, unsigned int b, unsigned int a)
{
   return r<<cube->rOffset | g<<cube->gOffset | b<<cube->bOffset | a<<cube->aOffset;
}

static long
color_bucket_offset(const ColorCube cube, const Pixel *p) {
   unsigned int r = p->c.r>>(8-cube->rBits);
   unsigned int g = p->c.g>>(8-cube->gBits);
   unsigned int b = p->c.b>>(8-cube->bBits);
   unsigned int a = p->c.a>>(8-cube->aBits);
   return color_bucket_offset_pos(cube, r, g, b, a);
}

static ColorBucket
color_bucket_from_cube(const ColorCube cube, const Pixel *p) {
   unsigned int offset = color_bucket_offset(cube, p);
   return &cube->buckets[offset];
}

static void
add_color_to_color_cube(const ColorCube cube, const Pixel *p) {
   ColorBucket bucket = color_bucket_from_cube(cube, p);
   bucket->count += 1;
   bucket->r += p->c.r;
   bucket->g += p->c.g;
   bucket->b += p->c.b;
   bucket->a += p->c.a;
}

static long
count_used_color_buckets(const ColorCube cube) {
   long usedBuckets = 0;
   long i;
   for (i=0; i < cube->size; i++) {
      if (cube->buckets[i].count > 0) {
         usedBuckets += 1;
      }
   }
   return usedBuckets;
}

static void
avg_color_from_color_bucket(const ColorBucket bucket, Pixel *dst) {
   float count = bucket->count;
   dst->c.r = (int)(bucket->r / count);
   dst->c.g = (int)(bucket->g / count);
   dst->c.b = (int)(bucket->b / count);
   dst->c.a = (int)(bucket->a / count);
}

static int
compare_bucket_count(const ColorBucket a, const ColorBucket b) {
   return b->count - a->count;
}

static ColorBucket
create_sorted_color_palette(const ColorCube cube) {
   ColorBucket buckets;
   buckets = malloc(sizeof(struct _ColorBucket)*cube->size);
   if (!buckets) return NULL;
   memcpy(buckets, cube->buckets, sizeof(struct _ColorBucket)*cube->size);

   qsort(buckets, cube->size, sizeof(struct _ColorBucket),
         (int (*)(void const *, void const *))&compare_bucket_count);

   return buckets;
}

void add_bucket_values(ColorBucket src, ColorBucket dst) {
   dst->count += src->count;
   dst->r += src->r;
   dst->g += src->g;
   dst->b += src->b;
   dst->a += src->a;
}

/* expand or shrink a given cube to level */
static ColorCube copy_color_cube(const ColorCube cube,
   int rBits, int gBits, int bBits, int aBits)
{
   unsigned int r, g, b, a;
   long src_pos, dst_pos;
   unsigned int src_reduce[4] = {0}, dst_reduce[4] = {0};
   unsigned int width[4];
   ColorCube result;

   result = new_color_cube(rBits, gBits, bBits, aBits);
   if (!result) return NULL;

   if (cube->rBits > rBits) {
      dst_reduce[0] = cube->rBits - result->rBits;
      width[0] = cube->rWidth;
   } else {
      src_reduce[0] = result->rBits - cube->rBits;
      width[0] = result->rWidth;
   }
   if (cube->gBits > gBits) {
      dst_reduce[1] = cube->gBits - result->gBits;
      width[1] = cube->gWidth;
   } else {
      src_reduce[1] = result->gBits - cube->gBits;
      width[1] = result->gWidth;
   }
   if (cube->bBits > bBits) {
      dst_reduce[2] = cube->bBits - result->bBits;
      width[2] = cube->bWidth;
   } else {
      src_reduce[2] = result->bBits - cube->bBits;
      width[2] = result->bWidth;
   }
   if (cube->aBits > aBits) {
      dst_reduce[3] = cube->aBits - result->aBits;
      width[3] = cube->aWidth;
   } else {
      src_reduce[3] = result->aBits - cube->aBits;
      width[3] = result->aWidth;
   }

   for (r=0; r<width[0]; r++) {
      for (g=0; g<width[1]; g++) {
         for (b=0; b<width[2]; b++) {
            for (a=0; a<width[3]; a++) {
               src_pos = color_bucket_offset_pos(cube,
                                               r>>src_reduce[0],
                                               g>>src_reduce[1],
                                               b>>src_reduce[2],
                                               a>>src_reduce[3]);
               dst_pos = color_bucket_offset_pos(result,
                                               r>>dst_reduce[0],
                                               g>>dst_reduce[1],
                                               b>>dst_reduce[2],
                                               a>>dst_reduce[3]);
               add_bucket_values(
                  &cube->buckets[src_pos],
                  &result->buckets[dst_pos]
               );
            }
         }
      }
   }
   return result;
}

void
subtract_color_buckets(ColorCube cube, ColorBucket buckets, long nBuckets) {
   ColorBucket minuend, subtrahend;
   long i;
   Pixel p;
   for (i=0; i<nBuckets; i++) {
      subtrahend = &buckets[i];
      avg_color_from_color_bucket(subtrahend, &p);
      minuend = color_bucket_from_cube(cube, &p);
      minuend->count -= subtrahend->count;
      minuend->r -= subtrahend->r;
      minuend->g -= subtrahend->g;
      minuend->b -= subtrahend->b;
      minuend->a -= subtrahend->a;
   }
}

static void
set_lookup_value(const ColorCube cube, const Pixel *p, long value) {
   ColorBucket bucket = color_bucket_from_cube(cube, p);
   bucket->count = value;
}

uint64_t
lookup_color(const ColorCube cube, const Pixel *p) {
   ColorBucket bucket = color_bucket_from_cube(cube, p);
   return bucket->count;
}

void add_lookup_buckets(ColorCube cube, ColorBucket palette, long nColors, long offset) {
   long i;
   Pixel p;
   for (i=offset; i<offset+nColors; i++) {
      avg_color_from_color_bucket(&palette[i], &p);
      set_lookup_value(cube, &p, i);
   }
}

ColorBucket
combined_palette(ColorBucket bucketsA, long nBucketsA, ColorBucket bucketsB, long nBucketsB) {
   ColorBucket result;
   result = malloc(sizeof(struct _ColorBucket)*(nBucketsA+nBucketsB));
   memcpy(result, bucketsA, sizeof(struct _ColorBucket) * nBucketsA);
   memcpy(&result[nBucketsA], bucketsB, sizeof(struct _ColorBucket) * nBucketsB);
   return result;
}

static Pixel *
create_palette_array(const ColorBucket palette, unsigned int paletteLength) {
   Pixel *paletteArray;
   unsigned int i;

   paletteArray = malloc(sizeof(Pixel)*paletteLength);
   if (!paletteArray) return NULL;

   for (i=0; i<paletteLength; i++) {
      avg_color_from_color_bucket(&palette[i], &paletteArray[i]);
   }
   return paletteArray;
}

static void
map_image_pixels(const Pixel *pixelData,
                 uint32_t nPixels,
                 const ColorCube lookupCube,
                 uint32_t *pixelArray)
{
   long i;
   for (i=0; i<nPixels; i++) {
      pixelArray[i] = lookup_color(lookupCube, &pixelData[i]);
   }
}

const int CUBE_LEVELS[8]       = {4, 4, 4, 0, 2, 2, 2, 0};
const int CUBE_LEVELS_ALPHA[8] = {3, 4, 3, 3, 2, 2, 2, 2};

int quantize_octree(Pixel *pixelData,
          uint32_t nPixels,
          uint32_t nQuantPixels,
          Pixel **palette,
          uint32_t *paletteLength,
          uint32_t **quantizedPixels,
          int withAlpha)
{
   ColorCube fineCube = NULL;
   ColorCube coarseCube = NULL;
   ColorCube lookupCube = NULL;
   ColorCube coarseLookupCube = NULL;
   ColorBucket paletteBucketsCoarse = NULL;
   ColorBucket paletteBucketsFine = NULL;
   ColorBucket paletteBuckets = NULL;
   uint32_t *qp = NULL;
   long i;
   long nCoarseColors, nFineColors, nAlreadySubtracted;
   const int *cubeBits;

   if (withAlpha) {
       cubeBits = CUBE_LEVELS_ALPHA;
   }
   else {
       cubeBits = CUBE_LEVELS;
   }

   /*
   Create two color cubes, one fine grained with 8x16x8=1024
   colors buckets and a coarse with 4x4x4=64 color buckets.
   The coarse one guarantees that there are color buckets available for
   the whole color range (assuming nQuantPixels > 64).

   For a quantization to 256 colors all 64 coarse colors will be used
   plus the 192 most used color buckets from the fine color cube.
   The average of all colors within one bucket is used as the actual
   color for that bucket.

    For images with alpha the cubes gets a forth dimension,
    8x16x8x8 and 4x4x4x4.
   */

   /* create fine cube */
   fineCube = new_color_cube(cubeBits[0], cubeBits[1],
                             cubeBits[2], cubeBits[3]);
   if (!fineCube) goto error;
   for (i=0; i<nPixels; i++) {
      add_color_to_color_cube(fineCube, &pixelData[i]);
   }

   /* create coarse cube */
   coarseCube = copy_color_cube(fineCube, cubeBits[4], cubeBits[5],
                                          cubeBits[6], cubeBits[7]);
   if (!coarseCube) goto error;
   nCoarseColors = count_used_color_buckets(coarseCube);

   /* limit to nQuantPixels */
   if (nCoarseColors > nQuantPixels)
      nCoarseColors = nQuantPixels;

   /* how many space do we have in our palette for fine colors? */
   nFineColors = nQuantPixels - nCoarseColors;

   /* create fine color palette */
   paletteBucketsFine = create_sorted_color_palette(fineCube);
   if (!paletteBucketsFine) goto error;

   /* remove the used fine colors from the coarse cube */
   subtract_color_buckets(coarseCube, paletteBucketsFine, nFineColors);

   /* did the substraction cleared one or more coarse bucket? */
   while (nCoarseColors > count_used_color_buckets(coarseCube)) {
      /* then we can use the free buckets for fine colors */
      nAlreadySubtracted = nFineColors;
      nCoarseColors = count_used_color_buckets(coarseCube);
      nFineColors = nQuantPixels - nCoarseColors;
      subtract_color_buckets(coarseCube, &paletteBucketsFine[nAlreadySubtracted],
                             nFineColors-nAlreadySubtracted);
   }

   /* create our palette buckets with fine and coarse combined */
   paletteBucketsCoarse = create_sorted_color_palette(coarseCube);
   if (!paletteBucketsCoarse) goto error;
   paletteBuckets = combined_palette(paletteBucketsCoarse, nCoarseColors,
                                     paletteBucketsFine, nFineColors);

   free(paletteBucketsFine);
   paletteBucketsFine = NULL;
   free(paletteBucketsCoarse);
   paletteBucketsCoarse = NULL;

   /* add all coarse colors to our coarse lookup cube. */
   coarseLookupCube = new_color_cube(cubeBits[4], cubeBits[5],
                                     cubeBits[6], cubeBits[7]);
   if (!coarseLookupCube) goto error;
   add_lookup_buckets(coarseLookupCube, paletteBuckets, nCoarseColors, 0);

   /* expand coarse cube (64) to larger fine cube (4k). the value of each
      coarse bucket is then present in the according 64 fine buckets. */
   lookupCube = copy_color_cube(coarseLookupCube, cubeBits[0], cubeBits[1],
                                                  cubeBits[2], cubeBits[3]);
   if (!lookupCube) goto error;

   /* add fine colors to the lookup cube */
   add_lookup_buckets(lookupCube, paletteBuckets, nFineColors, nCoarseColors);

   /* create result pixels and map palette indices */
   qp = malloc(sizeof(Pixel)*nPixels);
   if (!qp) goto error;
   map_image_pixels(pixelData, nPixels, lookupCube, qp);

   /* convert palette buckets to RGB pixel palette */
   *palette = create_palette_array(paletteBuckets, nQuantPixels);
   if (!(*palette)) goto error;

   *quantizedPixels = qp;
   *paletteLength = nQuantPixels;

   free_color_cube(coarseCube);
   free_color_cube(fineCube);
   free_color_cube(lookupCube);
   free_color_cube(coarseLookupCube);
   free(paletteBuckets);
   return 1;

error:
   /* everything is initialized to NULL
      so we are safe to call free */
   free(qp);
   free_color_cube(lookupCube);
   free_color_cube(coarseLookupCube);
   free(paletteBucketsCoarse);
   free(paletteBucketsFine);
   free_color_cube(coarseCube);
   free_color_cube(fineCube);
   return 0;
}