text:
package org.elasticsearch.index;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.util.Strings;
import org.apache.lucene.index.MergePolicy;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.IndexScopedSettings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.ingest.IngestService;
import org.elasticsearch.node.Node;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;

import static org.elasticsearch.index.mapper.MapperService.INDEX_MAPPING_DEPTH_LIMIT_SETTING;
import static org.elasticsearch.index.mapper.MapperService.INDEX_MAPPING_FIELD_NAME_LENGTH_LIMIT_SETTING;
import static org.elasticsearch.index.mapper.MapperService.INDEX_MAPPING_NESTED_DOCS_LIMIT_SETTING;
import static org.elasticsearch.index.mapper.MapperService.INDEX_MAPPING_NESTED_FIELDS_LIMIT_SETTING;
import static org.elasticsearch.index.mapper.MapperService.INDEX_MAPPING_TOTAL_FIELDS_LIMIT_SETTING;

/**
 * This class encapsulates all index level settings and handles settings updates.
 * It's created per index and available to all index level classes and allows them to retrieve
 * the latest updated settings instance. Classes that need to listen to settings updates can register
 * a settings consumer at index creation via {@link IndexModule#addSettingsUpdateConsumer(Setting, Consumer)} that will
 * be called for each settings update.
 */
public final class IndexSettings {
    public static final Setting<List<String>> DEFAULT_FIELD_SETTING =
        Setting.listSetting("index.query.default_field", Collections.singletonList("*"),
            Function.identity(), Property.IndexScope, Property.Dynamic);
    public static final Setting<Boolean> QUERY_STRING_LENIENT_SETTING =
        Setting.boolSetting("index.query_string.lenient", false, Property.IndexScope);
    public static final Setting<Boolean> QUERY_STRING_ANALYZE_WILDCARD =
        Setting.boolSetting("indices.query.query_string.analyze_wildcard", false, Property.NodeScope);
    public static final Setting<Boolean> QUERY_STRING_ALLOW_LEADING_WILDCARD =
        Setting.boolSetting("indices.query.query_string.allowLeadingWildcard", true, Property.NodeScope);
    public static final Setting<Boolean> ALLOW_UNMAPPED =
        Setting.boolSetting("index.query.parse.allow_unmapped_fields", true, Property.IndexScope);
    public static final Setting<TimeValue> INDEX_TRANSLOG_SYNC_INTERVAL_SETTING =
        Setting.timeSetting("index.translog.sync_interval", TimeValue.timeValueSeconds(5), TimeValue.timeValueMillis(100),
            Property.Dynamic, Property.IndexScope);
    public static final Setting<TimeValue> INDEX_SEARCH_IDLE_AFTER =
        Setting.timeSetting("index.search.idle.after", TimeValue.timeValueSeconds(30),
            TimeValue.timeValueMinutes(0), Property.IndexScope, Property.Dynamic);
    public static final Setting<Translog.Durability> INDEX_TRANSLOG_DURABILITY_SETTING =
        Setting.enumSetting(Translog.Durability.class, "index.translog.durability", Translog.Durability.REQUEST,
            Property.Dynamic, Property.IndexScope);
    public static final Setting<Boolean> INDEX_WARMER_ENABLED_SETTING =
        Setting.boolSetting("index.warmer.enabled", true, Property.Dynamic, Property.IndexScope);
    public static final Setting<String> INDEX_CHECK_ON_STARTUP =
        new Setting<>("index.shard.check_on_startup", "false", (s) -> {
            switch (s) {
                case "false":
                case "true":
                case "checksum":
                    return s;
                default:
                    throw new IllegalArgumentException("unknown value for [index.shard.check_on_startup] must be one of " +
                        "[true, false, checksum] but was: " + s);
            }
        }, Property.IndexScope);

    /**
     * Index setting describing the maximum value of from + size on a query.
     * The Default maximum value of from + size on a query is 10,000. This was chosen as
     * a conservative default as it is sure to not cause trouble. Users can
     * certainly profile their cluster and decide to set it to 100,000
     * safely. 1,000,000 is probably way to high for any cluster to set
     * safely.
     */
    public static final Setting<Integer> MAX_RESULT_WINDOW_SETTING =
        Setting.intSetting("index.max_result_window", 10000, 1, Property.Dynamic, Property.IndexScope);
    /**
     * Index setting describing the maximum value of from + size on an individual inner hit definition or
     * top hits aggregation. The default maximum of 100 is defensive for the reason that the number of inner hit responses
     * and number of top hits buckets returned is unbounded. Profile your cluster when increasing this setting.
     */
    public static final Setting<Integer> MAX_INNER_RESULT_WINDOW_SETTING =
        Setting.intSetting("index.max_inner_result_window", 100, 1, Property.Dynamic, Property.IndexScope);

    /**
     * Index setting describing the maximum value of allowed `script_fields`that can be retrieved
     * per search request. The default maximum of 32 is defensive for the reason that retrieving
     * script fields is a costly operation.
     */
    public static final Setting<Integer> MAX_SCRIPT_FIELDS_SETTING =
        Setting.intSetting("index.max_script_fields", 32, 0, Property.Dynamic, Property.IndexScope);

    /**
     * A setting describing the maximum number of tokens that can be
     * produced using _analyze API. The default maximum of 10000 is defensive
     * to prevent generating too many token objects.
     */
    public static final Setting<Integer> MAX_TOKEN_COUNT_SETTING =
        Setting.intSetting("index.analyze.max_token_count", 10000, 1, Property.Dynamic, Property.IndexScope);

    /**
     * A setting describing the maximum number of characters that will be analyzed for a highlight request.
     * This setting is only applicable when highlighting is requested on a text that was indexed without
     * offsets or term vectors.
     * The default maximum of 1M characters is defensive as for highlighting larger texts,
     * indexing with offsets or term vectors is recommended.
     */
    public static final Setting<Integer> MAX_ANALYZED_OFFSET_SETTING =
        Setting.intSetting("index.highlight.max_analyzed_offset", 1000000, 1,
            Property.Dynamic, Property.IndexScope);

    /**
     * Index setting describing the maximum number of terms that can be used in Terms Query.
     * The default maximum of 65536 terms is defensive, as extra processing and memory is involved
     * for each additional term, and a large number of terms degrade the cluster performance.
     */
    public static final Setting<Integer> MAX_TERMS_COUNT_SETTING =
        Setting.intSetting("index.max_terms_count", 65536, 1, Property.Dynamic, Property.IndexScope);

    /**
     * Index setting describing for NGramTokenizer and NGramTokenFilter
     * the maximum difference between
     * max_gram (maximum length of characters in a gram) and
     * min_gram (minimum length of characters in a gram).
     * The default value is 1 as this is default difference in NGramTokenizer,
     * and is defensive as it prevents generating too many index terms.
     */
    public static final Setting<Integer> MAX_NGRAM_DIFF_SETTING =
        Setting.intSetting("index.max_ngram_diff", 1, 0, Property.Dynamic, Property.IndexScope);

    /**
     * Index setting describing for ShingleTokenFilter
     * the maximum difference between
     * max_shingle_size and min_shingle_size.
     * The default value is 3 is defensive as it prevents generating too many tokens.
     */
    public static final Setting<Integer> MAX_SHINGLE_DIFF_SETTING =
        Setting.intSetting("index.max_shingle_diff", 3, 0, Property.Dynamic, Property.IndexScope);

    /**
     * Index setting describing the maximum value of allowed `docvalue_fields`that can be retrieved
     * per search request. The default maximum of 100 is defensive for the reason that retrieving
     * doc values might incur a per-field per-document seek.
     */
    public static final Setting<Integer> MAX_DOCVALUE_FIELDS_SEARCH_SETTING =
        Setting.intSetting("index.max_docvalue_fields_search", 100, 0, Property.Dynamic, Property.IndexScope);
    /**
     * Index setting describing the maximum size of the rescore window. Defaults to {@link #MAX_RESULT_WINDOW_SETTING}
     * because they both do the same thing: control the size of the heap of hits.
     */
    public static final Setting<Integer> MAX_RESCORE_WINDOW_SETTING =
            Setting.intSetting("index.max_rescore_window", MAX_RESULT_WINDOW_SETTING, 1,
                Property.Dynamic, Property.IndexScope);
    public static final TimeValue DEFAULT_REFRESH_INTERVAL = new TimeValue(1, TimeUnit.SECONDS);
    public static final Setting<TimeValue> INDEX_REFRESH_INTERVAL_SETTING =
        Setting.timeSetting("index.refresh_interval", DEFAULT_REFRESH_INTERVAL, new TimeValue(-1, TimeUnit.MILLISECONDS),
            Property.Dynamic, Property.IndexScope);
    public static final Setting<ByteSizeValue> INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING =
        Setting.byteSizeSetting("index.translog.flush_threshold_size", new ByteSizeValue(512, ByteSizeUnit.MB),
            /*
             * An empty translog occupies 55 bytes on disk. If the flush threshold is below this, the flush thread
             * can get stuck in an infinite loop as the shouldPeriodicallyFlush can still be true after flushing.
             * However, small thresholds are useful for testing so we do not add a large lower bound here.
             */
            new ByteSizeValue(Translog.DEFAULT_HEADER_SIZE_IN_BYTES + 1, ByteSizeUnit.BYTES),
            new ByteSizeValue(Long.MAX_VALUE, ByteSizeUnit.BYTES),
            Property.Dynamic, Property.IndexScope);

    /**
     * The minimum size of a merge that triggers a flush in order to free resources
     */
    public static final Setting<ByteSizeValue> INDEX_FLUSH_AFTER_MERGE_THRESHOLD_SIZE_SETTING =
        Setting.byteSizeSetting("index.flush_after_merge", new ByteSizeValue(512, ByteSizeUnit.MB),
            new ByteSizeValue(0, ByteSizeUnit.BYTES), // always flush after merge
            new ByteSizeValue(Long.MAX_VALUE, ByteSizeUnit.BYTES), // never flush after merge
            Property.Dynamic, Property.IndexScope);
    /**
     * The maximum size of a translog generation. This is independent of the maximum size of
     * translog operations that have not been flushed.
     */
    public static final Setting<ByteSizeValue> INDEX_TRANSLOG_GENERATION_THRESHOLD_SIZE_SETTING =
            Setting.byteSizeSetting(
                    "index.translog.generation_threshold_size",
                    new ByteSizeValue(64, ByteSizeUnit.MB),
                    /*
                     * An empty translog occupies 55 bytes on disk. If the generation threshold is
                     * below this, the flush thread can get stuck in an infinite loop repeatedly
                     * rolling the generation as every new generation will already exceed the
                     * generation threshold. However, small thresholds are useful for testing so we
                     * do not add a large lower bound here.
                     */
                    new ByteSizeValue(Translog.DEFAULT_HEADER_SIZE_IN_BYTES + 1, ByteSizeUnit.BYTES),
                    new ByteSizeValue(Long.MAX_VALUE, ByteSizeUnit.BYTES),
                    Property.Dynamic, Property.IndexScope);

    /**
     * Index setting to enable / disable deletes garbage collection.
     * This setting is realtime updateable
     */
    public static final TimeValue DEFAULT_GC_DELETES = TimeValue.timeValueSeconds(60);
    public static final Setting<TimeValue> INDEX_GC_DELETES_SETTING =
        Setting.timeSetting("index.gc_deletes", DEFAULT_GC_DELETES, new TimeValue(-1, TimeUnit.MILLISECONDS),
            Property.Dynamic, Property.IndexScope);

