text:
package org.elasticsearch.search.suggest;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.plugins.ScriptPlugin;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.TemplateScript;
import org.elasticsearch.search.suggest.phrase.DirectCandidateGeneratorBuilder;
import org.elasticsearch.search.suggest.phrase.Laplace;
import org.elasticsearch.search.suggest.phrase.LinearInterpolation;
import org.elasticsearch.search.suggest.phrase.PhraseSuggestionBuilder;
import org.elasticsearch.search.suggest.phrase.StupidBackoff;
import org.elasticsearch.search.suggest.term.TermSuggestionBuilder;
import org.elasticsearch.search.suggest.term.TermSuggestionBuilder.SuggestMode;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.hamcrest.ElasticsearchAssertions;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutionException;

import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_REPLICAS;
import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.search.suggest.SuggestBuilders.phraseSuggestion;
import static org.elasticsearch.search.suggest.SuggestBuilders.termSuggestion;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertRequestBuilderThrows;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSuggestion;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSuggestionPhraseCollateMatchExists;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSuggestionSize;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.nullValue;

/**
 * Integration tests for term and phrase suggestions.  Many of these tests many requests that vary only slightly from one another.  Where
 * possible these tests should declare for the first request, make the request, modify the configuration for the next request, make that
 * request, modify again, request again, etc.  This makes it very obvious what changes between requests.
 */
public class SuggestSearchIT extends ESIntegTestCase {

    // see #3196
    public void testSuggestAcrossMultipleIndices() throws IOException {
        assertAcked(prepareCreate("test").setMapping("text", "type=text"));
        ensureGreen();

        indexDoc("test", "1", "text", "abcd");
        indexDoc("test", "2", "text", "aacd");
        indexDoc("test", "3", "text", "abbd");
        indexDoc("test", "4", "text", "abcc");
        refresh();

        TermSuggestionBuilder termSuggest = termSuggestion("text")
                .suggestMode(SuggestMode.ALWAYS) // Always, otherwise the results can vary between requests.
                .text("abcd");
        logger.info("--> run suggestions with one index");
        searchSuggest("test", termSuggest);
        assertAcked(prepareCreate("test_1").setMapping("text", "type=text"));
        ensureGreen();

        indexDoc("test_1", "1", "text", "ab cd");
        indexDoc("test_1", "2", "text", "aa cd");
        indexDoc("test_1", "3", "text", "ab bd");
        indexDoc("test_1", "4", "text", "ab cc");
        refresh();
        termSuggest = termSuggestion("text")
                .suggestMode(SuggestMode.ALWAYS) // Always, otherwise the results can vary between requests.
                .text("ab cd")
                .minWordLength(1);
        logger.info("--> run suggestions with two indices");
        searchSuggest("test", termSuggest);

        XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("_doc")
                .startObject("properties")
                .startObject("text").field("type", "text").field("analyzer", "keyword").endObject()
                .endObject()
                .endObject().endObject();
        assertAcked(prepareCreate("test_2").setMapping(mapping));
        ensureGreen();

        indexDoc("test_2", "1", "text", "ab cd");
        indexDoc("test_2", "2", "text", "aa cd");
        indexDoc("test_2", "3", "text", "ab bd");
        indexDoc("test_2", "4", "text", "ab cc");
        indexDoc("test_2", "1", "text", "abcd");
        indexDoc("test_2", "2", "text", "aacd");
        indexDoc("test_2", "3", "text", "abbd");
        indexDoc("test_2", "4", "text", "abcc");
        refresh();

        termSuggest = termSuggestion("text")
                .suggestMode(SuggestMode.ALWAYS) // Always, otherwise the results can vary between requests.
                .text("ab cd")
                .minWordLength(1);
        logger.info("--> run suggestions with three indices");
        try {
            searchSuggest("test", termSuggest);
            fail(" can not suggest across multiple indices with different analysis chains");
        } catch (SearchPhaseExecutionException ex) {
            assertThat(ex.getCause(), instanceOf(IllegalStateException.class));
            assertThat(ex.getCause().getMessage(),
                    anyOf(endsWith("Suggest entries have different sizes actual [1] expected [2]"),
                            endsWith("Suggest entries have different sizes actual [2] expected [1]")));
        } catch (IllegalStateException ex) {
            assertThat(ex.getMessage(), anyOf(endsWith("Suggest entries have different sizes actual [1] expected [2]"),
                    endsWith("Suggest entries have different sizes actual [2] expected [1]")));
        }

        termSuggest = termSuggestion("text")
                .suggestMode(SuggestMode.ALWAYS) // Always, otherwise the results can vary between requests.
                .text("ABCD")
                .minWordLength(1);
        logger.info("--> run suggestions with four indices");
        try {
            searchSuggest("test", termSuggest);
            fail(" can not suggest across multiple indices with different analysis chains");
        } catch (SearchPhaseExecutionException ex) {
            assertThat(ex.getCause(), instanceOf(IllegalStateException.class));
            assertThat(ex.getCause().getMessage(), anyOf(endsWith("Suggest entries have different text actual [ABCD] expected [abcd]"),
                    endsWith("Suggest entries have different text actual [abcd] expected [ABCD]")));
        } catch (IllegalStateException ex) {
            assertThat(ex.getMessage(), anyOf(endsWith("Suggest entries have different text actual [ABCD] expected [abcd]"),
                    endsWith("Suggest entries have different text actual [abcd] expected [ABCD]")));
        }
    }

    // see #3037
    public void testSuggestModes() throws IOException {
        CreateIndexRequestBuilder builder = prepareCreate("test").setSettings(Settings.builder()
                .put(SETTING_NUMBER_OF_SHARDS, 1)
                .put(SETTING_NUMBER_OF_REPLICAS, 0)
                .put("index.analysis.analyzer.biword.tokenizer", "standard")
                .putList("index.analysis.analyzer.biword.filter", "shingler", "lowercase")
                .put("index.analysis.filter.shingler.type", "shingle")
                .put("index.analysis.filter.shingler.min_shingle_size", 2)
                .put("index.analysis.filter.shingler.max_shingle_size", 3));

        XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("_doc")
                .startObject("properties")
                .startObject("name")
                    .field("type", "text")
                    .startObject("fields")
                        .startObject("shingled")
                            .field("type", "text")
                            .field("analyzer", "biword")
                            .field("search_analyzer", "standard")
                        .endObject()
                    .endObject()
                .endObject()
                .endObject()
                .endObject().endObject();
        assertAcked(builder.setMapping(mapping));
        ensureGreen();

        indexDoc("test", "1", "name", "I like iced tea");
        indexDoc("test", "2", "name", "I like tea.");
        indexDoc("test", "3", "name", "I like ice cream.");
        refresh();

        DirectCandidateGeneratorBuilder generator = candidateGenerator("name").prefixLength(0).minWordLength(0).suggestMode("always")
            .maxEdits(2);
        PhraseSuggestionBuilder phraseSuggestion = phraseSuggestion("name.shingled")
                .addCandidateGenerator(generator)
                .gramSize(3);
        Suggest searchSuggest = searchSuggest("ice tea", "did_you_mean", phraseSuggestion);
        assertSuggestion(searchSuggest, 0, "did_you_mean", "iced tea");

        generator.suggestMode(null);
        searchSuggest = searchSuggest( "ice tea", "did_you_mean", phraseSuggestion);
        assertSuggestionSize(searchSuggest, 0, 0, "did_you_mean");
    }

    /**
     * Creates a new {@link DirectCandidateGeneratorBuilder}
     *
     * @param field
     *            the field this candidate generator operates on.
     */
    private DirectCandidateGeneratorBuilder candidateGenerator(String field) {
        return new DirectCandidateGeneratorBuilder(field);
    }

    // see #2729
    public void testSizeOneShard() throws Exception {
        prepareCreate("test").setSettings(Settings.builder().put(SETTING_NUMBER_OF_SHARDS, 1).put(SETTING_NUMBER_OF_REPLICAS, 0)).get();
        ensureGreen();

        for (int i = 0; i < 15; i++) {
            indexDoc("test", Integer.toString(i), "text", "abc" + i);
        }
        refresh();

        SearchResponse search = client().prepareSearch().setQuery(matchQuery("text", "spellchecker")).get();
        assertThat("didn't ask for suggestions but got some", search.getSuggest(), nullValue());

        TermSuggestionBuilder termSuggestion = termSuggestion("text")
                .suggestMode(SuggestMode.ALWAYS) // Always, otherwise the results can vary between requests.
                .text("abcd")
                .size(10);
        Suggest suggest = searchSuggest("test", termSuggestion);
        assertSuggestion(suggest, 0, "test", 10, "abc0");

        termSuggestion.text("abcd").shardSize(5);
        suggest = searchSuggest("test", termSuggestion);
        assertSuggestion(suggest, 0, "test", 5, "abc0");
    }

    public void testUnmappedField() throws IOException, InterruptedException, ExecutionException {
        CreateIndexRequestBuilder builder = prepareCreate("test").setSettings(Settings.builder()
                .put(indexSettings())
                .put("index.analysis.analyzer.biword.tokenizer", "standard")
                .putList("index.analysis.analyzer.biword.filter", "shingler", "lowercase")
                .put("index.analysis.filter.shingler.type", "shingle")
                .put("index.analysis.filter.shingler.min_shingle_size", 2)
                .put("index.analysis.filter.shingler.max_shingle_size", 3));
        XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("_doc")
                .startObject("properties")
                .startObject("name")
                    .field("type", "text")
                    .startObject("fields")
                        .startObject("shingled")
                            .field("type", "text")
                            .field("analyzer", "biword")
                            .field("search_analyzer", "standard")
                        .endObject()
                    .endObject()
                .endObject()
                .endObject()
                .endObject().endObject();
        assertAcked(builder.setMapping(mapping));
        ensureGreen();

        indexRandom(true, client().prepareIndex("test").setSource("name", "I like iced tea"),
        client().prepareIndex("test").setSource("name", "I like tea."),
        client().prepareIndex("test").setSource("name", "I like ice cream."));
        refresh();

        PhraseSuggestionBuilder phraseSuggestion = phraseSuggestion("name.shingled")
                .addCandidateGenerator(candidateGenerator("name").prefixLength(0).minWordLength(0).suggestMode("always").maxEdits(2))
                .gramSize(3);
        Suggest searchSuggest = searchSuggest("ice tea", "did_you_mean", phraseSuggestion);
        assertSuggestion(searchSuggest, 0, 0, "did_you_mean", "iced tea");

        phraseSuggestion = phraseSuggestion("nosuchField")
                .addCandidateGenerator(candidateGenerator("name").prefixLength(0).minWordLength(0).suggestMode("always").maxEdits(2))
                .gramSize(3);
        {
            SearchRequestBuilder searchBuilder = client().prepareSearch().setSize(0);
            searchBuilder.suggest(new SuggestBuilder().setGlobalText("tetsting sugestion").addSuggestion("did_you_mean", phraseSuggestion));
            assertRequestBuilderThrows(searchBuilder, SearchPhaseExecutionException.class);
        }
        {
            SearchRequestBuilder searchBuilder = client().prepareSearch().setSize(0);
            searchBuilder.suggest(new SuggestBuilder().setGlobalText("tetsting sugestion").addSuggestion("did_you_mean", phraseSuggestion));
            assertRequestBuilderThrows(searchBuilder, SearchPhaseExecutionException.class);
        }
    }

