text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium.DevTools.V107.Fetch;
using OpenQA.Selenium.DevTools.V107.Network;

namespace OpenQA.Selenium.DevTools.V107
{
    /// <summary>
    /// Class providing functionality for manipulating network calls using version 107 of the DevTools Protocol
    /// </summary>
    public class V107Network : DevTools.Network
    {
        private FetchAdapter fetch;
        private NetworkAdapter network;

        /// <summary>
        /// Initializes a new instance of the <see cref="V107Network"/> class.
        /// </summary>
        /// <param name="network">The adapter for the Network domain.</param>
        /// <param name="fetch">The adapter for the Fetch domain.</param>
        public V107Network(NetworkAdapter network, FetchAdapter fetch)
        {
            this.network = network;
            this.fetch = fetch;
            fetch.AuthRequired += OnFetchAuthRequired;
            fetch.RequestPaused += OnFetchRequestPaused;
        }

        /// <summary>
        /// Asynchronously disables network caching.
        /// </summary>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public override async Task DisableNetworkCaching()
        {
            await network.SetCacheDisabled(new SetCacheDisabledCommandSettings() { CacheDisabled = true });
        }

        /// <summary>
        /// Asynchronously enables network caching.
        /// </summary>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public override async Task EnableNetworkCaching()
        {
            await network.SetCacheDisabled(new SetCacheDisabledCommandSettings() { CacheDisabled = false });
        }

        public override async Task EnableNetwork()
        {
            await network.Enable(new Network.EnableCommandSettings());
        }

        public override async Task DisableNetwork()
        {
            await network.Disable();
        }

        /// <summary>
        /// Asynchronously enables the fetch domain for all URL patterns.
        /// </summary>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public override async Task EnableFetchForAllPatterns()
        {
            await fetch.Enable(new OpenQA.Selenium.DevTools.V107.Fetch.EnableCommandSettings()
            {
                Patterns = new OpenQA.Selenium.DevTools.V107.Fetch.RequestPattern[]
                {
                    new OpenQA.Selenium.DevTools.V107.Fetch.RequestPattern() { UrlPattern = "*", RequestStage = RequestStage.Request },
                    new OpenQA.Selenium.DevTools.V107.Fetch.RequestPattern() { UrlPattern = "*", RequestStage = RequestStage.Response }
                },
                HandleAuthRequests = true
            });
        }

        /// <summary>
        /// Asynchronously diables the fetch domain.
        /// </summary>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public override async Task DisableFetch()
        {
            await fetch.Disable();
        }

        /// <summary>
        /// Asynchronously sets the override of the user agent settings.
        /// </summary>
        /// <param name="userAgent">A <see cref="UserAgent"/> object containing the user agent values to override.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public override async Task SetUserAgentOverride(UserAgent userAgent)
        {
            await network.SetUserAgentOverride(new SetUserAgentOverrideCommandSettings()
            {
                UserAgent = userAgent.UserAgentString,
                AcceptLanguage = userAgent.AcceptLanguage,
                Platform = userAgent.Platform
            });
        }

        /// <summary>
        /// Asynchronously continues an intercepted network request.
        /// </summary>
        /// <param name="requestData">The <see cref="HttpRequestData"/> of the request.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public override async Task ContinueRequest(HttpRequestData requestData)
        {
            var commandSettings = new ContinueRequestCommandSettings()
            {
                RequestId = requestData.RequestId,
                Method = requestData.Method,
                Url = requestData.Url,
            };

            if (requestData.Headers.Count > 0)
            {
                List<HeaderEntry> headers = new List<HeaderEntry>();
                foreach (KeyValuePair<string, string> headerPair in requestData.Headers)
                {
                    headers.Add(new HeaderEntry() { Name = headerPair.Key, Value = headerPair.Value });
                }

                commandSettings.Headers = headers.ToArray();
            }

            if (!string.IsNullOrEmpty(requestData.PostData))
            {
                commandSettings.PostData = requestData.PostData;
            }

            await fetch.ContinueRequest(commandSettings);
        }

        /// <summary>
        /// Asynchronously continues an intercepted network request.
        /// </summary>
        /// <param name="requestData">The <see cref="HttpRequestData"/> of the request.</param>
        /// <param name="responseData">The <see cref="HttpResponseData"/> with which to respond to the request</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public override async Task ContinueRequestWithResponse(HttpRequestData requestData, HttpResponseData responseData)
        {
            var commandSettings = new FulfillRequestCommandSettings()
            {
                RequestId = requestData.RequestId,
                ResponseCode = responseData.StatusCode,
            };

            if (responseData.Headers.Count > 0 || responseData.CookieHeaders.Count > 0)
            {
                List<HeaderEntry> headers = new List<HeaderEntry>();
                foreach (KeyValuePair<string, string> headerPair in responseData.Headers)
                {
                    headers.Add(new HeaderEntry() { Name = headerPair.Key, Value = headerPair.Value });
                }

                foreach (string cookieHeader in responseData.CookieHeaders)
                {
                    headers.Add(new HeaderEntry() { Name = "Set-Cookie", Value = cookieHeader });
                }

                commandSettings.ResponseHeaders = headers.ToArray();
            }

            if (!string.IsNullOrEmpty(responseData.Body))
            {
                commandSettings.Body = Convert.ToBase64String(Encoding.UTF8.GetBytes(responseData.Body));
            }

            await fetch.FulfillRequest(commandSettings);
        }

        /// <summary>
        /// Asynchronously contines an intercepted network call without modification.
        /// </summary>
        /// <param name="requestData">The <see cref="HttpRequestData"/> of the network call.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public override async Task ContinueRequestWithoutModification(HttpRequestData requestData)
        {
            await fetch.ContinueRequest(new ContinueRequestCommandSettings() { RequestId = requestData.RequestId });
        }

        /// <summary>
        /// Asynchronously continues an intercepted network call using authentication.
        /// </summary>
        /// <param name="requestId">The ID of the network request for which to continue with authentication.</param>
        /// <param name="userName">The user name with which to authenticate.</param>
        /// <param name="password">The password with which to authenticate.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public override async Task ContinueWithAuth(string requestId, string userName, string password)
        {
            await fetch.ContinueWithAuth(new ContinueWithAuthCommandSettings()
            {
                RequestId = requestId,
                AuthChallengeResponse = new V107.Fetch.AuthChallengeResponse()
                {
                    Response = V107.Fetch.AuthChallengeResponseResponseValues.ProvideCredentials,
                    Username = userName,
                    Password = password
                }
            });
        }

        /// <summary>
        /// Asynchronously cancels authorization of an intercepted network request.
        /// </summary>
        /// <param name="requestId">The ID of the network request for which to cancel authentication.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public override async Task CancelAuth(string requestId)
        {
            await fetch.ContinueWithAuth(new ContinueWithAuthCommandSettings()
            {
                RequestId = requestId,
                AuthChallengeResponse = new OpenQA.Selenium.DevTools.V107.Fetch.AuthChallengeResponse()
                {
                    Response = V107.Fetch.AuthChallengeResponseResponseValues.CancelAuth
                }
            });
        }

        /// <summary>
        /// Asynchronously adds the response body to the provided <see cref="HttpResponseData"/> object.
        /// </summary>
        /// <param name="responseData">The <see cref="HttpResponseData"/> object to which to add the response body.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public override async Task AddResponseBody(HttpResponseData responseData)
        {
            // If the response is a redirect, retrieving the body will throw an error in CDP.
            if (responseData.StatusCode < 300 || responseData.StatusCode > 399)
            {
                var bodyResponse = await fetch.GetResponseBody(new Fetch.GetResponseBodyCommandSettings() { RequestId = responseData.RequestId });
                if (bodyResponse.Base64Encoded)
                {
                    responseData.Body = Encoding.UTF8.GetString(Convert.FromBase64String(bodyResponse.Body));
                }
                else
                {
                    responseData.Body = bodyResponse.Body;
                }
            }
        }

        /// <summary>
        /// Asynchronously contines an intercepted network response without modification.
        /// </summary>
        /// <param name="responseData">The <see cref="HttpResponseData"/> of the network response.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public override async Task ContinueResponseWithoutModification(HttpResponseData responseData)
        {
            await fetch.ContinueRequest(new ContinueRequestCommandSettings() { RequestId = responseData.RequestId });
        }

        private void OnFetchAuthRequired(object sender, Fetch.AuthRequiredEventArgs e)
        {
            AuthRequiredEventArgs wrapped = new AuthRequiredEventArgs()
            {
                RequestId = e.RequestId,
                Uri = e.Request.Url
            };

            this.OnAuthRequired(wrapped);
        }

        private void OnFetchRequestPaused(object sender, Fetch.RequestPausedEventArgs e)
        {
            if (e.ResponseErrorReason == null && e.ResponseStatusCode == null)
            {
                RequestPausedEventArgs wrapped = new RequestPausedEventArgs();
                wrapped.RequestData = new HttpRequestData()
                {
                    RequestId = e.RequestId,
                    Method = e.Request.Method,
                    Url = e.Request.Url,
                    PostData = e.Request.PostData,
                    Headers = new Dictionary<string, string>(e.Request.Headers)
                };

                this.OnRequestPaused(wrapped);
            }
            else
            {
                ResponsePausedEventArgs wrappedResponse = new ResponsePausedEventArgs();
                wrappedResponse.ResponseData = new HttpResponseData()
                {
                    RequestId = e.RequestId,
                    Url = e.Request.Url,
                    ResourceType = e.ResourceType.ToString()
                };

                if (e.ResponseStatusCode.HasValue)
                {
                    wrappedResponse.ResponseData.StatusCode = e.ResponseStatusCode.Value;
                }

                if (e.ResponseHeaders != null)
                {
                    foreach (var header in e.ResponseHeaders)
                    {
                        if (header.Name.ToLowerInvariant() == "set-cookie")
                        {
                            wrappedResponse.ResponseData.CookieHeaders.Add(header.Value);
                        }
                        else
                        {
                            if (wrappedResponse.ResponseData.Headers.ContainsKey(header.Name))
                            {
                                string currentHeaderValue = wrappedResponse.ResponseData.Headers[header.Name];
                                wrappedResponse.ResponseData.Headers[header.Name] = currentHeaderValue + ", " + header.Value;
                            }
                            else
                            {
                                wrappedResponse.ResponseData.Headers.Add(header.Name, header.Value);
                            }
                        }
                    }
                }

                this.OnResponsePaused(wrappedResponse);
            }
        }
    }
}


text:
package org.elasticsearch.xpack.analytics.stringstats;

import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermInSetQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.CheckedConsumer;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.mapper.IpFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.index.mapper.TextFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregator;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValueType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.search.lookup.LeafDocLookup;
import org.elasticsearch.xpack.analytics.AnalyticsPlugin;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;

import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static java.util.stream.Collectors.toList;

public class StringStatsAggregatorTests extends AggregatorTestCase {

    @Override
    protected List<SearchPlugin> getSearchPlugins() {
        return List.of(new AnalyticsPlugin());
    }

    private static final String VALUE_SCRIPT_NAME = "value_script";
    private static final String FIELD_SCRIPT_NAME = "field_script";

    public void testNoDocs() throws IOException {
        testAggregation(new MatchAllDocsQuery(), iw -> {
            // Intentionally not writing any docs
        }, stats -> {
            assertEquals(0, stats.getCount());
            assertEquals(Integer.MIN_VALUE, stats.getMaxLength());
            assertEquals(Integer.MAX_VALUE, stats.getMinLength());
            assertEquals(Double.NaN, stats.getAvgLength(), 0);
            assertTrue(stats.getDistribution().isEmpty());
            assertEquals(0.0, stats.getEntropy(), 0);
        });
    }