    /**
     * Specifies if the index should use soft-delete instead of hard-delete for update/delete operations.
     * Soft-deletes is enabled by default for 7.0 indices and mandatory for 8.0 indices.
     */
    public static final Setting<Boolean> INDEX_SOFT_DELETES_SETTING =
        Setting.boolSetting("index.soft_deletes.enabled", true, Property.IndexScope, Property.Final);

    /**
     * Controls how many soft-deleted documents will be kept around before being merged away. Keeping more deleted
     * documents increases the chance of operation-based recoveries and allows querying a longer history of documents.
     * If soft-deletes is enabled, an engine by default will retain all operations up to the global checkpoint.
     **/
    public static final Setting<Long> INDEX_SOFT_DELETES_RETENTION_OPERATIONS_SETTING =
        Setting.longSetting("index.soft_deletes.retention.operations", 0, 0,
            Property.IndexScope, Property.Dynamic);

    /**
     * Controls how long translog files that are no longer needed for persistence reasons
     * will be kept around before being deleted. Keeping more files is useful to increase
     * the chance of ops based recoveries for indices with soft-deletes disabled.
     * TODO: Remove this setting in 9.0.
     **/
    public static final Setting<TimeValue> INDEX_TRANSLOG_RETENTION_AGE_SETTING =
        Setting.timeSetting("index.translog.retention.age", settings -> TimeValue.MINUS_ONE,
            TimeValue.MINUS_ONE, Property.Dynamic, Property.IndexScope);

    /**
     * Controls how many translog files that are no longer needed for persistence reasons
     * will be kept around before being deleted. Keeping more files is useful to increase
     * the chance of ops based recoveries for indices with soft-deletes disabled.
     * TODO: Remove this setting in 9.0.
     **/
    public static final Setting<ByteSizeValue> INDEX_TRANSLOG_RETENTION_SIZE_SETTING =
        Setting.byteSizeSetting("index.translog.retention.size", settings -> "-1", Property.Dynamic, Property.IndexScope);

    /**
     * Controls the maximum length of time since a retention lease is created or renewed before it is considered expired.
     */
    public static final Setting<TimeValue> INDEX_SOFT_DELETES_RETENTION_LEASE_PERIOD_SETTING =
            Setting.timeSetting(
                    "index.soft_deletes.retention_lease.period",
                    TimeValue.timeValueHours(12),
                    TimeValue.ZERO,
                    Property.Dynamic,
                    Property.IndexScope);

    /**
     * The maximum number of refresh listeners allows on this shard.
     */
    public static final Setting<Integer> MAX_REFRESH_LISTENERS_PER_SHARD = Setting.intSetting("index.max_refresh_listeners",
        1000, 0, Property.Dynamic, Property.IndexScope);

    /**
     * The maximum number of slices allowed in a scroll request
     */
    public static final Setting<Integer> MAX_SLICES_PER_SCROLL = Setting.intSetting("index.max_slices_per_scroll",
        1024, 1, Property.Dynamic, Property.IndexScope);

    /**
     * The maximum length of regex string allowed in a regexp query.
     */
    public static final Setting<Integer> MAX_REGEX_LENGTH_SETTING = Setting.intSetting("index.max_regex_length",
        1000, 1, Property.Dynamic, Property.IndexScope);

    public static final Setting<String> DEFAULT_PIPELINE =
        new Setting<>("index.default_pipeline",
        IngestService.NOOP_PIPELINE_NAME,
        Function.identity(),
        Property.Dynamic,
        Property.IndexScope);

    public static final Setting<String> FINAL_PIPELINE =
        new Setting<>("index.final_pipeline",
            IngestService.NOOP_PIPELINE_NAME,
            Function.identity(),
            Property.Dynamic,
            Property.IndexScope);

    /**
     * Marks an index to be searched throttled. This means that never more than one shard of such an index will be searched concurrently
     */
    public static final Setting<Boolean> INDEX_SEARCH_THROTTLED = Setting.boolSetting("index.search.throttled", false,
        Property.IndexScope, Property.PrivateIndex, Property.Dynamic);

    /**
     * Determines a balance between file-based and operations-based peer recoveries. The number of operations that will be used in an
     * operations-based peer recovery is limited to this proportion of the total number of documents in the shard (including deleted
     * documents) on the grounds that a file-based peer recovery may copy all of the documents in the shard over to the new peer, but is
     * significantly faster than replaying the missing operations on the peer, so once a peer falls far enough behind the primary it makes
     * more sense to copy all the data over again instead of replaying history.
     *
     * Defaults to retaining history for up to 10% of the documents in the shard. This can only be changed in tests, since this setting is
     * intentionally unregistered.
     */
    public static final Setting<Double> FILE_BASED_RECOVERY_THRESHOLD_SETTING
        = Setting.doubleSetting("index.recovery.file_based_threshold", 0.1d, 0.0d, Setting.Property.IndexScope);

    private final Index index;
    private final Version version;
    private final Logger logger;
    private final String nodeName;
    private final Settings nodeSettings;
    private final int numberOfShards;
    // volatile fields are updated via #updateIndexMetadata(IndexMetadata) under lock
    private volatile Settings settings;
    private volatile IndexMetadata indexMetadata;
    private volatile List<String> defaultFields;
    private final boolean queryStringLenient;
    private final boolean queryStringAnalyzeWildcard;
    private final boolean queryStringAllowLeadingWildcard;
    private final boolean defaultAllowUnmappedFields;
    private volatile Translog.Durability durability;
    private volatile TimeValue syncInterval;
    private volatile TimeValue refreshInterval;
    private volatile ByteSizeValue flushThresholdSize;
    private volatile ByteSizeValue generationThresholdSize;
    private volatile ByteSizeValue flushAfterMergeThresholdSize;
    private final MergeSchedulerConfig mergeSchedulerConfig;
    private final MergePolicyConfig mergePolicyConfig;
    private final IndexSortConfig indexSortConfig;
    private final IndexScopedSettings scopedSettings;
    private long gcDeletesInMillis = DEFAULT_GC_DELETES.millis();
    private final boolean softDeleteEnabled;
    private volatile long softDeleteRetentionOperations;

    private volatile long retentionLeaseMillis;

    /**
     * The maximum age of a retention lease before it is considered expired.
     *
     * @return the maximum age
     */
    public long getRetentionLeaseMillis() {
        return retentionLeaseMillis;
    }

    private void setRetentionLeaseMillis(final TimeValue retentionLease) {
        this.retentionLeaseMillis = retentionLease.millis();
    }

    private volatile boolean warmerEnabled;
    private volatile int maxResultWindow;
    private volatile int maxInnerResultWindow;
    private volatile int maxRescoreWindow;
    private volatile int maxDocvalueFields;
    private volatile int maxScriptFields;
    private volatile int maxTokenCount;
    private volatile int maxNgramDiff;
    private volatile int maxShingleDiff;
    private volatile TimeValue searchIdleAfter;
    private volatile int maxAnalyzedOffset;
    private volatile int maxTermsCount;
    private volatile String defaultPipeline;
    private volatile String requiredPipeline;
    private volatile boolean searchThrottled;
    private volatile long mappingNestedFieldsLimit;
    private volatile long mappingNestedDocsLimit;
    private volatile long mappingTotalFieldsLimit;
    private volatile long mappingDepthLimit;
    private volatile long mappingFieldNameLengthLimit;

    /**
     * The maximum number of refresh listeners allows on this shard.
     */
    private volatile int maxRefreshListeners;
    /**
     * The maximum number of slices allowed in a scroll request.
     */
    private volatile int maxSlicesPerScroll;

    /**
     * The maximum length of regex string allowed in a regexp query.
     */
    private volatile int maxRegexLength;

    /**
     * Returns the default search fields for this index.
     */
    public List<String> getDefaultFields() {
        return defaultFields;
    }

    private void setDefaultFields(List<String> defaultFields) {
        this.defaultFields = defaultFields;
    }

    /**
     * Returns <code>true</code> if query string parsing should be lenient. The default is <code>false</code>
     */
    public boolean isQueryStringLenient() {
        return queryStringLenient;
    }

    /**
     * Returns <code>true</code> if the query string should analyze wildcards. The default is <code>false</code>
     */
    public boolean isQueryStringAnalyzeWildcard() {
        return queryStringAnalyzeWildcard;
    }

    /**
     * Returns <code>true</code> if the query string parser should allow leading wildcards. The default is <code>true</code>
     */
    public boolean isQueryStringAllowLeadingWildcard() {
        return queryStringAllowLeadingWildcard;
    }

    /**
     * Returns <code>true</code> if queries should be lenient about unmapped fields. The default is <code>true</code>
     */
    public boolean isDefaultAllowUnmappedFields() {
        return defaultAllowUnmappedFields;
    }

    /**
     * Creates a new {@link IndexSettings} instance. The given node settings will be merged with the settings in the metadata
     * while index level settings will overwrite node settings.
     *
     * @param indexMetadata the index metadata this settings object is associated with
     * @param nodeSettings the nodes settings this index is allocated on.
     */
    public IndexSettings(final IndexMetadata indexMetadata, final Settings nodeSettings) {
        this(indexMetadata, nodeSettings, IndexScopedSettings.DEFAULT_SCOPED_SETTINGS);
    }