    public void testSimple() throws Exception {
        assertAcked(prepareCreate("test").setMapping("text", "type=text"));
        ensureGreen();

        indexDoc("test", "1", "text", "abcd");
        indexDoc("test", "2", "text", "aacd");
        indexDoc("test", "3", "text", "abbd");
        indexDoc("test", "4", "text", "abcc");
        refresh();

        SearchResponse search = client().prepareSearch().setQuery(matchQuery("text", "spellcecker")).get();
        assertThat("didn't ask for suggestions but got some", search.getSuggest(), nullValue());

        TermSuggestionBuilder termSuggest = termSuggestion("text")
                .suggestMode(SuggestMode.ALWAYS) // Always, otherwise the results can vary between requests.
                .text("abcd");
        Suggest suggest = searchSuggest("test", termSuggest);
        assertSuggestion(suggest, 0, "test", "aacd", "abbd", "abcc");
        assertThat(suggest.getSuggestion("test").getEntries().get(0).getText().string(), equalTo("abcd"));

        suggest = searchSuggest("test", termSuggest);
        assertSuggestion(suggest, 0, "test", "aacd","abbd", "abcc");
        assertThat(suggest.getSuggestion("test").getEntries().get(0).getText().string(), equalTo("abcd"));
    }

    public void testEmpty() throws Exception {
        assertAcked(prepareCreate("test").setMapping("text", "type=text"));
        ensureGreen();

        indexDoc("test", "1", "text", "bar");
        refresh();

        TermSuggestionBuilder termSuggest = termSuggestion("text")
                .suggestMode(SuggestMode.ALWAYS) // Always, otherwise the results can vary between requests.
                .text("abcd");
        Suggest suggest = searchSuggest("test", termSuggest);
        assertSuggestionSize(suggest, 0, 0, "test");
        assertThat(suggest.getSuggestion("test").getEntries().get(0).getText().string(), equalTo("abcd"));

        suggest = searchSuggest("test", termSuggest);
        assertSuggestionSize(suggest, 0, 0, "test");
        assertThat(suggest.getSuggestion("test").getEntries().get(0).getText().string(), equalTo("abcd"));
    }

    public void testEmptyIndex() throws Exception {
        assertAcked(prepareCreate("test").setMapping("text", "type=text"));
        ensureGreen();

        // use SuggestMode.ALWAYS, otherwise the results can vary between requests.
        TermSuggestionBuilder termSuggest = termSuggestion("text")
                .suggestMode(SuggestMode.ALWAYS)
                .text("abcd");
        Suggest suggest = searchSuggest("test", termSuggest);
        assertSuggestionSize(suggest, 0, 0, "test");
        assertThat(suggest.getSuggestion("test").getEntries().get(0).getText().string(), equalTo("abcd"));

        suggest = searchSuggest("test", termSuggest);
        assertSuggestionSize(suggest, 0, 0, "test");
        assertThat(suggest.getSuggestion("test").getEntries().get(0).getText().string(), equalTo("abcd"));

        indexDoc("test", "1", "text", "bar");
        refresh();

        suggest = searchSuggest("test", termSuggest);
        assertSuggestionSize(suggest, 0, 0, "test");
        assertThat(suggest.getSuggestion("test").getEntries().get(0).getText().string(), equalTo("abcd"));

        suggest = searchSuggest("test", termSuggest);
        assertSuggestionSize(suggest, 0, 0, "test");
        assertThat(suggest.getSuggestion("test").getEntries().get(0).getText().string(), equalTo("abcd"));
    }

    public void testWithMultipleCommands() throws Exception {
        assertAcked(prepareCreate("test").setMapping("field1", "type=text", "field2", "type=text"));
        ensureGreen();

        indexDoc("test", "1", "field1", "prefix_abcd", "field2", "prefix_efgh");
        indexDoc("test", "2", "field1", "prefix_aacd", "field2", "prefix_eeeh");
        indexDoc("test", "3", "field1", "prefix_abbd", "field2", "prefix_efff");
        indexDoc("test", "4", "field1", "prefix_abcc", "field2", "prefix_eggg");
        refresh();

        Map<String, SuggestionBuilder<?>> suggestions = new HashMap<>();
        suggestions.put("size1", termSuggestion("field1")
                .size(1).text("prefix_abcd").maxTermFreq(10).prefixLength(1).minDocFreq(0)
                .suggestMode(SuggestMode.ALWAYS));
        suggestions.put("field2", termSuggestion("field2")
                .text("prefix_eeeh prefix_efgh")
                .maxTermFreq(10).minDocFreq(0).suggestMode(SuggestMode.ALWAYS));
        suggestions.put("accuracy", termSuggestion("field2")
                .text("prefix_efgh").accuracy(1f)
                .maxTermFreq(10).minDocFreq(0).suggestMode(SuggestMode.ALWAYS));
        Suggest suggest = searchSuggest(null, 0, suggestions);
        assertSuggestion(suggest, 0, "size1", "prefix_aacd");
        assertThat(suggest.getSuggestion("field2").getEntries().get(0).getText().string(), equalTo("prefix_eeeh"));
        assertSuggestion(suggest, 0, "field2", "prefix_efgh");
        assertThat(suggest.getSuggestion("field2").getEntries().get(1).getText().string(), equalTo("prefix_efgh"));
        assertSuggestion(suggest, 1, "field2", "prefix_eeeh", "prefix_efff", "prefix_eggg");
        assertSuggestionSize(suggest, 0, 0, "accuracy");
    }

    public void testSizeAndSort() throws Exception {
        createIndex("test");
        ensureGreen();

        Map<String, Integer> termsAndDocCount = new HashMap<>();
        termsAndDocCount.put("prefix_aaad", 20);
        termsAndDocCount.put("prefix_abbb", 18);
        termsAndDocCount.put("prefix_aaca", 16);
        termsAndDocCount.put("prefix_abba", 14);
        termsAndDocCount.put("prefix_accc", 12);
        termsAndDocCount.put("prefix_addd", 10);
        termsAndDocCount.put("prefix_abaa", 8);
        termsAndDocCount.put("prefix_dbca", 6);
        termsAndDocCount.put("prefix_cbad", 4);
        termsAndDocCount.put("prefix_aacd", 1);
        termsAndDocCount.put("prefix_abcc", 1);
        termsAndDocCount.put("prefix_accd", 1);

        for (Entry<String, Integer> entry : termsAndDocCount.entrySet()) {
            for (int i = 0; i < entry.getValue(); i++) {
                indexDoc("test", entry.getKey() + i, "field1", entry.getKey());
            }
        }
        refresh();

        Map<String, SuggestionBuilder<?>> suggestions = new HashMap<>();
        suggestions.put("size3SortScoreFirst", termSuggestion("field1")
                .size(3).minDocFreq(0).suggestMode(SuggestMode.ALWAYS));
        suggestions.put("size10SortScoreFirst", termSuggestion("field1")
                .size(10).minDocFreq(0).suggestMode(SuggestMode.ALWAYS).shardSize(50));
        suggestions.put("size3SortScoreFirstMaxEdits1", termSuggestion("field1")
                .maxEdits(1)
                .size(10).minDocFreq(0).suggestMode(SuggestMode.ALWAYS));
        suggestions.put("size10SortFrequencyFirst", termSuggestion("field1")
                .size(10).sort(SortBy.FREQUENCY).shardSize(1000)
                .minDocFreq(0).suggestMode(SuggestMode.ALWAYS));
        Suggest suggest = searchSuggest("prefix_abcd", 0, suggestions);

        // The commented out assertions fail sometimes because suggestions are based off of shard frequencies instead of index frequencies.
        assertSuggestion(suggest, 0, "size3SortScoreFirst", "prefix_aacd", "prefix_abcc", "prefix_accd");
        assertSuggestion(suggest, 0, "size10SortScoreFirst", 10, "prefix_aacd", "prefix_abcc", "prefix_accd" /*, "prefix_aaad" */);
        assertSuggestion(suggest, 0, "size3SortScoreFirstMaxEdits1", "prefix_aacd", "prefix_abcc", "prefix_accd");
        assertSuggestion(suggest, 0, "size10SortFrequencyFirst", "prefix_aaad", "prefix_abbb", "prefix_aaca", "prefix_abba",
                "prefix_accc", "prefix_addd", "prefix_abaa", "prefix_dbca", "prefix_cbad", "prefix_aacd");

        // assertThat(suggest.get(3).getSuggestedWords().get("prefix_abcd").get(4).getTerm(), equalTo("prefix_abcc"));
        // assertThat(suggest.get(3).getSuggestedWords().get("prefix_abcd").get(4).getTerm(), equalTo("prefix_accd"));
    }

    // see #2817
    public void testStopwordsOnlyPhraseSuggest() throws IOException {
        assertAcked(prepareCreate("test").setMapping("body", "type=text,analyzer=stopwd").setSettings(
                Settings.builder()
                        .put("index.analysis.analyzer.stopwd.tokenizer", "standard")
                        .putList("index.analysis.analyzer.stopwd.filter", "stop")
        ));
        ensureGreen();
        indexDoc("test", "1", "body", "this is a test");
        refresh();

        Suggest searchSuggest = searchSuggest( "a an the", "simple_phrase",
                phraseSuggestion("body").gramSize(1)
                        .addCandidateGenerator(candidateGenerator("body").minWordLength(1).suggestMode("always"))
                        .size(1));
        assertSuggestionSize(searchSuggest, 0, 0, "simple_phrase");
    }

