text:
package org.elasticsearch.percolator;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.DelegatingAnalyzerWrapper;
import org.apache.lucene.index.BinaryDocValues;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReaderContext;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.ReaderUtil;
import org.apache.lucene.index.memory.MemoryIndex;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
import org.apache.lucene.search.join.BitSetProducer;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.BitDocIdSet;
import org.apache.lucene.util.BitSet;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.SetOnce;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ResourceNotFoundException;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.InputStreamStreamInput;
import org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.xcontent.XContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.analysis.FieldNameAnalyzer;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.fielddata.IndexFieldDataCache;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.DocumentMapperForType;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryRewriteContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryShardException;
import org.elasticsearch.indices.breaker.CircuitBreakerService;
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Objects;
import java.util.function.Supplier;

import static org.elasticsearch.index.mapper.SourceToParse.source;
import static org.elasticsearch.percolator.PercolatorFieldMapper.parseQuery;

public class PercolateQueryBuilder extends AbstractQueryBuilder<PercolateQueryBuilder> {
    public static final String NAME = "percolate";

    private static final DeprecationLogger DEPRECATION_LOGGER = new DeprecationLogger(Loggers.getLogger(ParseField.class));

    static final ParseField DOCUMENT_FIELD = new ParseField("document");
    private static final ParseField QUERY_FIELD = new ParseField("field");
    private static final ParseField DOCUMENT_TYPE_FIELD = new ParseField("document_type");
    private static final ParseField INDEXED_DOCUMENT_FIELD_INDEX = new ParseField("index");
    private static final ParseField INDEXED_DOCUMENT_FIELD_TYPE = new ParseField("type");
    private static final ParseField INDEXED_DOCUMENT_FIELD_ID = new ParseField("id");
    private static final ParseField INDEXED_DOCUMENT_FIELD_ROUTING = new ParseField("routing");
    private static final ParseField INDEXED_DOCUMENT_FIELD_PREFERENCE = new ParseField("preference");
    private static final ParseField INDEXED_DOCUMENT_FIELD_VERSION = new ParseField("version");

    private final String field;
    @Deprecated
    private final String documentType;
    private final BytesReference document;
    private final XContentType documentXContentType;

    private final String indexedDocumentIndex;
    private final String indexedDocumentType;
    private final String indexedDocumentId;
    private final String indexedDocumentRouting;
    private final String indexedDocumentPreference;
    private final Long indexedDocumentVersion;
    private final Supplier<BytesReference> documentSupplier;

    /**
     * @deprecated use {@link #PercolateQueryBuilder(String, BytesReference, XContentType)} with the document content
     * type to avoid autodetection.
     */
    @Deprecated
    public PercolateQueryBuilder(String field, String documentType, BytesReference document) {
        this(field, documentType, document, XContentFactory.xContentType(document));
    }

    /**
     * Creates a percolator query builder instance for percolating a provided document.
     *
     * @param field                     The field that contains the percolator query
     * @param document                  The binary blob containing document to percolate
     * @param documentXContentType      The content type of the binary blob containing the document to percolate
     */
    public PercolateQueryBuilder(String field, BytesReference document, XContentType documentXContentType) {
        this(field, null, document, documentXContentType);
    }

    @Deprecated
    public PercolateQueryBuilder(String field, String documentType, BytesReference document, XContentType documentXContentType) {
        if (field == null) {
            throw new IllegalArgumentException("[field] is a required argument");
        }
        if (document == null) {
            throw new IllegalArgumentException("[document] is a required argument");
        }
        this.field = field;
        this.documentType = documentType;
        this.document = document;
        this.documentXContentType = Objects.requireNonNull(documentXContentType);
        indexedDocumentIndex = null;
        indexedDocumentType = null;
        indexedDocumentId = null;
        indexedDocumentRouting = null;
        indexedDocumentPreference = null;
        indexedDocumentVersion = null;
        this.documentSupplier = null;
    }

    private PercolateQueryBuilder(String field, String documentType, Supplier<BytesReference> documentSupplier) {
        if (field == null) {
            throw new IllegalArgumentException("[field] is a required argument");
        }
        this.field = field;
        this.documentType = documentType;
        this.document = null;
        this.documentXContentType = null;
        this.documentSupplier = documentSupplier;
        indexedDocumentIndex = null;
        indexedDocumentType = null;
        indexedDocumentId = null;
        indexedDocumentRouting = null;
        indexedDocumentPreference = null;
        indexedDocumentVersion = null;
    }

    /**
     * Creates a percolator query builder instance for percolating a document in a remote index.
     *
     * @param field                     The field that contains the percolator query
     * @param indexedDocumentIndex      The index containing the document to percolate
     * @param indexedDocumentType       The type containing the document to percolate
     * @param indexedDocumentId         The id of the document to percolate
     * @param indexedDocumentRouting    The routing value for the document to percolate
     * @param indexedDocumentPreference The preference to use when fetching the document to percolate
     * @param indexedDocumentVersion    The expected version of the document to percolate
     */
    public PercolateQueryBuilder(String field, String indexedDocumentIndex, String indexedDocumentType, String indexedDocumentId,
                                 String indexedDocumentRouting, String indexedDocumentPreference, Long indexedDocumentVersion) {
        this(field, null, indexedDocumentIndex, indexedDocumentType, indexedDocumentId, indexedDocumentRouting,
            indexedDocumentPreference, indexedDocumentVersion);
    }

    @Deprecated
    public PercolateQueryBuilder(String field, String documentType, String indexedDocumentIndex,
                                 String indexedDocumentType, String indexedDocumentId, String indexedDocumentRouting,
                                 String indexedDocumentPreference, Long indexedDocumentVersion) {
        if (field == null) {
            throw new IllegalArgumentException("[field] is a required argument");
        }
        if (indexedDocumentIndex == null) {
            throw new IllegalArgumentException("[index] is a required argument");
        }
        if (indexedDocumentType == null) {
            throw new IllegalArgumentException("[type] is a required argument");
        }
        if (indexedDocumentId == null) {
            throw new IllegalArgumentException("[id] is a required argument");
        }
        this.field = field;
        this.documentType = documentType;
        this.indexedDocumentIndex = indexedDocumentIndex;
        this.indexedDocumentType = indexedDocumentType;
        this.indexedDocumentId = indexedDocumentId;
        this.indexedDocumentRouting = indexedDocumentRouting;
        this.indexedDocumentPreference = indexedDocumentPreference;
        this.indexedDocumentVersion = indexedDocumentVersion;
        this.document = null;
        this.documentXContentType = null;
        this.documentSupplier = null;
    }

    /**
     * Read from a stream.
     */
    PercolateQueryBuilder(StreamInput in) throws IOException {
        super(in);
        field = in.readString();
        if (in.getVersion().before(Version.V_6_0_0_beta1)) {
            documentType = in.readString();
        } else {
            documentType = in.readOptionalString();
        }
        indexedDocumentIndex = in.readOptionalString();
        indexedDocumentType = in.readOptionalString();
        indexedDocumentId = in.readOptionalString();
        indexedDocumentRouting = in.readOptionalString();
        indexedDocumentPreference = in.readOptionalString();
        if (in.readBoolean()) {
            indexedDocumentVersion = in.readVLong();
        } else {
            indexedDocumentVersion = null;
        }
        document = in.readOptionalBytesReference();
        if (document != null) {
            if (in.getVersion().onOrAfter(Version.V_5_3_0)) {
                documentXContentType = XContentType.readFrom(in);
            } else {
                documentXContentType = XContentFactory.xContentType(document);
            }
        } else {
            documentXContentType = null;
        }
        documentSupplier = null;
    }

    @Override
    protected void doWriteTo(StreamOutput out) throws IOException {
        if (documentSupplier != null) {
            throw new IllegalStateException("supplier must be null, can't serialize suppliers, missing a rewriteAndFetch?");
        }
        out.writeString(field);
        if (out.getVersion().before(Version.V_6_0_0_beta1)) {
            out.writeString(documentType);
        } else {
            out.writeOptionalString(documentType);
        }
        out.writeOptionalString(indexedDocumentIndex);
        out.writeOptionalString(indexedDocumentType);
        out.writeOptionalString(indexedDocumentId);
        out.writeOptionalString(indexedDocumentRouting);
        out.writeOptionalString(indexedDocumentPreference);
        if (indexedDocumentVersion != null) {
            out.writeBoolean(true);
            out.writeVLong(indexedDocumentVersion);
        } else {
            out.writeBoolean(false);
        }
        out.writeOptionalBytesReference(document);
        if (document != null && out.getVersion().onOrAfter(Version.V_5_3_0)) {
            documentXContentType.writeTo(out);
        }
    }