    /**
     * Creates a new {@link IndexSettings} instance. The given node settings will be merged with the settings in the metadata
     * while index level settings will overwrite node settings.
     *
     * @param indexMetadata the index metadata this settings object is associated with
     * @param nodeSettings the nodes settings this index is allocated on.
     */
    public IndexSettings(final IndexMetadata indexMetadata, final Settings nodeSettings, IndexScopedSettings indexScopedSettings) {
        scopedSettings = indexScopedSettings.copy(nodeSettings, indexMetadata);
        this.nodeSettings = nodeSettings;
        this.settings = Settings.builder().put(nodeSettings).put(indexMetadata.getSettings()).build();
        this.index = indexMetadata.getIndex();
        version = IndexMetadata.SETTING_INDEX_VERSION_CREATED.get(settings);
        logger = Loggers.getLogger(getClass(), index);
        nodeName = Node.NODE_NAME_SETTING.get(settings);
        this.indexMetadata = indexMetadata;
        numberOfShards = settings.getAsInt(IndexMetadata.SETTING_NUMBER_OF_SHARDS, null);

        this.searchThrottled = INDEX_SEARCH_THROTTLED.get(settings);
        this.queryStringLenient = QUERY_STRING_LENIENT_SETTING.get(settings);
        this.queryStringAnalyzeWildcard = QUERY_STRING_ANALYZE_WILDCARD.get(nodeSettings);
        this.queryStringAllowLeadingWildcard = QUERY_STRING_ALLOW_LEADING_WILDCARD.get(nodeSettings);
        this.defaultAllowUnmappedFields = scopedSettings.get(ALLOW_UNMAPPED);
        this.durability = scopedSettings.get(INDEX_TRANSLOG_DURABILITY_SETTING);
        defaultFields = scopedSettings.get(DEFAULT_FIELD_SETTING);
        syncInterval = INDEX_TRANSLOG_SYNC_INTERVAL_SETTING.get(settings);
        refreshInterval = scopedSettings.get(INDEX_REFRESH_INTERVAL_SETTING);
        flushThresholdSize = scopedSettings.get(INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING);
        generationThresholdSize = scopedSettings.get(INDEX_TRANSLOG_GENERATION_THRESHOLD_SIZE_SETTING);
        flushAfterMergeThresholdSize = scopedSettings.get(INDEX_FLUSH_AFTER_MERGE_THRESHOLD_SIZE_SETTING);
        mergeSchedulerConfig = new MergeSchedulerConfig(this);
        gcDeletesInMillis = scopedSettings.get(INDEX_GC_DELETES_SETTING).getMillis();
        softDeleteEnabled = scopedSettings.get(INDEX_SOFT_DELETES_SETTING);
        assert softDeleteEnabled || version.before(Version.V_8_0_0) : "soft deletes must be enabled in version " + version;
        softDeleteRetentionOperations = scopedSettings.get(INDEX_SOFT_DELETES_RETENTION_OPERATIONS_SETTING);
        retentionLeaseMillis = scopedSettings.get(INDEX_SOFT_DELETES_RETENTION_LEASE_PERIOD_SETTING).millis();
        warmerEnabled = scopedSettings.get(INDEX_WARMER_ENABLED_SETTING);
        maxResultWindow = scopedSettings.get(MAX_RESULT_WINDOW_SETTING);
        maxInnerResultWindow = scopedSettings.get(MAX_INNER_RESULT_WINDOW_SETTING);
        maxRescoreWindow = scopedSettings.get(MAX_RESCORE_WINDOW_SETTING);
        maxDocvalueFields = scopedSettings.get(MAX_DOCVALUE_FIELDS_SEARCH_SETTING);
        maxScriptFields = scopedSettings.get(MAX_SCRIPT_FIELDS_SETTING);
        maxTokenCount = scopedSettings.get(MAX_TOKEN_COUNT_SETTING);
        maxNgramDiff = scopedSettings.get(MAX_NGRAM_DIFF_SETTING);
        maxShingleDiff = scopedSettings.get(MAX_SHINGLE_DIFF_SETTING);
        maxRefreshListeners = scopedSettings.get(MAX_REFRESH_LISTENERS_PER_SHARD);
        maxSlicesPerScroll = scopedSettings.get(MAX_SLICES_PER_SCROLL);
        maxAnalyzedOffset = scopedSettings.get(MAX_ANALYZED_OFFSET_SETTING);
        maxTermsCount = scopedSettings.get(MAX_TERMS_COUNT_SETTING);
        maxRegexLength = scopedSettings.get(MAX_REGEX_LENGTH_SETTING);
        this.mergePolicyConfig = new MergePolicyConfig(logger, this);
        this.indexSortConfig = new IndexSortConfig(this);
        searchIdleAfter = scopedSettings.get(INDEX_SEARCH_IDLE_AFTER);
        defaultPipeline = scopedSettings.get(DEFAULT_PIPELINE);
        mappingNestedFieldsLimit = scopedSettings.get(INDEX_MAPPING_NESTED_FIELDS_LIMIT_SETTING);
        mappingNestedDocsLimit = scopedSettings.get(INDEX_MAPPING_NESTED_DOCS_LIMIT_SETTING);
        mappingTotalFieldsLimit = scopedSettings.get(INDEX_MAPPING_TOTAL_FIELDS_LIMIT_SETTING);
        mappingDepthLimit = scopedSettings.get(INDEX_MAPPING_DEPTH_LIMIT_SETTING);
        mappingFieldNameLengthLimit = scopedSettings.get(INDEX_MAPPING_FIELD_NAME_LENGTH_LIMIT_SETTING);

        scopedSettings.addSettingsUpdateConsumer(MergePolicyConfig.INDEX_COMPOUND_FORMAT_SETTING, mergePolicyConfig::setNoCFSRatio);
        scopedSettings.addSettingsUpdateConsumer(MergePolicyConfig.INDEX_MERGE_POLICY_DELETES_PCT_ALLOWED_SETTING,
            mergePolicyConfig::setDeletesPctAllowed);
        scopedSettings.addSettingsUpdateConsumer(MergePolicyConfig.INDEX_MERGE_POLICY_EXPUNGE_DELETES_ALLOWED_SETTING,
            mergePolicyConfig::setExpungeDeletesAllowed);
        scopedSettings.addSettingsUpdateConsumer(MergePolicyConfig.INDEX_MERGE_POLICY_FLOOR_SEGMENT_SETTING,
            mergePolicyConfig::setFloorSegmentSetting);
        scopedSettings.addSettingsUpdateConsumer(MergePolicyConfig.INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_SETTING,
            mergePolicyConfig::setMaxMergesAtOnce);
        scopedSettings.addSettingsUpdateConsumer(MergePolicyConfig.INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_EXPLICIT_SETTING,
            mergePolicyConfig::setMaxMergesAtOnceExplicit);
        scopedSettings.addSettingsUpdateConsumer(MergePolicyConfig.INDEX_MERGE_POLICY_MAX_MERGED_SEGMENT_SETTING,
            mergePolicyConfig::setMaxMergedSegment);
        scopedSettings.addSettingsUpdateConsumer(MergePolicyConfig.INDEX_MERGE_POLICY_SEGMENTS_PER_TIER_SETTING,
            mergePolicyConfig::setSegmentsPerTier);

        scopedSettings.addSettingsUpdateConsumer(MergeSchedulerConfig.MAX_THREAD_COUNT_SETTING,
            MergeSchedulerConfig.MAX_MERGE_COUNT_SETTING, mergeSchedulerConfig::setMaxThreadAndMergeCount);
        scopedSettings.addSettingsUpdateConsumer(MergeSchedulerConfig.AUTO_THROTTLE_SETTING, mergeSchedulerConfig::setAutoThrottle);
        scopedSettings.addSettingsUpdateConsumer(INDEX_TRANSLOG_DURABILITY_SETTING, this::setTranslogDurability);
        scopedSettings.addSettingsUpdateConsumer(INDEX_TRANSLOG_SYNC_INTERVAL_SETTING, this::setTranslogSyncInterval);
        scopedSettings.addSettingsUpdateConsumer(MAX_RESULT_WINDOW_SETTING, this::setMaxResultWindow);
        scopedSettings.addSettingsUpdateConsumer(MAX_INNER_RESULT_WINDOW_SETTING, this::setMaxInnerResultWindow);
        scopedSettings.addSettingsUpdateConsumer(MAX_RESCORE_WINDOW_SETTING, this::setMaxRescoreWindow);
        scopedSettings.addSettingsUpdateConsumer(MAX_DOCVALUE_FIELDS_SEARCH_SETTING, this::setMaxDocvalueFields);
        scopedSettings.addSettingsUpdateConsumer(MAX_SCRIPT_FIELDS_SETTING, this::setMaxScriptFields);
        scopedSettings.addSettingsUpdateConsumer(MAX_TOKEN_COUNT_SETTING, this::setMaxTokenCount);
        scopedSettings.addSettingsUpdateConsumer(MAX_NGRAM_DIFF_SETTING, this::setMaxNgramDiff);
        scopedSettings.addSettingsUpdateConsumer(MAX_SHINGLE_DIFF_SETTING, this::setMaxShingleDiff);
        scopedSettings.addSettingsUpdateConsumer(INDEX_WARMER_ENABLED_SETTING, this::setEnableWarmer);
        scopedSettings.addSettingsUpdateConsumer(INDEX_GC_DELETES_SETTING, this::setGCDeletes);
        scopedSettings.addSettingsUpdateConsumer(INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING, this::setTranslogFlushThresholdSize);
        scopedSettings.addSettingsUpdateConsumer(INDEX_FLUSH_AFTER_MERGE_THRESHOLD_SIZE_SETTING, this::setFlushAfterMergeThresholdSize);
        scopedSettings.addSettingsUpdateConsumer(
                INDEX_TRANSLOG_GENERATION_THRESHOLD_SIZE_SETTING,
                this::setGenerationThresholdSize);
        scopedSettings.addSettingsUpdateConsumer(INDEX_REFRESH_INTERVAL_SETTING, this::setRefreshInterval);
        scopedSettings.addSettingsUpdateConsumer(MAX_REFRESH_LISTENERS_PER_SHARD, this::setMaxRefreshListeners);
        scopedSettings.addSettingsUpdateConsumer(MAX_ANALYZED_OFFSET_SETTING, this::setHighlightMaxAnalyzedOffset);
        scopedSettings.addSettingsUpdateConsumer(MAX_TERMS_COUNT_SETTING, this::setMaxTermsCount);
        scopedSettings.addSettingsUpdateConsumer(MAX_SLICES_PER_SCROLL, this::setMaxSlicesPerScroll);
        scopedSettings.addSettingsUpdateConsumer(DEFAULT_FIELD_SETTING, this::setDefaultFields);
        scopedSettings.addSettingsUpdateConsumer(INDEX_SEARCH_IDLE_AFTER, this::setSearchIdleAfter);
        scopedSettings.addSettingsUpdateConsumer(MAX_REGEX_LENGTH_SETTING, this::setMaxRegexLength);
        scopedSettings.addSettingsUpdateConsumer(DEFAULT_PIPELINE, this::setDefaultPipeline);
        scopedSettings.addSettingsUpdateConsumer(FINAL_PIPELINE, this::setRequiredPipeline);
        scopedSettings.addSettingsUpdateConsumer(INDEX_SOFT_DELETES_RETENTION_OPERATIONS_SETTING, this::setSoftDeleteRetentionOperations);
        scopedSettings.addSettingsUpdateConsumer(INDEX_SEARCH_THROTTLED, this::setSearchThrottled);
        scopedSettings.addSettingsUpdateConsumer(INDEX_SOFT_DELETES_RETENTION_LEASE_PERIOD_SETTING, this::setRetentionLeaseMillis);
        scopedSettings.addSettingsUpdateConsumer(INDEX_MAPPING_NESTED_FIELDS_LIMIT_SETTING, this::setMappingNestedFieldsLimit);
        scopedSettings.addSettingsUpdateConsumer(INDEX_MAPPING_NESTED_DOCS_LIMIT_SETTING, this::setMappingNestedDocsLimit);
        scopedSettings.addSettingsUpdateConsumer(INDEX_MAPPING_TOTAL_FIELDS_LIMIT_SETTING, this::setMappingTotalFieldsLimit);
        scopedSettings.addSettingsUpdateConsumer(INDEX_MAPPING_DEPTH_LIMIT_SETTING, this::setMappingDepthLimit);
        scopedSettings.addSettingsUpdateConsumer(INDEX_MAPPING_FIELD_NAME_LENGTH_LIMIT_SETTING, this::setMappingFieldNameLengthLimit);
    }

    private void setSearchIdleAfter(TimeValue searchIdleAfter) { this.searchIdleAfter = searchIdleAfter; }

    private void setTranslogFlushThresholdSize(ByteSizeValue byteSizeValue) {
        this.flushThresholdSize = byteSizeValue;
    }

    private void setFlushAfterMergeThresholdSize(ByteSizeValue byteSizeValue) {
        this.flushAfterMergeThresholdSize = byteSizeValue;
    }

    private void setGenerationThresholdSize(final ByteSizeValue generationThresholdSize) {
        this.generationThresholdSize = generationThresholdSize;
    }

    private void setGCDeletes(TimeValue timeValue) {
        this.gcDeletesInMillis = timeValue.getMillis();
    }

    private void setRefreshInterval(TimeValue timeValue) {
        this.refreshInterval = timeValue;
    }

    /**
     * Returns the settings for this index. These settings contain the node and index level settings where
     * settings that are specified on both index and node level are overwritten by the index settings.
     */
    public Settings getSettings() { return settings; }

    /**
     * Returns the index this settings object belongs to
     */
    public Index getIndex() {
        return index;
    }

    /**
     * Returns the indexes UUID
     */
    public String getUUID() {
        return getIndex().getUUID();
    }

    /**
     * Returns <code>true</code> if the index has a custom data path
     */
    public boolean hasCustomDataPath() {
        return Strings.isNotEmpty(customDataPath());
    }

    /**
     * Returns the customDataPath for this index, if configured. <code>""</code> o.w.
     */
    public String customDataPath() {
        return IndexMetadata.INDEX_DATA_PATH_SETTING.get(settings);
    }