    public void testPrefixLength() throws IOException {
        CreateIndexRequestBuilder builder = prepareCreate("test").setSettings(Settings.builder()
                .put(SETTING_NUMBER_OF_SHARDS, 1)
                .put("index.analysis.analyzer.body.tokenizer", "standard")
                .putList("index.analysis.analyzer.body.filter", "lowercase")
                .put("index.analysis.analyzer.bigram.tokenizer", "standard")
                .putList("index.analysis.analyzer.bigram.filter", "my_shingle", "lowercase")
                .put("index.analysis.filter.my_shingle.type", "shingle")
                .put("index.analysis.filter.my_shingle.output_unigrams", false)
                .put("index.analysis.filter.my_shingle.min_shingle_size", 2)
                .put("index.analysis.filter.my_shingle.max_shingle_size", 2));
        XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("_doc")
                .startObject("properties")
                .startObject("body").field("type", "text").field("analyzer", "body").endObject()
                .startObject("bigram").field("type", "text").field("analyzer", "bigram").endObject()
                .endObject()
                .endObject().endObject();
        assertAcked(builder.setMapping(mapping));
        ensureGreen();

        indexDoc("test", "1", "body", "hello world");
        indexDoc("test", "2", "body", "hello world");
        indexDoc("test", "3", "body", "hello words");
        refresh();

        Suggest searchSuggest = searchSuggest( "hello word", "simple_phrase",
                phraseSuggestion("body")
                        .addCandidateGenerator(candidateGenerator("body").prefixLength(4).minWordLength(1).suggestMode("always"))
                        .size(1).confidence(1.0f));
        assertSuggestion(searchSuggest, 0, "simple_phrase", "hello words");

        searchSuggest = searchSuggest( "hello word", "simple_phrase",
                phraseSuggestion("body")
                        .addCandidateGenerator(candidateGenerator("body").prefixLength(2).minWordLength(1).suggestMode("always"))
                        .size(1).confidence(1.0f));
        assertSuggestion(searchSuggest, 0, "simple_phrase", "hello world");
    }

    public void testBasicPhraseSuggest() throws IOException, URISyntaxException {
        CreateIndexRequestBuilder builder = prepareCreate("test").setSettings(Settings.builder()
                .put(indexSettings())
                .put("index.analysis.analyzer.body.tokenizer", "standard")
                .putList("index.analysis.analyzer.body.filter", "lowercase")
                .put("index.analysis.analyzer.bigram.tokenizer", "standard")
                .putList("index.analysis.analyzer.bigram.filter", "my_shingle", "lowercase")
                .put("index.analysis.filter.my_shingle.type", "shingle")
                .put("index.analysis.filter.my_shingle.output_unigrams", false)
                .put("index.analysis.filter.my_shingle.min_shingle_size", 2)
                .put("index.analysis.filter.my_shingle.max_shingle_size", 2)
                .put("index.number_of_shards", 1));
        XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("_doc")
                    .startObject("properties")
                        .startObject("body").
                            field("type", "text").
                            field("analyzer", "body")
                        .endObject()
                         .startObject("bigram").
                             field("type", "text").
                             field("analyzer", "bigram")
                         .endObject()
                     .endObject()
                .endObject().endObject();
        assertAcked(builder.setMapping(mapping));
        ensureGreen();

        String[] strings = new String[]{
            "Arthur, King of the Britons",
            "Sir Lancelot the Brave",
            "Patsy, Arthur's Servant",
            "Sir Robin the Not-Quite-So-Brave-as-Sir-Lancelot",
            "Sir Bedevere the Wise",
            "Sir Galahad the Pure",
            "Miss Islington, the Witch",
            "Zoot",
            "Leader of Robin's Minstrels",
            "Old Crone",
            "Frank, the Historian",
            "Frank's Wife",
            "Dr. Piglet",
            "Dr. Winston",
            "Sir Robin (Stand-in)",
            "Knight Who Says Ni",
            "Police sergeant who stops the film",
        };
        for (String line : strings) {
            indexDoc("test", line, "body", line, "bigram", line);
        }
        refresh();

        PhraseSuggestionBuilder phraseSuggest = phraseSuggestion("bigram").gramSize(2).analyzer("body")
                .addCandidateGenerator(candidateGenerator("body").minWordLength(1).suggestMode("always"))
                .size(1);
        Suggest searchSuggest = searchSuggest( "Frank's Wise", "simple_phrase", phraseSuggest);
        assertSuggestion(searchSuggest, 0, "simple_phrase", "frank's wife");
        assertThat(searchSuggest.getSuggestion("simple_phrase").getEntries().get(0).getText().string(), equalTo("Frank's Wise"));

        phraseSuggest.realWordErrorLikelihood(0.95f);
        searchSuggest = searchSuggest( "Artur, Kinh of the Britons", "simple_phrase", phraseSuggest);
        assertSuggestion(searchSuggest, 0, "simple_phrase", "arthur king of the britons");
        // Check the "text" field this one time.
        assertThat(searchSuggest.getSuggestion("simple_phrase").getEntries().get(0).getText().string(),
            equalTo("Artur, Kinh of the Britons"));

        // Ask for highlighting
        phraseSuggest.highlight("<em>", "</em>");
        searchSuggest = searchSuggest( "Artur, King of the Britns", "simple_phrase", phraseSuggest);
        assertSuggestion(searchSuggest, 0, "simple_phrase", "arthur king of the britons");
        assertThat(searchSuggest.getSuggestion("simple_phrase").getEntries().get(0).getOptions().get(0).getHighlighted().string(),
            equalTo("<em>arthur</em> king of the <em>britons</em>"));

        // pass in a correct phrase
        phraseSuggest.highlight(null, null).confidence(0f).size(1).maxErrors(0.5f);
        searchSuggest = searchSuggest( "Arthur, King of the Britons", "simple_phrase", phraseSuggest);
        assertSuggestion(searchSuggest, 0, "simple_phrase", "arthur king of the britons");

        // pass in a correct phrase - set confidence to 2
        phraseSuggest.confidence(2f);
        searchSuggest = searchSuggest( "Arthur, King of the Britons", "simple_phrase", phraseSuggest);
        assertSuggestionSize(searchSuggest, 0, 0, "simple_phrase");

        // pass in a correct phrase - set confidence to 0.99
        phraseSuggest.confidence(0.99f);
        searchSuggest = searchSuggest( "Arthur, King of the Britons", "simple_phrase", phraseSuggest);
        assertSuggestion(searchSuggest, 0, "simple_phrase", "arthur king of the britons");

        // set all mass to trigrams (not indexed)
        phraseSuggest.clearCandidateGenerators()
            .addCandidateGenerator(candidateGenerator("body").minWordLength(1).suggestMode("always"))
            .smoothingModel(new LinearInterpolation(1,0,0));
        searchSuggest = searchSuggest( "Artur, King of the Britns", "simple_phrase", phraseSuggest);
        assertSuggestionSize(searchSuggest, 0, 0, "simple_phrase");

        // set all mass to bigrams
        phraseSuggest.smoothingModel(new LinearInterpolation(0,1,0));
        searchSuggest =  searchSuggest( "Artur, King of the Britns", "simple_phrase", phraseSuggest);
        assertSuggestion(searchSuggest, 0, "simple_phrase", "arthur king of the britons");

        // distribute mass
        phraseSuggest.smoothingModel(new LinearInterpolation(0.4,0.4,0.2));
        searchSuggest = searchSuggest( "Artur, King of the Britns", "simple_phrase", phraseSuggest);
        assertSuggestion(searchSuggest, 0, "simple_phrase", "arthur king of the britons");

        searchSuggest = searchSuggest( "Frank's Wise", "simple_phrase", phraseSuggest);
        assertSuggestion(searchSuggest, 0, "simple_phrase", "frank's wife");

        // try all smoothing methods
        phraseSuggest.smoothingModel(new LinearInterpolation(0.4,0.4,0.2));
        searchSuggest = searchSuggest( "Artur, King of the Britns", "simple_phrase", phraseSuggest);
        assertSuggestion(searchSuggest, 0, "simple_phrase", "arthur king of the britons");

        phraseSuggest.smoothingModel(new Laplace(0.2));
        searchSuggest = searchSuggest( "Artur, King of the Britns",  "simple_phrase", phraseSuggest);
        assertSuggestion(searchSuggest, 0, "simple_phrase", "arthur king of the britons");

        phraseSuggest.smoothingModel(new StupidBackoff(0.1));
        searchSuggest = searchSuggest( "Artur, King of the Britns",  "simple_phrase",phraseSuggest);
        assertSuggestion(searchSuggest, 0, "simple_phrase", "arthur king of the britons");

        // check tokenLimit
        phraseSuggest.smoothingModel(null).tokenLimit(4);
        searchSuggest = searchSuggest( "Artur, King of the Britns", "simple_phrase", phraseSuggest);
        assertSuggestionSize(searchSuggest, 0, 0, "simple_phrase");

        phraseSuggest.tokenLimit(15).smoothingModel(new StupidBackoff(0.1));
        searchSuggest = searchSuggest( "Sir Bedever the Wife Sir Bedever the Wife Sir Bedever the Wife", "simple_phrase", phraseSuggest);
        assertSuggestion(searchSuggest, 0, "simple_phrase", "sir bedevere the wise sir bedevere the wise sir bedevere the wise");
        // Check the name this time because we're repeating it which is funky
        assertThat(searchSuggest.getSuggestion("simple_phrase").getEntries().get(0).getText().string(),
            equalTo("Sir Bedever the Wife Sir Bedever the Wife Sir Bedever the Wife"));
    }