    public void testUnmappedField() throws IOException {
        StringStatsAggregationBuilder aggregationBuilder = new StringStatsAggregationBuilder("_name").field("text");
        testAggregation(aggregationBuilder, new MatchAllDocsQuery(), iw -> {
            for(int i = 0; i < 10; i++) {
                iw.addDocument(singleton(new TextField("text", "test" + i, Field.Store.NO)));
            }
        },  stats -> {
            assertEquals(0, stats.getCount());
            assertEquals(Integer.MIN_VALUE, stats.getMaxLength());
            assertEquals(Integer.MAX_VALUE, stats.getMinLength());
            assertEquals(Double.NaN, stats.getAvgLength(), 0);
            assertTrue(stats.getDistribution().isEmpty());
            assertEquals(0.0, stats.getEntropy(), 0);

        }, null);
    }

    public void testUnmappedWithMissingField() throws IOException {
        StringStatsAggregationBuilder aggregationBuilder = new StringStatsAggregationBuilder("_name")
            .field("text")
            .missing("abca");
        testAggregation(aggregationBuilder, new MatchAllDocsQuery(), iw -> {
            for(int i=0; i < 10; i++) {
                iw.addDocument(singleton(new TextField("text", "test" + i, Field.Store.NO)));
            }
        }, stats -> {
            assertEquals(10, stats.getCount());
            assertEquals(4, stats.getMaxLength());
            assertEquals(4, stats.getMinLength());
            assertEquals(4.0, stats.getAvgLength(), 0);
            assertEquals(3, stats.getDistribution().size());
            assertEquals(0.50, stats.getDistribution().get("a"), 0);
            assertEquals(0.25, stats.getDistribution().get("b"), 0);
            assertEquals(0.25, stats.getDistribution().get("c"), 0);
            assertEquals(1.5, stats.getEntropy(), 0);
        }, null);
    }

    public void testMissing() throws IOException {
        final TextFieldMapper.TextFieldType fieldType = new TextFieldMapper.TextFieldType();
        fieldType.setName("text");
        fieldType.setFielddata(true);

        final StringStatsAggregationBuilder aggregationBuilder = new StringStatsAggregationBuilder("_name")
            .field(fieldType.name())
            .missing("b");

        testAggregation(aggregationBuilder, new MatchAllDocsQuery(), iw -> {
            iw.addDocument(singleton(new TextField(fieldType.name(), "a", Field.Store.NO)));
            iw.addDocument(emptySet());
            iw.addDocument(singleton(new TextField(fieldType.name(), "a", Field.Store.NO)));
            iw.addDocument(emptySet());
        }, stats -> {
            assertEquals(4, stats.getCount());
            assertEquals(1, stats.getMaxLength());
            assertEquals(1, stats.getMinLength());
            assertEquals(1.0, stats.getAvgLength(), 0);
            assertEquals(2, stats.getDistribution().size());
            assertEquals(0.5, stats.getDistribution().get("a"), 0);
            assertEquals(0.5, stats.getDistribution().get("b"), 0);
            assertEquals(1.0, stats.getEntropy(), 0);
        }, fieldType);
    }

    public void testSingleValuedField() throws IOException {
        testAggregation(new MatchAllDocsQuery(), iw -> {
            for(int i=0; i < 10; i++) {
                iw.addDocument(singleton(new TextField("text", "test" + i, Field.Store.NO)));
            }
        }, stats -> {
            assertEquals(10, stats.getCount());
            assertEquals(5, stats.getMaxLength());
            assertEquals(5, stats.getMinLength());
            assertEquals(5.0, stats.getAvgLength(), 0);
            assertEquals(13, stats.getDistribution().size());
            assertEquals(0.4, stats.getDistribution().get("t"), 0);
            assertEquals(0.2, stats.getDistribution().get("e"), 0);
            assertEquals(0.02, stats.getDistribution().get("0"), 0);
            assertEquals(2.58631, stats.getEntropy(), 0.00001);
        });
    }

    public void testNoMatchingField() throws IOException {
        testAggregation(new MatchAllDocsQuery(), iw -> {
            for(int i=0; i < 10; i++) {
                iw.addDocument(singleton(new TextField("wrong_field", "test" + i, Field.Store.NO)));
            }
        }, stats -> {
            assertEquals(0, stats.getCount());
            assertEquals(Integer.MIN_VALUE, stats.getMaxLength());
            assertEquals(Integer.MAX_VALUE, stats.getMinLength());
            assertEquals(Double.NaN, stats.getAvgLength(), 0);
            assertTrue(stats.getDistribution().isEmpty());
            assertEquals(0.0, stats.getEntropy(), 0);
        });
    }

    public void testQueryFiltering() throws IOException {
        testAggregation(new TermInSetQuery("text", new BytesRef("test0"), new BytesRef("test1")), iw -> {
            for(int i=0; i < 10; i++) {
                iw.addDocument(singleton(new TextField("text", "test" + i, Field.Store.NO)));
            }
        }, stats -> {
            assertEquals(2, stats.getCount());
            assertEquals(5, stats.getMaxLength());
            assertEquals(5, stats.getMinLength());
            assertEquals(5.0, stats.getAvgLength(), 0);
            assertEquals(5, stats.getDistribution().size());
            assertEquals(0.4, stats.getDistribution().get("t"), 0);
            assertEquals(0.2, stats.getDistribution().get("e"), 0);
            assertEquals(0.1, stats.getDistribution().get("0"), 0);
            assertEquals(2.12193, stats.getEntropy(), 0.00001);
        });
    }

    @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/47469")
    public void testSingleValuedFieldWithFormatter() throws IOException {
        TextFieldMapper.TextFieldType fieldType = new TextFieldMapper.TextFieldType();
        fieldType.setName("text");
        fieldType.setFielddata(true);

        StringStatsAggregationBuilder aggregationBuilder = new StringStatsAggregationBuilder("_name")
            .field("text")
            .format("0000.00")
            .showDistribution(true);

        testAggregation(aggregationBuilder, new MatchAllDocsQuery(), iw -> {
            for(int i=0; i < 10; i++) {
                iw.addDocument(singleton(new TextField("text", "test" + i, Field.Store.NO)));
            }
        }, stats -> {
            assertEquals("0010.00", stats.getCountAsString());
            assertEquals("0005.00", stats.getMaxLengthAsString());
            assertEquals("0005.00", stats.getMinLengthAsString());
            assertEquals("0005.00", stats.getAvgLengthAsString());
            assertEquals("0002.58", stats.getEntropyAsString());
        }, fieldType);
    }

    /**
     * Test a string_stats aggregation as a subaggregation of a terms aggregation
     */
    public void testNestedAggregation() throws IOException {
        MappedFieldType numericFieldType = new NumberFieldMapper.NumberFieldType(NumberFieldMapper.NumberType.INTEGER);
        numericFieldType.setName("value");
        numericFieldType.setHasDocValues(true);

        TextFieldMapper.TextFieldType textFieldType = new TextFieldMapper.TextFieldType();
        textFieldType.setName("text");
        textFieldType.setFielddata(true);

        TermsAggregationBuilder aggregationBuilder = new TermsAggregationBuilder("terms")
            .userValueTypeHint(ValueType.NUMERIC)
            .field("value")
            .subAggregation(new StringStatsAggregationBuilder("text_stats").field("text").userValueTypeHint(ValueType.STRING));

        Directory directory = newDirectory();
        RandomIndexWriter indexWriter = new RandomIndexWriter(random(), directory);
        final int numDocs = 10;
        for (int i = 0; i < numDocs; i++) {
            for (int j = 0; j < 4; j++)
            indexWriter.addDocument(List.of(
                new NumericDocValuesField("value", i + 1),
                new TextField("text", "test" + j, Field.Store.NO))
            );
        }
        indexWriter.close();

        IndexReader indexReader = DirectoryReader.open(directory);
        IndexSearcher indexSearcher = newSearcher(indexReader, true, true);

        TermsAggregator aggregator = createAggregator(aggregationBuilder, indexSearcher, numericFieldType, textFieldType);
        aggregator.preCollection();
        indexSearcher.search(new MatchAllDocsQuery(), aggregator);
        aggregator.postCollection();

        Terms terms = (Terms) aggregator.buildTopLevel();
        assertNotNull(terms);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        assertNotNull(buckets);
        assertEquals(10, buckets.size());

        for (int i = 0; i < 10; i++) {
            Terms.Bucket bucket = buckets.get(i);
            assertNotNull(bucket);
            assertEquals((long) i + 1, bucket.getKeyAsNumber());
            assertEquals(4L, bucket.getDocCount());

            InternalStringStats stats = bucket.getAggregations().get("text_stats");
            assertNotNull(stats);
            assertEquals(4L, stats.getCount());
            assertEquals(5, stats.getMaxLength());
            assertEquals(5, stats.getMinLength());
            assertEquals(5.0, stats.getAvgLength(), 0);
            assertEquals(7, stats.getDistribution().size());
            assertEquals(0.4, stats.getDistribution().get("t"), 0);
            assertEquals(0.2, stats.getDistribution().get("e"), 0);
            assertEquals(2.32193, stats.getEntropy(), 0.00001);
        }

        indexReader.close();
        directory.close();
    }