    /**
     * Returns the version the index was created on.
     * @see IndexMetadata#SETTING_VERSION_CREATED
     */
    public Version getIndexVersionCreated() {
        return version;
    }

    /**
     * Returns the current node name
     */
    public String getNodeName() {
        return nodeName;
    }

    /**
     * Returns the current IndexMetadata for this index
     */
    public IndexMetadata getIndexMetadata() {
        return indexMetadata;
    }

    /**
     * Returns the number of shards this index has.
     */
    public int getNumberOfShards() { return numberOfShards; }

    /**
     * Returns the number of replicas this index has.
     */
    public int getNumberOfReplicas() { return settings.getAsInt(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, null); }

    /**
     * Returns the node settings. The settings returned from {@link #getSettings()} are a merged version of the
     * index settings and the node settings where node settings are overwritten by index settings.
     */
    public Settings getNodeSettings() {
        return nodeSettings;
    }

    /**
     * Updates the settings and index metadata and notifies all registered settings consumers with the new settings iff at least one
     * setting has changed.
     *
     * @return <code>true</code> iff any setting has been updated otherwise <code>false</code>.
     */
    public synchronized boolean updateIndexMetadata(IndexMetadata indexMetadata) {
        final Settings newSettings = indexMetadata.getSettings();
        Version newIndexVersion = IndexMetadata.SETTING_INDEX_VERSION_CREATED.get(newSettings);
        if (version.equals(newIndexVersion) == false) {
            throw new IllegalArgumentException("version mismatch on settings update expected: " + version + " but was: " + newIndexVersion);
        }
        final String newUUID = newSettings.get(IndexMetadata.SETTING_INDEX_UUID, IndexMetadata.INDEX_UUID_NA_VALUE);
        if (newUUID.equals(getUUID()) == false) {
            throw new IllegalArgumentException("uuid mismatch on settings update expected: " + getUUID() + " but was: " + newUUID);
        }
        final String newRestoreUUID = newSettings.get(IndexMetadata.SETTING_HISTORY_UUID, IndexMetadata.INDEX_UUID_NA_VALUE);
        final String restoreUUID = this.settings.get(IndexMetadata.SETTING_HISTORY_UUID, IndexMetadata.INDEX_UUID_NA_VALUE);
        if (newRestoreUUID.equals(restoreUUID) == false) {
            throw new IllegalArgumentException("uuid mismatch on settings update expected: " + restoreUUID + " but was: " + newRestoreUUID);
        }
        this.indexMetadata = indexMetadata;
        final Settings newIndexSettings = Settings.builder().put(nodeSettings).put(newSettings).build();
        if (same(this.settings, newIndexSettings)) {
            // nothing to update, same settings
            return false;
        }
        scopedSettings.applySettings(newSettings);
        this.settings = newIndexSettings;
        return true;
    }

    /**
     * Compare the specified settings for equality.
     *
     * @param left  the left settings
     * @param right the right settings
     * @return true if the settings are the same, otherwise false
     */
    public static boolean same(final Settings left, final Settings right) {
        return left.filter(IndexScopedSettings.INDEX_SETTINGS_KEY_PREDICATE)
                .equals(right.filter(IndexScopedSettings.INDEX_SETTINGS_KEY_PREDICATE));
    }

    /**
     * Returns the translog durability for this index.
     */
    public Translog.Durability getTranslogDurability() {
        return durability;
    }

    private void setTranslogDurability(Translog.Durability durability) {
        this.durability = durability;
    }

    /**
     * Returns true if index warmers are enabled, otherwise <code>false</code>
     */
    public boolean isWarmerEnabled() {
        return warmerEnabled;
    }

    private void setEnableWarmer(boolean enableWarmer) {
        this.warmerEnabled = enableWarmer;
    }

    /**
     * Returns the translog sync interval. This is the interval in which the transaction log is asynchronously fsynced unless
     * the transaction log is fsyncing on every operations
     */
    public TimeValue getTranslogSyncInterval() {
        return syncInterval;
    }

    public void setTranslogSyncInterval(TimeValue translogSyncInterval) {
        this.syncInterval = translogSyncInterval;
    }

    /**
     * Returns this interval in which the shards of this index are asynchronously refreshed. {@code -1} means async refresh is disabled.
     */
    public TimeValue getRefreshInterval() {
        return refreshInterval;
    }

    /**
     * Returns the transaction log threshold size when to forcefully flush the index and clear the transaction log.
     */
    public ByteSizeValue getFlushThresholdSize() { return flushThresholdSize; }

    /**
     * Returns the merge threshold size when to forcefully flush the index and free resources.
     */
    public ByteSizeValue getFlushAfterMergeThresholdSize() { return flushAfterMergeThresholdSize; }

    /**
     * Returns the generation threshold size. As sequence numbers can cause multiple generations to
     * be preserved for rollback purposes, we want to keep the size of individual generations from
     * growing too large to avoid excessive disk space consumption. Therefore, the translog is
     * automatically rolled to a new generation when the current generation exceeds this generation
     * threshold size.
     *
     * @return the generation threshold size
     */
    public ByteSizeValue getGenerationThresholdSize() {
        return generationThresholdSize;
    }

    /**
     * Returns the {@link MergeSchedulerConfig}
     */
    public MergeSchedulerConfig getMergeSchedulerConfig() { return mergeSchedulerConfig; }

    /**
     * Returns the max result window for search requests, describing the maximum value of from + size on a query.
     */
    public int getMaxResultWindow() {
        return this.maxResultWindow;
    }

    private void setMaxResultWindow(int maxResultWindow) {
        this.maxResultWindow = maxResultWindow;
    }

    /**
     * Returns the max result window for an individual inner hit definition or top hits aggregation.
     */
    public int getMaxInnerResultWindow() {
        return maxInnerResultWindow;
    }

    private void setMaxInnerResultWindow(int maxInnerResultWindow) {
        this.maxInnerResultWindow = maxInnerResultWindow;
    }

    /**
     * Returns the maximum rescore window for search requests.
     */
    public int getMaxRescoreWindow() {
        return maxRescoreWindow;
    }

    private void setMaxRescoreWindow(int maxRescoreWindow) {
        this.maxRescoreWindow = maxRescoreWindow;
    }

    /**
     * Returns the maximum number of allowed docvalue_fields to retrieve in a search request
     */
    public int getMaxDocvalueFields() {
        return this.maxDocvalueFields;
    }

    private void setMaxDocvalueFields(int maxDocvalueFields) {
        this.maxDocvalueFields = maxDocvalueFields;
    }

    /**
     * Returns the maximum number of tokens that can be produced
     */
    public int getMaxTokenCount() {
        return maxTokenCount;
    }

    private void setMaxTokenCount(int maxTokenCount) {
        this.maxTokenCount = maxTokenCount;
    }

    /**
     * Returns the maximum allowed difference between max and min length of ngram
     */
    public int getMaxNgramDiff() { return this.maxNgramDiff; }

    private void setMaxNgramDiff(int maxNgramDiff) { this.maxNgramDiff = maxNgramDiff; }

    /**
     * Returns the maximum allowed difference between max and min shingle_size
     */
    public int getMaxShingleDiff() { return this.maxShingleDiff; }

    private void setMaxShingleDiff(int maxShingleDiff) { this.maxShingleDiff = maxShingleDiff; }

    /**
     *  Returns the maximum number of chars that will be analyzed in a highlight request
     */
    public int getHighlightMaxAnalyzedOffset() { return this.maxAnalyzedOffset; }

    private void setHighlightMaxAnalyzedOffset(int maxAnalyzedOffset) { this.maxAnalyzedOffset = maxAnalyzedOffset; }

    /**
     *  Returns the maximum number of terms that can be used in a Terms Query request
     */
    public int getMaxTermsCount() { return this.maxTermsCount; }

    private void setMaxTermsCount (int maxTermsCount) { this.maxTermsCount = maxTermsCount; }

    /**
     * Returns the maximum number of allowed script_fields to retrieve in a search request
     */
    public int getMaxScriptFields() {
        return this.maxScriptFields;
    }

    private void setMaxScriptFields(int maxScriptFields) {
        this.maxScriptFields = maxScriptFields;
    }

    /**
     * Returns the GC deletes cycle in milliseconds.
     */
    public long getGcDeletesInMillis() {
        return gcDeletesInMillis;
    }

    /**
     * Returns the merge policy that should be used for this index.
     */
    public MergePolicy getMergePolicy() {
        return mergePolicyConfig.getMergePolicy();
    }

    public <T> T getValue(Setting<T> setting) {
        return scopedSettings.get(setting);
    }

    /**
     * The maximum number of refresh listeners allows on this shard.
     */
    public int getMaxRefreshListeners() {
        return maxRefreshListeners;
    }

    private void setMaxRefreshListeners(int maxRefreshListeners) {
        this.maxRefreshListeners = maxRefreshListeners;
    }

    /**
     * The maximum number of slices allowed in a scroll request.
     */
    public int getMaxSlicesPerScroll() {
        return maxSlicesPerScroll;
    }

    private void setMaxSlicesPerScroll(int value) {
        this.maxSlicesPerScroll = value;
    }

    /**
     * The maximum length of regex string allowed in a regexp query.
     */
    public int getMaxRegexLength() {
        return maxRegexLength;
    }

    private void setMaxRegexLength(int maxRegexLength) {
        this.maxRegexLength = maxRegexLength;
    }

    /**
     * Returns the index sort config that should be used for this index.
     */
    public IndexSortConfig getIndexSortConfig() {
        return indexSortConfig;
    }

    public IndexScopedSettings getScopedSettings() { return scopedSettings;}

    /**
     * Returns true iff the refresh setting exists or in other words is explicitly set.
     */
    public boolean isExplicitRefresh() {
        return INDEX_REFRESH_INTERVAL_SETTING.exists(settings);
    }

    /**
     * Returns the time that an index shard becomes search idle unless it's accessed in between
     */
    public TimeValue getSearchIdleAfter() { return searchIdleAfter; }

    public String getDefaultPipeline() {
        return defaultPipeline;
    }

    public void setDefaultPipeline(String defaultPipeline) {
        this.defaultPipeline = defaultPipeline;
    }

    public String getRequiredPipeline() {
        return requiredPipeline;
    }

    public void setRequiredPipeline(final String requiredPipeline) {
        this.requiredPipeline = requiredPipeline;
    }

    /**
     * Returns <code>true</code> if soft-delete is enabled.
     */
    public boolean isSoftDeleteEnabled() {
        return softDeleteEnabled;
    }

    private void setSoftDeleteRetentionOperations(long ops) {
        this.softDeleteRetentionOperations = ops;
    }

    /**
     * Returns the number of extra operations (i.e. soft-deleted documents) to be kept for recoveries and history purpose.
     */
    public long getSoftDeleteRetentionOperations() {
        return this.softDeleteRetentionOperations;
    }

    /**
     * Returns true if the this index should be searched throttled ie. using the
     * {@link org.elasticsearch.threadpool.ThreadPool.Names#SEARCH_THROTTLED} thread-pool
     */
    public boolean isSearchThrottled() {
        return searchThrottled;
    }

    private void setSearchThrottled(boolean searchThrottled) {
        this.searchThrottled = searchThrottled;
    }

    public long getMappingNestedFieldsLimit() {
        return mappingNestedFieldsLimit;
    }

    private void setMappingNestedFieldsLimit(long value) {
        this.mappingNestedFieldsLimit = value;
    }

    public long getMappingNestedDocsLimit() {
        return mappingNestedDocsLimit;
    }

    private void setMappingNestedDocsLimit(long value) {
        this.mappingNestedDocsLimit = value;
    }