    public void testSizeParam() throws IOException {
        CreateIndexRequestBuilder builder = prepareCreate("test").setSettings(Settings.builder()
                .put(SETTING_NUMBER_OF_SHARDS, 1)
                .put("index.analysis.analyzer.body.tokenizer", "standard")
                .putList("index.analysis.analyzer.body.filter", "lowercase")
                .put("index.analysis.analyzer.bigram.tokenizer", "standard")
                .putList("index.analysis.analyzer.bigram.filter", "my_shingle", "lowercase")
                .put("index.analysis.filter.my_shingle.type", "shingle")
                .put("index.analysis.filter.my_shingle.output_unigrams", false)
                .put("index.analysis.filter.my_shingle.min_shingle_size", 2)
                .put("index.analysis.filter.my_shingle.max_shingle_size", 2));

        XContentBuilder mapping = XContentFactory.jsonBuilder()
                .startObject()
                    .startObject("_doc")
                        .startObject("properties")
                            .startObject("body")
                                .field("type", "text")
                                .field("analyzer", "body")
                            .endObject()
                         .startObject("bigram")
                             .field("type", "text")
                             .field("analyzer", "bigram")
                         .endObject()
                     .endObject()
                 .endObject()
             .endObject();
        assertAcked(builder.setMapping(mapping));
        ensureGreen();

        String line = "xorr the god jewel";
        indexDoc("test", "1", "body", line, "bigram", line);
        line = "I got it this time";
        indexDoc("test", "2", "body", line, "bigram", line);
        refresh();

        PhraseSuggestionBuilder phraseSuggestion = phraseSuggestion("bigram")
                .realWordErrorLikelihood(0.95f)
                .gramSize(2)
                .analyzer("body")
                .addCandidateGenerator(candidateGenerator("body").minWordLength(1).prefixLength(1).suggestMode("always").size(1)
                    .accuracy(0.1f))
                .smoothingModel(new StupidBackoff(0.1))
                .maxErrors(1.0f)
                .size(5);
        Suggest searchSuggest = searchSuggest("Xorr the Gut-Jewel", "simple_phrase", phraseSuggestion);
        assertSuggestionSize(searchSuggest, 0, 0, "simple_phrase");

        // we allow a size of 2 now on the shard generator level so "god" will be found since it's LD2
        phraseSuggestion.clearCandidateGenerators()
                .addCandidateGenerator(candidateGenerator("body").minWordLength(1).prefixLength(1).suggestMode("always").size(2)
                    .accuracy(0.1f));
        searchSuggest = searchSuggest( "Xorr the Gut-Jewel", "simple_phrase", phraseSuggestion);
        assertSuggestion(searchSuggest, 0, "simple_phrase", "xorr the god jewel");
    }

    public void testDifferentShardSize() throws Exception {
        createIndex("test");
        ensureGreen();
        indexRandom(true, client().prepareIndex("test").setId("1").setSource("field1", "foobar1").setRouting("1"),
                client().prepareIndex("test").setId("2").setSource("field1", "foobar2").setRouting("2"),
                client().prepareIndex("test").setId("3").setSource("field1", "foobar3").setRouting("3"));

        Suggest suggest = searchSuggest( "foobar", "simple",
                termSuggestion("field1")
                        .size(10).minDocFreq(0).suggestMode(SuggestMode.ALWAYS));
        ElasticsearchAssertions.assertSuggestionSize(suggest, 0, 3, "simple");
    }

    // see #3469
    public void testShardFailures() throws IOException, InterruptedException {
        CreateIndexRequestBuilder builder = prepareCreate("test").setSettings(Settings.builder()
                .put(indexSettings())
                .put(IndexSettings.MAX_SHINGLE_DIFF_SETTING.getKey(), 4)
                .put("index.analysis.analyzer.suggest.tokenizer", "standard")
                .putList("index.analysis.analyzer.suggest.filter", "lowercase", "shingler")
                .put("index.analysis.filter.shingler.type", "shingle")
                .put("index.analysis.filter.shingler.min_shingle_size", 2)
                .put("index.analysis.filter.shingler.max_shingle_size", 5)
                .put("index.analysis.filter.shingler.output_unigrams", true));

        XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("_doc")
                .startObject("properties")
                    .startObject("name")
                        .field("type", "text")
                        .field("analyzer", "suggest")
                    .endObject()
                .endObject()
                .endObject().endObject();
        assertAcked(builder.setMapping(mapping));
        ensureGreen();

        indexDoc("test", "1", "foo", "bar");
        indexDoc("test", "2", "foo", "bar");
        indexDoc("test", "3", "foo", "bar");
        indexDoc("test", "4", "foo", "bar");
        indexDoc("test", "5", "foo", "bar");
        indexDoc("test", "1", "name", "Just testing the suggestions api");
        indexDoc("test", "2", "name", "An other title about equal length");
        // Note that the last document has to have about the same length as the other or cutoff rechecking will remove the useful suggestion
        refresh();

        // When searching on a shard with a non existing mapping, we should fail
        SearchRequestBuilder request = client().prepareSearch().setSize(0)
                .suggest(
                        new SuggestBuilder().setGlobalText("tetsting sugestion").addSuggestion("did_you_mean",
                                phraseSuggestion("fielddoesnotexist").maxErrors(5.0f)));
        assertRequestBuilderThrows(request, SearchPhaseExecutionException.class);

        // When searching on a shard which does not hold yet any document of an existing type, we should not fail
        SearchResponse searchResponse = client().prepareSearch().setSize(0)
                .suggest(
                        new SuggestBuilder().setGlobalText("tetsting sugestion").addSuggestion("did_you_mean",
                                phraseSuggestion("name").maxErrors(5.0f)))
            .get();
        ElasticsearchAssertions.assertNoFailures(searchResponse);
        ElasticsearchAssertions.assertSuggestion(searchResponse.getSuggest(), 0, 0, "did_you_mean", "testing suggestions");
    }

    // see #3469
    public void testEmptyShards() throws IOException, InterruptedException {
        XContentBuilder mappingBuilder = XContentFactory.jsonBuilder().
                startObject().
                    startObject("_doc").
                        startObject("properties").
                            startObject("name").
                                field("type", "text").
                                field("analyzer", "suggest").
                            endObject().
                        endObject().
                    endObject().
                endObject();
        assertAcked(prepareCreate("test").setSettings(Settings.builder()
                .put(indexSettings())
                .put(IndexSettings.MAX_SHINGLE_DIFF_SETTING.getKey(), 4)
                .put("index.refresh_interval", -1)  // prevents occasional scoring glitches due to multi segments
                .put("index.analysis.analyzer.suggest.tokenizer", "standard")
                .putList("index.analysis.analyzer.suggest.filter", "lowercase", "shingler")
                .put("index.analysis.filter.shingler.type", "shingle")
                .put("index.analysis.filter.shingler.min_shingle_size", 2)
                .put("index.analysis.filter.shingler.max_shingle_size", 5)
                .put("index.analysis.filter.shingler.output_unigrams", true)).setMapping(mappingBuilder));
        ensureGreen();

        // test phrase suggestion on completely empty index
        SearchResponse searchResponse = client().prepareSearch()
                .setSize(0)
                .suggest(
                        new SuggestBuilder().setGlobalText("tetsting sugestion").addSuggestion("did_you_mean",
                                phraseSuggestion("name").maxErrors(5.0f)))
                .get();

        assertNoFailures(searchResponse);
        Suggest suggest = searchResponse.getSuggest();
        assertSuggestionSize(suggest, 0, 0, "did_you_mean");
        assertThat(suggest.getSuggestion("did_you_mean").getEntries().get(0).getText().string(), equalTo("tetsting sugestion"));

        indexDoc("test", "11", "foo", "bar");
        indexDoc("test", "12", "foo", "bar");
        indexDoc("test", "2", "name", "An other title about equal length");
        refresh();

        // test phrase suggestion but nothing matches
        searchResponse = client().prepareSearch()
                .setSize(0)
                .suggest(
                        new SuggestBuilder().setGlobalText("tetsting sugestion").addSuggestion("did_you_mean",
                                phraseSuggestion("name").maxErrors(5.0f)))
                .get();

        assertNoFailures(searchResponse);
        suggest = searchResponse.getSuggest();
        assertSuggestionSize(suggest, 0, 0, "did_you_mean");
        assertThat(suggest.getSuggestion("did_you_mean").getEntries().get(0).getText().string(), equalTo("tetsting sugestion"));

        // finally indexing a document that will produce some meaningful suggestion
        indexDoc("test", "1", "name", "Just testing the suggestions api");
        refresh();

        searchResponse = client().prepareSearch()
                .setSize(0)
                .suggest(
                        new SuggestBuilder().setGlobalText("tetsting sugestion").addSuggestion("did_you_mean",
                                phraseSuggestion("name").maxErrors(5.0f)))
                .get();

        assertNoFailures(searchResponse);
        suggest = searchResponse.getSuggest();
        assertSuggestionSize(suggest, 0, 3, "did_you_mean");
        assertSuggestion(suggest, 0, 0, "did_you_mean", "testing suggestions");
    }

    /**
     * Searching for a rare phrase shouldn't provide any suggestions if confidence > 1.  This was possible before we rechecked the cutoff
     * score during the reduce phase.  Failures don't occur every time - maybe two out of five tries but we don't repeat it to save time.
     */
    public void testSearchForRarePhrase() throws IOException {
        // If there isn't enough chaf per shard then shards can become unbalanced, making the cutoff recheck this is testing do more harm
        // then good.
        int chafPerShard = 100;

        CreateIndexRequestBuilder builder = prepareCreate("test").setSettings(Settings.builder()
                .put(indexSettings())
                .put("index.analysis.analyzer.body.tokenizer", "standard")
                .putList("index.analysis.analyzer.body.filter", "lowercase", "my_shingle")
                .put("index.analysis.filter.my_shingle.type", "shingle")
                .put("index.analysis.filter.my_shingle.output_unigrams", true)
                .put("index.analysis.filter.my_shingle.min_shingle_size", 2)
                .put("index.analysis.filter.my_shingle.max_shingle_size", 2));

        XContentBuilder mapping = XContentFactory.jsonBuilder()
                .startObject()
                    .startObject("_doc")
                        .startObject("properties")
                            .startObject("body")
                                .field("type", "text")
                                .field("analyzer", "body")
                            .endObject()
                        .endObject()
                    .endObject()
                .endObject();
        assertAcked(builder.setMapping(mapping));
        ensureGreen();

        NumShards test = getNumShards("test");

        List<String> phrases = new ArrayList<>();
        Collections.addAll(phrases, "nobel prize", "noble gases", "somethingelse prize", "pride and joy", "notes are fun");
        for (int i = 0; i < 8; i++) {
            phrases.add("noble somethingelse" + i);
        }
        for (int i = 0; i < test.numPrimaries * chafPerShard; i++) {
            phrases.add("chaff" + i);
        }
        for (String phrase: phrases) {
            indexDoc("test", phrase, "body", phrase);
        }
        refresh();

        Suggest searchSuggest = searchSuggest("nobel prize", "simple_phrase", phraseSuggestion("body")
                .addCandidateGenerator(candidateGenerator("body").minWordLength(1).suggestMode("always").maxTermFreq(.99f))
                .confidence(2f)
                .maxErrors(5f)
                .size(1));
        assertSuggestionSize(searchSuggest, 0, 0, "simple_phrase");

        searchSuggest = searchSuggest("noble prize", "simple_phrase", phraseSuggestion("body")
                .addCandidateGenerator(candidateGenerator("body").minWordLength(1).suggestMode("always").maxTermFreq(.99f))
                .confidence(2f)
                .maxErrors(5f)
                .size(1));
        assertSuggestion(searchSuggest, 0, 0, "simple_phrase", "nobel prize");
    }