    @Override
    protected void doXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject(NAME);
        builder.field(DOCUMENT_TYPE_FIELD.getPreferredName(), documentType);
        builder.field(QUERY_FIELD.getPreferredName(), field);
        if (document != null) {
            builder.rawField(DOCUMENT_FIELD.getPreferredName(), document);
        }
        if (indexedDocumentIndex != null || indexedDocumentType != null || indexedDocumentId != null) {
            if (indexedDocumentIndex != null) {
                builder.field(INDEXED_DOCUMENT_FIELD_INDEX.getPreferredName(), indexedDocumentIndex);
            }
            if (indexedDocumentType != null) {
                builder.field(INDEXED_DOCUMENT_FIELD_TYPE.getPreferredName(), indexedDocumentType);
            }
            if (indexedDocumentId != null) {
                builder.field(INDEXED_DOCUMENT_FIELD_ID.getPreferredName(), indexedDocumentId);
            }
            if (indexedDocumentRouting != null) {
                builder.field(INDEXED_DOCUMENT_FIELD_ROUTING.getPreferredName(), indexedDocumentRouting);
            }
            if (indexedDocumentPreference != null) {
                builder.field(INDEXED_DOCUMENT_FIELD_PREFERENCE.getPreferredName(), indexedDocumentPreference);
            }
            if (indexedDocumentVersion != null) {
                builder.field(INDEXED_DOCUMENT_FIELD_VERSION.getPreferredName(), indexedDocumentVersion);
            }
        }
        printBoostAndQueryName(builder);
        builder.endObject();
    }

    public static PercolateQueryBuilder fromXContent(XContentParser parser) throws IOException {
        float boost = AbstractQueryBuilder.DEFAULT_BOOST;

        String field = null;
        String documentType = null;

        String indexedDocumentIndex = null;
        String indexedDocumentType = null;
        String indexedDocumentId = null;
        String indexedDocumentRouting = null;
        String indexedDocumentPreference = null;
        Long indexedDocumentVersion = null;

        BytesReference source = null;

        String queryName = null;
        String currentFieldName = null;

        XContentParser.Token token;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (token == XContentParser.Token.START_OBJECT) {
                if (DOCUMENT_FIELD.match(currentFieldName)) {
                    try (XContentBuilder builder = XContentFactory.jsonBuilder()) {
                        builder.copyCurrentStructure(parser);
                        builder.flush();
                        source = builder.bytes();
                    }
                } else {
                    throw new ParsingException(parser.getTokenLocation(), "[" + PercolateQueryBuilder.NAME +
                            "] query does not support [" + token + "]");
                }
            } else if (token.isValue() || token == XContentParser.Token.VALUE_NULL) {
                if (QUERY_FIELD.match(currentFieldName)) {
                    field = parser.text();
                } else if (DOCUMENT_TYPE_FIELD.match(currentFieldName)) {
                    documentType = parser.textOrNull();
                } else if (INDEXED_DOCUMENT_FIELD_INDEX.match(currentFieldName)) {
                    indexedDocumentIndex = parser.text();
                } else if (INDEXED_DOCUMENT_FIELD_TYPE.match(currentFieldName)) {
                    indexedDocumentType = parser.text();
                } else if (INDEXED_DOCUMENT_FIELD_ID.match(currentFieldName)) {
                    indexedDocumentId = parser.text();
                } else if (INDEXED_DOCUMENT_FIELD_ROUTING.match(currentFieldName)) {
                    indexedDocumentRouting = parser.text();
                } else if (INDEXED_DOCUMENT_FIELD_PREFERENCE.match(currentFieldName)) {
                    indexedDocumentPreference = parser.text();
                } else if (INDEXED_DOCUMENT_FIELD_VERSION.match(currentFieldName)) {
                    indexedDocumentVersion = parser.longValue();
                } else if (AbstractQueryBuilder.BOOST_FIELD.match(currentFieldName)) {
                    boost = parser.floatValue();
                } else if (AbstractQueryBuilder.NAME_FIELD.match(currentFieldName)) {
                    queryName = parser.text();
                } else {
                    throw new ParsingException(parser.getTokenLocation(), "[" + PercolateQueryBuilder.NAME +
                            "] query does not support [" + currentFieldName + "]");
                }
            } else {
                throw new ParsingException(parser.getTokenLocation(), "[" + PercolateQueryBuilder.NAME +
                        "] query does not support [" + token + "]");
            }
        }

        PercolateQueryBuilder queryBuilder;
        if (source != null) {
            queryBuilder = new PercolateQueryBuilder(field, documentType, source, XContentType.JSON);
        } else if (indexedDocumentId != null) {
            queryBuilder = new PercolateQueryBuilder(field, documentType, indexedDocumentIndex, indexedDocumentType,
                    indexedDocumentId, indexedDocumentRouting, indexedDocumentPreference, indexedDocumentVersion);
        } else {
            throw new IllegalArgumentException("[" + PercolateQueryBuilder.NAME + "] query, nothing to percolate");
        }
        queryBuilder.queryName(queryName);
        queryBuilder.boost(boost);
        return queryBuilder;
    }

    @Override
    protected boolean doEquals(PercolateQueryBuilder other) {
        return Objects.equals(field, other.field)
                && Objects.equals(documentType, other.documentType)
                && Objects.equals(document, other.document)
                && Objects.equals(indexedDocumentIndex, other.indexedDocumentIndex)
                && Objects.equals(indexedDocumentType, other.indexedDocumentType)
                && Objects.equals(documentSupplier, other.documentSupplier)
                && Objects.equals(indexedDocumentId, other.indexedDocumentId);

    }

    @Override
    protected int doHashCode() {
        return Objects.hash(field, documentType, document, indexedDocumentIndex, indexedDocumentType, indexedDocumentId, documentSupplier);
    }

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

    @Override
    protected QueryBuilder doRewrite(QueryRewriteContext queryShardContext) {
        if (document != null) {
            return this;
        } else if (documentSupplier != null) {
            final BytesReference source = documentSupplier.get();
            if (source == null) {
                return this; // not executed yet
            } else {
                return new PercolateQueryBuilder(field, documentType, source, XContentFactory.xContentType(source));
            }
        }
        GetRequest getRequest = new GetRequest(indexedDocumentIndex, indexedDocumentType, indexedDocumentId);
        getRequest.preference("_local");
        getRequest.routing(indexedDocumentRouting);
        getRequest.preference(indexedDocumentPreference);
        if (indexedDocumentVersion != null) {
            getRequest.version(indexedDocumentVersion);
        }
        SetOnce<BytesReference> documentSupplier = new SetOnce<>();
        queryShardContext.registerAsyncAction((client, listener) -> {
            client.get(getRequest, ActionListener.wrap(getResponse -> {
                if (getResponse.isExists() == false) {
                    throw new ResourceNotFoundException(
                        "indexed document [{}/{}/{}] couldn't be found", indexedDocumentIndex, indexedDocumentType, indexedDocumentId
                    );
                }
                if(getResponse.isSourceEmpty()) {
                    throw new IllegalArgumentException(
                        "indexed document [" + indexedDocumentIndex + "/" + indexedDocumentType + "/" + indexedDocumentId
                            + "] source disabled"
                    );
                }
                documentSupplier.set(getResponse.getSourceAsBytesRef());
                listener.onResponse(null);
            }, listener::onFailure));
        });
        return new PercolateQueryBuilder(field, documentType, documentSupplier::get);
    }

    @Override
    protected Query doToQuery(QueryShardContext context) throws IOException {
        // Call nowInMillis() so that this query becomes un-cacheable since we
        // can't be sure that it doesn't use now or scripts
        context.nowInMillis();
        if (indexedDocumentIndex != null || indexedDocumentType != null || indexedDocumentId != null || documentSupplier != null) {
            throw new IllegalStateException("query builder must be rewritten first");
        }

        if (document == null) {
            throw new IllegalStateException("no document to percolate");
        }

        MappedFieldType fieldType = context.fieldMapper(field);
        if (fieldType == null) {
            throw new QueryShardException(context, "field [" + field + "] does not exist");
        }

        if (!(fieldType instanceof PercolatorFieldMapper.FieldType)) {
            throw new QueryShardException(context, "expected field [" + field +
                "] to be of type [percolator], but is of type [" + fieldType.typeName() + "]");
        }

        final ParsedDocument doc;
        final DocumentMapper docMapper;
        final MapperService mapperService = context.getMapperService();
        if (context.getIndexSettings().isSingleType()) {
            Collection<String> types = mapperService.types();
            if (types.size() != 1) {
                throw new IllegalStateException("Only a single type should exist, but [" + types.size() + " types exists");
            }
            String type = types.iterator().next();
            if (documentType != null) {
                DEPRECATION_LOGGER.deprecated("[document_type] parameter has been deprecated because types have been deprecated");
                if (documentType.equals(type) == false) {
                    throw new IllegalArgumentException("specified document_type [" + documentType +
                        "] is not equal to the actual type [" + type + "]");
                }
            }
            docMapper = mapperService.documentMapper(type);
            doc = docMapper.parse(source(context.index().getName(), type, "_temp_id", document, documentXContentType));
        } else {
            if (documentType == null) {
                throw new IllegalArgumentException("[percolate] query is missing required [document_type] parameter");
            }
            DocumentMapperForType docMapperForType = mapperService.documentMapperWithAutoCreate(documentType);
            docMapper = docMapperForType.getDocumentMapper();
            doc = docMapper.parse(source(context.index().getName(), documentType, "_temp_id", document, documentXContentType));
        }

        FieldNameAnalyzer fieldNameAnalyzer = (FieldNameAnalyzer) docMapper.mappers().indexAnalyzer();
        // Need to this custom impl because FieldNameAnalyzer is strict and the percolator sometimes isn't when
        // 'index.percolator.map_unmapped_fields_as_string' is enabled:
        Analyzer analyzer = new DelegatingAnalyzerWrapper(Analyzer.PER_FIELD_REUSE_STRATEGY) {
            @Override
            protected Analyzer getWrappedAnalyzer(String fieldName) {
                Analyzer analyzer = fieldNameAnalyzer.analyzers().get(fieldName);
                if (analyzer != null) {
                    return analyzer;
                } else {
                    return context.getIndexAnalyzers().getDefaultIndexAnalyzer();
                }
            }
        };
        final IndexSearcher docSearcher;
        if (doc.docs().size() > 1) {
            assert docMapper.hasNestedObjects();
            docSearcher = createMultiDocumentSearcher(analyzer, doc);
        } else {
            MemoryIndex memoryIndex = MemoryIndex.fromDocument(doc.rootDoc(), analyzer, true, false);
            docSearcher = memoryIndex.createSearcher();
            docSearcher.setQueryCache(null);
        }

        boolean mapUnmappedFieldsAsString = context.getIndexSettings()
                .getValue(PercolatorFieldMapper.INDEX_MAP_UNMAPPED_FIELDS_AS_STRING_SETTING);
        QueryShardContext percolateShardContext = wrap(context);

        PercolatorFieldMapper.FieldType pft = (PercolatorFieldMapper.FieldType) fieldType;
        PercolateQuery.QueryStore queryStore = createStore(pft.queryBuilderField, percolateShardContext, mapUnmappedFieldsAsString);
        return pft.percolateQuery(queryStore, document, docSearcher);
    }

    public String getField() {
        return field;
    }

    public String getDocumentType() {
        return documentType;
    }

    public BytesReference getDocument() {
        return document;
    }

    //pkg-private for testing
    XContentType getXContentType() {
        return documentXContentType;
    }

    static IndexSearcher createMultiDocumentSearcher(Analyzer analyzer, ParsedDocument doc) {
        RAMDirectory ramDirectory = new RAMDirectory();
        try (IndexWriter indexWriter = new IndexWriter(ramDirectory, new IndexWriterConfig(analyzer))) {
            indexWriter.addDocuments(doc.docs());
            indexWriter.commit();
            DirectoryReader directoryReader = DirectoryReader.open(ramDirectory);
            assert directoryReader.leaves().size() == 1 : "Expected single leaf, but got [" + directoryReader.leaves().size() + "]";
            final IndexSearcher slowSearcher = new IndexSearcher(directoryReader) {

                @Override
                public Weight createNormalizedWeight(Query query, boolean needsScores) throws IOException {
                    BooleanQuery.Builder bq = new BooleanQuery.Builder();
                    bq.add(query, BooleanClause.Occur.MUST);
                    bq.add(Queries.newNestedFilter(), BooleanClause.Occur.MUST_NOT);
                    return super.createNormalizedWeight(bq.build(), needsScores);
                }

            };
            slowSearcher.setQueryCache(null);
            return slowSearcher;
        } catch (IOException e) {
            throw new ElasticsearchException("Failed to create index for percolator with nested document ", e);
        }
    }

    static PercolateQuery.QueryStore createStore(MappedFieldType queryBuilderFieldType,
                                                 QueryShardContext context,
                                                 boolean mapUnmappedFieldsAsString) {
        Version indexVersion = context.indexVersionCreated();
        NamedWriteableRegistry registry = context.getWriteableRegistry();
        return ctx -> {
            LeafReader leafReader = ctx.reader();
            BinaryDocValues binaryDocValues = leafReader.getBinaryDocValues(queryBuilderFieldType.name());
            if (binaryDocValues == null) {
                return docId -> null;
            }
            if (indexVersion.onOrAfter(Version.V_6_0_0_beta2)) {
                return docId -> {
                    if (binaryDocValues.advanceExact(docId)) {
                        BytesRef qbSource = binaryDocValues.binaryValue();
                        try (InputStream in = new ByteArrayInputStream(qbSource.bytes, qbSource.offset, qbSource.length)) {
                            try (StreamInput input = new NamedWriteableAwareStreamInput(new InputStreamStreamInput(in), registry)) {
                                input.setVersion(indexVersion);
                                // Query builder's content is stored via BinaryFieldMapper, which has a custom encoding
                                // to encode multiple binary values into a single binary doc values field.
                                // This is the reason we need to first need to read the number of values and
                                // then the length of the field value in bytes.
                                int numValues = input.readVInt();
                                assert numValues == 1;
                                int valueLength = input.readVInt();
                                assert valueLength > 0;
                                QueryBuilder queryBuilder = input.readNamedWriteable(QueryBuilder.class);
                                assert in.read() == -1;
                                return PercolatorFieldMapper.toQuery(context, mapUnmappedFieldsAsString, queryBuilder);
                            }
                        }
                    } else {
                        return null;
                    }
                };
            } else {
                return docId -> {
                    if (binaryDocValues.advanceExact(docId)) {
                        BytesRef qbSource = binaryDocValues.binaryValue();
                        if (qbSource.length > 0) {
                            XContent xContent = PercolatorFieldMapper.QUERY_BUILDER_CONTENT_TYPE.xContent();
                            try (XContentParser sourceParser = xContent.createParser(context.getXContentRegistry(), qbSource.bytes,
                                qbSource.offset, qbSource.length)) {
                                return parseQuery(context, mapUnmappedFieldsAsString, sourceParser);
                            }
                        } else {
                            return null;
                        }
                    } else {
                        return null;
                    }
                };
            }
        };
    }

    static QueryShardContext wrap(QueryShardContext shardContext) {
        return new QueryShardContext(shardContext) {

            @Override
            public BitSetProducer bitsetFilter(Query query) {
                return context -> {
                    final IndexReaderContext topLevelContext = ReaderUtil.getTopLevelContext(context);
                    final IndexSearcher searcher = new IndexSearcher(topLevelContext);
                    searcher.setQueryCache(null);
                    final Weight weight = searcher.createNormalizedWeight(query, false);
                    final Scorer s = weight.scorer(context);

                    if (s != null) {
                        return new BitDocIdSet(BitSet.of(s.iterator(), context.reader().maxDoc())).bits();
                    } else {
                        return null;
                    }
                };
            }

            @Override
            @SuppressWarnings("unchecked")
            public <IFD extends IndexFieldData<?>> IFD getForField(MappedFieldType fieldType) {
                IndexFieldData.Builder builder = fieldType.fielddataBuilder(shardContext.getFullyQualifiedIndexName());
                IndexFieldDataCache cache = new IndexFieldDataCache.None();
                CircuitBreakerService circuitBreaker = new NoneCircuitBreakerService();
                return (IFD) builder.build(shardContext.getIndexSettings(), fieldType, cache, circuitBreaker,
                        shardContext.getMapperService());
            }
        };
    }

}