    public long getMappingTotalFieldsLimit() {
        return mappingTotalFieldsLimit;
    }

    private void setMappingTotalFieldsLimit(long value) {
        this.mappingTotalFieldsLimit = value;
    }

    public long getMappingDepthLimit() {
        return mappingDepthLimit;
    }

    private void setMappingDepthLimit(long value) {
        this.mappingDepthLimit = value;
    }

    public long getMappingFieldNameLengthLimit() {
        return mappingFieldNameLengthLimit;
    }

    private void setMappingFieldNameLengthLimit(long value) {
        this.mappingFieldNameLengthLimit = value;
    }
}


text:
package LeetcodeTemplate;

import java.util.List;

public class _0797AllPathsFromSourceToTarget {
	public static void main(String[] args) {
		System.out.println(allPathsSourceTarget(
				new int[][] { new int[] { 1, 2 }, new int[] { 3 }, new int[] { 3 }, new int[] {} }));

		System.out.println(allPathsSourceTarget(new int[][] { new int[] { 4, 3, 1 }, new int[] { 3, 2, 4 },
				new int[] { 3 }, new int[] { 4 }, new int[] {} }));

		System.out.println(allPathsSourceTarget(new int[][] { new int[] { 1 }, new int[] {} }));

		System.out.println(allPathsSourceTarget(
				new int[][] { new int[] { 1, 2, 3 }, new int[] { 2 }, new int[] { 3 }, new int[] {} }));

		System.out.println(allPathsSourceTarget(
				new int[][] { new int[] { 1, 3 }, new int[] { 2 }, new int[] { 3 }, new int[] {} }));

	}

	public static List<List<Integer>> allPathsSourceTarget(int[][] graph) {

	}

}

redpajama_set_name: RedPajamaGithub


text:
[CmdletBinding()]
param(
    # Path of the folder to build from (defaults to the folder the Build script is in)
    [Alias("PSPath")]
    [string]$Path = $PSScriptRoot,

    # The Module name is used to identify Manifest and scrape version (defaults to the folder name)
    [string]$ModuleName = $(Split-Path $Path -Leaf),

    # The target framework for .net (for packages), with fallback versions
    # The default supports PS3+:  "net40","net35","net20","net45","net451","net452","net46","net461","net462"
    # To only support PS4, use:  "net45","net40","net35","net20"
    # To support PS2, you use:   "net35","net20"
    [string[]]$TargetFramework = @("net40","net35","net20","net45","net451","net452","net46","net461","net462"),

    # The last digit of the build version number (by default comes from AppVeyor)
    [Nullable[int]]$RevisionNumber = ${Env:APPVEYOR_BUILD_NUMBER},

    # MSBuild Target (defaults to "Build")
    $Target="Build",

    # MSBuild Configuration (defaults to "Release")
    $Configuration="Release"
)
$Path = Convert-Path $Path
$ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest
Write-Host "BUILDING: $ModuleName from $Path"

$OutputPath = Join-Path $Path output
$null = mkdir $OutputPath -Force

Write-Verbose "Get-Version -Module ${ModuleName}.psd1 -RevisionNumber:$RevisionNumber"
# If the RevisionNumber is specified as ZERO, this is a release build
$Version = &"${PSScriptRoot}\Get-Version.ps1" -Module (Join-Path $Path\src "${ModuleName}.psd1") -RevisionNumber:$RevisionNumber
$ReleasePath = Join-Path $Path $Version

Write-Verbose "OUTPUT Release Path: $ReleasePath"
if(Test-Path $ReleasePath) {
    Write-Verbose "       Clean up old build"
    Write-Verbose "DELETE $ReleasePath\"
    Remove-Item $ReleasePath -Recurse -Force -ErrorAction SilentlyContinue
}

## Find dependency Package Files
Write-Verbose "       Copying Packages"
$Packages = Join-Path $Path packages.config
if(Test-Path $Packages) {
    foreach($Package in ([xml](Get-Content $Packages)).packages.package) {
        $folder = Join-Path $Path "packages\$($Package.id)*"
        # Check for each TargetFramework, in order of preference, fall back to using the lib folder
        $targets = ($TargetFramework -replace '^','lib\') + 'lib' | ForEach-Object { Join-Path $folder $_ }
        $PackageSource = Get-Item $targets -ErrorAction SilentlyContinue | Select -First 1 -Expand FullName
        if(!$PackageSource) {
            throw "Could not find a lib folder for $($Package.id) from package. You may need to run Setup.ps1"
        }

        Write-Verbose "COPY   $PackageSource\"
        $null = robocopy $PackageSource $ReleasePath\lib /MIR /NP /LOG:"$OutputPath\build.log" /R:2 /W:15
        if($LASTEXITCODE -gt 1) {
            throw "Failed to copy Package $($Package.id) (${LASTEXITCODE}), see build.log for details"
        }
    }
}

## If there's a solution file, build it.
foreach($solution in Get-Item $Path\*.sln) {
    msbuild $solution.FullName /t:$Target /p:Configuration=$Configuration /p:OutputPath=$ReleasePath\lib
}

## Copy PowerShell source Files
Write-Verbose "       Copying Module Source"
Write-Verbose "COPY   '$Path\src\' '$ReleasePath'"
$null = robocopy $Path\src\  $ReleasePath /E /NP /LOG+:"$OutputPath\build.log" /R:2 /W:15
if($LASTEXITCODE -gt 3) {
    throw "Failed to copy Module (${LASTEXITCODE}), see build.log for details"
}
## Touch the PSD1 Version:
Write-Verbose "       Update Module Version"
$ReleaseManifest = Join-Path $ReleasePath "${ModuleName}.psd1"
Set-Content $ReleaseManifest ((Get-Content $ReleaseManifest) -Replace "^(\s*)ModuleVersion\s*=\s*'?[\d\.]+'?\s*`$", "`$1ModuleVersion = '$Version'")
Get-Module $ReleaseManifest -ListAvailable


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Pomaderris obovata Hook.

### Remarks
null


text:
require 'active_support/inflector'
require 'thor'
require 'thor/group'

require 'helper/basic'

module Ruby
  class App < ::Thor::Group
    include ::Thor::Actions

    include Helper::Basic

    desc "Generates a ruby application"

    # Define arguments and options
    argument :command
    argument :name

    # - please create [name] [--profiles] [--steps] [--user] [--in]
    # - please update [name] [--profiles] [--steps] [--user] [--in]
    # - please revert [name] [--user] [--in]
    #
    # - please install-step [name] [--url] [--user]
    # - please remove-step [name] [--url] [--user]
    #
    # - please create-user [name]
    # - please remove-user [name]
    #
    # - please create-profile [name] [--user]
    # - please remove-profile [name] [--user]

    class_option :profiles,   :type => :array,   :optional => true,   :desc => "Profiles to use"
    class_option :steps,      :type => :array,   :optional => true,   :desc => "Steps to use"

    class_option :user,       :type => :string,  :optional => true,   :desc => "Use specific user configuration"
    class_option :in,         :type => :string,  :optional => true,   :desc => "Override default destination of thing"
    class_option :type,       :type => :string,  :optional => true,   :desc => "Type of thing"

    def load_local_settings
      root_dir = ENV['PLEASE_ME_HOME']
    end

    def load_config_file
      config = YAML.load_file(get_config_file)
    end

    def set_destination
      # set destination dir, --in option takes precedence, otherwise use destination for type of thing, as set in config file!
      destination_dir options[:in] || config[:destination][type]
    end

    def execute
      require_command
      command_class = get_command_class
      command_class.new config, options
      command_class.execute
    end

    protected

    attr_accessor :config, :target, :command_class

    def get_config_file
      File.join(context_dir, 'config.yml')
    end

    TARGETS = [:step, :user, :profile, :project]

    def set_target
      TARGETS.each do |t|
        target = t if command =~ /#{t}/
      end
      return TARGETS.last if !target
    end

    def require_command
      require_all File.dirname(__FILE__) + "/#{target}/#{command}"
    end

    def get_command_class name
      command_class = "Command::#{target.camelize}::#{name.camelize}".constantize
    end

    def type
      options[:type]
    end

  end
end


text:
package support

import (
	"fmt"
	"os"
	"os/signal"
)

// WaitUntilSignal forces the caller to wait until an OS signal is received. This is typically called at the base of the main function
// of a go process.
func WaitUntilSignal() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill)

	// Block until a signal is received.
	s := <-c
	panic(fmt.Sprintf("killed by signal %v", s))
}


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mushapi.wcf"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.INTERNET" >
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS" >
    </uses-permission>
    <uses-permission android:name="android.permission.SEND_SMS" >
    </uses-permission>
    <uses-permission android:name="android.permission.READ_CONTACTS" >
    </uses-permission>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
package akka.kafka

/**
 * Ports to use for Kafka and Zookeeper throughout integration tests.
 * Zookeeper is Kafka port + 1 if nothing else specified.
 */
object KafkaPorts {

  val RetentionPeriodSpec = 9012
  val ReconnectSpec = 9032
  val ReconnectSpecProxy = 9034
  val MultiConsumerSpec = 9042
  val ScalaPartitionExamples = 9052
  val ScalaAvroSerialization = 9072
  val AssignmentTest = 9082
  val SerializationTest = 9092
  val ProducerExamplesTest = 9112
  val KafkaConnectionCheckerTest = 9122
  val PartitionAssignmentHandlerSpec = 9132
}


text:
package com.stream.wangxiang.event;

import com.stream.wangxiang.vo.NewsDetailVo;

/**
 * 新闻详情的event
 * Created by 张川川 on 2016/4/28.
 */
public class GetNewsDetailEvent extends BaseEvent {
    private NewsDetailVo detailVo;

    public NewsDetailVo getDetailVo() {
        return detailVo;
    }

    public void setDetailVo(NewsDetailVo detailVo) {
        this.detailVo = detailVo;
    }
}


text:
package com.pktippa

object SolveMeFirst {
  def main(args: Array[String]) {
    // Reading all the lines from command line input
    var lines = io.Source.stdin.getLines();
    // Taking only two lines from it - Iterator[String]
    var parameters = lines.take(2);
    // Converting taken parameters into Integer values - Iterator[Int]
    var integerParams = parameters.map(_.toInt);
    // Calculating sum on Iterator[Int]
    var sum = integerParams.sum;
    println(sum);
  }
}


text:
package ai.h2o.automl;

import ai.h2o.automl.StepDefinition.Step;
import ai.h2o.automl.events.EventLogEntry;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import water.TestUtil;
import water.fvec.Frame;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.junit.Assert.*;

public class ModelingStepRegistryTest extends TestUtil {

    private AutoML aml;
    private Frame fr;

    private static Set<String> sortedProviders;

    @BeforeClass
    public static void setup() {
        stall_till_cloudsize(1);

        sortedProviders = new TreeSet<>(String::compareToIgnoreCase);
        sortedProviders.addAll(ModelingStepsRegistry.stepsByName.keySet());
    }

    @Before
    public void createAutoML() {
        fr = parseTestFile("./smalldata/logreg/prostate_train.csv");
        AutoMLBuildSpec buildSpec = new AutoMLBuildSpec();
        buildSpec.input_spec.training_frame = fr._key;
        buildSpec.input_spec.response_column = "CAPSULE";
        aml = new AutoML(buildSpec);
    }

    @After
    public void cleanupAutoML() {
        if(aml!=null) aml.delete();
        if(fr!=null) fr.delete();
    }

    @Test
    public void test_registration_of_default_step_providers() {
        assertEquals(6, ModelingStepsRegistry.stepsByName.size());
        assertEquals("Detected some duplicate registration", 6, new HashSet<>(ModelingStepsRegistry.stepsByName.values()).size());
        for (Algo algo: Algo.values()) {
            assertTrue(ModelingStepsRegistry.stepsByName.containsKey(algo.name()));
            assertNotNull(ModelingStepsRegistry.stepsByName.get(algo.name()));
        }
    }