    public void testSuggestWithManyCandidates() throws InterruptedException, ExecutionException, IOException {
        CreateIndexRequestBuilder builder = prepareCreate("test").setSettings(Settings.builder()
                .put(indexSettings())
                .put(SETTING_NUMBER_OF_SHARDS, 1) // A single shard will help to keep the tests repeatable.
                .put("index.analysis.analyzer.text.tokenizer", "standard")
                .putList("index.analysis.analyzer.text.filter", "lowercase", "my_shingle")
                .put("index.analysis.filter.my_shingle.type", "shingle")
                .put("index.analysis.filter.my_shingle.output_unigrams", true)
                .put("index.analysis.filter.my_shingle.min_shingle_size", 2)
                .put("index.analysis.filter.my_shingle.max_shingle_size", 3));

        XContentBuilder mapping = XContentFactory.jsonBuilder()
                .startObject()
                    .startObject("_doc")
                        .startObject("properties")
                            .startObject("title")
                                .field("type", "text")
                                .field("analyzer", "text")
                            .endObject()
                        .endObject()
                    .endObject()
                .endObject();
        assertAcked(builder.setMapping(mapping));
        ensureGreen();

        List<String> titles = new ArrayList<>();

        // We're going to be searching for:
        //   united states house of representatives elections in washington 2006
        // But we need to make sure we generate a ton of suggestions so we add a bunch of candidates.
        // Many of these candidates are drawn from page names on English Wikipedia.

        // Tons of different options very near the exact query term
        titles.add("United States House of Representatives Elections in Washington 1789");
        for (int year = 1790; year < 2014; year+= 2) {
            titles.add("United States House of Representatives Elections in Washington " + year);
        }
        // Six of these are near enough to be viable suggestions, just not the top one

        // But we can't stop there!  Titles that are just a year are pretty common so lets just add one per year
        // since 0.  Why not?
        for (int year = 0; year < 2015; year++) {
            titles.add(Integer.toString(year));
        }
        // That ought to provide more less good candidates for the last term

        // Now remove or add plural copies of every term we can
        titles.add("State");
        titles.add("Houses of Parliament");
        titles.add("Representative Government");
        titles.add("Election");

        // Now some possessive
        titles.add("Washington's Birthday");

        // And some conjugation
        titles.add("Unified Modeling Language");
        titles.add("Unite Against Fascism");
        titles.add("Stated Income Tax");
        titles.add("Media organizations housed within colleges");

        // And other stuff
        titles.add("Untied shoelaces");
        titles.add("Unit circle");
        titles.add("Untitled");
        titles.add("Unicef");
        titles.add("Unrated");
        titles.add("UniRed");
        titles.add("Jalan Uniten–Dengkil"); // Highway in Malaysia
        titles.add("UNITAS");
        titles.add("UNITER");
        titles.add("Un-Led-Ed");
        titles.add("STATS LLC");
        titles.add("Staples");
        titles.add("Skates");
        titles.add("Statues of the Liberators");
        titles.add("Staten Island");
        titles.add("Statens Museum for Kunst");
        titles.add("Hause"); // The last name or the German word, whichever.
        titles.add("Hose");
        titles.add("Hoses");
        titles.add("Howse Peak");
        titles.add("The Hoose-Gow");
        titles.add("Hooser");
        titles.add("Electron");
        titles.add("Electors");
        titles.add("Evictions");
        titles.add("Coronal mass ejection");
        titles.add("Wasington"); // A film?
        titles.add("Warrington"); // A town in England
        titles.add("Waddington"); // Lots of places have this name
        titles.add("Watlington"); // Ditto
        titles.add("Waplington"); // Yup, also a town
        titles.add("Washing of the Spears"); // Book

        for (char c = 'A'; c <= 'Z'; c++) {
            // Can't forget lists, glorious lists!
            titles.add("List of former members of the United States House of Representatives (" + c + ")");

            // Lots of people are named Washington <Middle Initial>. LastName
            titles.add("Washington " + c + ". Lastname");

            // Lets just add some more to be evil
            titles.add("United " + c);
            titles.add("States " + c);
            titles.add("House " + c);
            titles.add("Elections " + c);
            titles.add("2006 " + c);
            titles.add(c + " United");
            titles.add(c + " States");
            titles.add(c + " House");
            titles.add(c + " Elections");
            titles.add(c + " 2006");
        }

        List<IndexRequestBuilder> builders = new ArrayList<>();
        for (String title: titles) {
            builders.add(client().prepareIndex("test").setSource("title", title));
        }

        indexRandom(true, builders);

        PhraseSuggestionBuilder suggest = phraseSuggestion("title")
                .addCandidateGenerator(candidateGenerator("title")
                        .suggestMode("always")
                        .maxTermFreq(.99f)
                        .size(1000) // Setting a silly high size helps of generate a larger list of candidates for testing.
                        .maxInspections(1000) // This too
                )
                .confidence(0f)
                .maxErrors(2f)
                .shardSize(30000)
                .size(30000);
        Suggest searchSuggest = searchSuggest("united states house of representatives elections in washington 2006", "title", suggest);
        assertSuggestion(searchSuggest, 0, 0, "title", "united states house of representatives elections in washington 2006");
        assertSuggestionSize(searchSuggest, 0, 25480, "title");  // Just to prove that we've run through a ton of options

        suggest.size(1);
        searchSuggest = searchSuggest("united states house of representatives elections in washington 2006", "title", suggest);
        assertSuggestion(searchSuggest, 0, 0, "title", "united states house of representatives elections in washington 2006");
    }

    public void testSuggestWithFieldAlias() throws Exception {
        XContentBuilder mapping = XContentFactory.jsonBuilder()
            .startObject()
                .startObject("_doc")
                    .startObject("properties")
                        .startObject("text")
                            .field("type", "keyword")
                        .endObject()
                        .startObject("alias")
                            .field("type", "alias")
                            .field("path", "text")
                        .endObject()
                    .endObject()
                .endObject()
            .endObject();
        assertAcked(prepareCreate("test").setMapping(mapping));

        List<IndexRequestBuilder> builders = new ArrayList<>();
        builders.add(client().prepareIndex("test").setSource("text", "apple"));
        builders.add(client().prepareIndex("test").setSource("text", "mango"));
        builders.add(client().prepareIndex("test").setSource("text", "papaya"));
        indexRandom(true, false, builders);

        TermSuggestionBuilder termSuggest = termSuggestion("alias").text("appple");

        Suggest searchSuggest = searchSuggest("suggestion", termSuggest);
        assertSuggestion(searchSuggest, 0, "suggestion", "apple");
    }

    public void testPhraseSuggestMinDocFreq() throws Exception {
        XContentBuilder mapping = XContentFactory.jsonBuilder()
            .startObject()
                .startObject("_doc")
                    .startObject("properties")
                        .startObject("text")
                            .field("type", "keyword")
                        .endObject()
                    .endObject()
                .endObject()
            .endObject();
        assertAcked(prepareCreate("test")
            .setSettings(Settings.builder().put("index.number_of_shards", 1).build())
            .setMapping(mapping));

        List<IndexRequestBuilder> builders = new ArrayList<>();
        builders.add(client().prepareIndex("test").setSource("text", "apple"));
        builders.add(client().prepareIndex("test").setSource("text", "apple"));
        builders.add(client().prepareIndex("test").setSource("text", "apple"));
        builders.add(client().prepareIndex("test").setSource("text", "appfle"));
        indexRandom(true, false, builders);

        PhraseSuggestionBuilder phraseSuggest = phraseSuggestion("text").text("appple")
            .size(2)
            .addCandidateGenerator(new DirectCandidateGeneratorBuilder("text")
                .suggestMode("popular"));

        Suggest searchSuggest = searchSuggest("suggestion", phraseSuggest);
        assertSuggestion(searchSuggest, 0, "suggestion", 2, "apple", "appfle");

        phraseSuggest = phraseSuggestion("text").text("appple")
            .addCandidateGenerator(new DirectCandidateGeneratorBuilder("text")
                .suggestMode("popular")
                .minDocFreq(2));

        searchSuggest = searchSuggest("suggestion", phraseSuggest);
        assertSuggestion(searchSuggest, 0, "suggestion", 1,"apple");

        phraseSuggest = phraseSuggestion("text").text("appple")
            .addCandidateGenerator(new DirectCandidateGeneratorBuilder("text")
                .suggestMode("popular")
                .minDocFreq(2));
        searchSuggest = searchSuggest("suggestion", phraseSuggest);
        assertSuggestion(searchSuggest, 0, "suggestion", 1,"apple");
    }

    @Override
    protected Collection<Class<? extends Plugin>> nodePlugins() {
        return Collections.singleton(DummyTemplatePlugin.class);
    }

    public static class DummyTemplatePlugin extends Plugin implements ScriptPlugin {
        @Override
        public ScriptEngine getScriptEngine(Settings settings, Collection<ScriptContext<?>> contexts) {
            return new DummyTemplateScriptEngine();
        }
    }

    public static class DummyTemplateScriptEngine implements ScriptEngine {

        // The collate query setter is hard coded to use mustache, so lets lie in this test about the script plugin,
        // which makes the collate code thinks mustache is evaluating the query.
        public static final String NAME = "mustache";

        @Override
        public String getType() {
            return NAME;
        }

        @Override
        public <T> T compile(
            String scriptName,
            String scriptSource,
            ScriptContext<T> context,
            Map<String, String> params
        ) {
            if (context.instanceClazz != TemplateScript.class) {
                throw new UnsupportedOperationException();
            }
            TemplateScript.Factory factory = p -> {
                String script = scriptSource;
                for (Entry<String, Object> entry : p.entrySet()) {
                    script = script.replace("{{" + entry.getKey() + "}}", String.valueOf(entry.getValue()));
                }
                String result = script;
                return new TemplateScript(null) {
                    @Override
                    public String execute() {
                        return result;
                    }
                };
            };
            return context.factoryClazz.cast(factory);
        }