    public void testValueScriptSingleValuedField() throws IOException {
        final TextFieldMapper.TextFieldType fieldType = new TextFieldMapper.TextFieldType();
        fieldType.setName("text");
        fieldType.setFielddata(true);

        final StringStatsAggregationBuilder aggregationBuilder = new StringStatsAggregationBuilder("_name")
            .field(fieldType.name())
            .script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT_NAME, emptyMap()));

        testAggregation(aggregationBuilder, new MatchAllDocsQuery(), iw -> {
            iw.addDocument(singleton(new TextField(fieldType.name(), "b", Field.Store.NO)));
            iw.addDocument(singleton(new TextField(fieldType.name(), "b", Field.Store.NO)));
        }, stats -> {
            assertEquals(2, stats.getCount());
            assertEquals(2, stats.getMaxLength());
            assertEquals(2, stats.getMinLength());
            assertEquals(2.0, stats.getAvgLength(), 0);
            assertEquals(2, stats.getDistribution().size());
            assertEquals(0.5, stats.getDistribution().get("a"), 0);
            assertEquals(0.5, stats.getDistribution().get("b"), 0);
            assertEquals(1.0, stats.getEntropy(), 0);
        }, fieldType);
    }

    public void testValueScriptMultiValuedField() throws IOException {
        final TextFieldMapper.TextFieldType fieldType = new TextFieldMapper.TextFieldType();
        fieldType.setName("text");
        fieldType.setFielddata(true);

        final StringStatsAggregationBuilder aggregationBuilder = new StringStatsAggregationBuilder("_name")
            .field(fieldType.name())
            .script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT_NAME, emptyMap()));

        testAggregation(aggregationBuilder, new MatchAllDocsQuery(), iw -> {
            iw.addDocument(Set.of(
                new TextField(fieldType.name(), "b", Field.Store.NO),
                new TextField(fieldType.name(), "c", Field.Store.NO)
            ));
            iw.addDocument(Set.of(
                new TextField(fieldType.name(), "b", Field.Store.NO),
                new TextField(fieldType.name(), "c", Field.Store.NO)
            ));
        }, stats -> {
            assertEquals(4, stats.getCount());
            assertEquals(2, stats.getMaxLength());
            assertEquals(2, stats.getMinLength());
            assertEquals(2.0, stats.getAvgLength(), 0);
            assertEquals(3, stats.getDistribution().size());
            assertEquals(0.5, stats.getDistribution().get("a"), 0);
            assertEquals(0.25, stats.getDistribution().get("b"), 0);
            assertEquals(0.25, stats.getDistribution().get("c"), 0);
            assertEquals(1.5, stats.getEntropy(), 0);
        }, fieldType);
    }

    public void testFieldScriptSingleValuedField() throws IOException {
        final TextFieldMapper.TextFieldType fieldType = new TextFieldMapper.TextFieldType();
        fieldType.setName("text");
        fieldType.setFielddata(true);

        final StringStatsAggregationBuilder aggregationBuilder = new StringStatsAggregationBuilder("_name")
            .script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, FIELD_SCRIPT_NAME, singletonMap("field", fieldType.name())));

        testAggregation(aggregationBuilder, new MatchAllDocsQuery(), iw -> {
            iw.addDocument(singleton(new TextField(fieldType.name(), "b", Field.Store.NO)));
            iw.addDocument(singleton(new TextField(fieldType.name(), "b", Field.Store.NO)));
        }, stats -> {
            assertEquals(2, stats.getCount());
            assertEquals(2, stats.getMaxLength());
            assertEquals(2, stats.getMinLength());
            assertEquals(2.0, stats.getAvgLength(), 0);
            assertEquals(2, stats.getDistribution().size());
            assertEquals(0.5, stats.getDistribution().get("a"), 0);
            assertEquals(0.5, stats.getDistribution().get("b"), 0);
            assertEquals(1.0, stats.getEntropy(), 0);
        }, fieldType);
    }

    public void testFieldScriptMultiValuedField() throws IOException {
        final TextFieldMapper.TextFieldType fieldType = new TextFieldMapper.TextFieldType();
        fieldType.setName("text");
        fieldType.setFielddata(true);

        final StringStatsAggregationBuilder aggregationBuilder = new StringStatsAggregationBuilder("_name")
            .script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, FIELD_SCRIPT_NAME, singletonMap("field", fieldType.name())));

        testAggregation(aggregationBuilder, new MatchAllDocsQuery(), iw -> {
            iw.addDocument(Set.of(
                new TextField(fieldType.name(), "b", Field.Store.NO),
                new TextField(fieldType.name(), "c", Field.Store.NO)
            ));
            iw.addDocument(Set.of(
                new TextField(fieldType.name(), "b", Field.Store.NO),
                new TextField(fieldType.name(), "c", Field.Store.NO)
            ));
        }, stats -> {
            assertEquals(4, stats.getCount());
            assertEquals(2, stats.getMaxLength());
            assertEquals(2, stats.getMinLength());
            assertEquals(2.0, stats.getAvgLength(), 0);
            assertEquals(3, stats.getDistribution().size());
            assertEquals(0.5, stats.getDistribution().get("a"), 0);
            assertEquals(0.25, stats.getDistribution().get("b"), 0);
            assertEquals(0.25, stats.getDistribution().get("c"), 0);
            assertEquals(1.5, stats.getEntropy(), 0);
        }, fieldType);
    }

    private void testAggregation(Query query,
        CheckedConsumer<RandomIndexWriter, IOException> buildIndex,
        Consumer<InternalStringStats> verify) throws IOException {
        TextFieldMapper.TextFieldType fieldType = new TextFieldMapper.TextFieldType();
        fieldType.setName("text");
        fieldType.setFielddata(true);

        AggregationBuilder aggregationBuilder = new StringStatsAggregationBuilder("_name").field("text");
        testAggregation(aggregationBuilder, query, buildIndex, verify, fieldType);
    }

    private void testAggregation(
        AggregationBuilder aggregationBuilder,
        Query query,
        CheckedConsumer<RandomIndexWriter, IOException> buildIndex,
        Consumer<InternalStringStats> verify,
        MappedFieldType fieldType)  throws IOException {
        testCase(aggregationBuilder, query, buildIndex, verify, fieldType);
    }

    @Override
    protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
        return new StringStatsAggregationBuilder("_name")
            .field(fieldName);
    }

    @Override
    protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
        return singletonList(CoreValuesSourceType.BYTES);
    }

    @Override
    protected List<String> unsupportedMappedFieldTypes() {
        return singletonList(IpFieldMapper.CONTENT_TYPE);
    }

    @Override
    protected ScriptService getMockScriptService() {
        final Map<String, Function<Map<String, Object>, Object>> scripts = Map.of(
            VALUE_SCRIPT_NAME, vars -> "a" + vars.get("_value"),
            FIELD_SCRIPT_NAME, vars -> {
                final String fieldName = (String) vars.get("field");
                final LeafDocLookup lookup = (LeafDocLookup) vars.get("doc");
                return lookup.get(fieldName).stream()
                    .map(value -> "a" + value)
                    .collect(toList());
            }
        );
        final MockScriptEngine engine = new MockScriptEngine(MockScriptEngine.NAME, scripts, emptyMap());
        final Map<String, ScriptEngine> engines = singletonMap(engine.getType(), engine);
        return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.ofbiz.entity.util;

/**
 * Contains a number of variables used to select certain advanced options for storing GenericEntities.
 */
@SuppressWarnings("serial")
public class EntityStoreOptions implements java.io.Serializable {

    /** Option for creating missing referenced values as dummy (pk-only) entries */
    protected boolean createDummyFks = false;

    /**
     * Default constructor. Defaults are as follows: createDummyFks = false
     */
    public EntityStoreOptions() {
    }

    /**
     * Optional constructor with options to specify.
     *
     * @param createDummyFks
     */
    public EntityStoreOptions(boolean createDummyFks) {
        this.createDummyFks = createDummyFks;
    }

    /**
     * If true, missing entries in FK referenced entities will be created while storing the given GenericValues.
     *
     * @return boolean
     */
    public boolean isCreateDummyFks() {
        return createDummyFks;
    }

    /**
     * If true, missing entries in FK referenced entities will be created while storing the given GenericValues.
     *
     * @param createDummyFks
     */
    public void setCreateDummyFks(boolean createDummyFks) {
        this.createDummyFks = createDummyFks;
    }
}


text:
package org.elasticsearch.shell.source;

import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.shell.console.Console;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintStream;

/**
 * Reader that is able to detect whether a source is compilable or wait for eventual more input
 * in order to read new lines and obtain a compilable source
 *
 * @author Luca Cavanna
 */
public class CompilableSourceReader {

    private static final Logger logger = LoggerFactory.getLogger(CompilableSourceReader.class);

    private final Console<PrintStream> console;
    private final InputAnalyzer inputAnalyzer;

    /**
     * Creates the source reader given the console to read from and the input analyzer
     * @param console the console to read from
     * @param inputAnalyzer analyzer that determines whether a source is compilable or not
     */
    @Inject
    public CompilableSourceReader(Console<PrintStream> console, InputAnalyzer inputAnalyzer) {
        this.console = console;
        this.inputAnalyzer = inputAnalyzer;
    }

    /**
     * Reads the input from the console and returns the input compilable source
     * @return the compilable source taken from the console as soon as it is compilable
     * @throws Exception
     */
    public CompilableSource read(String prompt) throws Exception {

        boolean previousLineWasEmpty = false;
        int lineNumber = 0;
        String source = "";

        while(true) {
            String line = console.readLine(lineNumber == 0 ? prompt : "... ");
            source = source + line + "\n";
            lineNumber++;

            if (inputAnalyzer.isCompilable(source)) {
                logger.debug("Source {} is compilable", source);
                break;
            }

            if (line.length() == 0) {
                if (previousLineWasEmpty) {
                    return null;
                }
                previousLineWasEmpty = true;
            }
            logger.debug("Source {} isn't compilable, waiting for more input", source);
        }

        return new CompilableSource(source, lineNumber);
    }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Translations>
  <Type Name="ActiveDirectoryAuthorizerMessage" />
  <Type Name="ActiveDirectoryConfigurationEmbedded" />
  <Type Name="ActivityWithRemarks" />
  <Type Name="AlertCurrentState" />
  <Type Name="AlertEntity" />
  <Type Name="AlertMessage" />
  <Type Name="AlertOperation" />
  <Type Name="AlertState" />
  <Type Name="AlertTypeEntity" />
  <Type Name="AlertTypeOperation" />
  <Type Name="AllowedRule`2" />
  <Type Name="AllowedRuleCoerced`2" />
  <Type Name="AppendixHelpEntity" />
  <Type Name="AppendixHelpOperation" />
  <Type Name="AsyncEmailSenderPermission" />
  <Type Name="AuthAdminMessage" />
  <Type Name="AuthEmailMessage" />
  <Type Name="AuthMessage" />
  <Type Name="AuthThumbnail" />
  <Type Name="AuthTokenConfigurationEmbedded" />
  <Type Name="AutoconfigureNeuralNetworkEntity" />
  <Type Name="BaseRulePack`1" />
  <Type Name="BasicPermission" />
  <Type Name="BpmnEntityPairEmbedded" />
  <Type Name="CachePermission" />
  <Type Name="CaseActivityEntity" />
  <Type Name="CaseActivityExecutedTimerEntity" />
  <Type Name="CaseActivityMessage" />
  <Type Name="CaseActivityOperation" />
  <Type Name="CaseActivityProcessAlgorithm" />
  <Type Name="CaseActivityQuery" />
  <Type Name="CaseActivityState" />
  <Type Name="CaseActivityTask" />
  <Type Name="CaseEntity" />
  <Type Name="CaseFlowColor" />
  <Type Name="CaseJunctionEntity" />
  <Type Name="CaseNotificationEntity" />
  <Type Name="CaseNotificationOperation" />
  <Type Name="CaseNotificationState" />
  <Type Name="CaseOperation" />
  <Type Name="CaseTagEntity" />
  <Type Name="CaseTagsModel" />
  <Type Name="CaseTagTypeEntity" />
  <Type Name="CaseTagTypeOperation" />
  <Type Name="CertFileType" />
  <Type Name="ChartColorEntity" />
  <Type Name="ChartColumnEmbedded" />
  <Type Name="ChartColumnType" />
  <Type Name="ChartMessage" />
  <Type Name="ChartPaletteModel" />
  <Type Name="ChartParameterEmbedded" />
  <Type Name="ChartParameterType" />
  <Type Name="ChartPermission" />
  <Type Name="ChartRequest" />
  <Type Name="ChartScriptColumnEmbedded" />
  <Type Name="ChartScriptEntity" />
  <Type Name="ChartScriptOperation" />
  <Type Name="ChartScriptParameterEmbedded" />
  <Type Name="ClientCertificationFileEmbedded" />
  <Type Name="CNTKPredictorAlgorithm" />
  <Type Name="ConnectionType" />
  <Type Name="CSharpMigrationEntity" />
  <Type Name="CultureInfoEntity" />
  <Type Name="CultureInfoOperation" />
  <Type Name="DashboardEmbedededInEntity" />
  <Type Name="DashboardEntity" />
  <Type Name="DashboardMessage" />
  <Type Name="DashboardOperation" />
  <Type Name="DashboardPermission" />
  <Type Name="DateFilterRange" />
  <Type Name="DateSpanEmbedded" />
  <Type Name="DefaultColumnEncodings" />
  <Type Name="DefaultState" />
  <Type Name="DelayOption" />
  <Type Name="DiffLogMessage" />
  <Type Name="DiffLogMixin" />
  <Type Name="DisabledMessage" />
  <Type Name="DisabledMixin" />
  <Type Name="DisableOperation" />
  <Type Name="DisconnectedCreatedMixin" />
  <Type Name="DisconnectedExportEntity" />
  <Type Name="DisconnectedExportState" />
  <Type Name="DisconnectedExportTableEmbedded" />
  <Type Name="DisconnectedImportEntity" />
  <Type Name="DisconnectedImportState" />
  <Type Name="DisconnectedImportTableEmbedded" />
  <Type Name="DisconnectedMachineEntity" />
  <Type Name="DisconnectedMachineOperation" />
  <Type Name="DisconnectedMachineState" />
  <Type Name="DisconnectedMessage" />
  <Type Name="DisconnectedSubsetMixin" />
  <Type Name="DoneType" />
  <Type Name="DynamicBaseType" />
  <Type Name="DynamicExpressionEntity" />
  <Type Name="DynamicExpressionOperation" />
  <Type Name="DynamicExpressionTranslation" />
  <Type Name="DynamicMixinConnectionEntity" />
  <Type Name="DynamicMixinConnectionOperation" />
  <Type Name="DynamicPanelPermission" />
  <Type Name="DynamicRenameEntity" />
  <Type Name="DynamicSqlMigrationEntity" />
  <Type Name="DynamicSqlMigrationMessage" />
  <Type Name="DynamicSqlMigrationOperation" />
  <Type Name="DynamicTypeConditionEntity" />
  <Type Name="DynamicTypeConditionEval" />
  <Type Name="DynamicTypeConditionOperation" />
  <Type Name="DynamicTypeConditionSymbolEntity" />
  <Type Name="DynamicTypeConditionSymbolOperation" />
  <Type Name="DynamicTypeEntity" />
  <Type Name="DynamicTypeMessage" />
  <Type Name="DynamicTypeOperation" />
  <Type Name="DynamicValidationEntity" />
  <Type Name="DynamicValidationEval" />
  <Type Name="DynamicValidationOperation" />
  <Type Name="DynamicViewEntity" />
  <Type Name="DynamicViewMessage" />
  <Type Name="DynamicViewOperation" />
  <Type Name="DynamicViewOverrideEntity" />
  <Type Name="DynamicViewOverrideOperation" />
  <Type Name="DynamicViewSelectorEntity" />
  <Type Name="DynamicViewSelectorOperation" />
  <Type Name="DynamicViewValidationMessage" />
  <Type Name="EmailAddressEmbedded" />
  <Type Name="EmailAttachmentEmbedded" />
  <Type Name="EmailAttachmentType" />
  <Type Name="EmailConfigurationEmbedded" />
  <Type Name="EmailFileType" />
  <Type Name="EmailMasterTemplateEntity" />
  <Type Name="EmailMasterTemplateMessageEmbedded" />
  <Type Name="EmailMasterTemplateOperation" />
  <Type Name="EmailMessageEntity" />
  <Type Name="EmailMessageMessage" />
  <Type Name="EmailMessageOperation" />
  <Type Name="EmailMessageProcess" />
  <Type Name="EmailMessageState" />
  <Type Name="EmailOwnerData" />
  <Type Name="EmailPackageEntity" />
  <Type Name="EmailReceptionInfoEmbedded" />
  <Type Name="EmailReceptionMixin" />
  <Type Name="EmailRecipientEntity" />
  <Type Name="EmailRecipientKind" />
  <Type Name="EmailTemplateContactEmbedded" />
  <Type Name="EmailTemplateEntity" />
  <Type Name="EmailTemplateMessage" />
  <Type Name="EmailTemplateMessageEmbedded" />
  <Type Name="EmailTemplateOperation" />
  <Type Name="EmailTemplateRecipientEntity" />
  <Type Name="EmailTemplateViewMessage" />
  <Type Name="EntityAction" />
  <Type Name="EntityHelpEntity" />
  <Type Name="EntityHelpOperation" />
  <Type Name="EvalEmbedded`1" />
  <Type Name="ExcelAttachmentEntity" />
  <Type Name="ExcelMessage" />
  <Type Name="ExcelReportEntity" />
  <Type Name="ExcelReportOperation" />
  <Type Name="FileEmbedded" />
  <Type Name="FileEntity" />
  <Type Name="FileMessage" />
  <Type Name="FilePathEmbedded" />
  <Type Name="FilePathEntity" />
  <Type Name="FilePathOperation" />
  <Type Name="FileTypeSymbol" />
  <Type Name="GroupByChart" />
  <Type Name="HelpKindMessage" />
  <Type Name="HelpMessage" />
  <Type Name="HelpPermissions" />
  <Type Name="HelpSearchMessage" />
  <Type Name="HelpSyntaxMessage" />
  <Type Name="HolidayCalendarEntity" />
  <Type Name="HolidayCalendarOperation" />
  <Type Name="HolidayEmbedded" />
  <Type Name="IAttachmentGeneratorEntity" />
  <Type Name="ICaseMainEntity" />
  <Type Name="IEmailOwnerEntity" />
  <Type Name="ImageAttachmentEntity" />
  <Type Name="InboxFilterModel" />
  <Type Name="InboxMessage" />
  <Type Name="InsertPlace" />
  <Type Name="IPartEntity" />
  <Type Name="IPredictorAlgorithmSettings" />
  <Type Name="IProcessDataEntity" />
  <Type Name="IProcessLineDataEntity" />
  <Type Name="IScheduleRuleEntity" />
  <Type Name="IsolationEntity" />
  <Type Name="IsolationMessage" />
  <Type Name="IsolationMixin" />
  <Type Name="IsolationOperation" />
  <Type Name="ITaskEntity" />
  <Type Name="ITaskMessage" />
  <Type Name="ITaskOperation" />
  <Type Name="IUserAssetEntity" />
  <Type Name="IWorkflowNodeEntity" />
  <Type Name="IWorkflowObjectEntity" />
  <Type Name="JoyrideEntity" />
  <Type Name="JoyrideMessage">
    <Member Name="Back" Description="Terug" />
    <Member Name="Close" Description="Sluiten" />
    <Member Name="Last" Description="Stop" />
    <Member Name="Next" Description="Volgende" />
    <Member Name="Skip" Description="Annuleren" />
  </Type>
  <Type Name="JoyrideOperation" />
  <Type Name="JoyrideStepEntity" />
  <Type Name="JoyrideStepOperation" />
  <Type Name="JoyrideStepPosition" />
  <Type Name="JoyrideStepStyleEntity" />
  <Type Name="JoyrideStepStyleOperation" />
  <Type Name="JoyrideStepType" />
  <Type Name="JoyrideType" />
  <Type Name="LinkElementEmbedded" />
  <Type Name="LinkListPartEntity" />
  <Type Name="LoadMethodLogEntity" />
  <Type Name="LoginAuthMessage">
    <Member Name="ChangePassword" Description="
Verander wachtwoord" />
    <Member Name="ChangePasswordAspx_ChangePassword" Description="
Verander wachtwoord" />
    <Member Name="Logout" Description="Afmelden" />
  </Type>
  <Type Name="MapMessage" />
  <Type Name="MapPermission" />
  <Type Name="MergeStrategy" />
  <Type Name="MessageLengthExceeded" />
  <Type Name="ModelConverterSymbol" />
  <Type Name="MoveTreeModel" />
  <Type Name="MultiEntityModel" />
  <Type Name="MultipleSMSModel" />
  <Type Name="NamespaceHelpEntity" />
  <Type Name="NamespaceHelpOperation" />
  <Type Name="NeuralNetworkActivation" />
  <Type Name="NeuralNetworkEvalFunction" />
  <Type Name="NeuralNetworkHidenLayerEmbedded" />
  <Type Name="NeuralNetworkInitializer" />
  <Type Name="NeuralNetworkLearner" />
  <Type Name="NeuralNetworkSettingsEntity" />
  <Type Name="NewsletterDeliveryEntity" />
  <Type Name="NewsletterEntity" />
  <Type Name="NewsletterOperation" />
  <Type Name="NewsletterProcess" />
  <Type Name="NewsletterState" />
  <Type Name="NoteEntity" />
  <Type Name="NoteMessage" />
  <Type Name="NoteOperation" />
  <Type Name="NoteTypeEntity" />
  <Type Name="NoteTypeOperation" />
  <Type Name="OmniboxMessage" />
  <Type Name="OperationAllowed" />
  <Type Name="OperationAllowedRule" />
  <Type Name="OperationHelpEmbedded" />
  <Type Name="OperationRulePack" />
  <Type Name="OperationTypeEmbedded" />
  <Type Name="PackageEntity" />
  <Type Name="PackageLineEntity" />
  <Type Name="PackageOperationEntity" />
  <Type Name="PackageOperationProcess" />
  <Type Name="PackageQuery" />
  <Type Name="PanelPartEmbedded" />
  <Type Name="PanelStyle" />
  <Type Name="PasswordExpiresIntervalEntity" />
  <Type Name="PasswordExpiresIntervalOperation" />
  <Type Name="PermissionAllowedRule" />
  <Type Name="PermissionRulePack" />
  <Type Name="PermissionSymbol" />
  <Type Name="Pop3ConfigurationAction" />
  <Type Name="Pop3ConfigurationEntity" />
  <Type Name="Pop3ConfigurationOperation" />
  <Type Name="Pop3ReceptionEntity" />
  <Type Name="Pop3ReceptionExceptionEntity" />
  <Type Name="PredictionSet" />
  <Type Name="PredictionType" />
  <Type Name="PredictorAlgorithmSymbol" />
  <Type Name="PredictorClassificationMetricsEmbedded" />
  <Type Name="PredictorCodificationEntity" />
  <Type Name="PredictorColumnEmbedded" />
  <Type Name="PredictorColumnEncodingSymbol" />
  <Type Name="PredictorColumnNullHandling" />
  <Type Name="PredictorColumnUsage" />
  <Type Name="PredictorEntity" />
  <Type Name="PredictorEpochProgressEntity" />
  <Type Name="PredictorFileType" />
  <Type Name="PredictorMainQueryEmbedded" />
  <Type Name="PredictorMessage" />
  <Type Name="PredictorMetricsEmbedded" />
  <Type Name="PredictorOperation" />
  <Type Name="PredictorProcessAlgorithm" />
  <Type Name="PredictorPublicationSymbol" />
  <Type Name="PredictorRegressionMetricsEmbedded" />
  <Type Name="PredictorResultSaverSymbol" />
  <Type Name="PredictorSettingsEmbedded" />
  <Type Name="PredictorSimpleResultSaver" />
  <Type Name="PredictorState" />
  <Type Name="PredictorSubQueryColumnEmbedded" />
  <Type Name="PredictorSubQueryColumnUsage" />
  <Type Name="PredictorSubQueryEntity" />
  <Type Name="PredictSimpleResultEntity" />
  <Type Name="PrintLineEntity" />
  <Type Name="PrintLineOperation" />
  <Type Name="PrintLineState" />
  <Type Name="PrintPackageEntity" />
  <Type Name="PrintPackageProcess" />
  <Type Name="PrintPermission" />
  <Type Name="PrintTask" />
  <Type Name="ProcessAlgorithmSymbol" />
  <Type Name="ProcessEntity" />
  <Type Name="ProcessExceptionLineEntity" />
  <Type Name="ProcessMessage" />
  <Type Name="ProcessOperation" />
  <Type Name="ProcessPermission" />
  <Type Name="ProcessState" />
  <Type Name="ProfilerPermission" />
  <Type Name="PropertyAllowed" />
  <Type Name="PropertyAllowedRule" />
  <Type Name="PropertyRouteHelpEmbedded" />
  <Type Name="PropertyRulePack" />
  <Type Name="QueryAllowed" />
  <Type Name="QueryAllowedRule" />
  <Type Name="QueryColumnEmbedded" />
  <Type Name="QueryColumnHelpEmbedded" />
  <Type Name="QueryFilterEmbedded" />
  <Type Name="QueryHelpEntity" />
  <Type Name="QueryHelpOperation" />
  <Type Name="QueryModel" />
  <Type Name="QueryModelMessage" />
  <Type Name="QueryOrderEmbedded" />
  <Type Name="QueryRulePack" />
  <Type Name="QueryStringValueEmbedded" />
  <Type Name="QueryTokenEmbedded" />
  <Type Name="ResetPasswordRequestEntity" />
  <Type Name="RestApiKeyEntity" />
  <Type Name="RestApiKeyOperation" />
  <Type Name="RestLogEntity" />
  <Type Name="RestLogReplayState" />
  <Type Name="RoleEntity" />
  <Type Name="RoleOperation" />
  <Type Name="RoleQuery" />
  <Type Name="RuleEntity`2" />
  <Type Name="RuleOperationEntity" />
  <Type Name="RulePermissionEntity" />
  <Type Name="RulePropertyEntity" />
  <Type Name="RuleQueryEntity" />
  <Type Name="RuleTypeConditionEmbedded" />
  <Type Name="RuleTypeEntity" />
  <Type Name="ScheduledTaskEntity" />
  <Type Name="ScheduledTaskLogEntity" />
  <Type Name="ScheduledTaskLogOperation" />
  <Type Name="ScheduledTaskOperation" />
  <Type Name="SchedulerMessage" />
  <Type Name="SchedulerPermission" />
  <Type Name="SchedulerTaskExceptionLineEntity" />
  <Type Name="ScheduleRuleMinutelyEntity" />
  <Type Name="ScheduleRuleMonthsEntity" />
  <Type Name="ScheduleRuleWeekDaysEntity" />
  <Type Name="ScriptExecutionEmbedded" />
  <Type Name="SendEmailTaskEntity" />
  <Type Name="SendEmailTaskOperation" />
  <Type Name="SessionLogEntity" />
  <Type Name="SessionLogPermission" />
  <Type Name="SimpleTaskSymbol" />
  <Type Name="SMSCharactersMessage" />
  <Type Name="SMSConfigurationEmbedded" />
  <Type Name="SMSMessageEntity" />
  <Type Name="SMSMessageOperation" />
  <Type Name="SMSMessageProcess" />
  <Type Name="SMSMessageState" />
  <Type Name="SMSPackageEntity" />
  <Type Name="SMSSendPackageEntity" />
  <Type Name="SMSTemplateEntity" />
  <Type Name="SMSTemplateMessage" />
  <Type Name="SMSTemplateMessageEmbedded" />
  <Type Name="SMSTemplateOperation" />
  <Type Name="SMSUpdatePackageEntity" />
  <Type Name="SmtpConfigurationEntity" />
  <Type Name="SmtpConfigurationOperation" />
  <Type Name="SmtpNetworkDeliveryEmbedded" />
  <Type Name="SqlMigrationEntity" />
  <Type Name="SubEntitiesEval" />
  <Type Name="SubWorkflowEmbedded" />
  <Type Name="SystemEmailEntity" />
  <Type Name="SystemEventLogEntity" />
  <Type Name="SystemWordTemplateEntity" />
  <Type Name="TemplateApplicableEval" />
  <Type Name="TemplateTokenMessage" />
  <Type Name="TimeMachineMessage" />
  <Type Name="TimeSpanEmbedded" />
  <Type Name="ToolbarElementEmbedded" />
  <Type Name="ToolbarElementType" />
  <Type Name="ToolbarEntity" />
  <Type Name="ToolbarLocation" />
  <Type Name="ToolbarMenuEntity" />
  <Type Name="ToolbarMenuOperation" />
  <Type Name="ToolbarOperation" />
  <Type Name="TranslatedInstanceEntity" />
  <Type Name="TranslationJavascriptMessage" />
  <Type Name="TranslationMessage" />
  <Type Name="TranslationPermission" />
  <Type Name="TranslationReplacementEntity" />
  <Type Name="TranslationReplacementOperation" />
  <Type Name="TreeEntity" />
  <Type Name="TreeMessage" />
  <Type Name="TreeOperation" />
  <Type Name="TreeViewerMessage" />
  <Type Name="TriggeredOn" />
  <Type Name="TypeAllowed" />
  <Type Name="TypeAllowedAndConditions" />
  <Type Name="TypeAllowedBasic" />
  <Type Name="TypeAllowedRule" />
  <Type Name="TypeConditionRuleEmbedded" />
  <Type Name="TypeConditionSymbol" />
  <Type Name="TypeRulePack" />
  <Type Name="TypeSearchResult" />
  <Type Name="UserAssetMessage" />
  <Type Name="UserAssetPermission" />
  <Type Name="UserAssetPreviewLineEmbedded" />
  <Type Name="UserAssetPreviewModel" />
  <Type Name="UserChartEntity" />
  <Type Name="UserChartOperation" />
  <Type Name="UserChartPartEntity" />
  <Type Name="UserEntity" />
  <Type Name="UserOperation" />
  <Type Name="UserQueryEntity" />
  <Type Name="UserQueryMessage" />
  <Type Name="UserQueryOperation" />
  <Type Name="UserQueryPartEntity" />
  <Type Name="UserQueryPartRenderMode" />
  <Type Name="UserQueryPermission" />
  <Type Name="UserState" />
  <Type Name="UserTicketEntity" />
  <Type Name="ValueUserQueryElementEmbedded" />
  <Type Name="ValueUserQueryListPartEntity" />
  <Type Name="ViewLogEntity" />
  <Type Name="ViewLogMessage" />
  <Type Name="WebDownload" />
  <Type Name="WebImage" />
  <Type Name="WordAttachmentEntity" />
  <Type Name="WordConverterSymbol" />
  <Type Name="WordTemplateEntity" />
  <Type Name="WordTemplateMessage" />
  <Type Name="WordTemplateOperation" />
  <Type Name="WordTemplatePermission" />
  <Type Name="WordTransformerSymbol" />
  <Type Name="WorkflowActionEntity" />
  <Type Name="WorkflowActionEval" />
  <Type Name="WorkflowActionOperation" />
  <Type Name="WorkflowActivityEntity" />
  <Type Name="WorkflowActivityMessage" />
  <Type Name="WorkflowActivityModel" />
  <Type Name="WorkflowActivityMonitorMessage" />
  <Type Name="WorkflowActivityOperation" />
  <Type Name="WorkflowActivityType" />
  <Type Name="WorkflowConditionEntity" />
  <Type Name="WorkflowConditionEval" />
  <Type Name="WorkflowConditionOperation" />
  <Type Name="WorkflowConfigurationEmbedded" />
  <Type Name="WorkflowConnectionEntity" />
  <Type Name="WorkflowConnectionModel" />
  <Type Name="WorkflowConnectionOperation" />
  <Type Name="WorkflowEntity" />
  <Type Name="WorkflowEventEntity" />
  <Type Name="WorkflowEventModel" />
  <Type Name="WorkflowEventOperation" />
  <Type Name="WorkflowEventTaskActionEval" />
  <Type Name="WorkflowEventTaskConditionEval" />
  <Type Name="WorkflowEventTaskConditionResultEntity" />
  <Type Name="WorkflowEventTaskEntity" />
  <Type Name="WorkflowEventTaskModel" />
  <Type Name="WorkflowEventTaskOperation" />
  <Type Name="WorkflowEventType" />
  <Type Name="WorkflowGatewayDirection" />
  <Type Name="WorkflowGatewayEntity" />
  <Type Name="WorkflowGatewayModel" />
  <Type Name="WorkflowGatewayOperation" />
  <Type Name="WorkflowGatewayType" />
  <Type Name="WorkflowIssueType" />
  <Type Name="WorkflowLaneActorsEval" />
  <Type Name="WorkflowLaneEntity" />
  <Type Name="WorkflowLaneModel" />
  <Type Name="WorkflowLaneOperation" />
  <Type Name="WorkflowMainEntityStrategy" />
  <Type Name="WorkflowMessage" />
  <Type Name="WorkflowModel" />
  <Type Name="WorkflowOperation" />
  <Type Name="WorkflowPanelPermission" />
  <Type Name="WorkflowPoolEntity" />
  <Type Name="WorkflowPoolModel" />
  <Type Name="WorkflowPoolOperation" />
  <Type Name="WorkflowReplacementItemEmbedded" />
  <Type Name="WorkflowReplacementModel" />
  <Type Name="WorkflowScriptEntity" />
  <Type Name="WorkflowScriptEval" />
  <Type Name="WorkflowScriptOperation" />
  <Type Name="WorkflowScriptPartEmbedded" />
  <Type Name="WorkflowScriptRetryStrategyEntity" />
  <Type Name="WorkflowScriptRetryStrategyOperation" />
  <Type Name="WorkflowTimerConditionEntity" />
  <Type Name="WorkflowTimerConditionEval" />
  <Type Name="WorkflowTimerConditionOperation" />
  <Type Name="WorkflowTimerEmbedded" />
  <Type Name="WorkflowValidationMessage" />
  <Type Name="WorkflowXmlEmbedded" />
</Translations>


text:
function init(virtual)
  if not virtual then

    -- if storage.state == nil then
    --   storage.state = false
    -- end
    throughput()

    updateAnimationState()
  end
end

function onInboundNodeChange(args)
  throughput()
end

function onNodeConnectionChange()
  throughput()
end

function throughput()
  storage.state = entity.getInboundNodeLevel(0)
  entity.setOutboundNodeLevel(0, storage.state)
end

function updateAnimationState()
  if entity.direction() == 1 then
    entity.setAnimationState("flipState", "default")
  else
    entity.setAnimationState("flipState", "flipped")
  end
end


text:
<?php
/**
 * @uses $vars['user'] ElggUser
 */

/* @var ElggUser $user */
$user = $vars['user'];

//@todo JS 1.8: no ?>

			<?php echo elgg_echo('notifications:subscriptions:friends:title'); ?>

	<?php echo elgg_echo('notifications:subscriptions:friends:description'); ?>

<?php
	$i = 0;
	$NOTIFICATION_HANDLERS = _elgg_services()->notifications->getMethodsAsDeprecatedGlobal();
	foreach($NOTIFICATION_HANDLERS as $method => $foo) {
		if ($i > 0) {
			echo " 	";
		}
?>
	<td class="<?php echo $method; ?>togglefield"><?php echo elgg_echo('notification:method:'.$method); ?>
<?php
		$i++;
	}
?>

<?php
	$members = array();
	$friends = $user->getFriends(array('limit' => 0));
	if ($friends) {
		foreach ($friends as $friend) {
			$members[] = $friend->guid;
		}
	}
	$memberno = sizeof($members);
	$members = implode(',',$members);

?>

				<?php echo elgg_echo('friends:all'); ?> (<?php echo $memberno; ?>)

<?php

	$fields = '';
	$i = 0;
	foreach($NOTIFICATION_HANDLERS as $method => $foo) {
		$metaname = 'collections_notifications_preferences_' . $method;
		if ($collections_preferences = $user->$metaname) {
			if (!empty($collections_preferences) && !is_array($collections_preferences)) {
				$collections_preferences = array($collections_preferences);
			}
			if (is_array($collections_preferences)) {
				if (in_array(-1,$collections_preferences)) {
					$collectionschecked[$method] = 'checked="checked"';
				} else {
					$collectionschecked[$method] = '';
				}
			}
		}
		if ($i > 0) {
			$fields .= " 	";
		}
		$fields .= <<< END

			<input type="checkbox" name="{$method}collections[]" id="{$method}checkbox" onclick="adjust{$method}('{$method}collections-1');" value="-1" {$collectionschecked[$method]} />
END;
		$i++;
	}
	echo $fields;

?>

<?php

	if ($collections = get_user_access_collections($user->guid)) {
		foreach ($collections as $collection) {
			$members = get_members_of_access_collection($collection->id, true);
			$memberno = 0;
			if ($members) {
				$memberno = sizeof($members);
				$members = implode(',', $members);
			} else {
				$members = '';
			}

?>

				<?php echo $collection->name; ?> (<?php echo $memberno; ?>)

<?php

			$fields = '';
			$i = 0;
			foreach($NOTIFICATION_HANDLERS as $method => $foo) {
				$metaname = 'collections_notifications_preferences_' . $method;
				if ($collections_preferences = $user->$metaname) {
					if (!empty($collections_preferences) && !is_array($collections_preferences)) {
						$collections_preferences = array($collections_preferences);
					}
					if (is_array($collections_preferences)) {
						if (in_array($collection->id,$collections_preferences)) {
							$collectionschecked[$method] = 'checked="checked"';
						} else {
							$collectionschecked[$method] = '';
						}
					}
				}
				if ($i > 0) {
					$fields .= " 	";
				}
				$fields .= <<< END

					id}" class="{$method}toggleOff" onclick="adjust{$method}_alt('{$method}collections{$collection->id}'); setCollection([{$members}],'{$method}',{$collection->id});">
					<input type="checkbox" name="{$method}collections[]" id="{$method}checkbox" onclick="adjust{$method}('{$method}collections{$collection->id}');" value="{$collection->id}" {$collectionschecked[$method]} />
END;
				$i++;
			}
			echo $fields;

?>

<?php

		}
	}

?>


text:
from webspider.web.handlers.keyword_statistics import KeywordStatisticsApiHandler, KeywordStatisticsPageHandler

__all__ = [
    'KeywordStatisticsApiHandler',
    'KeywordStatisticsPageHandler'
]


text:
'use strict';

require('./config/db');
const Organism = require('./organisms/aluno');
const query = {_id: '56f76d35c949c9137395d49a'}
const callback = require('./organisms/organelles/callbackRemove');

Organism.remove(query, callback);


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.munif.bereja.teste;

import br.com.munif.bereja.entidades.Usuario;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;

/**
 *
 * @author munif
 */
public class Teste {

    public static void main(String ... args){

        EntityManager em = Persistence.createEntityManagerFactory("berejaPU").createEntityManager();
        for (int i=0;i<100;i++){
            Usuario usu=new Usuario();
            usu.setNome(""+i);
            em.persist(usu);
        }
        em.close();
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 29: 386 (1931)

#### Original name
Thyridaria insueta Petr.

### Remarks
null


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Trans. & Proc. New Zealand Inst. 30: 387 (1898)

#### Original name
Lecidea leucoxantha Spreng.

### Remarks
null


text:
module.exports = function(grunt) {
  return {
    pkg: grunt.file.readJSON('package.json'),
    compass: require('./compass')(grunt),
    jshint: require('./jshint')(grunt),
    jasmine_node: require('./jasmine_node')(grunt),
    jasmine:  require('./jasmine')(grunt),
    watch: require('./watch')(grunt),
    requirejs: require('./requirejs')(grunt)
  };
};


text:
#include <iostream>

#include "FileOutput.h"
#include "IOBase.h"
#include "NBestList.h"
#include "NBestListEntry.h"

namespace Bavieca {

// constructor
NBestList::NBestList() {
}

// destructor
NBestList::~NBestList() {

	for(VNBestListEntry::iterator it = m_vEntries.begin() ; it != m_vEntries.end() ; ++it) {
		delete *it;
	}
}

// store to disk
void NBestList::store(const char *strFile, bool bTextFormat) {

	// text format
	if (bTextFormat) {
		FileOutput file(strFile,false);
		file.open();
		for(VNBestListEntry::iterator it = m_vEntries.begin() ; it != m_vEntries.end() ; ++it) {
			(*it)->store(file.getStream(),bTextFormat);
		}
		file.close();
	}
	// binary format
	else {
		FileOutput file(strFile,true);
		file.open();
		IOBase::write(file.getStream(),(unsigned int)m_vEntries.size(),true);
		for(VNBestListEntry::iterator it = m_vEntries.begin() ; it != m_vEntries.end() ; ++it) {
			(*it)->store(file.getStream());
		}
		file.close();
	}
}

// load from disk
void NBestList::load(const char *strFile) {

}

// print
void NBestList::print() {

	cout << "- n-best list ------- ( " << m_vEntries.size() << " entries )--------------------------------" << endl;
	for(VNBestListEntry::iterator it = m_vEntries.begin() ; it != m_vEntries.end() ; ++it) {
		(*it)->print();
	}
	cout << "---------------------------------------------------------------------------------------------" << endl;
}

};	// end-of-namespace


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class DbBackendUserPreferences extends Migration
{
    public function up()
    {
        Schema::create('backend_user_preferences', function ($table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('namespace', 100);
            $table->string('group', 50);
            $table->string('item', 150);
            $table->text('value')->nullable();
            $table->index(['user_id', 'namespace', 'group', 'item'], 'user_item_index');
        });
    }

    public function down()
    {
        Schema::dropIfExists('backend_user_preferences');
    }
}


text:
package com.emelwerx.world.services;

import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.physics.bullet.collision.ClosestRayResultCallback;
import com.badlogic.gdx.physics.bullet.collision.btCollisionObject;
import com.emelwerx.world.databags.components.CreatureComponent;

import static java.lang.String.format;

public class DamageChecker {
    public static void check(ClosestRayResultCallback resultCallback) {
        if (resultCallback.hasHit()) {
            btCollisionObject obj = resultCallback.getCollisionObject();
            Entity entity = (Entity)obj.userData;
            CreatureComponent creatureComponent = entity.getComponent(CreatureComponent.class);
            if (creatureComponent != null) {
                CreatureDamager.shoot(creatureComponent);
            } else {
                shootNonCreature(entity);
            }
        } else {
            Gdx.app.log("Shooter", "miss");
        }
    }

    private static void shootNonCreature(Entity entity) {
        Gdx.app.log("Shooter", format("hit not a creature %s", entity.toString()));
    }
}


text:
CSharpPartOne
=============

Telerik Academy C# part one


text:
import os
import platform
import shutil
from collections import OrderedDict
from os.path import join

from conans.client.cache.editable import EditablePackages
from conans.client.cache.remote_registry import RemoteRegistry
from conans.client.conf import ConanClientConfigParser, default_client_conf, default_settings_yml
from conans.client.conf.detect import detect_defaults_settings
from conans.client.output import Color
from conans.client.profile_loader import read_profile
from conans.errors import ConanException
from conans.model.profile import Profile
from conans.model.ref import ConanFileReference
from conans.model.settings import Settings
from conans.paths import PUT_HEADERS
from conans.paths.package_layouts.package_cache_layout import PackageCacheLayout
from conans.paths.package_layouts.package_editable_layout import PackageEditableLayout
from conans.unicode import get_cwd
from conans.util.files import list_folder_subdirs, load, normalize, save
from conans.util.locks import Lock

CONAN_CONF = 'conan.conf'
CONAN_SETTINGS = "settings.yml"
LOCALDB = ".conan.db"
REMOTES = "remotes.json"
PROFILES_FOLDER = "profiles"
HOOKS_FOLDER = "hooks"

def is_case_insensitive_os():
    system = platform.system()
    return system != "Linux" and system != "FreeBSD" and system != "SunOS"

if is_case_insensitive_os():
    def check_ref_case(ref, store_folder):
        if not os.path.exists(store_folder):
            return

        tmp = store_folder
        for part in ref.dir_repr().split("/"):
            items = os.listdir(tmp)
            try:
                idx = [item.lower() for item in items].index(part.lower())
                if part != items[idx]:
                    raise ConanException("Requested '%s' but found case incompatible '%s'\n"
                                         "Case insensitive filesystem can't manage this"
                                         % (str(ref), items[idx]))
                tmp = os.path.normpath(tmp + os.sep + part)
            except ValueError:
                return
else:
    def check_ref_case(ref, store_folder):  # @UnusedVariable
        pass

class ClientCache(object):
    """ Class to represent/store/compute all the paths involved in the execution
    of conans commands. Accesses to real disk and reads/write things. (OLD client ConanPaths)
    """

    def __init__(self, base_folder, output):
        self.cache_folder = base_folder
        self._output = output

        # Caching
        self._no_lock = None
        self._config = None
        self.editable_packages = EditablePackages(self.cache_folder)
        # paths
        self._store_folder = self.config.storage_path or self.cache_folder

    def all_refs(self):
        subdirs = list_folder_subdirs(basedir=self._store_folder, level=4)
        return [ConanFileReference(*folder.split("/")) for folder in subdirs]

    @property
    def store(self):
        return self._store_folder

    def package(self, pref, short_paths=False):
        # TODO: This is deprecated, only used in testing
        return self.package_layout(pref.ref, short_paths).package(pref)

    def installed_as_editable(self, ref):
        return isinstance(self.package_layout(ref), PackageEditableLayout)

    @property
    def config_install_file(self):
        return os.path.join(self.cache_folder, "config_install.json")

    def package_layout(self, ref, short_paths=None, *args, **kwargs):
        assert isinstance(ref, ConanFileReference), "It is a {}".format(type(ref))
        edited_ref = self.editable_packages.get(ref.copy_clear_rev())
        if edited_ref:
            base_path = edited_ref["path"]
            layout_file = edited_ref["layout"]
            return PackageEditableLayout(base_path, layout_file, ref)
        else:
            check_ref_case(ref, self.store)
            base_folder = os.path.normpath(os.path.join(self.store, ref.dir_repr()))
            return PackageCacheLayout(base_folder=base_folder, ref=ref,
                                      short_paths=short_paths, no_lock=self._no_locks())

    @property
    def registry_path(self):
        return join(self.cache_folder, REMOTES)

    @property
    def registry(self):
        return RemoteRegistry(self, self._output)

    def _no_locks(self):
        if self._no_lock is None:
            self._no_lock = self.config.cache_no_locks
        return self._no_lock

    @property
    def put_headers_path(self):
        return join(self.cache_folder, PUT_HEADERS)

    def read_put_headers(self):
        ret = {}
        if not os.path.exists(self.put_headers_path):
            save(self.put_headers_path, "")
            return ret
        try:
            contents = load(self.put_headers_path)
            for line in contents.splitlines():
                if line and not line.strip().startswith("#"):
                    tmp = line.split("=", 1)
                    if len(tmp) != 2:
                        raise Exception()
                    name = tmp[0].strip()
                    value = tmp[1].strip()
                    ret[str(name)] = str(value)
            return ret
        except Exception:
            raise ConanException("Invalid %s file!" % self.put_headers_path)

    @property
    def config(self):
        if not self._config:
            if not os.path.exists(self.conan_conf_path):
                save(self.conan_conf_path, normalize(default_client_conf))

            self._config = ConanClientConfigParser(self.conan_conf_path)
        return self._config

    @property
    def localdb(self):
        return join(self.cache_folder, LOCALDB)

    @property
    def conan_conf_path(self):
        return join(self.cache_folder, CONAN_CONF)

    @property
    def profiles_path(self):
        return join(self.cache_folder, PROFILES_FOLDER)

    @property
    def settings_path(self):
        return join(self.cache_folder, CONAN_SETTINGS)

    @property
    def default_profile_path(self):
        if os.path.isabs(self.config.default_profile):
            return self.config.default_profile
        else:
            return join(self.cache_folder, PROFILES_FOLDER,
                        self.config.default_profile)

    @property
    def hooks_path(self):
        """
        :return: Hooks folder in client cache
        """
        return join(self.cache_folder, HOOKS_FOLDER)

    @property
    def default_profile(self):
        if not os.path.exists(self.default_profile_path):
            self._output.writeln("Auto detecting your dev setup to initialize the "
                                 "default profile (%s)" % self.default_profile_path,
                                 Color.BRIGHT_YELLOW)

            default_settings = detect_defaults_settings(self._output,
                                                        profile_path=self.default_profile_path)
            self._output.writeln("Default settings", Color.BRIGHT_YELLOW)
            self._output.writeln("\n".join(["\t%s=%s" % (k, v) for (k, v) in default_settings]),
                                 Color.BRIGHT_YELLOW)
            self._output.writeln("*** You can change them in %s ***" % self.default_profile_path,
                                 Color.BRIGHT_MAGENTA)
            self._output.writeln("*** Or override with -s compiler='other' -s ...s***\n\n",
                                 Color.BRIGHT_MAGENTA)

            default_profile = Profile()
            tmp = OrderedDict(default_settings)
            default_profile.update_settings(tmp)
            save(self.default_profile_path, default_profile.dumps())
        else:
            default_profile, _ = read_profile(self.default_profile_path, get_cwd(),
                                              self.profiles_path)

        # Mix profile settings with environment
        mixed_settings = _mix_settings_with_env(default_profile.settings)
        default_profile.settings = mixed_settings
        return default_profile

    @property
    def settings(self):
        """Returns {setting: [value, ...]} defining all the possible
           settings without values"""

        if not os.path.exists(self.settings_path):
            save(self.settings_path, normalize(default_settings_yml))
            settings = Settings.loads(default_settings_yml)
        else:
            content = load(self.settings_path)
            settings = Settings.loads(content)

        return settings

    @property
    def hooks(self):
        """Returns a list of hooks inside the hooks folder"""
        hooks = []
        for hook_name in os.listdir(self.hooks_path):
            if os.path.isfile(hook_name) and hook_name.endswith(".py"):
                hooks.append(hook_name[:-3])
        return hooks

    def delete_empty_dirs(self, deleted_refs):
        for ref in deleted_refs:
            ref_path = self.package_layout(ref).base_folder()
            for _ in range(4):
                if os.path.exists(ref_path):
                    try:  # Take advantage that os.rmdir does not delete non-empty dirs
                        os.rmdir(ref_path)
                    except OSError:
                        break  # not empty
                ref_path = os.path.dirname(ref_path)

    def remove_locks(self):
        folders = list_folder_subdirs(self._store_folder, 4)
        for folder in folders:
            conan_folder = os.path.join(self._store_folder, folder)
            Lock.clean(conan_folder)
            shutil.rmtree(os.path.join(conan_folder, "locks"), ignore_errors=True)

    def invalidate(self):
        self._config = None
        self._no_lock = None

def _mix_settings_with_env(settings):
    """Reads CONAN_ENV_XXXX variables from environment
    and if it's defined uses these value instead of the default
    from conf file. If you specify a compiler with ENV variable you
    need to specify all the subsettings, the file defaulted will be
    ignored"""

    def get_env_value(name):
        env_name = "CONAN_ENV_%s" % name.upper().replace(".", "_")
        return os.getenv(env_name, None)

    def get_setting_name(env_name):
        return env_name[10:].lower().replace("_", ".")

    ret = OrderedDict()
    for name, value in settings.items():
        if get_env_value(name):
            ret[name] = get_env_value(name)
        else:
            # being a subsetting, if parent exist in env discard this, because
            # env doesn't define this setting. EX: env=>Visual Studio but
            # env doesn't define compiler.libcxx
            if "." not in name or not get_env_value(name.split(".")[0]):
                ret[name] = value
    # Now read if there are more env variables
    for env, value in sorted(os.environ.items()):
        if env.startswith("CONAN_ENV_") and get_setting_name(env) not in ret:
            ret[get_setting_name(env)] = value
    return ret


text:
package birpc

import (
	"fmt"
)

// Message is the on-wire description of a method call or result.
//
// Examples:
//
//   {"id":"1","fn":"Arith.Add","args":{"A":1,"B":1}}
//   {"id":"1","result":{"C":2}}
//
// or
//
//   {"id":"1","error":{"msg":"Math is hard, let's go shopping"}}
type Message struct {
	// 0 or omitted for untagged request (untagged response is illegal).
	ID uint64 `json:"id,string,omitempty"`

	// Name of the function to call. If set, this is a request; if
	// unset, this is a response.
	Func string `json:"fn,omitempty"`

	// Arguments for the RPC call. Only valid for a request.
	Args interface{} `json:"args,omitempty"`

	// Result of the function call. A response will always have
	// either Result or Error set. Only valid for a response.
	Result interface{} `json:"result,omitempty"`

	// Information on how the call failed. Only valid for a
	// response. Must be present if Result is omitted.
	Error *Error `json:"error,omitempty"`
}

// Error is the on-wire description of an error that occurred while
// serving the method call.
type Error struct {
	Msg string `json:"msg,omitempty"`

	// more fields may be added later

	// TODO ponder about error detail, way for clients to tell
	// transient/permanent, bad request vs out of memory
}

func (e Error) Error() string {
	return e.Msg
}

func (e Error) GoString() string {
	return fmt.Sprintf("%T{Msg: %q}", e, e.Msg)
}


text:
DROP DATABASE IF EXISTS GONQBOX;
DROP DATABASE IF EXISTS gonqbox;

CREATE DATABASE IF NOT EXISTS gonqbox;

USE gonqbox;

CREATE TABLE IF NOT EXISTS `gonqbox`.`tbluser` (
	`user_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
	`username` VARCHAR(20) NOT NULL UNIQUE,
	`account_creation_date` DATE NOT NULL,
	`last_logged_in_date` DATE NOT NULL,
	`user_mail` VARCHAR(40) NOT NULL UNIQUE,
	`password` VARCHAR(255) NULL,
	`salt` NVARCHAR(128) NOT NULL,
	`hash` NVARCHAR(128) NOT NULL,
	PRIMARY KEY (`user_id`)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS `gonqbox`.`tblpermission` (
	`permission_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
	`permission_name` VARCHAR(24) NOT NULL UNIQUE,
	PRIMARY KEY (`permission_id`)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS `gonqbox`.`tblfolder` (
	`folder_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
	`owner_id` INT UNSIGNED NOT NULL,
	`folder_size` INT UNSIGNED NOT NULL,
	`file_count` INT UNSIGNED NOT NULL,
	PRIMARY KEY (`folder_id`),
    FOREIGN KEY (`owner_id`) REFERENCES tbluser(`user_id`) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS `gonqbox`.`tblfile` (
	`file_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(255) NOT NULL,
	`file_size` INT UNSIGNED NOT NULL,
	`sequence` VARCHAR(24) NOT NULL UNIQUE,
	`uploader_id` INT UNSIGNED NOT NULL,
	`folder_id` INT UNSIGNED NOT NULL,
	`checksum` VARCHAR(64) NOT NULL,
	`checksum_date` DATE NOT NULL,
	`checksum_date_last_verified` DATE NOT NULL,
	PRIMARY KEY (`file_id`),
	FOREIGN KEY (`uploader_id`) REFERENCES tbluser(`user_id`) ON DELETE CASCADE,
	FOREIGN KEY (`folder_id`) REFERENCES tblfolder(`folder_id`) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS `gonqbox`.`tblcollaborator` (
	`collaborator_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
	`user_id` INT UNSIGNED NOT NULL,
	`file_id` INT UNSIGNED NOT NULL,
	`folder_id` INT UNSIGNED NOT NULL,
	PRIMARY KEY (`collaborator_id`),
	FOREIGN KEY (`user_id`) REFERENCES tbluser(`user_id`) ON DELETE CASCADE,
	FOREIGN KEY (`file_id`) REFERENCES tblfile(`file_id`) ON DELETE CASCADE,
	FOREIGN KEY (`folder_id`) REFERENCES tblfolder(`folder_id`) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS `gonqbox`.`tblComment` (
  	`comment_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  	`user_id` INT UNSIGNED NOT NULL,
  	`file_id` INT UNSIGNED NOT NULL,
  	`body` text collate utf8_unicode_ci NOT NULL,
  	`dt` timestamp NOT NULL default CURRENT_TIMESTAMP,
  	PRIMARY KEY (`comment_id`),
	FOREIGN KEY (`user_id`) REFERENCES tbluser(`user_id`) ON DELETE CASCADE,
	FOREIGN KEY (`file_id`) REFERENCES tblfile(`file_id`) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS `gonqbox`.`tblfilepublic` (
	`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
	`file_id` INT UNSIGNED NOT NULL,
    `public` BOOL NOT NULL DEFAULT FALSE,
	PRIMARY KEY (`id`),
	FOREIGN KEY (`file_id`) REFERENCES tblfile(`file_id`) ON DELETE CASCADE
) ENGINE=InnoDB;

/*tblUser Test Data*/

INSERT INTO `gonqbox`.`tbluser`(`username`,`account_creation_date`,`last_logged_in_date`,`user_mail`,`password`,`salt`,`hash`)
VALUES('~Billy',CURDATE(),CURDATE(),'~Billy@mail.com','~test-password','~test-salt','~test-hash');
INSERT INTO `gonqbox`.`tbluser`(`username`,`account_creation_date`,`last_logged_in_date`,`user_mail`,`password`,`salt`,`hash`)
VALUES('~Sally',CURDATE(),CURDATE(),'~Sally@mail.com','~test-password','~test-salt','~test-hash');
INSERT INTO `gonqbox`.`tbluser`(`username`,`account_creation_date`,`last_logged_in_date`,`user_mail`,`password`,`salt`,`hash`)
VALUES('~Greg',CURDATE(),CURDATE(),'~Greg@mail.com','~test-password','~test-salt','~test-hash');
INSERT INTO `gonqbox`.`tbluser`(`username`,`account_creation_date`,`last_logged_in_date`,`user_mail`,`password`,`salt`,`hash`)
VALUES('~Laquisha',CURDATE(),CURDATE(),'~Laquisha@mail.com','~test-password','~test-salt','~test-hash');

/*tblPermission Test Data*/

INSERT INTO `gonqbox`.`tblpermission`(`permission_name`)
VALUES('CONTENT_OWNER');
INSERT INTO `gonqbox`.`tblpermission`(`permission_name`)
VALUES('CONTENT_COLLABORATOR');
INSERT INTO `gonqbox`.`tblpermission`(`permission_name`)
VALUES('CONTENT_VIEWER');
INSERT INTO `gonqbox`.`tblpermission`(`permission_name`)
VALUES('ADMIN');
INSERT INTO `gonqbox`.`tblpermission`(`permission_name`)
VALUES('GUEST');

/*tblFolder Test Data*/

INSERT INTO `gonqbox`.`tblfolder`(`owner_id`,`folder_size`,`file_count`)
VALUES(1,800,2);
INSERT INTO `gonqbox`.`tblfolder`(`owner_id`,`folder_size`,`file_count`)
VALUES(2,0,0);
INSERT INTO `gonqbox`.`tblfolder`(`owner_id`,`folder_size`,`file_count`)
VALUES(3,200,1);
INSERT INTO `gonqbox`.`tblfolder`(`owner_id`,`folder_size`,`file_count`)
VALUES(4,0,0);

/*tblFile Test Data*/

INSERT INTO `gonqbox`.`tblfile`(`name`,`file_size`,`sequence`,`uploader_id`,`folder_id`,`checksum`,`checksum_date`,`checksum_date_last_verified`)
VALUES('cat.jpg','200','sequence1',3,3,'checksum',CURDATE(),CURDATE());
INSERT INTO `gonqbox`.`tblfile`(`name`,`file_size`,`sequence`,`uploader_id`,`folder_id`,`checksum`,`checksum_date`,`checksum_date_last_verified`)
VALUES('two_cats.png','600','sequence2',1,1,'checksum',CURDATE(),CURDATE());
INSERT INTO `gonqbox`.`tblfile`(`name`,`file_size`,`sequence`,`uploader_id`,`folder_id`,`checksum`,`checksum_date`,`checksum_date_last_verified`)
VALUES('dog.webm','200','sequence3',2,1,'checksum',CURDATE(),CURDATE());

/*tblCollaborator Test Data*/

INSERT INTO `gonqbox`.`tblcollaborator`(`user_id`,`file_id`,`folder_id`)
VALUES(2,3,1);

/*tblComent Test data*/

INSERT INTO `gonqbox`.`tblComment`(`user_id`,`file_id`,`body`, `dt`)
VALUES(2,2,'First Post', CURDATE());
INSERT INTO `gonqbox`.`tblComment`(`user_id`,`file_id`,`body`, `dt`)
VALUES(3,2,'Youre so lame', CURDATE());
INSERT INTO `gonqbox`.`tblComment`(`user_id`,`file_id`,`body`, `dt`)
VALUES(2,2,'Second Post', CURDATE());
INSERT INTO `gonqbox`.`tblComment`(`user_id`,`file_id`,`body`, `dt`)
VALUES(3,2,'Go away', CURDATE());


text:
package ca.uhn.fhir.rest.server;

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.Include;
import ca.uhn.fhir.rest.annotation.IncludeParam;
import ca.uhn.fhir.rest.annotation.Search;
import ca.uhn.fhir.rest.api.EncodingEnum;
import ca.uhn.fhir.test.utilities.JettyUtil;
import ca.uhn.fhir.util.TestUtil;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.hl7.fhir.dstu3.model.Organization;
import org.hl7.fhir.dstu3.model.Patient;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class SearchWithIncludesDstu3Test {

	private static CloseableHttpClient ourClient;
	private static FhirContext ourCtx = FhirContext.forDstu3();
	private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchWithIncludesDstu3Test.class);
	private static int ourPort;
	private static Server ourServer;

	@Test
	public void testSearchIncludesReferences() throws Exception {
		HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_pretty=true&_include=Patient:organization&_include=Organization:" + Organization.SP_PARTOF);
		HttpResponse status = ourClient.execute(httpGet);
		String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8);
		IOUtils.closeQuietly(status.getEntity().getContent());
		ourLog.info(responseContent);
		assertEquals(200, status.getStatusLine().getStatusCode());

		// Response should include both the patient, and the organization that was referred to
		// by a linked resource

		assertThat(responseContent, containsString("<name value=\"child\"/>"));
		assertThat(responseContent, containsString("<name value=\"parent\"/>"));
		assertThat(responseContent, containsString("<name value=\"grandparent\"/>"));
		assertThat(responseContent, containsString("<mode value=\"include\"/>"));

	}

	 @AfterAll
	  public static void afterClassClearContext() throws Exception {
	    JettyUtil.closeServer(ourServer);
	    TestUtil.clearAllStaticFieldsForUnitTest();
	  }

	@BeforeAll
	public static void beforeClass() throws Exception {
		ourServer = new Server(0);

		DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider();

		ServletHandler proxyHandler = new ServletHandler();
		RestfulServer servlet = new RestfulServer(ourCtx);
		servlet.setPagingProvider(new FifoMemoryPagingProvider(10));
		servlet.setResourceProviders(patientProvider);
		servlet.setDefaultResponseEncoding(EncodingEnum.XML);

		ServletHolder servletHolder = new ServletHolder(servlet);
		proxyHandler.addServletWithMapping(servletHolder, "/*");
		ourServer.setHandler(proxyHandler);
		JettyUtil.startServer(ourServer);
        ourPort = JettyUtil.getPortForStartedServer(ourServer);

		PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
		HttpClientBuilder builder = HttpClientBuilder.create();
		builder.setConnectionManager(connectionManager);
		ourClient = builder.build();

	}

	public static class DummyPatientResourceProvider implements IResourceProvider {

		@Override
		public Class<? extends IBaseResource> getResourceType() {
			return Patient.class;
		}

		//@formatter:off
		@Search()
		public List<Patient> search(@IncludeParam() Set<Include> theIncludes) {
			ourLog.info("Includes: {}", theIncludes);

			// Grandparent has ID, other orgs don't
			Organization gp = new Organization();
			gp.setId("Organization/GP");
			gp.setName("grandparent");

			Organization parent = new Organization();
			parent.setName("parent");
			parent.getPartOf().setResource(gp);

			Organization child = new Organization();
			child.setName("child");
			child.getPartOf().setResource(parent);

			Patient patient = new Patient();
			patient.setId("Patient/FOO");
			patient.getManagingOrganization().setResource(child);

			ArrayList<Patient> retVal = new ArrayList<Patient>();
			retVal.add(patient);
			return retVal;
		}
		//@formatter:on

	}

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. Mag. (Tokyo) 15:25. 1901 "<I>albo-marginata</I>"

#### Original name
null

### Remarks
null


text:
require 'spec_helper'
module Gisele::Analysis
  describe Ghmsc, "to_graph" do

    subject{ ghmsc.to_graph }

    let(:ghmsc){
      s = Compiling::Ast2Session.call(meeting_scheduling_sexpr)
      Ghmsc.new(s) do |g|
        g.ast = meeting_scheduling_sexpr
      end
    }

    it{ should be_a(Yargi::Digraph) }

  end
end


text:
Cryptography Details
=====================

Here is a high-level description of how this library works. Any discrepancy
between this documentation and the actual implementation will be considered
a security bug.

Let's start with the following definitions:

- HKDF-SHA256(*k*, *n*, *info*, *s*) is the key derivation function specified in
  RFC 5869 (using the SHA256 hash function). The parameters are:
    - *k*: The initial keying material.
    - *n*: The number of output bytes.
    - *info*: The info string.
    - *s*: The salt.
- AES-256-CTR(*m*, *k*, *iv*) is AES-256 encryption in CTR mode. The parameters
  are:
    - *m*: An arbitrary-length (possibly zero-length) message.
    - *k*: A 32-byte key.
    - *iv*: A 16-byte initialization vector (nonce).
- PBKDF2-SHA256(*p*, *s*, *i*, *n*) is the password-based key derivation
  function defined in RFC 2898 (using the SHA256 hash function). The parameters
  are:
    - *p*: The password string.
    - *s*: The salt string.
    - *i*: The iteration count.
    - *n*: The output length in bytes.
- VERSION is the string `"\xDE\xF5\x02\x00"`.
- AUTHINFO is the string `"DefusePHP|V2|KeyForAuthentication"`.
- ENCRINFO is the string `"DefusePHP|V2|KeyForEncryption"`.

To encrypt a message *m* using a 32-byte key *k*, the following steps are taken:

1. Generate a random 32-byte string *salt*.
2. Derive the 32-byte authentication key *akey* = HKDF-SHA256(*k*, 32, AUTHINFO, *salt*).
3. Derive the 32-byte encryption key *ekey* = HKDF-SHA256(*k*, 32, ENCRINFO, *salt*).
4. Generate a random 16-byte initialization vector *iv*.
5. Compute *c* = AES-256-CTR(*m*, *ekey*, *iv*).
6. Combine *ctxt* = VERSION || *salt* || *iv* || *c*.
7. Compute *h* = HMAC-SHA256(*ctxt*, *akey*).
8. Output *ctxt* || *h*.

Decryption is roughly the reverse process (see the code for details, since the
security of the decryption routine is highly implementation-dependent).

For encryption using a password *p*, steps 1-3 above are replaced by:

1. Generate a random 32-byte string *salt*.
2. Compute *k* = PBKDF2-SHA256(SHA256(*p*), *salt*, 100000, 32).
3. Derive the 32-byte authentication key *akey* = HKDF-SHA256(*k*, 32, AUTHINFO, *salt*)
4. Derive the 32-byte encryption key *ekey* = HKDF-SHA256(*k*, 32, ENCRINFO, *salt*)

The remainder of the process is the same. Notice the reuse of the same *salt*
for PBKDF2-SHA256 and HKDF-SHA256. The prehashing of the password in step 2 is
done to prevent a [DoS attack using long
passwords](https://github.com/defuse/php-encryption/issues/230).

For `KeyProtectedByPassword`, the serialized key is encrypted according to the
password encryption defined above. However, the actual password used for
encryption is the SHA256 hash of the password the user provided. This is done in
order to provide domain separation between the message encryption in the user's
application and the internal key encryption done by this library. It fixes
a [key replacement chosen-protocol
attack](https://github.com/defuse/php-encryption/issues/240).


text:
package protocol

import (
	"context"
)

// Opener is the common interface for things that need to be opened.
type Opener interface {
	// OpenInbound is a blocking call and ctx is used to stop the Inbound message Receiver/Responder.
	// Closing the context won't close the Receiver/Responder, aka it won't invoke Close(ctx).
	OpenInbound(ctx context.Context) error
}

// Closer is the common interface for things that can be closed.
// After invoking Close(ctx), you cannot reuse the object you closed.
type Closer interface {
	Close(ctx context.Context) error
}


text:
package com.bcnx.data.dao;

import java.sql.SQLException;

import com.bcnx.data.entity.BalMsg;

public interface BalMsgDao {
	public void update(BalMsg balMsg) throws SQLException;
	public String getDe02() throws SQLException;
	public String getDe03() throws SQLException;
	public String getDe04() throws SQLException;
	public String getDe18() throws SQLException;
	public String getDe19() throws SQLException;
	public String getDe22() throws SQLException;
	public String getDe25() throws SQLException;
	public String getDe28() throws SQLException;
	public String getDe32() throws SQLException;
	public String getDe41() throws SQLException;
	public String getDe42() throws SQLException;
	public String getDe43() throws SQLException;
	public String getDe49() throws SQLException;
	public String getDe52() throws SQLException;
	public int check() throws SQLException;
	public void save(BalMsg balMsg) throws SQLException;
}


text:
* Relax upper bound for aeson

## v0.9.1.2 - 2015-05-15

* Relax upper bound for attoparsec

## v0.9.1.1 - 2015-03-07

* Allow retry >= 0.6 && < 0.7

## v0.9.1 - 2015-03-07

* Add `writeSeriesData`
* Relax upper version bound for exceptions
* Drop support for old retry package
    * retry < 0.6 had an unexpected behavior wrt exception masking state (https://github.com/Soostone/retry/pull/12)

## v0.9.0.1 - 2015-01-06

* Support for GHC 7.10.1

## v0.9.0 - 2014-11-27

* The `Value` parsers (accidentally) could throw exceptions. It's fixed now.
* Add `fromSeriesData_` which discards parsing errors and returns only successful data
* Remove `listInterfaces`

## v0.8.0 - 2014-11-07

* Retry on connection failure and response timeout in addition to IOException
    * Note that this may break existing code silently

## v0.7.1.1 - 2014-09-19

* Relax upper bound for http-client
* Set upper bounds for some packages

## v0.7.1 - 2014-09-16

* Add more lenses

## v0.7.0 - 2014-09-12

* Support for influxdb v0.8 (#15)
    * Add shard spaces API
    * Add `configureDatabase`
* Add Typeable and Generic instances where missing
* Remove unused `ScheduledDelete` type

## v0.6.0 - 2014-08-19

* Support for retry-0.5 (#16)
    * `newServerPoolWithRetrySettings` has been renamed to `newServerPoolWithRetryPolicy`
    * `serverRetrySettings` field in `ServerPool` has been renamed to `serverRetryPolicy`
* Support for network-uri (#17)

## v0.5.1 - 2014-07-18

* Export `InfluxException` from `Database.InfluxDB`

## v0.5.0 - 2014-07-18

* Add `InfluxException` type and use it when decoding JSON or SeriesData (#12)
* New API
    * `ping`
    * `listInterfaces`
    * `isInSync`
* BUGFIX: Fix `when expecting a Float, encountered Int instead` error (#14)

## v0.4.2 - 2014-06-06

* Export `newServerPoolWithRetrySettings` from `Database.InfluxDB`

## v0.4.1 - 2014-06-05

* Make retry settings configurable (#5)

## v0.4.0 - 2014-06-05

* Remove `databaseReplicationFactor` field from `Database` type

## v0.3.0.1 - 2014-06-04

* Allow exceptions-0.6 (@JohnLato)

## v0.3.0 - 2014-06-03

* Support for InfluxDB v0.7
    * Renamed `username` field for `/cluster_admins` to `user`
    * No support for the old field name

## v0.2.2 - 2014-05-08

* Support for retry-0.4
* Add deleteSeries
* Add authenticateClusterAdmin and authenticateDatabaseUser

## v0.2.1.1 - 2014-04-22

* Bug fix: Treat as integer if base10Exponent is positive

## v0.2.1 - 2014-04-22

* Add `stripPrefixSnake`

## v0.2.0.1 - 2014-04-17

* Drop unnecessary dependency on `scientific` when using old `aeson`.

## v0.2.0 - 2014-04-16

* Add more `FromValue` instances
* Add `(.:?)` and `(.!=)`
* Add `deriveSeriesData` and some variants
* Add left folds for `Stream` type

## v0.1.0.1 - 2014-04-07

* Support for older aeson
* Textual paramters in some functions for convenience
* A lot of bug fixes

## v0.0.0 - 2014-04-03

* Initial release


text:
<?php
/**
 * @author blutze-media
 * @since 2020-11-05
 */

namespace Enhavo\Bundle\UserBundle\Tests\EventListener;

use Enhavo\Bundle\UserBundle\EventListener\SaveUserSubscriber;
use Enhavo\Bundle\UserBundle\Tests\Mocks\UserMock;
use Enhavo\Bundle\UserBundle\User\UserManager;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\GenericEvent;

class SaveUserSubscriberTest extends TestCase
{
    private function createDependencies(): SaveUserSubscriberTestDependencies
    {
        $dependencies = new SaveUserSubscriberTestDependencies();
        $dependencies->userManager = $this->getMockBuilder(UserManager::class)->disableOriginalConstructor()->getMock();

        return $dependencies;
    }

    private function createInstance(SaveUserSubscriberTestDependencies $dependencies): SaveUserSubscriber
    {
        return new SaveUserSubscriber(
            $dependencies->userManager
        );
    }

    public function testGetSubscribedEvents()
    {
        $events = SaveUserSubscriber::getSubscribedEvents();

        $this->assertEquals([
            'enhavo_user.user.pre_update' => ['onSave', 1],
            'enhavo_user.user.pre_create' => ['onSave', 1],
        ], $events);
    }

    public function testOnSave()
    {
        $dependencies = $this->createDependencies();

        $user = new UserMock();
        $user->setEmail('user@enhavo.com');
        $event = new GenericEvent($user);

        $subscriber = $this->createInstance($dependencies);
        $dependencies->userManager->expects($this->once())->method('updatePassword');
        $dependencies->userManager->expects($this->once())->method('updateUsername');

        $subscriber->onSave($event);
    }
}

class SaveUserSubscriberTestDependencies
{
    /** @var UserManager|MockObject */
    public $userManager;
}