    @Test
    public void test_empty_definition() {
        ModelingStepsRegistry registry = new ModelingStepsRegistry();
        assertEquals(0, registry.getOrderedSteps(new StepDefinition[0], aml).length);
    }

    @Test
    public void test_non_empty_definition() {
        ModelingStepsRegistry registry = new ModelingStepsRegistry();
        assertEquals(3, registry.getOrderedSteps(new StepDefinition[]{
                new StepDefinition(Algo.StackedEnsemble.name(), StepDefinition.Alias.defaults)
        }, aml).length);
    }

    @Test
    public void test_all_registered_steps() {
        ModelingStepsRegistry registry = new ModelingStepsRegistry();
        List<StepDefinition> allSteps = sortedProviders.stream()
                .map(name -> new StepDefinition(name, StepDefinition.Alias.all))
                .collect(Collectors.toList());
        ModelingStep[] modelingSteps = registry.getOrderedSteps(allSteps.toArray(new StepDefinition[0]), aml);
        assertEquals((1 + 3/*DL*/) + (2/*DRF*/) + (5 + 1 + 1/*GBM*/) + (1/*GLM*/) + (3/*SE*/) + (3 + 1 + 2/*XGB*/),
                modelingSteps.length);
        assertEquals(1, Stream.of(modelingSteps).filter(s -> s._algo == Algo.DeepLearning).filter(ModelingStep.ModelStep.class::isInstance).count());
        assertEquals(3, Stream.of(modelingSteps).filter(s -> s._algo == Algo.DeepLearning).filter(ModelingStep.GridStep.class::isInstance).count());
        assertEquals(2, Stream.of(modelingSteps).filter(s -> s._algo == Algo.DRF).filter(ModelingStep.ModelStep.class::isInstance).count());
        assertEquals(5, Stream.of(modelingSteps).filter(s -> s._algo == Algo.GBM).filter(ModelingStep.ModelStep.class::isInstance).count());
        assertEquals(1, Stream.of(modelingSteps).filter(s -> s._algo == Algo.GBM).filter(ModelingStep.GridStep.class::isInstance).count());
        assertEquals(1, Stream.of(modelingSteps).filter(s -> s._algo == Algo.GBM).filter(ModelingStep.SelectionStep.class::isInstance).count());
        assertEquals(1, Stream.of(modelingSteps).filter(s -> s._algo == Algo.GLM).filter(ModelingStep.ModelStep.class::isInstance).count());
        assertEquals(3, Stream.of(modelingSteps).filter(s -> s._algo == Algo.StackedEnsemble).filter(ModelingStep.ModelStep.class::isInstance).count());
        assertEquals(3, Stream.of(modelingSteps).filter(s -> s._algo == Algo.XGBoost).filter(ModelingStep.ModelStep.class::isInstance).count());
        assertEquals(1, Stream.of(modelingSteps).filter(s -> s._algo == Algo.XGBoost).filter(ModelingStep.GridStep.class::isInstance).count());
        assertEquals(2, Stream.of(modelingSteps).filter(s -> s._algo == Algo.XGBoost).filter(ModelingStep.SelectionStep.class::isInstance).count());

        List<String> orderedStepIds = Arrays.stream(modelingSteps).map(s -> s._id).collect(Collectors.toList());
        assertEquals(Arrays.asList(
                "def_1", "grid_1", "grid_2", "grid_3",
                "def_1", "XRT",
                "def_1", "def_2", "def_3", "def_4", "def_5", "grid_1", "lr_annealing",
                "def_1",
                "best", "all", "monotonic",
                "def_1", "def_2", "def_3", "grid_1", "lr_annealing", "lr_search"
        ), orderedStepIds);

    }

    @Test
    public void test_all_default_models() {
        StepDefinition[] allDefaultSteps = sortedProviders.stream()
                .map(name -> new StepDefinition(name, StepDefinition.Alias.defaults))
                .toArray(StepDefinition[]::new);
        ModelingStepsRegistry registry = new ModelingStepsRegistry();
        ModelingStep[] modelingSteps = registry.getOrderedSteps(allDefaultSteps, aml);
        assertEquals((1/*DL*/) + (2/*DRF*/) + (5/*GBM*/) + (1/*GLM*/) + (3/*SE*/) + (3/*XGB*/),
                modelingSteps.length);
    }

    @Test
    public void test_all_grids() {
        StepDefinition[] allGridSteps = sortedProviders.stream()
                .map(name -> new StepDefinition(name, StepDefinition.Alias.grids))
                .toArray(StepDefinition[]::new);
        ModelingStepsRegistry registry = new ModelingStepsRegistry();
        ModelingStep[] modelingSteps = registry.getOrderedSteps(allGridSteps, aml);
        assertEquals((3/*DL*/) + (1/*GBM*/) + (1/*XGB*/),
                modelingSteps.length);
    }

    @Test
    public void test_registration_by_id() {
        StepDefinition[] byIdSteps = new StepDefinition[]{
                new StepDefinition(Algo.DRF.name(), new String[]{"XRT"}),
                new StepDefinition(Algo.XGBoost.name(), new String[]{"grid_1"}),
                new StepDefinition(Algo.StackedEnsemble.name(), new String[]{"all", "best"})
        };
        ModelingStepsRegistry registry = new ModelingStepsRegistry();
        ModelingStep[] modelingSteps = registry.getOrderedSteps(byIdSteps, aml);
        assertEquals(4, modelingSteps.length);
        assertEquals(Arrays.asList("XRT", "grid_1", "all", "best"), Arrays.stream(modelingSteps).map(s -> s._id).collect(Collectors.toList()));
        assertEquals(Arrays.asList(10, 100, 10, 10), Arrays.stream(modelingSteps).map(s -> s._weight).collect(Collectors.toList()));
    }

    @Test
    public void test_registration_with_weight() {
        StepDefinition[] withWeightSteps = new StepDefinition[]{
                new StepDefinition(Algo.DRF.name(), new Step[] { new Step("XRT", 666)}),
                new StepDefinition(Algo.GBM.name(), new Step[] { new Step("def_3", 42), new Step("grid_1", 777)})
        };
        ModelingStepsRegistry registry = new ModelingStepsRegistry();
        ModelingStep[] modelingSteps = registry.getOrderedSteps(withWeightSteps, aml);
        assertEquals(3, modelingSteps.length);
        assertEquals(Arrays.asList("XRT", "def_3", "grid_1"), Arrays.stream(modelingSteps).map(s -> s._id).collect(Collectors.toList()));
        assertEquals(Arrays.asList(666, 42, 777), Arrays.stream(modelingSteps).map(s -> s._weight).collect(Collectors.toList()));
    }

    @Test(expected = IllegalArgumentException.class)
    public void test_unknown_provider_names_raise_error() {
        StepDefinition[] unknownProviderSteps = new StepDefinition[]{
                new StepDefinition("dummy", StepDefinition.Alias.all)
        };
        ModelingStepsRegistry registry = new ModelingStepsRegistry();
        ModelingStep[] modelingSteps = registry.getOrderedSteps(unknownProviderSteps, aml);
        assertEquals(0, modelingSteps.length);
    }

    @Test
    public void test_unknown_ids_are_skipped_with_warning() {
        StepDefinition[] unknownIdsSteps = new StepDefinition[]{
                new StepDefinition(Algo.GBM.name(), new String[] {"dummy"})
        };
        ModelingStepsRegistry registry = new ModelingStepsRegistry();
        ModelingStep[] modelingSteps = registry.getOrderedSteps(unknownIdsSteps, aml);
        assertEquals(0, modelingSteps.length);
        assertTrue(Stream.of(aml.eventLog()._events)
                .anyMatch(e ->
                        e.getLevel() == EventLogEntry.Level.Warn
                        && e.getMessage().equals("Step 'dummy' not defined in provider 'GBM': skipping it.")));
    }

}


text:
package com.snowplowanalytics
package snowplow
package enrich
package common
package enrichments

// Scalaz
import scalaz._
import Scalaz._

// json4s
import org.json4s.scalaz.JsonScalaz._
import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._

// Iglu
import iglu.client.{
  SchemaKey,
  SchemaCriterion,
  Resolver
}
import iglu.client.validation.ValidatableJsonMethods._
import iglu.client.validation.ProcessingMessageMethods._
import iglu.client.validation.ValidatableJsonNode

// This project
import registry.{
  Enrichment,
  AnonIpEnrichment,
  IpLookupsEnrichment,
  RefererParserEnrichment,
  CampaignAttributionEnrichment,
  UserAgentUtilsEnrichment,
  UaParserEnrichment,
  CurrencyConversionEnrichment,
  JavascriptScriptEnrichment,
  EventFingerprintEnrichment,
  CookieExtractorEnrichment,
  WeatherEnrichment,
  UserAgentUtilsEnrichmentConfig,
  UaParserEnrichmentConfig,
  CurrencyConversionEnrichmentConfig,
  JavascriptScriptEnrichmentConfig,
  EventFingerprintEnrichmentConfig,
  CookieExtractorEnrichmentConfig,
  WeatherEnrichmentConfig
}

import utils.ScalazJson4sUtils

/**
 * Companion which holds a constructor
 * for the EnrichmentRegistry.
 */
object EnrichmentRegistry {

  private val EnrichmentConfigSchemaCriterion = SchemaCriterion("com.snowplowanalytics.snowplow", "enrichments", "jsonschema", 1, 0)

  /**
   * Constructs our EnrichmentRegistry
   * from the supplied JSON JValue.
   *
   * @param node A JValue representing an array of enrichment JSONs
   * @param localMode Whether to use the local MaxMind data file
   *        Enabled for tests
   * @param resolver (implicit) The Iglu resolver used for
   *        schema lookup and validation
   * @return Validation boxing an EnrichmentRegistry object
   *         containing enrichments configured from node
   * @todo remove all the JsonNode round-tripping when
   *       we have ValidatableJValue
   */
  def parse(node: JValue, localMode: Boolean)(implicit resolver: Resolver): ValidatedNelMessage[EnrichmentRegistry] =  {

    // Check schema, validate against schema, convert to List[JValue]
    val enrichments: ValidatedNelMessage[List[JValue]] = for {
        d <- asJsonNode(node).verifySchemaAndValidate(EnrichmentConfigSchemaCriterion, true)
      } yield (fromJsonNode(d) match {
        case JArray(x) => x
        case _ => throw new Exception("Enrichments JSON not an array - the enrichments JSON schema should prevent this happening")
      })

    // Check each enrichment validates against its own schema
    val configs: ValidatedNelMessage[EnrichmentMap] = (for {
        jsons <- enrichments
      } yield for {
        json  <- jsons
      } yield for {
        pair  <- asJsonNode(json).validateAndIdentifySchema(dataOnly = true)
        conf  <- buildEnrichmentConfig(pair._1, fromJsonNode(pair._2), localMode)
      } yield conf)
      .flatMap(_.sequenceU) // Swap nested List[scalaz.Validation[...]
      .map(_.flatten.toMap) // Eliminate our Option boxing (drop Nones)

    // Build an EnrichmentRegistry from the Map
    configs.bimap(
      e => NonEmptyList(e.toString.toProcessingMessage),
      s => EnrichmentRegistry(s))
  }