        @Override
        public Set<ScriptContext<?>> getSupportedContexts() {
            return Set.of(TemplateScript.CONTEXT);
        }
    }

    public void testPhraseSuggesterCollate() throws InterruptedException, ExecutionException, IOException {
        CreateIndexRequestBuilder builder = prepareCreate("test").setSettings(Settings.builder()
                .put(indexSettings())
                .put(SETTING_NUMBER_OF_SHARDS, 1) // A single shard will help to keep the tests repeatable.
                .put("index.analysis.analyzer.text.tokenizer", "standard")
                .putList("index.analysis.analyzer.text.filter", "lowercase", "my_shingle")
                .put("index.analysis.filter.my_shingle.type", "shingle")
                .put("index.analysis.filter.my_shingle.output_unigrams", true)
                .put("index.analysis.filter.my_shingle.min_shingle_size", 2)
                .put("index.analysis.filter.my_shingle.max_shingle_size", 3));

        XContentBuilder mapping = XContentFactory.jsonBuilder()
                .startObject()
                .startObject("_doc")
                .startObject("properties")
                .startObject("title")
                .field("type", "text")
                .field("analyzer", "text")
                .endObject()
                .endObject()
                .endObject()
                .endObject();
        assertAcked(builder.setMapping(mapping));
        ensureGreen();

        List<String> titles = new ArrayList<>();

        titles.add("United States House of Representatives Elections in Washington 2006");
        titles.add("United States House of Representatives Elections in Washington 2005");
        titles.add("State");
        titles.add("Houses of Parliament");
        titles.add("Representative Government");
        titles.add("Election");

        List<IndexRequestBuilder> builders = new ArrayList<>();
        for (String title: titles) {
            builders.add(client().prepareIndex("test").setSource("title", title));
        }
        indexRandom(true, builders);

        // suggest without collate
        PhraseSuggestionBuilder suggest = phraseSuggestion("title")
                .addCandidateGenerator(new DirectCandidateGeneratorBuilder("title")
                        .suggestMode("always")
                        .maxTermFreq(.99f)
                        .size(10)
                        .maxInspections(200)
                )
                .confidence(0f)
                .maxErrors(2f)
                .shardSize(30000)
                .size(10);
        Suggest searchSuggest = searchSuggest("united states house of representatives elections in washington 2006", "title", suggest);
        assertSuggestionSize(searchSuggest, 0, 10, "title");

        // suggest with collate
        String filterString = Strings
                .toString(XContentFactory.jsonBuilder()
                        .startObject()
                        .startObject("match_phrase")
                        .field("{{field}}", "{{suggestion}}")
                        .endObject()
                        .endObject());
        PhraseSuggestionBuilder filteredQuerySuggest = suggest.collateQuery(filterString);
        filteredQuerySuggest.collateParams(Collections.singletonMap("field", "title"));
        searchSuggest = searchSuggest("united states house of representatives elections in washington 2006", "title", filteredQuerySuggest);
        assertSuggestionSize(searchSuggest, 0, 2, "title");

        // collate suggest with no result (boundary case)
        searchSuggest = searchSuggest("Elections of Representatives Parliament", "title", filteredQuerySuggest);
        assertSuggestionSize(searchSuggest, 0, 0, "title");

        NumShards numShards = getNumShards("test");

        // collate suggest with bad query
        String incorrectFilterString = Strings
                .toString(XContentFactory.jsonBuilder()
                        .startObject()
                        .startObject("test")
                        .field("title", "{{suggestion}}")
                        .endObject()
                        .endObject());
        PhraseSuggestionBuilder incorrectFilteredSuggest = suggest.collateQuery(incorrectFilterString);
        Map<String, SuggestionBuilder<?>> namedSuggestion = new HashMap<>();
        namedSuggestion.put("my_title_suggestion", incorrectFilteredSuggest);
        try {
            searchSuggest("united states house of representatives elections in washington 2006", numShards.numPrimaries, namedSuggestion);
            fail("Post query error has been swallowed");
        } catch(ElasticsearchException e) {
            // expected
        }

        // suggest with collation
        String filterStringAsFilter = Strings
                .toString(XContentFactory.jsonBuilder()
                        .startObject()
                        .startObject("match_phrase")
                        .field("title", "{{suggestion}}")
                        .endObject()
                        .endObject());

        PhraseSuggestionBuilder filteredFilterSuggest = suggest.collateQuery(filterStringAsFilter);
        searchSuggest = searchSuggest("united states house of representatives elections in washington 2006", "title",
                filteredFilterSuggest);
        assertSuggestionSize(searchSuggest, 0, 2, "title");

        // collate suggest with bad query
        String filterStr = Strings
                .toString(XContentFactory.jsonBuilder()
                        .startObject()
                        .startObject("pprefix")
                        .field("title", "{{suggestion}}")
                        .endObject()
                        .endObject());

        suggest.collateQuery(filterStr);
        try {
            searchSuggest("united states house of representatives elections in washington 2006", numShards.numPrimaries, namedSuggestion);
            fail("Post filter error has been swallowed");
        } catch(ElasticsearchException e) {
            //expected
        }

        // collate script failure due to no additional params
        String collateWithParams = Strings
                .toString(XContentFactory.jsonBuilder()
                        .startObject()
                        .startObject("{{query_type}}")
                        .field("{{query_field}}", "{{suggestion}}")
                        .endObject()
                        .endObject());

        try {
            searchSuggest("united states house of representatives elections in washington 2006", numShards.numPrimaries, namedSuggestion);
            fail("Malformed query (lack of additional params) should fail");
        } catch (ElasticsearchException e) {
            // expected
        }

        // collate script with additional params
        Map<String, Object> params = new HashMap<>();
        params.put("query_type", "match_phrase");
        params.put("query_field", "title");

        PhraseSuggestionBuilder phraseSuggestWithParams = suggest.collateQuery(collateWithParams).collateParams(params);
        searchSuggest = searchSuggest("united states house of representatives elections in washington 2006", "title",
                phraseSuggestWithParams);
        assertSuggestionSize(searchSuggest, 0, 2, "title");

        // collate query request with prune set to true
        PhraseSuggestionBuilder phraseSuggestWithParamsAndReturn = suggest.collateQuery(collateWithParams).collateParams(params)
                .collatePrune(true);
        searchSuggest = searchSuggest("united states house of representatives elections in washington 2006", "title",
                phraseSuggestWithParamsAndReturn);
        assertSuggestionSize(searchSuggest, 0, 10, "title");
        assertSuggestionPhraseCollateMatchExists(searchSuggest, "title", 2);
    }

    protected Suggest searchSuggest(String name, SuggestionBuilder<?> suggestion) {
        return searchSuggest(null, name, suggestion);
    }

    protected Suggest searchSuggest(String suggestText, String name, SuggestionBuilder<?> suggestion) {
        Map<String, SuggestionBuilder<?>> map = new HashMap<>();
        map.put(name, suggestion);
        return searchSuggest(suggestText, 0, map);
    }

    protected Suggest searchSuggest(String suggestText, int expectShardsFailed, Map<String, SuggestionBuilder<?>> suggestions) {
        SearchRequestBuilder builder = client().prepareSearch().setSize(0);
        SuggestBuilder suggestBuilder = new SuggestBuilder();
        if (suggestText != null) {
            suggestBuilder.setGlobalText(suggestText);
        }
        for (Entry<String, SuggestionBuilder<?>> suggestion : suggestions.entrySet()) {
            suggestBuilder.addSuggestion(suggestion.getKey(), suggestion.getValue());
        }
        builder.suggest(suggestBuilder);
        SearchResponse actionGet = builder.get();
        assertThat(Arrays.toString(actionGet.getShardFailures()), actionGet.getFailedShards(), equalTo(expectShardsFailed));
        return actionGet.getSuggest();
    }
}

redpajama_set_name: RedPajamaGithub


The Washington Wizards acquired former second overall pick Jabari Parker from the Chicago Bulls last month, and they seem to be pretty impressed with his performance so far.
After expressing his frustrations during his stints with the Bulls and Milwaukee Bucks, Parker seems to be feeling good in the nation's capital. The Wizards have adjusted their offensive schemes a bit after acquiring Parker, opting to go fast-paced rather than settling for half-court sets.
Parker is responding well to the Wizards' style of play. Despite being listed at 6-foot-8 and almost 250 pounds, Parker is running the floor faster than anyone his size, at least according to head coach Scott Brooks.
Since joining the Wizards, Parker is averaging 13.9 points, 6.9 rebounds, and 3.1 assists per game. The Wizards are utilizing him as a point forward because of his size and strength. He can battle it out with some of the bigs in the league, and when he gets the rebound, he has the approval of the coaching staff to push the ball and get Washington into tis offense.
Parker's stint with the Wizards looks promising after the disappointments in Milwaukee and Chicago. He better do his best to make it work this time around, and he's off to a good start.


text:
About IPF
Presidents Corner
Coach License
Rules/Codes/Info
Approved List
Technical Rules
IPF GL Formula
Codes and Guidances
IOC Programmes
IPF Magazine
IPF Apps
IPF Anti-Doping Rules
Lifter's Platform
Prohibited List
WADA Speak Up
IPF Notice on Data Privacy
Useful Anti-Doping Links
The Basics of Powerlifting
Strength is the primary ingredient of athletic performance. Powerlifting's lifts are the definitive measure of strength. Powerlifting is the ultimate strength competition. The powerlifting athlete competes in three specific disciplines, each designed to measure different areas of human strength. The sum or total of the best lift in each discipline determines the winner. Powerlifting is an exciting sport where athletes compete against the force of iron as well as other athletes.
Powerlifting is an international sport practiced in over 100 countries on all continents. Athletes, men and women from age 14 and upwards compete in given age groups and weight categories. Weight categories begin with 43kg women's class and end in the men's over 120kg class (unlimited). Powerlifters are unique athletes competing in an exciting sport. They move massive amounts of weight in hi-tech supportive gear that protects against injury. Contests and appreciative fans can be found from Delhi, India, to Dallas, USA. The unique powerlifting athletes compete in a wide variety of local, state, regional, national and international competitions.
The three disciplines, in contest order, that make up the sport are the Squat, Bench press and Deadlift.
The lift starts with the lifter standing erect and the bar loaded with weights resting on the lifter's shoulders. At the referee's command the lift begins. The lifter bends his knees and lowers him into a squatting position with the hips slightly below parallel position. The lifter returns to an erect position. At the referees command the bar is returned to the rack and the lift is completed.
With his or her back resting on the bench, the lifter takes the loaded bar at arm's length. At the referee's command the powerlifter lowers the bar to the chest. On the chest the bar must be hold motionless until the referee give the "press" signal. The powerlifter pushes the weight up until the arms are straight and the elbows locked. Then the referee will call 'rack' and the lift is completed as the weight is returned to the rack.
The deadlift is often described as the king of the powerlifting disciplines. In the deadlift the athlete grasps the loaded bar which is resting on the platform floor. The powerlifter pulls the weights off the floor and assumes a standing erect position. The knees must be locked and shoulders back with the weight held in the lifters' grip. At the referees command the bar will be returned to the floor under the control of the lifter.
Official VIP Partners
Official Broadcasting Partner