text:
package opennlp.tools.postag;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;

import opennlp.maxent.DataStream;
import opennlp.maxent.GISModel;
import opennlp.maxent.PlainTextByLineDataStream;
import opennlp.maxent.io.SuffixSensitiveGISModelWriter;
import opennlp.model.AbstractModel;
import opennlp.model.EventStream;
import opennlp.model.SequenceStream;
import opennlp.model.TwoPassDataIndexer;
import opennlp.perceptron.SimplePerceptronSequenceTrainer;
import opennlp.perceptron.SuffixSensitivePerceptronModelWriter;
import opennlp.tools.dictionary.Dictionary;
import opennlp.tools.ngram.NGramModel;
import opennlp.tools.util.ObjectStream;
import opennlp.tools.util.ObjectStreamException;
import opennlp.tools.util.StringList;

public class POSTaggerTrainer {

  private static void usage() {
    System.err.println("Usage: POSTaggerTrainer [-encoding encoding] [-dict dict_file] -model [perceptron,maxnet] training_data model_file_name [cutoff] [iterations]");
    System.err.println("This trains a new model on the specified training file and writes the trained model to the model file.");
    System.err.println("-encoding Specifies the encoding of the training file");
    System.err.println("-dict Specifies that a dictionary file should be created for use in distinguising between rare and non-rare words");
    System.err.println("-model [perceptron|maxent] Specifies what type of model should be used.");
    System.exit(1);
  }

  /**
   *
   * @param samples
   * @param tagDictionary
   * @param ngramDictionary
   * @param beamSize
   * @param cutoff
   * @return
   *
   * @throws IOException  its throws if an {@link IOException} is thrown
   * during IO operations on a temp file which is created during training occur.
   */
  public static POSModel train(ObjectStream<POSSample> samples, POSDictionary tagDictionary,
      Dictionary ngramDictionary, int cutoff) throws IOException {

   int iterations = 100;

    GISModel posModel = opennlp.maxent.GIS.trainModel(iterations,
        new TwoPassDataIndexer(new POSSampleEventStream(samples,
        new DefaultPOSContextGenerator(ngramDictionary)), cutoff));

    return new POSModel("en", posModel, tagDictionary, ngramDictionary);
  }

  /**
   * Trains a new model.
   *
   * @param evc
   * @param modelFile
   * @throws IOException
   */
  @Deprecated
  public static void trainMaxentModel(EventStream evc, File modelFile) throws IOException {
    AbstractModel model = trainMaxentModel(evc, 100,5);
    new SuffixSensitiveGISModelWriter(model, modelFile).persist();
  }

  /**
   * Trains a new model
   *
   * @param es
   * @param iterations
   * @param cut
   * @return the new model
   * @throws IOException
   */
  @Deprecated
  public static AbstractModel trainMaxentModel(EventStream es, int iterations, int cut) throws IOException {
    return opennlp.maxent.GIS.trainModel(iterations, new TwoPassDataIndexer(es, cut));
  }

  public static AbstractModel trainPerceptronModel(EventStream es, int iterations, int cut, boolean useAverage) throws IOException {
    return new opennlp.perceptron.PerceptronTrainer().trainModel(iterations, new TwoPassDataIndexer(es, cut, false), cut, useAverage);
  }

  public static AbstractModel trainPerceptronModel(EventStream es, int iterations, int cut) throws IOException {
    return trainPerceptronModel(es,iterations,cut,true);
  }

  public static AbstractModel trainPerceptronSequenceModel(SequenceStream ss, int iterations, int cut, boolean useAverage) {
    return new SimplePerceptronSequenceTrainer().trainModel(iterations, ss, cut,useAverage);
  }

  public static void test(AbstractModel model) throws IOException {
    POSTaggerME tagger = new POSTaggerME(model, (TagDictionary) null);

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    for (String line = in.readLine(); line != null; line = in.readLine()) {
      System.out.println(tagger.tag(line));
    }
  }