  /**
   * Builds an Enrichment from a JValue if it has a
   * recognized name field and matches a schema key
   *
   * @param enrichmentConfig JValue with enrichment information
   * @param schemaKey SchemaKey for the JValue
   * @param localMode Whether to use the local MaxMind data file
   *        Enabled for tests
   * @return ValidatedNelMessage boxing Option boxing Tuple2 containing
   *         the Enrichment object and the schemaKey
   */
  private def buildEnrichmentConfig(schemaKey: SchemaKey, enrichmentConfig: JValue, localMode: Boolean): ValidatedNelMessage[Option[Tuple2[String, Enrichment]]] = {

    val enabled = ScalazJson4sUtils.extract[Boolean](enrichmentConfig, "enabled").toValidationNel

    enabled match {
      case Success(false) => None.success.toValidationNel // Enrichment is disabled
      case e => {
        val name = ScalazJson4sUtils.extract[String](enrichmentConfig, "name").toValidationNel
        name.flatMap( nm => {

          if (nm == "ip_lookups") {
            IpLookupsEnrichment.parse(enrichmentConfig, schemaKey, localMode).map((nm, _).some)
          } else if (nm == "anon_ip") {
            AnonIpEnrichment.parse(enrichmentConfig, schemaKey).map((nm, _).some)
          } else if (nm == "referer_parser") {
            RefererParserEnrichment.parse(enrichmentConfig, schemaKey).map((nm, _).some)
          } else if (nm == "campaign_attribution") {
            CampaignAttributionEnrichment.parse(enrichmentConfig, schemaKey).map((nm, _).some)
          } else if (nm == "user_agent_utils_config") {
            UserAgentUtilsEnrichmentConfig.parse(enrichmentConfig, schemaKey).map((nm, _).some)
          } else if (nm == "ua_parser_config") {
            UaParserEnrichmentConfig.parse(enrichmentConfig, schemaKey).map((nm, _).some)
          } else if (nm == "currency_conversion_config") {
            CurrencyConversionEnrichmentConfig.parse(enrichmentConfig, schemaKey).map((nm, _).some)
          } else if (nm == "javascript_script_config") {
            JavascriptScriptEnrichmentConfig.parse(enrichmentConfig, schemaKey).map((nm, _).some)
          } else if (nm == "event_fingerprint_config") {
            EventFingerprintEnrichmentConfig.parse(enrichmentConfig, schemaKey).map((nm, _).some)
          } else if (nm == "cookie_extractor_config") {
            CookieExtractorEnrichmentConfig.parse(enrichmentConfig, schemaKey).map((nm, _).some)
          } else if (nm == "weather_enrichment_config") {
            WeatherEnrichmentConfig.parse(enrichmentConfig, schemaKey).map((nm, _).some)
          } else {
            None.success // Enrichment is not recognized yet
          }
        })
      }
    }

  }

}

/**
 * A registry to hold all of our enrichment
 * configurations.
 *
 * In the future this may evolve to holding
 * all of our enrichments themselves.
 *
 * @param configs Map whose keys are enrichment
 *        names and whose values are the
 *        corresponding enrichment objects
 */
case class EnrichmentRegistry(private val configs: EnrichmentMap) {

  /**
   * Returns an Option boxing the AnonIpEnrichment
   * config value if present, or None if not
   *
   * @return Option boxing the AnonIpEnrichment instance
   */
  def getAnonIpEnrichment: Option[AnonIpEnrichment] =
    getEnrichment[AnonIpEnrichment]("anon_ip")

  /**
   * Returns an Option boxing the IpLookupsEnrichment
   * config value if present, or None if not
   *
   * @return Option boxing the IpLookupsEnrichment instance
   */
  def getIpLookupsEnrichment: Option[IpLookupsEnrichment] =
    getEnrichment[IpLookupsEnrichment]("ip_lookups")

  /**
   * Returns an Option boxing the RefererParserEnrichment
   * config value if present, or None if not
   *
   * @return Option boxing the RefererParserEnrichment instance
   */
  def getRefererParserEnrichment: Option[RefererParserEnrichment] =
    getEnrichment[RefererParserEnrichment]("referer_parser")

  /**
   * Returns an Option boxing the CampaignAttributionEnrichment
   * config value if present, or None if not
   *
   * @return Option boxing the CampaignAttributionEnrichment instance
   */
  def getCampaignAttributionEnrichment: Option[CampaignAttributionEnrichment] =
    getEnrichment[CampaignAttributionEnrichment]("campaign_attribution")

  /**
   * Returns an Option boxing the CurrencyConversionEnrichment
   * config value if present, or None if not
   *
   * @return Option boxing the CurrencyConversionEnrichment instance
   */
  def getCurrencyConversionEnrichment: Option[CurrencyConversionEnrichment] =
    getEnrichment[CurrencyConversionEnrichment]("currency_conversion_config")

  /**
   * Returns an Option boxing the UserAgentUtilsEnrichment
   * config value if present, or None if not
   *
   * @return Option boxing the UserAgentUtilsEnrichment instance
   */
  def getUserAgentUtilsEnrichment: Option[UserAgentUtilsEnrichment.type] =
    getEnrichment[UserAgentUtilsEnrichment.type]("user_agent_utils_config")

  /**
   * Returns an Option boxing the UaParserEnrichment
   * config value if present, or None if not
   *
   * @return Option boxing the UaParserEnrichment instance
   */
  def getUaParserEnrichment: Option[UaParserEnrichment.type] =
    getEnrichment[UaParserEnrichment.type]("ua_parser_config")

  /**
   * Returns an Option boxing the JavascriptScriptEnrichment
   * config value if present, or None if not
   *
   * @return Option boxing the JavascriptScriptEnrichment instance
   */
  def getJavascriptScriptEnrichment: Option[JavascriptScriptEnrichment] =
    getEnrichment[JavascriptScriptEnrichment]("javascript_script_config")

  /**
   * Returns an Option boxing the getEventFingerprintEnrichment
   * config value if present, or None if not
   *
   * @return Option boxing the getEventFingerprintEnrichment instance
   */
  def getEventFingerprintEnrichment: Option[EventFingerprintEnrichment] =
    getEnrichment[EventFingerprintEnrichment]("event_fingerprint_config")

  /*
   * Returns an Option boxing the CookieExtractorEnrichment
   * config value if present, or None if not
   *
   * @return Option boxing the CookieExtractorEnrichment instance
   */
  def getCookieExtractorEnrichment: Option[CookieExtractorEnrichment] =
    getEnrichment[CookieExtractorEnrichment]("cookie_extractor_config")

  /**
   * Returns an Option boxing the WeatherEnrichment
   * config value if present, or None if not
   *
   * @return Option boxing the WeatherEnrichment instance
   */
  def getWeatherEnrichment: Option[WeatherEnrichment] =
    getEnrichment[WeatherEnrichment]("weather_enrichment_config")

  /**
   * Returns an Option boxing an Enrichment
   * config value if present, or None if not
   *
   * @tparam A Expected type of the enrichment to get
   * @param name The name of the enrichment to get
   * @return Option boxing the enrichment
   */
  private def getEnrichment[A <: Enrichment: Manifest](name: String): Option[A] =
    configs.get(name).map(cast[A](_))

  /**
   * Adapted from http://stackoverflow.com/questions/6686992/scala-asinstanceof-with-parameterized-types
   * Used to convert an Enrichment to a
   * specific subtype of Enrichment
   *
   * @tparam A Type to cast to
   * @param a The object to cast to type A
   * @return a, converted to type A
   */
  private def cast[A <: AnyRef : Manifest](a : Any) : A =
    manifest.runtimeClass.cast(a).asInstanceOf[A]
}


text:
package com.ericmguimaraes.gaso.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class StringUtils {

    public static String formatMoney(String vlr) {

        NumberFormat moneyFormat = NumberFormat.getCurrencyInstance(new Locale(
                "pt", "BR"));
        DecimalFormat formatter = (DecimalFormat) moneyFormat
                .getCurrencyInstance();
        String symbol = formatter.getCurrency().getSymbol();
        formatter.setNegativePrefix("-" + symbol);
        formatter.setNegativeSuffix("");

        BigDecimal result = new BigDecimal(vlr);
        return formatter.format(result);
    }

    public static String formatMoney(double value) {
        return formatMoney(Double.toString(value));
    }

    public static String millisecondsToDateDMY(long milliseconds) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliseconds);
        return formatter.format(calendar.getTime());
    }

    public static String millisecondsToHM(long milliseconds) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliseconds);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        return String.format("%02d:%02d", hour, minute);
    }
}


text:
This directory contains reSolve adapters:

* [Read Model Adapters](readmodel-adapters/) - specifies how to store read models
* [Event Store Adapters](eventstore-adapters/) - specifies where to store events