redpajama_set_name: RedPajamaCommonCrawl


Why purchase a single recreation room game when you can get two for one? Keep in mind that far too many hybrid products that promise to deliver various options or set-ups end up providing at best mediocre results in any configuration. That's not to say that creating a usable and easily convertible hybrid item is not possible. In fact, Hathaway's Maverick pool and table tennis table combination does a decent job of giving recreational players the choice to shoot billiards or play ping-pong.
This is a compact pool table (it measures a little over 6 feet by 3 feet) that comes with two MDF boards to place on top of the frame that then allow users to play table tennis. The size means the unit can be placed in smaller playing areas. Converting to table tennis play is simple, and the table tennis playing surface measures 84 inches by 46 inches. Lay them atop the pool table, add the nets, and get ready to play a different game.
Pool tables, by nature, are pretty substantial. A solid frame is essential for a good game play in pool and in table tennis, and this table rests on large pedestal-like legs. Many portions of the Maverick table, which including outer surfaces, the felt covered pool playing surface, and the table tennis surface are made from environmentally friendly CARB certified MDF (medium density fiberboard). You might wonder why this is important. CARB stands for California Air Resources Board. CARB works to reduce airborne toxins, including formaldehyde emissions from composite wood products, which is a good thing. MDF is a reliable and sturdy building material as long as it is protected from wetness, but keep in mind that most higher-end tables use slate to ensure smoothness.
Other pool playing enhancing features are white inlay sights for lining up bumper shots. However, for table tennis players, what might matter most is the stability and construction of the table itself. The outer matte black melamine surfaces are made even sturdier with molded ABS corner connections. ABS is a thermoplastic polymer that stands up to a lot of use (and abuse – it's what Lego building blocks are made from). The table tennis top is constructed from ½-inch CARB certified MDF that has been coated with a blue laminate. Its edge trim is black.
Most people find the Maverick reasonably easy to assemble, taking a little over an hour for one person to put it together. Assembly consists of attaching the legs and side aprons with bolts, attaching the leveling feet, and then turning it upright. The key is having all the right pieces packaged in the box. Once properly assembled, however, the table is sturdy and other than being a bit heavy, putting it together is a manageable one-man project.
In terms of looks, the table is not bad. The legs and side apron have a nice arching detail. The top rails (the area surrounding the felt playing surface) is silver toned laminate. The corners are set off with chrome-plated caps. The overall feel of the table's styling is modern, but it is not, by any means, a high-end look. However, it includes leg levelers, which are essential to achieving an even playing surface no matter how level you think your floors are. Hathaway even includes the cues, pool balls, net and paddles for both games.
This is a "you get what you pay for" item. It is nowhere near regulation size and still requires a fair amount of space to play. In terms of the pool-playing surface, the gum rubber bumpers may lack accuracy in rebounding shots and as a result, pool shots may lose speed.
The felt on the pool table covers a slab of MDF, and the table tennis top is made from laminated MDF. While MDF is generally a decent building material, watch out if it gets wet. From swelling to stained felt, liquid poses major problems. If you allow liquids into your game room (and who doesn't?) have cleanup materials at hand to handle any spills.
Putting the Maverick together is simple IF all the proper parts are included (missing and damaged items seem intrinsic to just about any product requiring assembly these days). Additionally, the felt on this table may be a bit on the thin side, so users may want to take extra care when installing and removing the table tennis top so that it does not inadvertently damage the felt.


text:
MLB doubles camera angles for video reviews of umpires
by: RONALD BLUM, Associated Press
In this photo provided by MLB, Major League Baseball's new replay operations center and ballpark video rooms are viewed in New York in Jan. 2020. Major League Baseball has doubled the isolated camera angles available for video review from 12 to 24 and arranged for high-frame rate cameras to stream directly to the new replay operations center and ballpark video rooms. The shift to a new replay operations center twice the size of the old one is part of the move of Major League Baseball and MLB Advanced Media to a combined office space in Manhattan, across the street from Radio City Music Hall. (MLB via AP)
NEW YORK (AP) — Taking a chance to review instant replay, Major League Baseball doubled the isolated cameras available for video reviews to 24 this year.
MLB also arranged for high-frame rate cameras to stream directly to the new replay operations center and ballpark video rooms, and for MLB-controlled 4K cameras with zoom lenses to be installed at high locations behind home plate.
A new replay hub about twice the size of the old one was constructed as part of the move of Major League Baseball and MLB Advanced Media to a combined office space in Manhattan, across the street from Radio City Music Hall.
"We think that the product of all these items is going to result in a much more rapid review process, so that we'll be getting video available much more quickly to the umpires, who will be making decision more quickly," Chris Marinak, MLB executive vice president of strategy, technology and innovation, said Monday. "The same will be true of the replay personnel in the ballpark, who are helping their manager make a decision on whether to challenge."
Each manager will have 20 seconds to decide whether to ask for a video review of a call subject to a challenge, down from 30.
MLB's pandemic-delayed season starts Thursday with the New York Yankees at the World Series champion Washington Nationals.
MLB started widespread video review in 2014 after years of embarrassing calls, such as the blown call by first base umpire Jim Joyce that denied Detroit's Armando Galarraga what should have been the final of out a perfect game.
There were 1,275 reviews during the 2019 regular season, including 1,051 requested by managers that averaged 1 minute, 46 seconds. Among those calls, 603 (47.3%) were overturned, 310 (24.3%) were confirmed, 352 (27.6%) were allowed to stand and 10 (0.8%) were for record keeping.
Clear plastic barriers have been installed, and additional conference rooms will be used to enable social distancing. If the Toronto Blue Jays play home games at a non-regular season MLB facility, cameras for video review would be installed.
Also debuting this week is a second-generation Statcast system that shifts from TrackMan and Doppler radar to Hawk-Eye and an array of 12 cameras whose data will be stored on Google Cloud to create graphics for scoreboards and broadcasts. Five of the cameras are targeted for pitch tracking, four behind the plate and one in center field, and seven are used to track players. Each camera is 4K resolution and typically tracks at a rate of 100 frames per second, though they can be sped to as fast as 500 frames per second.
"We're trying to set a foundation here with this new deployment that is a foundation that we can innovate on for the next five years as technology continues to progress," said Jason Gaedtke, MLB's chief technology officer.
MLB said the error margin, which had averaged mostly 1-2 inches in 2016, is expected to drop to 0.1 inches this season. The system is designed to eliminate previous blind spots on high popups and in outfield corners. Error margins on fielder movements are expected to drop from 3 feet to less than one foot.
TrackMan took over pitch velocity tracking from PITCHf/x in 2017.
"We would argue that it's more accurate than what you've seen in the past," MLB executive vice president of strategy, technology and innovation Chris Marinak said. He added it "mirrors historical data at closely as possible."
Gaedtke said extensive testing was employed to avoid changes to velocities that some claimed resulted from the 2017 switch.
To enforce social distancing, group viewing of in-game videos by players has been prohibited and each team is being given 15 iPads for player use that will be wiped clean after each game. The iPads have software the prohibits connectivity during games and can be shut remotely if lost.
MLB also is working with clubs and Sony to create simulated fan noise for games to be played in empty ballparks. Each team had an iPad with more than 75 sound samples, ranging from murmurs to cheers to organists. The scoreboard operators have an app to use as guidance. Broadcasters may add more audio.
"What we've basically told the clubs is that they need to produce sound that mimics sounds that would otherwise have been in the ballpark if there had been fans in the ballpark," Marinak said. "The club needs to match what they would have expected to hear had there been fans in the ballpark. To the extent that there's issues or disputes around that, that'll be managed by our baseball operations department."
by Cassidy Wood / Jan 18, 2021
CHARLESTON, WV (WOWK) - The 'Famous Superstars' competitive dance team just got back from Atlanta after competing in nationals, and they came out champions.
A huge accomplishment that took a ton of work, both on and off the mat.
12SportsZone Twitter
Tweets by 12SportsZone


text:
Florida Statutes > Chapter 112 > Part V > § 112.52
Florida Statutes 112.52 – Removal of a public official when a method is not otherwise provided
Terms Used In Florida Statutes 112.52
Felony: A crime carrying a penalty of more than a year in prison.
Misdemeanor: Usually a petty offense, a less serious crime than a felony, punishable by less than a year of confinement.
Nolo contendere: No contest-has the same effect as a plea of guilty, as far as the criminal sentence is concerned, but may not be considered as an admission of guilt for any other purpose.
person: includes individuals, children, firms, associations, joint adventures, partnerships, estates, trusts, business trusts, syndicates, fiduciaries, corporations, and all other groups or combinations. See Florida Statutes 88.6011
(1) When a method for removal from office is not otherwise provided by the State Constitution or by law, the Governor may by executive order suspend from office an elected or appointed public official, by whatever title known, who is indicted or informed against for commission of any felony, or for any misdemeanor arising directly out of his or her official conduct or duties, and may fill the office by appointment for the period of suspension, not to extend beyond the term.
(2) During the period of the suspension, the public official shall not perform any official act, duty, or function or receive any pay, allowance, emolument, or privilege of office.
(3) If convicted, the public official may be removed from office by executive order of the Governor. For the purpose of this section, any person who pleads guilty or nolo contendere or who is found guilty shall be deemed to have been convicted, notwithstanding the suspension of sentence or the withholding of adjudication.
(4) If the public official is acquitted or found not guilty, or the charges are otherwise dismissed, the Governor shall by executive order revoke the suspension; and the public official shall be entitled to full back pay and such other emoluments or allowances to which he or she would have been entitled had he or she not been suspended.
Part V Contents
CFR > Title 4 > Chapter I > Subchapter A - Personnel System
CFR > Title 5 - Administrative Personnel
U.S. Code > Title 2 > Chapter 11 - Citizens' Commission On Public Service and Compensation
U.S. Code > Title 39 > Part II - Personnel
U.S. Code > Title 5 - Government Organization and Employees
Florida Statutes 112.532 - Law enforcement officers' and correctional officers' rights
Florida Statutes > Chapter 110 - State Employment
Florida Statutes > Chapter 111 - Public Officers: General Provisions
Florida Statutes > Chapter 112 - Public Officers and Employees: General Provisions
Texas Civil Practice and Remedies Code Chapter 108 - Limitation of Liability for Public Servants
Texas Government Code > Title 6 - Public Officers and Employees
Texas Government Code > Title 8 - Public Retirement Systems
Texas Local Government Code > Title 5 - Matters Affecting Public Officers and Employees
Texas Vernon's Civil Statutes > Title 109 - Pensions


Laboratory data are an essential component of a comprehensive examination of patients to establish the correct diagnosis, as well as the identification of various diseases at an early stage.
Abnormalities in the tests indicate changes in the human body.
In some cases, the results of the tests are the decisive factor in the diagnosis (eg, viral hepatitis, etc.), the choice of treatment tactics, determining the nature of the disease severity, the prognosis of the disease, the control of the treatment process.
The results of laboratory studies allow one to detect abnormalities long before the appearance of clinical manifestations and visible changes in the structure of the affected organs. It is known that it is easier to prevent a disease than to treat it.
In the medical center «Health Clinic» you have the opportunity to undergo a modern laboratory examination in a certified laboratory.


Fire Emblem Echoes opens at over 131,000 copies.
Fire Emblem Echoes: Shadows of Valentia for 3DS sold 131,668 copies during its first week of release in Japan, the latest Media Create sales figures reveal.
Coming it at second most sold this past week is Bandai Namco's for Pro Yakyuu Famista Climax, which opened at 48,142 copies sold. Also new this week, Dark Souls III: The Fire Fades Edition for PlayStation 4 sold 33,088 copies, and Dungeon Travelers 2-2 or PS Vita sold 27,8381 copies.
On the hardware side, Switch sales remain strong, selling 3,000 additional units over last week's 45,000.


text:
Z Energy Limited
About Z
Who is Z Energy
Home › About Z › News › General News › Z Energy welcomes release of the Sustainable Biofuels Mandate
Z Energy welcomes release of the Sustainable Biofuels Mandate
16/12/2021 - General News
Z Energy (Z) welcomes today's announcement from the Government that New Zealand's Sustainable Biofuels Mandate will be in place by 1 April 2023.
"Biofuels are an important step on the journey to help New Zealand decarbonise the transport sector," says Z Energy GM Transition Julian Hughes.
"This announcement sets a clear agenda for us and the wider industry on what we need to achieve and how to get there."
Many other countries such as Europe, the UK, US, Japan and South Korea already have a biofuels mandate, as well as production incentives that have helped to create a biofuel industry in those markets. Z has been advocating for this type of policy as a way to reduce the carbon intensity of the fuel that all retailers sell.
"We've long said that we want to be at the heart of the climate change solution and biofuels is an area we have been committed to for some time now. We built a biodiesel production plant, and despite a pause in local production, continue to supply biodiesel to our most committed commercial customers. We've also signed an MoU with Neste, the world's leading producer of renewable diesel and sustainable aviation fuel (SAF), to collaborate to bring low-carbon fuels to the New Zealand market," continues Julian.
Z believes this mandate will create mass demand for low emissions fuels for use in existing internal combustion engine vehicles and looks forward to working with Government and industry on how it can supply this to its customers.
"We commend the Government for making key changes from the initial proposals, including increasing the maximum penalty from $300 to $800 per tonne of carbon dioxide equivalent emissions not achieved, to incentivise compliance," says Julian.
"However, we would like to continue working with the Government on ways to support domestic production, including access to domestic feedstocks as a way to allow local producers to compete more effectively with demand from subsidised markets overseas. For example, we suggest that double accounting for the emissions reductions created by locally produced biofuels could be considered as a way of supporting a domestic biofuel industry."
As we have advocated for, Z supports the development of a separate mandate for sustainable aviation fuel (SAF) during 2022 given the unique challenges the sector faces and looks forward to responding to the RFP set by Air New Zealand and MBIE.
Z believes the best fuel for the best use case will be the foundation of a successful energy transition, recognising electric and hydrogen will have a role to play alongside biofuels. It sees the announcement today as a step in the right direction on our journey to a low carbon future, with biofuels helping to reduce emissions as we make the transition to low emissions vehicles.
Media enquiries: Haley Mortimer — haley.mortimer@z.co.nz; 027 549 9323
Submissions and Presentations
Z Business
The fuel card programme that keeps business moving
Pumped at Z
Save on fuel now, stack for later, plus earn rewards
Flybuys and Airpoints™
Fuel your rewards balance on eligible purchases at Z
News about Z
Login to Z Business
Apply for a Z account
© Z Energy Limited. All trademarks are used under license.


Dementia Australia is growing rapidly.
With more than 425,000 Australians living with dementia there is an urgent and growing need for our services. At every level of the organisation we have hard working and passionate team members who are committed to making a difference in the lives of people with dementia and their carers.


The University of New England provides excellent opportunities for both Australian and International students to study overseas for one semester or one year as part of their degree.
A popular way to study overseas is to take advantage of an exchange program for one or two semesters. UNE has exchange agreements with partner institutions in many countries around the world.
Cultural awareness: Your experiences will raise your awareness and understanding of other cultures – something that is increasingly important in today's multicultural and globally connected world. Being able to show that you have the ability to interact effectively with people from different cultures is a valuable work skill.
The right stuff: Students who have studied overseas are seen to have desirable traits such as determination, confidence and an ability to adapt to new surroundings.
Global connections: Obviously while living and studying overseas you will meet lots of new people and make friends from around the world. This will have a positive effect on your contacts list.
Personal growth: Making your mark in a new country and environment will allow you to develop yourself. You are likely to return feeling more self-sufficient, self-aware and self-confident – all appealing traits from an employer's perspective.


Back when it was originally released, the Puma Disc Blaze was at the forefront of the sneaker game due to its innovative technology. These days, Puma has brought back the classic model, but has made it slimmer and lighter, all the while leaving in the Trinomic Disc closure that we've come to know and love. Here we're getting a look at a pair that blends white, purple, and yellow. If you're interested in a pair, you can find it now at Finish Line.


Jacob Moffitt is the founder and managing director of 'Movement Co' a gym or 'movement facility' that seeks to "redefine possible".
Movement Co. apply the small scale personal training model to the large scale 24-hour gym model creating a truly unique workout experience. Jacob's business brings movement back to the way the body was designed to move focusing on body weight training and the 'play aspect' of movement.
Jacob's business however was not a success from the very beginning. With an initial 250K investment and a need for 80K per month to break even, Jacob really needed to Change the Game to make his business work.
Supported by The Game Changers team, Jacob learned the value of his time, focused on what matters and developed his mindset, growing to who he needed to be. Jacob grew his client base by 30% in just three weeks while spending 2 days less at the business each week.


Suitable for wigs, hairpieces, toupees, wefts, extensions etc.
Just put on the fitting of the hairpiece and fix it with your own hair after putting it on.
The self-adhesive attachment variant is suitable if your own hair is present. The hair can be long or short (regrowing). Also suitable if your own hair for attachment with metal clips are still too short.
The adhesive clip can be stuck on a PU film that is in your hairpiece. If there is no PU foil / adhesive surface in your wig, you can sew it.


PERPETUA CORP. is a business entity registered in the state of New York under the legal form of DOMESTIC BUSINESS CORPORATION. It can be found in the register by the DOS ID 2976554. The company was established and set into the register at 13th November 2003 and its current status is ACTIVE. Company´s jurisdiction is in the state of NEW YORK in county BRONX. Process address of this entity is at 3045 GRAND CONCOURSE APT #FL, BRONX, 10468, NEW YORK.
PRESTON TRUCK & EQUIPMENT, INC.
BROADWAY PHO BANG RESTAURANT INC.
LONG BEACH FRUIT COMPANY, LTD.
DEAN'S GENERAL TIRE SERVICE, INC.
1364 9W GAS & MART CORP.
NEW YORK INTERNATIONAL PRESS FOR ARTS & ENTERTAINMENT, INC.
EXECUTIVE INSURANCE BROKERAGE & FINANCIAL SERVICES, INC.
EAST ASIAN SOCIAL CLUB, INC.
COW PALACE BUTCHER SHOP PATCHOGUE, INC.
ADVANCING GIRLS EDUCATION IN INDIA, INC.
MAPLEWOOD VOLUNTEER FIRE DEPT. INC.
FORCE ONE ENTERTAINMENT NY/LA, INC.


Republished from RSS Connect Volume 3, Issue 1. September 28, 2016.
These questions have no easy answers, but a conversation on this topic with Rabbi Ben Spratt, CRS Associate Rabbi, and RSS Rabbi-in-Residence, was enlightening and helpful. He's quick to note that there are no "silver bullets" here and that the entire concept of gratitude is more something that must be modeled than taught. He tells me he's speaking to me with his "parent hat" on, as this is a question he and his wife ask themselves often. In his house, gratitude is a priority. He tells me this in a non-judgmental way. Gratitude manifests itself in simple ways; one example is taking a moment for a blessing before food. That one act physically and mentally slows down the meal and gives time for a brief reflection. Rabbi Ben also offers that it's important to carve out fixed time, for one thing, meaning focus on the activity at hand and really be present in the moment. I make a note to try that at home.
Rabbi Ben starts out his day asking his children on the way to school for one thing they are excited for and one thing they are grateful for. He said sometimes the answers are amazingly profound and sometimes the answers are typically childlike, and that both are okay. It's the act of saying it out loud; taking time to find an answer and sharing it is what counts. He mentions also modeling what we are grateful for as adults. This concept resonates with me because I am always wondering am I teaching or am I practicing? This especially rings true when there are disruptions in life, a bump in the road so to speak. "Disruptions are not bad," he says, "gratitude, by definition, is disruption because you are stepping out of the flow of life and pausing for appreciation." I cannot tell him enough how much I love this philosophy.