  public static void main(String[] args) throws IOException, ObjectStreamException {
    if (args.length == 0){
      usage();
    }
    int ai=0;
    try {
      String encoding = null;
      String dict = null;
      boolean perceptron = false;
      boolean sequence = false;
      while (args[ai].startsWith("-")) {
        if (args[ai].equals("-encoding")) {
          ai++;
          if (ai < args.length) {
            encoding = args[ai++];
          }
          else {
            usage();
          }
        }
        else if (args[ai].equals("-dict")) {
          ai++;
          if (ai < args.length) {
            dict = args[ai++];
          }
          else {
            usage();
          }
        }
        else if (args[ai].equals("-sequence")) {
          ai++;
          sequence = true;
        }
        else if (args[ai].equals("-model")) {
          ai++;
          if (ai < args.length) {
            String type = args[ai++];
            if (type.equals("perceptron")) {
              perceptron = true;
            }
            else if (type.equals("maxent")) {

            }
            else {
              usage();
            }
          }
          else {
            usage();
          }
        }
        else {
          System.err.println("Unknown option "+args[ai]);
          usage();
        }
      }
      File inFile = new File(args[ai++]);
      File outFile = new File(args[ai++]);
      int cutoff = 5;
      int iterations = 100;
      if (args.length > ai) {
        cutoff = Integer.parseInt(args[ai++]);
        iterations = Integer.parseInt(args[ai++]);
      }
      AbstractModel mod;
      if (dict != null) {
        buildDictionary(dict, inFile, cutoff);
      }
      if (sequence) {
        POSSampleSequenceStream ss;
        if (encoding == null) {
          if (dict == null) {
            ss = new POSSampleSequenceStream(new WordTagSampleStream(
                new InputStreamReader(new FileInputStream(inFile))));
          }
          else {
            POSContextGenerator cg = new DefaultPOSContextGenerator(new Dictionary(new FileInputStream(dict)));

            ss = new POSSampleSequenceStream(new WordTagSampleStream((
                new InputStreamReader(new FileInputStream(inFile)))),
                cg);
          }
        }
        else {
          if (dict == null) {

            ss = new POSSampleSequenceStream(new WordTagSampleStream((
                new InputStreamReader(new FileInputStream(inFile), encoding))));
          }
          else {
            POSContextGenerator cg = new DefaultPOSContextGenerator(new Dictionary(new FileInputStream(dict)));

            ss = new POSSampleSequenceStream(new WordTagSampleStream((
                new InputStreamReader(new FileInputStream(inFile), encoding))), cg);
          }
        }
        mod = new SimplePerceptronSequenceTrainer().trainModel(iterations, ss, cutoff, true);
        System.out.println("Saving the model as: " + outFile);
        new SuffixSensitivePerceptronModelWriter(mod, outFile).persist();
      }
      else {
        POSSampleEventStream es;
        if (encoding == null) {
          if (dict == null) {
            es = new POSSampleEventStream(new WordTagSampleStream((
                new InputStreamReader(new FileInputStream(inFile)))));
          }
          else {
            POSContextGenerator cg = new DefaultPOSContextGenerator(new Dictionary(new FileInputStream(dict)));

            es = new POSSampleEventStream(new WordTagSampleStream((
                new InputStreamReader(new FileInputStream(inFile)))),
                cg);
          }
        }
        else {
          if (dict == null) {

            es = new POSSampleEventStream(new WordTagSampleStream((
                new InputStreamReader(new FileInputStream(inFile), encoding))));
          }
          else {
            POSContextGenerator cg = new DefaultPOSContextGenerator(new Dictionary(new FileInputStream(dict)));

            es = new POSSampleEventStream(new WordTagSampleStream((
                new InputStreamReader(new FileInputStream(inFile), encoding))), cg);
          }
        }
        if (perceptron) {
          mod = trainPerceptronModel(es,iterations, cutoff);
          System.out.println("Saving the model as: " + outFile);
          new SuffixSensitivePerceptronModelWriter(mod, outFile).persist();
        }
        else {
          mod = trainMaxentModel(es, iterations, cutoff);

          System.out.println("Saving the model as: " + outFile);

          new SuffixSensitiveGISModelWriter(mod, outFile).persist();
        }
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  private static void buildDictionary(String dict, File inFile, int cutoff)
      throws FileNotFoundException, IOException {
    System.err.println("Building dictionary");

    NGramModel ngramModel = new NGramModel();

    DataStream data = new opennlp.maxent.PlainTextByLineDataStream(new java.io.FileReader(inFile));
    while(data.hasNext()) {
      String tagStr = (String) data.nextToken();
      String[] tt = tagStr.split(" ");
      String[] words = new String[tt.length];
      for (int wi=0;wi<words.length;wi++) {
        words[wi] =
            tt[wi].substring(0,tt[wi].lastIndexOf('_'));
      }

      ngramModel.add(new StringList(words), 1, 1);
    }

    System.out.println("Saving the dictionary");

    ngramModel.cutoff(cutoff, Integer.MAX_VALUE);
    Dictionary dictionary = ngramModel.toDictionary(true);

    dictionary.serialize(new FileOutputStream(dict));
  }

}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Vermicularia fallax Sacc.

### Remarks
null


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Monogr. Discom. Bohem. (Prague) 146 (1934)

#### Original name
Trichobelonium berberidis Velen.

### Remarks
null


text:
<?php

namespace ZfcDatagrid\DataSource;

use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\EntityManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use ZfcDatagrid\Column;
use ZfcDatagrid\DataSource\PhpArray as SourceArray;

class Doctrine2Collection extends AbstractDataSource
{
    /**
     * @var Collection
     */
    private $data;

    /**
     * @var EntityManager
     */
    private $em;

    /**
     * Data source.
     *
     * @param mixed $data
     */
    public function __construct($data)
    {
        if ($data instanceof Collection) {
            $this->data = $data;
        } else {
            $return = $data;
            if (is_object($data)) {
                $return = 'instanceof '.get_class($return);
            }
            throw new \InvalidArgumentException('Unknown data input: "'.$return.'"');
        }
    }

    /**
     * @return Collection
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * @param EntityManager $em
     */
    public function setEntityManager(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     * @return EntityManager
     */
    public function getEntityManager()
    {
        return $this->em;
    }

    public function execute()
    {
        $hydrator = new DoctrineHydrator($this->getEntityManager());

        $dataPrepared = [];
        foreach ($this->getData() as $row) {
            $dataExtracted = $hydrator->extract($row);

            $rowExtracted = [];
            foreach ($this->getColumns() as $col) {
                /* @var $col \ZfcDatagrid\Column\Select */
                if (!$col instanceof Column\Select) {
                    continue;
                }

                $part1 = $col->getSelectPart1();
                $part2 = $col->getSelectPart2();

                if (null === $part2) {
                    if (isset($dataExtracted[$part1])) {
                        $rowExtracted[$col->getUniqueId()] = $dataExtracted[$part1];
                    }
                } else {
                    // NESTED
                    if (isset($dataExtracted[$part1])) {
                        $dataExtractedNested = $hydrator->extract($dataExtracted[$part1]);
                        if (isset($dataExtractedNested[$part2])) {
                            $rowExtracted[$col->getUniqueId()] = $dataExtractedNested[$part2];
                        }
                    }
                }
            }

            $dataPrepared[] = $rowExtracted;
        }

        $source = new SourceArray($dataPrepared);
        $source->setColumns($this->getColumns());
        $source->setSortConditions($this->getSortConditions());
        $source->setFilters($this->getFilters());
        $source->execute();

        $this->setPaginatorAdapter($source->getPaginatorAdapter());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.silvermoon.contacts.list">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- To get the MAC Address only -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar"
        android:name="com.silvermoon.views.BaseApplication">
        <activity
            android:name="com.silvermoon.contacts.list.ContactListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <activity android:name="com.silvermoon.contacts.details.ContactDetailsActivity"
            android:theme="@style/AppTheme.NoActionBar"/>
    </application>

</manifest>


text:
package org.gwtbootstrap3.client.ui;

import java.util.List;

import org.gwtbootstrap3.client.ui.base.ComplexWidget;
import org.gwtbootstrap3.client.ui.base.HasDataTarget;
import org.gwtbootstrap3.client.ui.base.helper.StyleHelper;
import org.gwtbootstrap3.client.ui.base.mixin.DataTargetMixin;
import org.gwtbootstrap3.client.ui.constants.Attributes;
import org.gwtbootstrap3.client.ui.constants.IconType;
import org.gwtbootstrap3.client.ui.constants.Styles;

import com.google.gwt.dom.client.Document;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author Joshua Godi
 */
public class CarouselControl extends ComplexWidget implements HasDataTarget {
    private final DataTargetMixin<CarouselControl> targetMixin = new DataTargetMixin<CarouselControl>(this);

    private final Icon icon = new Icon();

    public CarouselControl() {
        setElement(Document.get().createAnchorElement());
        setStyleName(Styles.CAROUSEL_CONTROL);

        add(icon);
    }

    public void setIconType(final IconType iconType) {
        icon.setType(iconType);
    }

    public void setPrev(final boolean prev) {
        getElement().removeAttribute(Attributes.DATA_SLIDE);
        getElement().setAttribute(Attributes.DATA_SLIDE, Carousel.PREV);
        StyleHelper.toggleStyleName(this, prev, Styles.LEFT);
        icon.addStyleName(Styles.ICON_PREV);
    }

    public void setNext(final boolean next) {
        getElement().removeAttribute(Attributes.DATA_SLIDE);
        getElement().setAttribute(Attributes.DATA_SLIDE, Carousel.NEXT);
        StyleHelper.toggleStyleName(this, next, Styles.RIGHT);
        icon.addStyleName(Styles.ICON_NEXT);
    }

    @Override
    public void setDataTargetWidgets(final List<Widget> widgets) {
        targetMixin.setDataTargetWidgets(widgets);
    }

    @Override
    public void setDataTargetWidget(final Widget widget) {
        targetMixin.setDataTargetWidget(widget);
    }

    @Override
    public void setDataTarget(final String dataTarget) {
        targetMixin.setDataTarget(dataTarget);
    }

    @Override
    public String getDataTarget() {
        return targetMixin.getDataTarget();
    }
}


text:
[Google Cloud Resource Manager](https://cloud.google.com/resource-manager/) ([docs](https://cloud.google.com/resource-manager/reference/rest/)) enables you to
programmatically manage  container resources such as Organizations and Projects, that allow you to group and hierarchically organize other Cloud Platform resources. This hierarchical organization lets you easily manage common aspects of your resources such as access control and configuration settings. You may be familiar with managing projects in the [Developers Console](https://developers.google.com/console/help/new/). With this API you can do the following:

* Get a list of all projects associated with an account
* Create new projects
* Update existing projects
* Delete projects
* Undelete, or recover, projects that you don't want to delete

- [google-cloud-resource_manager API documentation](http://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud-resource_manager/latest)
- [google-cloud-resource_manager on RubyGems](https://rubygems.org/gems/google-cloud-resource_manager)
- [Google Cloud Resource Manager documentation](https://cloud.google.com/resource-manager/)

## Quick Start

```sh
$ gem install google-cloud-resource_manager
```

## Authentication

The Resource Manager API currently requires authentication of a [User
Account](https://developers.google.com/identity/protocols/OAuth2), and
cannot currently be accessed with a [Service
Account](https://developers.google.com/identity/protocols/OAuth2ServiceAccount).
To use a User Account install the [Google Cloud
SDK](http://cloud.google.com/sdk) and authenticate with the following:

```
$ gcloud auth login
```

Also make sure all environment variables are cleared of any
service account credentials. Then google-cloud-resource_manager will be able to detect the user
authentication and connect with those credentials.

Instructions and configuration options are covered in the [Authentication Guide](https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud-resource_manager/guides/authentication).

## Example

```ruby
require "google/cloud/resource_manager"

resource_manager = Google::Cloud::ResourceManager.new

# List all projects
resource_manager.projects.each do |project|
  puts projects.project_id
end

# Label a project as production
project = resource_manager.project "tokyo-rain-123"
project.update do |p|
  p.labels["env"] = "production"
end

# List only projects with the "production" label
projects = resource_manager.projects filter: "labels.env:production"
```

## Enabling Logging

To enable logging for this library, set the logger for the underlying [Google API Client](https://github.com/google/google-api-ruby-client/blob/master/README.md#logging) library. The logger that you set may be a Ruby stdlib [`Logger`](https://ruby-doc.org/stdlib-2.4.0/libdoc/logger/rdoc/Logger.html) as shown below, or a [`Google::Cloud::Logging::Logger`](https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud-logging/latest/google/cloud/logging/logger) that will write logs to [Stackdriver Logging](https://cloud.google.com/logging/).

If you do not set the logger explicitly and your application is running in a Rails environment, it will default to `Rails.logger`. Otherwise, if you do not set the logger and you are not using Rails, logging is disabled by default.

Configuring a Ruby stdlib logger:

```ruby
require "logger"

my_logger = Logger.new $stderr
my_logger.level = Logger::WARN

# Set the Google API Client logger
Google::Apis.logger = my_logger
```

## Supported Ruby Versions

This library is supported on Ruby 2.0+.

However, Ruby 2.3 or later is strongly recommended, as earlier releases have
reached or are nearing end-of-life. After June 1, 2018, Google will provide
official support only for Ruby versions that are considered current and
supported by Ruby Core (that is, Ruby versions that are either in normal
maintenance or in security maintenance).
See https://www.ruby-lang.org/en/downloads/branches/ for further details.

## Versioning

This library follows [Semantic Versioning](http://semver.org/).

It is currently in major version zero (0.y.z), which means that anything may change at any time and the public API should not be considered stable.

## Contributing

Contributions to this library are always welcome and highly encouraged.

See the [Contributing Guide](https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/guides/contributing) for more information on how to get started.

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. See [Code of Conduct](../CODE_OF_CONDUCT.md) for more information.

## License

This library is licensed under Apache 2.0. Full license text is available in [LICENSE](LICENSE).

## Support

Please [report bugs at the project on Github](https://github.com/GoogleCloudPlatform/google-cloud-ruby/issues).
Don't hesitate to [ask questions](http://stackoverflow.com/questions/tagged/google-cloud-platform+ruby) about the client or APIs on [StackOverflow](http://stackoverflow.com).


text:
#include "SortNodeHandler.h"
#include<lang/log/LogLevel.h>

#include <commonlib/commonlib.h>
#include <lang/model/allmodel.h>

#include "../CallbackRegister.h"

namespace IAS {
namespace Lang {
namespace Export{
namespace Text {
namespace Stmt {

/*************************************************************************/
SortNodeHandler::SortNodeHandler(){
	IAS_TRACER;
}

/*************************************************************************/
SortNodeHandler::~SortNodeHandler() throw(){
	IAS_TRACER;
}
/*************************************************************************/
void SortNodeHandler::call(const Model::Node* pNode,
						    CallbackCtx *pCtx,
						    CallbackSignature::Result& aResult){
	IAS_TRACER;

	IAS_TYPEID_CHECK(Model::Stmt::SortNode, pNode);
	const Model::Stmt::SortNode *pSortNode = IAS_DYNAMICCAST_CONST(Model::Stmt::SortNode, pNode);

	const Model::Expr::XPath::XPathAccessNode   *pListXPathAccessNode = pSortNode->getListXPathAccessNode();

	const Model::Dec::QualifiedNameNode         *pQualifiedNameNode  = pSortNode->getQualifiedNameNode();

	printKeyword(aResult,"SORT");
  aResult.ssOutput<<" ";
	CallbackRegister::SubCall(pListXPathAccessNode,pCtx,aResult);

	if(pQualifiedNameNode){
    aResult.ssOutput<<" ";
		printKeyword(aResult,"USING");
    aResult.ssOutput<<" ";
		CallbackRegister::SubCall(pQualifiedNameNode,pCtx,aResult);
	}
}
/*************************************************************************/
}
}
}
}
}


text:
typedef id (^CRCreatorBlock)();

@interface CRLazyObject : NSProxy

- (id) initWithCreator:(CRCreatorBlock)creator;
+ (id) lazyObjectWithCreator:(CRCreatorBlock)creator;

@end


text:
GenderSelect:

```
initialState = { value: 'unknown' };

const handleChange = (value) => {
  setState({ value });
};

<GenderSelect
  value={state.value}
  onChange={handleChange}
/>
```


text:
layout: post
title: Implementing Unit Of Work with NHibernate
date: 2009-08-31T12:54:00.001Z
author: Marcus Hammarberg
tags:
  - DDD
  - NHibernate
  - Agile
modified_time: 2009-08-31T12:56:38.686Z
blogger_id: tag:blogger.com,1999:blog-36533086.post-49902724261637921
blogger_orig_url: http://www.marcusoft.net/2009/08/implementing-unit-of-work-with.html
---

The more I work with it the more stupid I feel around what I have been
doing before; why have I written so much SQL? It feel just …
unnecessary. Who said stupid? Not me…

Jimmy
Nilsson said something like; "I just want the database and storage
problems to be a consequence of my domain model. I don't want to think
about it".  And that is one of the goals with DDD and the solution is,
for example, NHibernate.

I have been doing some labs with NHibernate the last couple. And as
often with me – I think I am in love. NHibernate really rocks. The
mapping files are quite hard to chew off at first and I suspect that
there are many tricks and traps for me to find. But still – so
beautiful.

Of course the Net has helped me a lot on my quest. Here are some
articles that I've used:

- The NHibernate API Reference
- A great first-time tutorial that helped me in the early
    stages
- Here is a great couple of articles describing the unit of work
    pattern implemented with NHibernate (part 1, 2, 3)
- More advanced mapping scenarios
- Description on how to map many-to-many entities, without having to
    specify a connection entity that matches the connection table.

A bit on the sad side (or NOT) is that we were trying to create a
Unit Of Work implementation for NHibernate. Not only
has this been done before, but also apparently NHibernate hooks into
the System.TransactionScope implementation of the .NET
framework.  Thanks a lot to the gurus of level 3 – Magnus and Calle who
show me that. All my code – down the drain… :)

OK – this has been a great learning experience. If you want the code –
drop me a line and you'll have it in a jiffy.


text:
<?php

?>
<?php
$error->add('jobpack-test', 'Loaded test jobpack successfully');
$error->add('jobpack-test', 'Gathered job data for '.$jobid.'. Data: '.json_encode($jobdata));
$update = $amm->update_jobstatus($jobid, 'closed');
if (!$update[0]) {
    $error->add('jobpack-test', 'jobstatus update failed for '.$jobid." '".$update[1]."'");
} unset($update);
?>


text:
<?php

namespace EPManager\MainBundle\TaskLauncher\Buzz;

use Buzz\Browser;
use EPManager\MainBundle\Entity\Launcher;

/**
 * Custom EPLauncher browser
 *
 * @author Julien Brochet <julien.brochet@orange.com>
 */
class EPLauncherBrowser extends Browser
{
    /**
     * Post a new execution to the launcher
     *
     * @param Launcher $launcher A launcher instance
     * @param array    $params   List of parameters
     *
     * @return Response
     */
    public function postExecution(Launcher $launcher, array $params)
    {
        // Add the authentification cookie
        $headers = ['Key' => $launcher->getKey()];

        return $this->post($launcher->getAddress(), $headers, http_build_query($params));
    }

    /**
     * Gets a list of executions from the launcher
     *
     * @param Launcher $launcher A launcher instance
     *
     * @return Response
     */
    public function getExecutions(Launcher $launcher)
    {
        $headers = [
            'Key' => $launcher->getKey(),
            'Accept' => 'application/xml'
        ];

        return $this->get($launcher->getAddress(), $headers);
    }
}


text:
import { Pipe, PipeTransform } from '@angular/core';

/**
 * Transform a "Person" object with `first` and `last` properties into full name string: "{first} {last}".
 * Notice that it must be an "impure" pipe because the properties can change even when the object doesn't.
 * Remove the "pure: false" and see what happens!
 */
@Pipe({ name: 'fullname', pure: false })
export class FullNamePipe implements PipeTransform {
  transform(person: { first?: string, last?: string }): string {
    return calcFullName(person);
  }
}

export function calcFullName(person: { first?: string, last?: string }): string {
  return person ? ((person.first || '') + ' ' + (person.last || '')).trim() : '';
}


text:
![Ratpack](https://github.com/jprante/elasticsearch-plugin-ratpack/raw/master/src/site/resources/ratpack.png)

# Elasticsearch Ratpack plugin

This plugin demonstrates how [Ratpack](http://www.ratpack.io) applications can be embedded into Elasticsearch.

Ratpack is a set of Java libraries that facilitate fast, efficient, evolvable and well tested HTTP applications.

It is built on the highly performant and efficient Netty event-driven networking engine.

Ratpack focuses on allowing HTTP applications to be efficient, modular, adaptive to new requirements and
technologies, and well-tested over time.

This plugin is written in Groovy and uses Gradle as build system. With the
endorsement of Groovy in Elasticsearch, embedding Ratpack applications into Elasticsearch is an interesting
option.

For demonstration purpose, you can issue a HTTP GET request to port 5050 of the Elasticsearch node after plugin
installation.

     curl '0:5050'

As an example result, you will see the Elasticsearch node info, retrieved by Ratpack.

## Versions

| Release date | Plugin version | Elasticsearch version | Ratpack version |
| -------------| ---------------| ----------------------|-----------------|
| Dec 20, 2014 | 1.4.0.0        | 1.4.0                 | 0.9.11          |

## Prerequisites

- Java 8
- Groovy 2.3.6

## Installation

    ./bin/plugin --install ratpack --url http://xbib.org/repository/org/xbib/elasticsearch/plugin/elasticsearch-plugin-ratpack/1.4.0.0/elasticsearch-plugin-ratpack-1.4.0.0-plugin.zip

Do not forget to restart the nodes after installing.

Note: this plugin comes with Groovy 2.3.6. If there is a Groovy jar in the 'lib' folder of Elasticsearch, you will get an error

    org.elasticsearch.ElasticsearchException: Failed to load plugin class [org.xbib.elasticsearch.plugin.ratpack.RatpackPlugin]
    [...]
    Caused by: groovy.lang.GroovyRuntimeException: Conflicting module versions. Module [groovy-all is loaded in version 2.3.2 and you are trying to load version 2.3.6

In that case, use the newer instead of the older Groovy jar, and ensure you have only one Groovy jar in the Elasticsearch classpath.

For example

    rm lib/groovy-all-2.3.2.jar
    mv plugins/ratpack/groovy-all-2.3.6.jar lib/

## Project docs

The Maven project site is available at [Github](http://jprante.github.io/elasticsearch-plugin-ratpack)

## Issues

All feedback is welcome! If you find issues, please post them at
[Github](https://github.com/jprante/elasticsearch-plugin-ratpack/issues)

# License

Elasticsearch Ratpack Plugin

Copyright (C) 2014 Jörg Prante

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


text:
/* global describe, it, expect, before */
/* jshint expr: true */

var chai = require('chai')
  , Strategy = require('../lib/strategy');

describe('Strategy', function() {

  describe('handling a request without a body, but no token, with message option to authenticate', function() {
    var strategy = new Strategy(function(token, done) {
      throw new Error('should not be called');
    });

    var info, status;

    before(function(done) {
      chai.passport(strategy)
        .fail(function(i, s) {
          info = i;
          status = s;
          done();
        })
        .req(function(req) {
          req.body = {};
        })
        .authenticate({ badRequestMessage: 'Something is wrong with this request' });
    });

    it('should fail with info and status', function() {
      expect(info).to.be.an.object;
      expect(info.message).to.equal('Something is wrong with this request');
      expect(status).to.equal(400);
    });
  });

});


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Input;
using osu.Framework.Input.Events;
using osu.Framework.MathUtils;

namespace osu.Framework.Graphics.Visualisation
{
    [Cached]
    internal class DrawVisualiser : OverlayContainer, IContainVisualisedDrawables
    {
        [Cached]
        private readonly TreeContainer treeContainer;

        private VisualisedDrawable highlightedTarget;

        private readonly PropertyDisplay propertyDisplay;

        private readonly InfoOverlay overlay;

        private InputManager inputManager;

        public DrawVisualiser()
        {
            RelativeSizeAxes = Axes.Both;
            Children = new Drawable[]
            {
                overlay = new InfoOverlay(),
                treeContainer = new TreeContainer
                {
                    ChooseTarget = () =>
                    {
                        Searching = true;
                        Target = null;
                    },
                    GoUpOneParent = delegate
                    {
                        Drawable lastHighlight = highlightedTarget?.Target;

                        var parent = Target?.Parent;
                        if (parent != null)
                        {
                            var lastVisualiser = targetVisualiser;

                            Target = parent;
                            lastVisualiser.SetContainer(targetVisualiser);

                            targetVisualiser.Expand();
                        }

                        // Rehighlight the last highlight
                        if (lastHighlight != null)
                        {
                            VisualisedDrawable visualised = targetVisualiser.FindVisualisedDrawable(lastHighlight);
                            if (visualised != null)
                            {
                                propertyDisplay.State = Visibility.Visible;
                                setHighlight(visualised);
                            }
                        }
                    },
                    ToggleProperties = delegate
                    {
                        if (targetVisualiser == null)
                            return;

                        propertyDisplay.ToggleVisibility();

                        if (propertyDisplay.State == Visibility.Visible)
                            setHighlight(targetVisualiser);
                    },
                },
                new CursorContainer()
            };

            propertyDisplay = treeContainer.PropertyDisplay;

            propertyDisplay.StateChanged += visibility =>
            {
                switch (visibility)
                {
                    case Visibility.Hidden:
                        // Dehighlight everything automatically if property display is closed
                        setHighlight(null);
                        break;
                }
            };
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();
            inputManager = GetContainingInputManager();
        }

        protected override bool BlockPositionalInput => false;

        protected override void PopIn()
        {
            this.FadeIn(100);
            Searching = Target == null;
        }

        protected override void PopOut()
        {
            this.FadeOut(100);

            setHighlight(null);
            propertyDisplay.Hide();

            recycleVisualisers();
        }

        void IContainVisualisedDrawables.AddVisualiser(VisualisedDrawable visualiser)
        {
            visualiser.RequestTarget = d =>
            {
                Target = d;
                targetVisualiser.ExpandAll();
            };

            visualiser.HighlightTarget = d =>
            {
                propertyDisplay.State = Visibility.Visible;

                // Either highlight or dehighlight the target, depending on whether
                // it is currently highlighted
                setHighlight(d);
            };

            visualiser.Depth = 0;

            treeContainer.Child = targetVisualiser = visualiser;
        }

        void IContainVisualisedDrawables.RemoveVisualiser(VisualisedDrawable visualiser)
        {
            target = null;
            targetVisualiser = null;
            treeContainer.Remove(visualiser);

            if (Target == null)
                propertyDisplay.State = Visibility.Hidden;
        }

        private VisualisedDrawable targetVisualiser;
        private Drawable target;
        public Drawable Target
        {
            get => target;
            set
            {
                if (target != null)
                {
                    GetVisualiserFor(target).SetContainer(null);
                    targetVisualiser = null;
                }

                target = value;

                if (target != null)
                {
                    targetVisualiser = GetVisualiserFor(target);
                    targetVisualiser.SetContainer(this);
                }
            }
        }

        private Drawable cursorTarget;

        protected override void Update()
        {
            base.Update();

            updateCursorTarget();
        }

        private void updateCursorTarget()
        {
            Drawable drawableTarget = null;
            CompositeDrawable compositeTarget = null;

            findTarget(inputManager);

            cursorTarget = drawableTarget ?? compositeTarget;

            // Finds the targeted drawable and composite drawable. The search stops if a drawable is targeted.
            void findTarget(Drawable drawable)
            {
                if (!isValidTarget(drawable))
                    return;

                if (drawable is CompositeDrawable composite)
                {
                    for (int i = composite.AliveInternalChildren.Count - 1; i >= 0; i--)
                    {
                        findTarget(composite.AliveInternalChildren[i]);

                        if (drawableTarget != null)
                            return;
                    }

                    if (compositeTarget == null)
                        compositeTarget = composite;
                }
                else if (!(drawable is Component))
                    drawableTarget = drawable;
            }

            bool isValidTarget(Drawable drawable)
            {
                if (drawable == this || drawable is CursorContainer)
                    return false;

                if (!drawable.IsPresent)
                    return false;

                if (drawable.AlwaysPresent && Precision.AlmostEquals(drawable.Alpha, 0f))
                    return false;

                bool containsCursor = drawable.ScreenSpaceDrawQuad.Contains(inputManager.CurrentState.Mouse.Position);
                // This is an optimization: We don't need to consider drawables which we don't hover, and which do not
                // forward input further to children (via d.ReceivePositionalInputAt). If they do forward input to children, then there
                // is a good chance they have children poking out of their bounds, which we need to catch.
                if (!containsCursor && !drawable.ReceivePositionalInputAt(inputManager.CurrentState.Mouse.Position))
                    return false;

                return true;
            }
        }

        public bool Searching { get; private set; }

        private void setHighlight(VisualisedDrawable newHighlight)
        {
            if (highlightedTarget != null)
            {
                // Dehighlight the lastly highlighted target
                highlightedTarget.IsHighlighted = false;
                highlightedTarget = null;
            }

            if (newHighlight == null)
            {
                propertyDisplay.UpdateFrom(null);
                return;
            }

            // Only update when property display is visible
            if (propertyDisplay.State == Visibility.Visible)
            {
                highlightedTarget = newHighlight;
                newHighlight.IsHighlighted = true;

                propertyDisplay.UpdateFrom(newHighlight.Target);
            }
        }

        protected override bool OnMouseDown(MouseDownEvent e) => Searching;

        protected override bool OnClick(ClickEvent e)
        {
            if (Searching)
            {
                Target = cursorTarget?.Parent;

                if (Target != null)
                {
                    overlay.Target = null;
                    targetVisualiser.ExpandAll();

                    Searching = false;
                    return true;
                }
            }

            return base.OnClick(e);
        }

        protected override bool OnMouseMove(MouseMoveEvent e)
        {
            overlay.Target = Searching ? cursorTarget : inputManager.HoveredDrawables.OfType<VisualisedDrawable>().FirstOrDefault()?.Target;
            return overlay.Target != null;
        }

        private readonly Dictionary<Drawable, VisualisedDrawable> visCache = new Dictionary<Drawable, VisualisedDrawable>();

        public VisualisedDrawable GetVisualiserFor(Drawable drawable)
        {
            if (visCache.TryGetValue(drawable, out var existing))
                return existing;

            var vis = new VisualisedDrawable(drawable);
            vis.OnDispose += () => visCache.Remove(vis.Target);

            return visCache[drawable] = vis;
        }

        private void recycleVisualisers()
        {
            // May come from the disposal thread, in which case they won't ever be reused anyway
            Schedule(() => treeContainer.Clear());

            // We don't really know where the visualised drawables are, so we have to dispose them manually
            // This is done as an optimisation so that events aren't handled while the visualiser is hidden
            var visualisers = visCache.Values.ToList();
            foreach (var v in visualisers)
                v.Dispose();

            target = null;
            targetVisualiser = null;
        }

        protected override void Dispose(bool isDisposing)
        {
            base.Dispose(isDisposing);
            recycleVisualisers();
        }
    }
}


text:
@interface SVProgressHUDHelper : NSObject

+(void)show;

@end


text:
logcat_file=$1
echo "===== Jorge Log - Start =====" > $logcat_file

for i in `seq 1 10`;
do
    adb logcat  -d -v time >> $logcat_file
    adb logcat -c
    sleep 150
done

echo "===== Jorge Log - END =====" >> $logcat_file

terminal-notifier -title "Jorge Log finished" -message "Let's see if it really works"


text:
'use strict';

var SWAMP_FILE_NAME     = 'Swampfile.js';

var path        = require('path'),
    version     = require('../package.json').version;

process.title = 'swamp ' + version;

var swampConfRunner;

require('../swamp')(run);

function run(appolo) {

    var utils = appolo.inject.getObject('utils');

    // looking for SWAMP_FILE_NAME
    var swampConfPath = path.resolve(process.cwd(), SWAMP_FILE_NAME);

    if (swampConfPath && utils.fileExist(swampConfPath)) {

        utils.log(SWAMP_FILE_NAME + ' file found (' + swampConfPath + ')!', utils.LOG_TYPE.SUCCESS);

    } else {

        utils.log(SWAMP_FILE_NAME + ' not exist. did you mean `swamp create`?', utils.LOG_TYPE.ERROR);

        return;
    }

    // try load configurations file from path
    utils.log('Validating Swamp configurations...', utils.LOG_TYPE.INFO);

    try {

        swampConfRunner = require(swampConfPath);

    } catch(err) {

        utils.log('Invalid `{0}`: {1}'.format(SWAMP_FILE_NAME, err), utils.LOG_TYPE.ERROR);
        process.exit();
        return;

    }

    // creating a Swamp
    utils.log('Swamp configurations are valid, creating a Swamp...', utils.LOG_TYPE.SUCCESS);
    var swamp = appolo.inject.getObject('initializer');

    // running Swamp configurations
    swampConfRunner(swamp);
}


text:
package main

import (
	"log"
	"net/http"

	"github.com/gorilla/handlers"
)

func main() {

	router := NewRouter()

	originsOk := handlers.AllowedOrigins([]string{"*"})

	log.Fatal(http.ListenAndServe(":8080", handlers.CORS(originsOk)(router)))
}


text:
from __future__ import unicode_literals

from django.db import models, migrations
import uuid

class Migration(migrations.Migration):

    dependencies = [
        ('elos', '0010_auto_20151021_1635'),
    ]

    operations = [
        migrations.AddField(
            model_name='elo',
            name='parent_elo2',
            field=models.ForeignKey(related_name='elos_parent2', default=1, blank=True, to='elos.ELO'),
        ),
        migrations.AddField(
            model_name='elo',
            name='parent_elo2_uuid',
            field=models.UUIDField(default=uuid.uuid4, verbose_name='Parent ELO2 UUID', blank=True),
        ),
        migrations.AddField(
            model_name='elo',
            name='parent_elo2_version',
            field=models.PositiveIntegerField(default=0, verbose_name='Parent ELO2 version', blank=True),
        ),
    ]


text:
<?php

namespace Zorbus\ApiBundle\Cache;

class NewsCacheConfiguration
{

    public static function getNewsKey($id)
    {
        return 'Zorbus.news.id.' . $id;
    }

    public function getNewsLifetime()
    {
        return 3600;
    }

}


text:
  No authorization is performed. Everyone gets full control of Jenkins,
  including anonymous users who haven't signed on.

    This is useful in situations where you run Jenkins in a trusted environment
    (such as a company intranet) and just want to use authentication for
    personalization support. In this way, if someone needs to make a quick
    change to Jenkins, they won't be forced to log in.


text:
namespace Machete.HL7Schema.V26
{
    using System;
    using HL7;

    /// <summary>
    /// OM7 (Segment) - Additional Basic Attributes
    /// </summary>
    public interface OM7 :
        HL7V26Segment
    {
        /// <summary>
        /// OM7-1: Sequence Number - Test/Observation Master File
        /// </summary>
        Value<decimal> SequenceNumberTestObservationMasterFile { get; }

        /// <summary>
        /// OM7-2: Universal Service Identifier
        /// </summary>
        Value<CWE> UniversalServiceIdentifier { get; }

        /// <summary>
        /// OM7-3: Category Identifier
        /// </summary>
        ValueList<CWE> CategoryIdentifier { get; }

        /// <summary>
        /// OM7-4: Category Description
        /// </summary>
        Value<TX> CategoryDescription { get; }

        /// <summary>
        /// OM7-5: Category Synonym
        /// </summary>
        ValueList<string> CategorySynonym { get; }

        /// <summary>
        /// OM7-6: Effective Test/Service Start Date/Time
        /// </summary>
        Value<DateTimeOffset> EffectiveTestServiceStartDateTime { get; }

        /// <summary>
        /// OM7-7: Effective Test/Service End Date/Time
        /// </summary>
        Value<DateTimeOffset> EffectiveTestServiceEndDateTime { get; }

        /// <summary>
        /// OM7-8: Test/Service Default Duration Quantity
        /// </summary>
        Value<decimal> TestServiceDefaultDurationQuantity { get; }

        /// <summary>
        /// OM7-9: Test/Service Default Duration Units
        /// </summary>
        Value<CWE> TestServiceDefaultDurationUnits { get; }

        /// <summary>
        /// OM7-10: Test/Service Default Frequency
        /// </summary>
        Value<string> TestServiceDefaultFrequency { get; }

        /// <summary>
        /// OM7-11: Consent Indicator
        /// </summary>
        Value<string> ConsentIndicator { get; }

        /// <summary>
        /// OM7-12: Consent Identifier
        /// </summary>
        Value<CWE> ConsentIdentifier { get; }

        /// <summary>
        /// OM7-13: Consent Effective Start Date/Time
        /// </summary>
        Value<DateTimeOffset> ConsentEffectiveStartDateTime { get; }

        /// <summary>
        /// OM7-14: Consent Effective End Date/Time
        /// </summary>
        Value<DateTimeOffset> ConsentEffectiveEndDateTime { get; }

        /// <summary>
        /// OM7-15: Consent Interval Quantity
        /// </summary>
        Value<decimal> ConsentIntervalQuantity { get; }

        /// <summary>
        /// OM7-16: Consent Interval Units
        /// </summary>
        Value<CWE> ConsentIntervalUnits { get; }

        /// <summary>
        /// OM7-17: Consent Waiting Period Quantity
        /// </summary>
        Value<decimal> ConsentWaitingPeriodQuantity { get; }

        /// <summary>
        /// OM7-18: Consent Waiting Period Units
        /// </summary>
        Value<CWE> ConsentWaitingPeriodUnits { get; }

        /// <summary>
        /// OM7-19: Effective Date/Time of Change
        /// </summary>
        Value<DateTimeOffset> EffectiveDateTimeOfChange { get; }

        /// <summary>
        /// OM7-20: Entered By
        /// </summary>
        Value<XCN> EnteredBy { get; }

        /// <summary>
        /// OM7-21: Orderable-at Location
        /// </summary>
        ValueList<PL> OrderableAtLocation { get; }

        /// <summary>
        /// OM7-22: Formulary Status
        /// </summary>
        Value<string> FormularyStatus { get; }

        /// <summary>
        /// OM7-23: Special Order Indicator
        /// </summary>
        Value<string> SpecialOrderIndicator { get; }

        /// <summary>
        /// OM7-24: Primary Key Value - CDM
        /// </summary>
        ValueList<CWE> PrimaryKeyValueCDM { get; }
    }
}


text:
<?php

namespace Opifer\CmsBundle\Entity;

use APY\DataGridBundle\Grid\Mapping as GRID;
use Doctrine\Common\Collections\ArrayCollection;
use FOS\UserBundle\Model\GroupInterface;
use FOS\UserBundle\Model\User as FOSUser;
use Opifer\MediaBundle\Model\MediaInterface;
use Scheb\TwoFactorBundle\Model\Google\TwoFactorInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
use Opifer\CmsBundle\Validator\Constraints as CmsAssert;

/**
 * @UniqueEntity("username")
 * @UniqueEntity("email")
 * @GRID\Source(columns="id, enabled, username, email, roles")
 */
class User extends FOSUser implements TwoFactorInterface
{
    /**
     * @GRID\Column(title="Id", size="10", type="number")
     */
    protected $id;

    /**
     * @var string
     *
     * ORM mapping is handled by the BaseUser
     */
    protected $username;

    /**
     * @var string
     */
    protected $firstName;

    /**
     * @var string
     */
    protected $lastName;

    /**
     * @var MediaInterface
     */
    protected $avatar;

    /**
     * @var string
     *
     * ORM mapping is handled by the BaseUser
     *
     * @Assert\NotBlank()
     * @Assert\Email()
     */
    protected $email;

    /**
     * @CmsAssert\Password
     *
     * @var string
     *
     * Plain password. Used for model validation. Must not be persisted.
     */
    protected $plainPassword;

    /**
     * @var string
     */
    protected $company;

    /**
     * @var string
     */
    protected $jobPosition;

    /**
     * @var ArrayCollection
     */
    protected $groups;

    /**
     * @var ArrayCollection
     */
    protected $contents;

    /**
     * @var \DateTime
     */
    protected $createdAt;

    /**
     * @var \DateTime
     */
    protected $updatedAt;

    /**
     * @var \DateTime
     */
    protected $deletedAt;

    /**
     * @var boolean
     *
     * @GRID\Column(type="boolean")
     */
    protected $enabled;

    /**
     * @var boolean
     *
     * @GRID\Column(type="boolean")
     */
    protected $twoFactorEnabled = false;

    private $googleAuthenticatorSecret;

    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();

        $this->groups = new ArrayCollection();
        $this->contents = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set first name
     *
     * @param string $firstName
     *
     * @return User
     */
    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;

        return $this;
    }

    /**
     * Get first name
     *
     * @return string
     */
    public function getFirstName()
    {
        return $this->firstName;
    }

    /**
     * Set last name
     *
     * @param string $lastName
     *
     * @return User
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * Get last name
     *
     * @return string
     */
    public function getLastName()
    {
        return $this->lastName;
    }

    /**
     * Get the full name
     *
     * @return string
     */
    public function getFullName()
    {
        return $this->firstName.' '.$this->lastName;
    }

    /**
     * @return MediaInterface
     */
    public function getAvatar()
    {
        return $this->avatar;
    }

    /**
     * @param MediaInterface $avatar
     * @return User
     */
    public function setAvatar(MediaInterface $avatar)
    {
        $this->avatar = $avatar;

        return $this;
    }

    /**
     * @return string
     */
    public function getCompany()
    {
        return $this->company;
    }

    /**
     * @param string $company
     * @return User
     */
    public function setCompany($company)
    {
        $this->company = $company;
        return $this;
    }

    /**
     * @return string
     */
    public function getJobPosition()
    {
        return $this->jobPosition;
    }

    /**
     * @param string $jobPosition
     * @return User
     */
    public function setJobPosition($jobPosition)
    {
        $this->jobPosition = $jobPosition;
        return $this;
    }

    /**
     * Get expires at
     *
     * @return \DateTime
     */
    public function getExpiresAt()
    {
        return $this->expiresAt;
    }

    /**
     * Get credentials expire at
     *
     * @return \DateTime
     */
    public function getCredentialsExpireAt()
    {
        return $this->credentialsExpireAt;
    }

    /**
     * Add groups
     *
     * @param \Opifer\CmsBundle\Entity\Group $groups
     *
     * @return User
     */
    public function addGroup(GroupInterface $groups)
    {
        $this->groups[] = $groups;

        return $this;
    }

    /**
     * Remove groups
     *
     * @param \Opifer\CmsBundle\Entity\Group $groups
     * @return $this
     */
    public function removeGroup(GroupInterface $groups)
    {
        $this->groups->removeElement($groups);

        return $this;
    }

    /**
     * Get groups
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getGroups()
    {
        return $this->groups;
    }

    /**
     * Returns all related content items
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getContents()
    {
        return $this->contents;
    }

    /**
     * Get created at
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Get updated at
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Set deletedAt
     *
     * @param  \DateTime $deletedAt
     * @return $this
     */
    public function setDeletedAt($deletedAt)
    {
        $this->deletedAt = $deletedAt;

        return $this;
    }

    /**
     * @return bool
     */
    public function isTwoFactorEnabled(): bool
    {
        return $this->twoFactorEnabled;
    }

    /**
     * @return bool
     */
    public function setTwoFactorEnabled($twoFactorEnabled)
    {
        $this->twoFactorEnabled = $twoFactorEnabled;
        return $this;
    }

    /**
     * Get deletedAt
     *
     * @return \DateTime
     */
    public function getDeletedAt()
    {
        return $this->deletedAt;
    }

    public function isGoogleAuthenticatorEnabled(): bool
    {
        return $this->googleAuthenticatorSecret ? true : false;
    }

    public function getGoogleAuthenticatorUsername(): string
    {
        return $this->username;
    }

    public function getGoogleAuthenticatorSecret(): string
    {
        return $this->googleAuthenticatorSecret ? $this->googleAuthenticatorSecret : "";
    }

    public function setGoogleAuthenticatorSecret($googleAuthenticatorSecret)
    {
        $this->googleAuthenticatorSecret = $googleAuthenticatorSecret;
    }
}


text:
module General.Cleanup(
    Cleanup, newCleanup, withCleanup,
    register, release, allocate, unprotect
    ) where

import Control.Exception
import qualified Data.HashMap.Strict as Map
import Data.IORef
import Data.List.Extra
import Data.Maybe

data S = S
    {unique :: {-# UNPACK #-} !Int -- next index to be used to items
    ,items :: !(Map.HashMap Int (IO ()))
    }

newtype Cleanup = Cleanup (IORef S)

data ReleaseKey = ReleaseKey (IORef S) {-# UNPACK #-} !Int

-- | Run with some cleanup scope. Regardless of exceptions/threads, all 'register' actions
--   will be run by the time it exits.
--   The 'register' actions will be run in reverse order, i.e. the last to be added will be run first.
withCleanup :: (Cleanup -> IO a) -> IO a
withCleanup act = do
    (c, clean) <- newCleanup
    act c `finally` clean

newCleanup :: IO (Cleanup, IO ())
newCleanup = do
    ref <- newIORef $ S 0 Map.empty
    -- important to use uninterruptibleMask_ otherwise in things like allocateThread
    -- we might end up being interrupted and failing to close down the thread
    -- e.g. see https://github.com/digital-asset/ghcide/issues/381
    -- note that packages like safe-exceptions also use uninterruptibleMask_
    let clean = uninterruptibleMask_ $ do
            items <- atomicModifyIORef' ref $ \s -> (s{items=Map.empty}, items s)
            mapM_ snd $ sortOn (negate . fst) $ Map.toList items
    pure (Cleanup ref, clean)

register :: Cleanup -> IO () -> IO ReleaseKey
register (Cleanup ref) act = atomicModifyIORef' ref $ \s -> let i = unique s in
    (S (unique s + 1) (Map.insert i act $ items s), ReleaseKey ref i)

unprotect :: ReleaseKey -> IO ()
unprotect (ReleaseKey ref i) = atomicModifyIORef' ref $ \s -> (s{items = Map.delete i $ items s}, ())

release :: ReleaseKey -> IO ()
release (ReleaseKey ref i) = uninterruptibleMask_ $ do
    undo <- atomicModifyIORef' ref $ \s -> (s{items = Map.delete i $ items s}, Map.lookup i $ items s)
    fromMaybe (pure ()) undo

allocate :: Cleanup -> IO a -> (a -> IO ()) -> IO a
allocate cleanup acquire release =
    mask_ $ do
        v <- acquire
        register cleanup $ release v
        pure v


text:
@interface ZFSearchPhotoByCategoryHttpPostIn : FLModelObject {
@private
    NSString* _limit;
    NSString* _offset;
    NSString* _searchId;
    NSString* _sortOrder;
    NSString* _categoryCode;
}

@property (readwrite, strong, nonatomic) NSString* categoryCode;
@property (readwrite, strong, nonatomic) NSString* limit;
@property (readwrite, strong, nonatomic) NSString* offset;
@property (readwrite, strong, nonatomic) NSString* searchId;
@property (readwrite, strong, nonatomic) NSString* sortOrder;

+ (ZFSearchPhotoByCategoryHttpPostIn*) searchPhotoByCategoryHttpPostIn;

@end


text:
FROM node:18-alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --no-audit --legacy-peer-deps

# Rebuild the source code only when needed
FROM node:18-alpine AS builder
RUN apk add --no-cache git

WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
ENV NEXT_TELEMETRY_DISABLED 1

RUN git config --global --add safe.directory /app

RUN npm run build

# Production image, copy all the files and run next
FROM node:18-alpine AS runner
RUN apk add --no-cache git
WORKDIR /app

ENV NODE_ENV production
# Uncomment the following line in case you want to disable telemetry during runtime.
ENV NEXT_TELEMETRY_DISABLED 1

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

RUN mkdir -p /app/.next/cache/images && chown nextjs:nodejs /app/.next/cache/images

COPY --from=builder --chown=nextjs:nodejs /app ./

VOLUME /app/.next/cache/images
VOLUME /app/public/images/opengraph/cache

USER nextjs

RUN git config --global --add safe.directory /app

EXPOSE 3000

ENV PORT 3000

CMD ["node", "server.js"]


text:
using System;
using System.IO;
using System.Collections.Generic;
using UnityEngine;

namespace DarkMultiPlayer
{
    public class DarkLog
    {
        public static Queue<string> messageQueue = new Queue<string>();
        private static object externalLogLock = new object();
        private static int mainThreadID;

        public static void SetMainThread()
        {
            mainThreadID = System.Threading.Thread.CurrentThread.ManagedThreadId;
        }

        public static void Debug(string message)
        {
            message = string.Format("[{0}] {1}", Client.realtimeSinceStartup, message);
            if (System.Threading.Thread.CurrentThread.ManagedThreadId == mainThreadID)
            {
                UnityEngine.Debug.Log("DarkMultiPlayer: " + message);
            }
            else
            {
                lock (messageQueue)
                {
                    messageQueue.Enqueue("DarkMultiPlayer: [THREAD] " + message);
                }
            }
        }

        public static void Update()
        {
            while (messageQueue.Count > 0)
            {
                lock (messageQueue)
                {
                    string message = messageQueue.Dequeue();
                    UnityEngine.Debug.Log(message);
                }
            }
        }

        public static void ExternalLog(string debugText)
        {
            lock (externalLogLock)
            {
                using (StreamWriter sw = new StreamWriter(Path.Combine(KSPUtil.ApplicationRootPath, "DMP.log"), true))
                {
                    sw.WriteLine(debugText);
                }
            }
        }
    }
}