![Analytics](https://ga-beacon.appspot.com/UA-118635726-1/packages-adapters-readme?pixel)


text:
using LiteNetLib.Utils;

namespace Game.Network {
    /// <summary>
    /// Simple abstract class defining a packet structure.
    /// </summary>
    public abstract class PacketBase : IEncodable{

        protected NetPacketType type;
        protected int sender;

        #region constructors

        public PacketBase() { }

        public PacketBase(NetPacketType type, int sender) {
            this.type = type;
            this.sender = sender;
        }

        #endregion

        #region properties

        public NetPacketType Type {
            get { return type; }
            set { type = value; }
        }

        public int Sender {
            get { return sender; }
            set { sender = value; }
        }

        #endregion

        #region virtual base functions

        /// <summary>
        /// Converts this packet into a byte array using the given writer.
        /// This method should be overridden in order to serialize custom fields.
        /// </summary>
        /// <param name="writer">the writer containing the buffer</param>
        public virtual void Serialize(NetDataWriter writer) {
            writer.Put((ushort)type);
            writer.Put(sender);
        }

        /// <summary>
        /// Extracts the packed data from the reader.
        /// This method should be overridden to deserialize custom fields.
        /// </summary>
        /// <param name="reader">the reader containing the buffer</param>
        public virtual void Deserialize(NetDataReader reader) {
            sender = reader.GetInt();
        }

        #endregion

        #region Static reader

        public static T Read<T> (NetDataReader reader) where T : PacketBase, new() {
            T packet = new T();
            packet.Deserialize(reader);
            return packet;
        }

        #endregion
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE126_Buffer_Overread__malloc_char_memmove_15.c
Label Definition File: CWE126_Buffer_Overread__malloc.label.xml
Template File: sources-sink-15.tmpl.c
*/
/*
 * @description
 * CWE: 126 Buffer Over-read
 * BadSource:  Use a small buffer
 * GoodSource: Use a large buffer
 * Sink: memmove
 *    BadSink : Copy data to string using memmove
 * Flow Variant: 15 Control flow: switch(6)
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifndef OMITBAD

void CWE126_Buffer_Overread__malloc_char_memmove_15_bad()
{
    char * data;
    data = NULL;
    switch(6)
    {
    case 6:
        /* FLAW: Use a small buffer */
        data = (char *)malloc(50*sizeof(char));
        memset(data, 'A', 50-1); /* fill with 'A's */
        data[50-1] = '\0'; /* null terminate */
        break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
    {
        char dest[100];
        memset(dest, 'C', 100-1);
        dest[100-1] = '\0'; /* null terminate */
        /* POTENTIAL FLAW: using memmove with the length of the dest where data
         * could be smaller than dest causing buffer overread */
        memmove(dest, data, strlen(dest)*sizeof(char));
        dest[100-1] = '\0';
        printLine(dest);
        free(data);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B1() - use goodsource and badsink by changing the switch to switch(5) */
static void goodG2B1()
{
    char * data;
    data = NULL;
    switch(5)
    {
    case 6:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    default:
        /* FIX: Use a large buffer */
        data = (char *)malloc(100*sizeof(char));
        memset(data, 'A', 100-1); /* fill with 'A's */
        data[100-1] = '\0'; /* null terminate */
        break;
    }
    {
        char dest[100];
        memset(dest, 'C', 100-1);
        dest[100-1] = '\0'; /* null terminate */
        /* POTENTIAL FLAW: using memmove with the length of the dest where data
         * could be smaller than dest causing buffer overread */
        memmove(dest, data, strlen(dest)*sizeof(char));
        dest[100-1] = '\0';
        printLine(dest);
        free(data);
    }
}

/* goodG2B2() - use goodsource and badsink by reversing the blocks in the switch */
static void goodG2B2()
{
    char * data;
    data = NULL;
    switch(6)
    {
    case 6:
        /* FIX: Use a large buffer */
        data = (char *)malloc(100*sizeof(char));
        memset(data, 'A', 100-1); /* fill with 'A's */
        data[100-1] = '\0'; /* null terminate */
        break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
    {
        char dest[100];
        memset(dest, 'C', 100-1);
        dest[100-1] = '\0'; /* null terminate */
        /* POTENTIAL FLAW: using memmove with the length of the dest where data
         * could be smaller than dest causing buffer overread */
        memmove(dest, data, strlen(dest)*sizeof(char));
        dest[100-1] = '\0';
        printLine(dest);
        free(data);
    }
}

void CWE126_Buffer_Overread__malloc_char_memmove_15_good()
{
    goodG2B1();
    goodG2B2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE126_Buffer_Overread__malloc_char_memmove_15_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE126_Buffer_Overread__malloc_char_memmove_15_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
import React, { PropTypes } from 'react';
import { IconButton } from '@jenkins-cd/design-language';

import { GithubIcon } from './GithubIcon';

export default function GitHubDefaultOption(props) {
    function onSelect() {
        if (props.onSelect) {
            props.onSelect();
        }
    }

    const className = `${props.className} monochrome ${props.isSelected ? 'active' : ''}`;

    return (
        <IconButton className={className} label={props.label} onClick={onSelect}>
            <GithubIcon />
        </IconButton>
    );
}

GitHubDefaultOption.propTypes = {
    className: PropTypes.string,
    label: PropTypes.string,
    onSelect: PropTypes.func,
    isSelected: PropTypes.bool,
};

GitHubDefaultOption.defaultProps = {
    className: 'github-creation',
    label: 'GitHub',
};


text:
{{'profile'| translate}}

            *

            <ng-form name="innerForm">

                    <ui-select  ng-model="selectedTei[attribute.id]"
                                theme="select2"
                                ng-required="attribute.mandatory || attribute.unique"
                                name="foo"
                                d2-attribute-validator
                                attribute-data={{attribute}}
                                selected-program-id={{selectedProgram.id}}
                                selected-tei-id={{selectedTei.trackedEntityInstance}}
                                ng-disabled="editingDisabled"
                                on-select="teiValueUpdated(selectedTei, attribute.id)"
                                style="width:100%;">
                        <ui-select-match allow-clear="true"  class="form-control-ui-select"  placeholder="{{'select_or_search' | translate}}">{{$select.selected.name  || $select.selected}}</ui-select-match>
                        <ui-select-choices  repeat="option.name as option in optionSets[attributesById[attribute.id].optionSet.id].options | filter: $select.search | limitTo:maxOptionSize">

                        </ui-select-choices>
                    </ui-select>

                        <input type="text"
                               placeholder="{{dhis2CalendarFormat.keyDateFormat}}"
                               name="foo"
                               class="form-control"
                               d2-date
                               d2-date-validator
                               max-date="attribute.allowFutureDate ? '' : 0"
                               ng-model="selectedTei[attribute.id]"
                               ng-model-options="{ updateOn: 'blur', allowInvalid: true }"
                               d2-attribute-validator
                               attribute-data={{attribute}}
                               selected-program-id={{selectedProgram.id}}
                               selected-tei-id={{selectedTei.trackedEntityInstance}}
                               ng-disabled="editingDisabled"
                               blur-or-change="teiValueUpdated(selectedTei, attribute.id)"
                               ng-required="attribute.mandatory || attribute.unique"/>

                        <input type="checkbox"
                               name="foo"
                               class="form-control"
                               ng-model="selectedTei[attribute.id]"
                               ng-model-options="{ updateOn: 'blur', allowInvalid: true }"
                               d2-attribute-validator
                               attribute-data={{attribute}}
                               selected-program-id={{selectedProgram.id}}
                               selected-tei-id={{selectedTei.trackedEntityInstance}}
                               ng-disabled="editingDisabled"
                               ng-change="teiValueUpdated(selectedTei, attribute.id)"
                               ng-required="attribute.mandatory || attribute.unique"/>

                        <select name="foo"
                                ng-model="selectedTei[attribute.id]"
                                ng-model-options="{ updateOn: 'blur', allowInvalid: true }"
                                d2-attribute-validator
                                attribute-data={{attribute}}
                                selected-program-id={{selectedProgram.id}}
                                selected-tei-id={{selectedTei.trackedEntityInstance}}
                                class="form-control"
                                ng-disabled="editingDisabled"
                                ng-change="teiValueUpdated(selectedTei, attribute.id)"
                                ng-required="attribute.mandatory || attribute.unique">
                            <option value="">{{'please_select'| translate}}</option>
                            <option value="false">{{'no'| translate}}</option>
                            <option value="true">{{'yes'| translate}}</option>
                        </select>

                        <input type="number"
                               name="foo"
                               class="form-control"
                               ng-model="selectedTei[attribute.id]"
                               ng-model-options="{ updateOn: 'blur', allowInvalid: true }"
                               d2-attribute-validator
                               attribute-data={{attribute}}
                               selected-program-id={{selectedProgram.id}}
                               selected-tei-id={{selectedTei.trackedEntityInstance}}
                               d2-number-validator
                               number-type={{attribute.valueType}}
                               ng-disabled="editingDisabled"
                               ng-blur="teiValueUpdated(selectedTei, attribute.id)"
                               ng-required="attribute.mandatory || attribute.unique"/>

                        <input type="email"
                               name="foo"
                               class="form-control"
                               ng-model="selectedTei[attribute.id]"
                               ng-model-options="{ updateOn: 'blur', allowInvalid: true }"
                               d2-attribute-validator
                               attribute-data={{attribute}}
                               selected-program-id={{selectedProgram.id}}
                               selected-tei-id={{selectedTei.trackedEntityInstance}}
                               ng-disabled="editingDisabled"
                               ng-blur="teiValueUpdated(selectedTei, attribute.id)"
                               ng-required="attribute.mandatory || attribute.unique"/>

                        <textarea row="3"
                               name="foo"
                               class="form-control"
                               ng-model="selectedTei[attribute.id]"
                               ng-model-options="{ updateOn: 'blur', allowInvalid: true }"
                               d2-attribute-validator
                               attribute-data={{attribute}}
                               selected-program-id={{selectedProgram.id}}
                               selected-tei-id={{selectedTei.trackedEntityInstance}}
                               ng-disabled="editingDisabled"
                               ng-blur="teiValueUpdated(selectedTei, attribute.id)"
                               ng-required="attribute.mandatory || attribute.unique">
                        </textarea>/>

                        <input type="text"
                               name="foo"
                               class="form-control-trimmed"
                               ng-model="selectedTei[attribute.id]"
                               ng-model-options="{ updateOn: 'blur', allowInvalid: true }"
                               d2-attribute-validator
                               attribute-data={{attribute}}
                               selected-program-id={{selectedProgram.id}}
                               selected-tei-id={{selectedTei.trackedEntityInstance}}
                               ng-model-options="{ updateOn: 'blur', allowInvalid: true }"
                               ng-disabled="true"
                               ng-blur="teiValueUpdated(selectedTei, attribute.id)"
                               style="width:75%;"
                               ng-required="attribute.mandatory || attribute.unique"/>

                        <input type="text"
                               name="foo"
                               class="form-control"
                               ng-model="selectedTei[attribute.id]"
                               ng-model-options="{ updateOn: 'blur', allowInvalid: true }"
                               d2-attribute-validator
                               attribute-data={{attribute}}
                               selected-program-id={{selectedProgram.id}}
                               selected-tei-id={{selectedTei.trackedEntityInstance}}
                               ng-disabled="editingDisabled"
                               ng-blur="teiValueUpdated(selectedTei, attribute.id)"
                               ng-required="attribute.mandatory || attribute.unique"/>

                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                        {{warningMessages[attribute.id]}}

                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                        {{errorMessages[attribute.id]}}

            </ng-form>


text:
<?xml version="1.0" encoding="utf-8" ?>
<widget id="RadioButtonList.widget.AttrRadioButtonList" needsEntityContext="true" xmlns="http://www.mendix.com/widget/1.0/">
  <name>Attribute Radiobutton List</name>
  <description>Creates a radiobutton list based on an enumeration or boolean attribute.</description>

  <icon>iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACx
jwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAABl0RVh0
U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuND6NzHYAAAGVSURBVDhPrVPBasJAFLRK6aG3/kB/wZNe
PPkHjaU38R88FHIKVAXBiCd/wXuhSCCUIniQnPsBAQmEQMCKBEXidGfrE2y0lNLAsslm583szNsc
gIvcfz+qaF6NazWu9uNGzbck+xVhGH/g+XWGxycbtfsHPfOb6z+KTdNd4c17x51RQ7vdhuM48H0f
ruui2+3qdf4/WYTS+NM0TYzHY8zncwRBgDAMEUUR4jjGZDKBZVm6iHoKh0IEUx4ZzoEXiwWWyyWm
06nex/0HP/jCM1K2MHMejUZoNBoYDodaxWq1QpIk6Pf72pOjAjSKZxbZBDebTdTrdVSrVfR6PQ1e
r9eYzb4MPipAt2mYnJnMBBuGgUqlgnK5rMGbzUYr4f6MArothlE2mQkuFovodDoavN1u4XleVgHP
xKjoNg1jIdu2USqVNJhrBKdpisFgkPVAUmBUdFsME9kCJnsmBebJXJkvc2ZUYpjIJjPBrVaLffCy
xxzfI9WJupnIwKjoNpUQSNnSidx3tqWVkss/3wWpKrfu25w/xfoJ0eY0PiQfhZcAAAAASUVORK5C
YII=</icon>

  <properties>
		<property key="entity" type="attribute" required="true">

Target attribute

		  <category>Data source</category>
		  <description>The attribute which has to be rendered as a radiobutton list.</description>
		  <attributeTypes>
			<attributeType name="Enum"/>
			<attributeType name="Boolean"/>
		  </attributeTypes>
		</property>
		<property key="direction" type="enumeration" defaultValue="vertical">

Direction

			<category>Behavior</category>
			<description>This field determines the display direction of the radiobutton options.</description>
			<enumerationValues>
				<enumerationValue key="horizontal">Horizontal</enumerationValue>
				<enumerationValue key="vertical">Vertical</enumerationValue>
			</enumerationValues>
		</property>
		<property key="captiontrue" type="translatableString" required="false">

True label (Boolean attribute)

			<category>Behavior</category>
			<description>In the case of the target attribute being a boolean, the text for the label can be defined here.</description>
		</property>
		<property key="captionfalse" type="translatableString" required="false">

False label (Boolean attribute)

			<category>Behavior</category>
			<description>In the case of the target attribute being a boolean, the text for the label can be defined here.</description>
		</property>
		<property key="readonly" type="boolean" required="true" defaultValue="false">

Read only

		  <category>Behavior</category>
		  <description>If true, the widget is not editable.</description>
		</property>
		<property key="onchangeAction" type="microflow" required="false">

On change

			<category>Events</category>
			<description></description>
			<returnType type="Void"></returnType>
		</property>
	</properties>
</widget>