text:
using Lucene.Net.Documents;
using Lucene.Net.Search;
using Lucene.Net.Spatial.Prefix.Tree;
using Lucene.Net.Spatial.Queries;
using Lucene.Net.Support;
using NUnit.Framework;
using Spatial4n.Core.Context;
using Spatial4n.Core.Shapes;
using Spatial4n.Core.Shapes.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using Console = Lucene.Net.Support.SystemConsole;

namespace Lucene.Net.Spatial.Prefix
{

    public class SpatialOpRecursivePrefixTreeTest : StrategyTestCase
    {
        const int ITERATIONS = 1;//Test Iterations

        private SpatialPrefixTree grid;

        public override void SetUp()
        {
            base.SetUp();
            DeleteAll();
        }

        public virtual void SetupGrid(int maxLevels)
        {
            if (Random().nextBoolean())
                SetupQuadGrid(maxLevels);
            else
                SetupGeohashGrid(maxLevels);
            //((PrefixTreeStrategy) strategy).setDistErrPct(0);//fully precise to grid

            Console.WriteLine("Strategy: " + strategy.toString());
        }

        private void SetupQuadGrid(int maxLevels)
        {
            //non-geospatial makes this test a little easier (in gridSnap), and using boundary values 2^X raises
            // the prospect of edge conditions we want to test, plus makes for simpler numbers (no decimals).
            FakeSpatialContextFactory factory = new FakeSpatialContextFactory();
            factory.geo = false;
            factory.worldBounds = new Rectangle(0, 256, -128, 128, null);
            this.ctx = factory.NewSpatialContext();
            //A fairly shallow grid, and default 2.5% distErrPct
            if (maxLevels == -1)
                maxLevels = randomIntBetween(1, 8);//max 64k cells (4^8), also 256*256
            this.grid = new QuadPrefixTree(ctx, maxLevels);
            this.strategy = new RecursivePrefixTreeStrategy(grid, GetType().Name);
        }

        /// <summary>
        /// LUCENENET specific class used to gain access to protected internal
        /// member NewSpatialContext(), since we are not strong-named and
        /// InternalsVisibleTo is not an option from a strong-named class.
        /// </summary>
        private class FakeSpatialContextFactory : SpatialContextFactory
        {
            new public SpatialContext NewSpatialContext()
            {
                return base.NewSpatialContext();
            }
        }

        public virtual void SetupGeohashGrid(int maxLevels)
        {
            this.ctx = SpatialContext.GEO;
            //A fairly shallow grid, and default 2.5% distErrPct
            if (maxLevels == -1)
                maxLevels = randomIntBetween(1, 3);//max 16k cells (32^3)
            this.grid = new GeohashPrefixTree(ctx, maxLevels);
            this.strategy = new RecursivePrefixTreeStrategy(grid, GetType().Name);
        }

        [Test, Repeat(ITERATIONS)]
        public virtual void TestIntersects()
        {
            SetupGrid(-1);
            doTest(SpatialOperation.Intersects);
        }

        [Test, Repeat(ITERATIONS)]
        public virtual void TestWithin()
        {
            SetupGrid(-1);
            doTest(SpatialOperation.IsWithin);
        }

        [Test, Repeat(ITERATIONS)]
        public virtual void TestContains()
        {
            SetupGrid(-1);
            doTest(SpatialOperation.Contains);
        }

        [Test, Repeat(ITERATIONS)]
        public virtual void TestDisjoint()
        {
            SetupGrid(-1);
            doTest(SpatialOperation.IsDisjointTo);
        }

        /** See LUCENE-5062, <see cref="ContainsPrefixTreeFilter.m_multiOverlappingIndexedShapes"/>. */
        [Test, Repeat(ITERATIONS)]
        public virtual void TestContainsPairOverlap()
        {
            SetupQuadGrid(3);
            adoc("0", new ShapePair(ctx.MakeRectangle(0, 33, -128, 128), ctx.MakeRectangle(33, 128, -128, 128), true, ctx));
            Commit();
            Query query = strategy.MakeQuery(new SpatialArgs(SpatialOperation.Contains,
                ctx.MakeRectangle(0, 128, -16, 128)));
            SearchResults searchResults = executeQuery(query, 1);
            assertEquals(1, searchResults.numFound);
        }

        [Test]
        public virtual void TestWithinDisjointParts()
        {
            SetupQuadGrid(7);
            //one shape comprised of two parts, quite separated apart
            adoc("0", new ShapePair(ctx.MakeRectangle(0, 10, -120, -100), ctx.MakeRectangle(220, 240, 110, 125), false, ctx));
            Commit();
            //query surrounds only the second part of the indexed shape
            Query query = strategy.MakeQuery(new SpatialArgs(SpatialOperation.IsWithin,
                ctx.MakeRectangle(210, 245, 105, 128)));
            SearchResults searchResults = executeQuery(query, 1);
            //we shouldn't find it because it's not completely within
            assertTrue(searchResults.numFound == 0);
        }

        [Test] /** LUCENE-4916 */
        public virtual void TestWithinLeafApproxRule()
        {
            SetupQuadGrid(2);//4x4 grid
                             //indexed shape will simplify to entire right half (2 top cells)
            adoc("0", ctx.MakeRectangle(192, 204, -128, 128));
            Commit();

            ((RecursivePrefixTreeStrategy)strategy).PrefixGridScanLevel = (Random().nextInt(2 + 1));

            //query does NOT contain it; both indexed cells are leaves to the query, and
            // when expanded to the full grid cells, the top one's top row is disjoint
            // from the query and thus not a match.
            assertTrue(executeQuery(strategy.MakeQuery(
                new SpatialArgs(SpatialOperation.IsWithin, ctx.MakeRectangle(38, 192, -72, 56))
            ), 1).numFound == 0);//no-match

            //this time the rect is a little bigger and is considered a match. It's a
            // an acceptable false-positive because of the grid approximation.
            assertTrue(executeQuery(strategy.MakeQuery(
                new SpatialArgs(SpatialOperation.IsWithin, ctx.MakeRectangle(38, 192, -72, 80))
            ), 1).numFound == 1);//match
        }

        //Override so we can index parts of a pair separately, resulting in the detailLevel
        // being independent for each shape vs the whole thing
        protected override Document newDoc(String id, IShape shape)
        {
            Document doc = new Document();
            doc.Add(new StringField("id", id, Field.Store.YES));
            if (shape != null)
            {
                IList<IShape> shapes;
                if (shape is ShapePair)
                {
                    shapes = new List<IShape>(2);
                    shapes.Add(((ShapePair)shape).shape1);
                    shapes.Add(((ShapePair)shape).shape2);
                }
                else
                {
                    shapes = new List<IShape>(new IShape[] { shape });//Collections.Singleton(shape);
                }
                foreach (IShape shapei in shapes)
                {
                    foreach (Field f in strategy.CreateIndexableFields(shapei))
                    {
                        doc.Add(f);
                    }
                }
                if (storeShape)//just for diagnostics
                    doc.Add(new StoredField(strategy.FieldName, shape.toString()));
            }
            return doc;
        }

        private void doTest(SpatialOperation operation)
        {
            //first show that when there's no data, a query will result in no results
            {
                Query query = strategy.MakeQuery(new SpatialArgs(operation, randomRectangle()));
                SearchResults searchResults = executeQuery(query, 1);
                assertEquals(0, searchResults.numFound);
            }

            bool biasContains = (operation == SpatialOperation.Contains);

            //Main index loop:
            IDictionary<String, IShape> indexedShapes = new LinkedHashMap<String, IShape>();
            IDictionary<String, IShape> indexedShapesGS = new LinkedHashMap<String, IShape>();//grid snapped
            int numIndexedShapes = randomIntBetween(1, 6);
#pragma warning disable 219
            bool indexedAtLeastOneShapePair = false;
#pragma warning restore 219
            for (int i = 0; i < numIndexedShapes; i++)
            {
                String id = "" + i;
                IShape indexedShape;
                int R = Random().nextInt(12);
                if (R == 0)
                {//1 in 12
                    indexedShape = null;
                }
                else if (R == 1)
                {//1 in 12
                    indexedShape = randomPoint();//just one point
                }
                else if (R <= 4)
                {//3 in 12
                 //comprised of more than one shape
                    indexedShape = randomShapePairRect(biasContains);
                    indexedAtLeastOneShapePair = true;
                }
                else
                {
                    indexedShape = randomRectangle();//just one rect
                }

                indexedShapes.Put(id, indexedShape);
                indexedShapesGS.Put(id, gridSnap(indexedShape));

                adoc(id, indexedShape);

                if (Random().nextInt(10) == 0)
                    Commit();//intermediate commit, produces extra segments

            }
            //delete some documents randomly
            IEnumerator<String> idIter = indexedShapes.Keys.ToList().GetEnumerator();
            while (idIter.MoveNext())
            {
                String id = idIter.Current;
                if (Random().nextInt(10) == 0)
                {
                    DeleteDoc(id);
                    //idIter.Remove();
                    indexedShapes.Remove(id);
                    indexedShapesGS.Remove(id);
                }
            }

            Commit();

            //Main query loop:
            int numQueryShapes = AtLeast(20);
            for (int i = 0; i < numQueryShapes; i++)
            {
                int scanLevel = randomInt(grid.MaxLevels);
                ((RecursivePrefixTreeStrategy)strategy).PrefixGridScanLevel = (scanLevel);

                IShape queryShape;
                switch (randomInt(10))
                {
                    case 0: queryShape = randomPoint(); break;
                    // LUCENE-5549
                    //TODO debug: -Dtests.method=testWithin -Dtests.multiplier=3 -Dtests.seed=5F5294CE2E075A3E:AAD2F0F79288CA64
                    //        case 1:case 2:case 3:
                    //          if (!indexedAtLeastOneShapePair) { // avoids ShapePair.relate(ShapePair), which isn't reliable
                    //            queryShape = randomShapePairRect(!biasContains);//invert biasContains for query side
                    //            break;
                    //          }
                    default: queryShape = randomRectangle(); break;
                }
                IShape queryShapeGS = gridSnap(queryShape);

                bool opIsDisjoint = operation == SpatialOperation.IsDisjointTo;

                //Generate truth via brute force:
                // We ensure true-positive matches (if the predicate on the raw shapes match
                //  then the search should find those same matches).
                // approximations, false-positive matches
                ISet<String> expectedIds = new /* LinkedHashSet<string>*/ HashSet<string>();//true-positives
                ISet<String> secondaryIds = new /* LinkedHashSet<string>*/ HashSet<string>();//false-positives (unless disjoint)
                foreach (var entry in indexedShapes)
                {
                    String id = entry.Key;
                    IShape indexedShapeCompare = entry.Value;
                    if (indexedShapeCompare == null)
                        continue;
                    IShape queryShapeCompare = queryShape;

                    if (operation.Evaluate(indexedShapeCompare, queryShapeCompare))
                    {
                        expectedIds.add(id);
                        if (opIsDisjoint)
                        {
                            //if no longer intersect after buffering them, for disjoint, remember this
                            indexedShapeCompare = indexedShapesGS[id];
                            queryShapeCompare = queryShapeGS;
                            if (!operation.Evaluate(indexedShapeCompare, queryShapeCompare))
                                secondaryIds.add(id);
                        }
                    }
                    else if (!opIsDisjoint)
                    {
                        //buffer either the indexed or query shape (via gridSnap) and try again
                        if (operation == SpatialOperation.Intersects)
                        {
                            indexedShapeCompare = indexedShapesGS[id];
                            queryShapeCompare = queryShapeGS;
                            //TODO Unfortunately, grid-snapping both can result in intersections that otherwise
                            // wouldn't happen when the grids are adjacent. Not a big deal but our test is just a
                            // bit more lenient.
                        }
                        else if (operation == SpatialOperation.Contains)
                        {
                            indexedShapeCompare = indexedShapesGS[id];
                        }
                        else if (operation == SpatialOperation.IsWithin)
                        {
                            queryShapeCompare = queryShapeGS;
                        }
                        if (operation.Evaluate(indexedShapeCompare, queryShapeCompare))
                            secondaryIds.add(id);
                    }
                }

                //Search and verify results
                SpatialArgs args = new SpatialArgs(operation, queryShape);
                if (queryShape is ShapePair)
                    args.DistErrPct = (0.0);//a hack; we want to be more detailed than gridSnap(queryShape)
                Query query = strategy.MakeQuery(args);
                SearchResults got = executeQuery(query, 100);
                ISet<String> remainingExpectedIds = new /* LinkedHashSet<string>*/ HashSet<string>(expectedIds);
                foreach (SearchResult result in got.results)
                {
                    String id = result.GetId();
                    bool removed = remainingExpectedIds.remove(id);
                    if (!removed && (!opIsDisjoint && !secondaryIds.contains(id)))
                    {
                        fail("Shouldn't match", id, indexedShapes, indexedShapesGS, queryShape);
                    }
                }
                if (opIsDisjoint)
                    remainingExpectedIds.removeAll(secondaryIds);
                if (remainingExpectedIds.Any())
                {
                    var iter = remainingExpectedIds.GetEnumerator();
                    iter.MoveNext();
                    String id = iter.Current;
                    fail("Should have matched", id, indexedShapes, indexedShapesGS, queryShape);
                }
            }
        }

        private IShape randomShapePairRect(bool biasContains)
        {
            IRectangle shape1 = randomRectangle();
            IRectangle shape2 = randomRectangle();
            return new ShapePair(shape1, shape2, biasContains, ctx);
        }

        private void fail(String label, String id, IDictionary<String, IShape> indexedShapes, IDictionary<String, IShape> indexedShapesGS, IShape queryShape)
        {
            Console.WriteLine("Ig:" + indexedShapesGS[id] + " Qg:" + gridSnap(queryShape));
            fail(label + " I#" + id + ":" + indexedShapes[id] + " Q:" + queryShape);
        }

        //  private Rectangle inset(Rectangle r) {
        //    //typically inset by 1 (whole numbers are easy to read)
        //    double d = Math.min(1.0, grid.getDistanceForLevel(grid.getMaxLevels()) / 4);
        //    return ctx.makeRectangle(r.getMinX() + d, r.getMaxX() - d, r.getMinY() + d, r.getMaxY() - d);
        //  }

        protected IShape gridSnap(IShape snapMe)
        {
            if (snapMe == null)
                return null;
            if (snapMe is ShapePair)
            {
                ShapePair me = (ShapePair)snapMe;
                return new ShapePair(gridSnap(me.shape1), gridSnap(me.shape2), me.biasContainsThenWithin, ctx);
            }
            if (snapMe is IPoint)
            {
                snapMe = snapMe.BoundingBox;
            }
            //The next 4 lines mimic PrefixTreeStrategy.createIndexableFields()
            double distErrPct = ((PrefixTreeStrategy)strategy).DistErrPct;
            double distErr = SpatialArgs.CalcDistanceFromErrPct(snapMe, distErrPct, ctx);
            int detailLevel = grid.GetLevelForDistance(distErr);
            IList<Cell> cells = grid.GetCells(snapMe, detailLevel, false, true);

            //calc bounding box of cells.
            List<IShape> cellShapes = new List<IShape>(cells.size());
            foreach (Cell cell in cells)
            {
                cellShapes.Add(cell.Shape);
            }
            return new ShapeCollection(cellShapes, ctx).BoundingBox;
        }

        /**
         * An aggregate of 2 shapes. Unfortunately we can't simply use a ShapeCollection because:
         * (a) ambiguity between CONTAINS & WITHIN for equal shapes, and
         * (b) adjacent pairs could as a whole contain the input shape.
         * The tests here are sensitive to these matters, although in practice ShapeCollection
         * is fine.
         */
        private class ShapePair : ShapeCollection /*<Shape>*/
        {

            private readonly SpatialContext ctx;
            internal IShape shape1, shape2;
            internal bool biasContainsThenWithin;//a hack

            public ShapePair(IShape shape1, IShape shape2, bool containsThenWithin, SpatialContext ctx)
                        : base(Arrays.AsList(shape1, shape2), ctx)
            {
                this.ctx = ctx;

                this.shape1 = shape1;
                this.shape2 = shape2;
                biasContainsThenWithin = containsThenWithin;
            }

            public override SpatialRelation Relate(IShape other)
            {
                SpatialRelation r = relateApprox(other);
                if (r == SpatialRelation.CONTAINS)
                    return r;
                if (r == SpatialRelation.DISJOINT)
                    return r;
                if (r == SpatialRelation.WITHIN && !biasContainsThenWithin)
                    return r;

                //See if the correct answer is actually Contains, when the indexed shapes are adjacent,
                // creating a larger shape that contains the input shape.
                bool pairTouches = shape1.Relate(shape2).Intersects();
                if (!pairTouches)
                    return r;
                //test all 4 corners
                IRectangle oRect = (IRectangle)other;
                if (Relate(ctx.MakePoint(oRect.MinX, oRect.MinY)) == SpatialRelation.CONTAINS
                    && Relate(ctx.MakePoint(oRect.MinX, oRect.MaxY)) == SpatialRelation.CONTAINS
                    && Relate(ctx.MakePoint(oRect.MaxX, oRect.MinY)) == SpatialRelation.CONTAINS
                    && Relate(ctx.MakePoint(oRect.MaxX, oRect.MaxY)) == SpatialRelation.CONTAINS)
                    return SpatialRelation.CONTAINS;
                return r;
            }

            private SpatialRelation relateApprox(IShape other)
            {
                if (biasContainsThenWithin)
                {
                    if (shape1.Relate(other) == SpatialRelation.CONTAINS || shape1.equals(other)
                        || shape2.Relate(other) == SpatialRelation.CONTAINS || shape2.equals(other)) return SpatialRelation.CONTAINS;

                    if (shape1.Relate(other) == SpatialRelation.WITHIN && shape2.Relate(other) == SpatialRelation.WITHIN) return SpatialRelation.WITHIN;

                }
                else
                {
                    if ((shape1.Relate(other) == SpatialRelation.WITHIN || shape1.equals(other))
                        && (shape2.Relate(other) == SpatialRelation.WITHIN || shape2.equals(other))) return SpatialRelation.WITHIN;

                    if (shape1.Relate(other) == SpatialRelation.CONTAINS || shape2.Relate(other) == SpatialRelation.CONTAINS) return SpatialRelation.CONTAINS;
                }

                if (shape1.Relate(other).Intersects() || shape2.Relate(other).Intersects())
                    return SpatialRelation.INTERSECTS;//might actually be 'CONTAINS' if the pair are adjacent but we handle that later
                return SpatialRelation.DISJOINT;
            }

            public override String ToString()
            {
                return "ShapePair(" + shape1 + " , " + shape2 + ")";
            }
        }
    }
}


text:
import * as vscode from 'vscode';
import * as log from './log';

const FUCHSIA_DIR_SETTING_KEY = 'fuchsiAware.fuchsia.rootDirectory';

export async function findFuchsiaBuildDir(): Promise<[vscode.Uri, string] | undefined> {
  const buildDirFilename = '.fx-build-dir';
  if (!vscode.workspace.workspaceFolders) {
    return;
  }
  let useFuchsiaDirFromEnv = false;
  let fuchsiaDirFromEnv: string | undefined =
    vscode.workspace.getConfiguration().get(FUCHSIA_DIR_SETTING_KEY);
  let fuchsiaDirVariable;
  if (fuchsiaDirFromEnv) {
    fuchsiaDirVariable = `VS Code setting '${FUCHSIA_DIR_SETTING_KEY}'`;
    useFuchsiaDirFromEnv = true;
  } else {
    fuchsiaDirFromEnv = process.env.FUCHSIA_DIR;
    if (fuchsiaDirFromEnv) {
      fuchsiaDirVariable = `environment variable '$FUCHSIA_DIR'`;
    } else {
      fuchsiaDirFromEnv = process.env.FUCHSIA_ROOT;
      if (fuchsiaDirFromEnv) {
        fuchsiaDirVariable = `environment variable '$FUCHSIA_ROOT'`;
      }
    }
  }
  let fuchsiaSubdirUri;
  for (const folder of vscode.workspace.workspaceFolders) {
    let buildDir;
    if (!useFuchsiaDirFromEnv || folder.uri.path === fuchsiaDirFromEnv) {
      buildDir = await _readBuildDirDoc(folder.uri, buildDirFilename);
    }
    if (buildDir) {
      return [folder.uri, buildDir];
    } else if (!fuchsiaSubdirUri && fuchsiaDirFromEnv &&
      folder.uri.fsPath.startsWith(fuchsiaDirFromEnv)) {
      fuchsiaSubdirUri = folder.uri;
    }
  }
  if (!useFuchsiaDirFromEnv) {
    log.info(
      `Could not find file '${buildDirFilename}' in the root of any workspace folder: \n  ` +
      vscode.workspace.workspaceFolders.map((folder) => folder.uri).join('\n  ')
    );
  }
  if (fuchsiaDirFromEnv) {
    if (fuchsiaSubdirUri) {
      const fuchsiaDirUri = fuchsiaSubdirUri.with({ path: fuchsiaDirFromEnv });
      const buildDir = await _readBuildDirDoc(fuchsiaDirUri, buildDirFilename);
      if (buildDir) {
        log.info(`Loading provider data from ${fuchsiaDirVariable} = '${fuchsiaDirUri}'`);
        return [fuchsiaDirUri, buildDir];
      } else {
        log.info(
          `nor was it found in the directory from ${fuchsiaDirVariable} (${fuchsiaDirUri}).`
        );
      }
    } else {
      log.info(
        `nor was any workspace folder found under the directory from ${fuchsiaDirVariable} ` +
        `(${fuchsiaDirFromEnv}).`
      );
    }
  } else {
    log.info(
      `and the fuchsia root directory could not be determined from either ` +
      `settings ('${FUCHSIA_DIR_SETTING_KEY}') or an environment variable ($FUCHSIA_DIR or ` +
      `$FUCHSIA_ROOT.`
    );
  }
  log.info(
    `If you have an open workspace for the 'fuchsia.git' source tree, make sure the ` +
    `workspace is rooted at the repository root directory (e.g., 'fuchsia'), and ` +
    'run `fx set ...` or `fx use ...`, then reload the VS Code window.'
  );
  return;
}

async function _readBuildDirDoc(
  folderUri: vscode.Uri,
  buildDirFilename: string
): Promise<string | undefined> {
  const buildDirFileUri = folderUri.with({ path: `${folderUri.path}/${buildDirFilename}` });
  try {
    const buildDirDoc = await vscode.workspace.openTextDocument(buildDirFileUri);
    let buildDir = buildDirDoc.getText().trim();
    // buildDir can be an absolute path; make it relative to folderUri.fsPath.
    if (buildDir.startsWith(`${folderUri.fsPath}/`)) {

        buildDir = buildDir.substring(folderUri.fsPath.length + 1);
    }
    log.info(
      `Folder '${folderUri.fsPath}' contains the '${buildDirFilename}' file, ` +
      `which specifies that the current Fuchsia build directory is '${buildDir}'`
    );
    return buildDir;
  } catch (err) {
    return;
  } // the file probably doesn't exist in this folder
}

redpajama_set_name: RedPajamaGithub


text:
package org.mapdb;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Serializer which handles POJO, object graphs etc.
 *
 * @author  Jan Kotek
 */
public class SerializerPojo extends SerializerBase implements Serializable{

    protected final Serializer<ClassInfo> classInfoSerializer = new Serializer<ClassInfo>() {

        @Override
		public void serialize(DataOutput out, ClassInfo ci) throws IOException {
            out.writeUTF(ci.name);
            out.writeBoolean(ci.isEnum);
            out.writeBoolean(ci.useObjectStream);
            if(ci.useObjectStream)
                return; //no fields

            DataIO.packInt(out, ci.fields.length);
            for (FieldInfo fi : ci.fields) {
                out.writeUTF(fi.name);
                out.writeBoolean(fi.primitive);
                out.writeUTF(fi.type);
            }
        }

        @Override
		public ClassInfo deserialize(DataInput in, int available) throws IOException{
            String className = in.readUTF();
            Class clazz = null;
            boolean isEnum = in.readBoolean();
            boolean isExternalizable = in.readBoolean();

            int fieldsNum = isExternalizable? 0 : DataIO.unpackInt(in);
            FieldInfo[] fields = new FieldInfo[fieldsNum];
            for (int j = 0; j < fieldsNum; j++) {
                String fieldName = in.readUTF();
                boolean primitive = in.readBoolean();
                String type = in.readUTF();
                if(clazz == null)
                    clazz = classLoader.run(className);

                fields[j] = new FieldInfo(fieldName,
                        type,
                        primitive?null:classLoader.run(type),
                        clazz);
            }
            return new ClassInfo(className, fields,isEnum,isExternalizable);
        }

        @Override
        public boolean isTrusted() {
            return true;
        }

    };
    private static final long serialVersionUID = 3181417366609199703L;

    protected static final Fun.Function1<Class, String> DEFAULT_CLASS_LOADER = new Fun.Function1<Class, String>() {
        @Override
        public Class run(String className) {
            ClassLoader loader =  Thread.currentThread().getContextClassLoader();
            return classForName(className, loader);
        }
    };

    protected static Class classForName(String className, ClassLoader loader) {
        try {
            return Class.forName(className, true, loader);
        } catch (ClassNotFoundException e) {
            throw new DBException.ClassNotFound(e);
        }
    }

    protected final Engine engine;

    protected final Fun.Function1<String,Object> getNameForObject;
    protected final Fun.Function1<Object,String> getNamedObject;

    protected final Fun.Function0<ClassInfo[]> getClassInfos;
    protected final Fun.Function1Int<ClassInfo> getClassInfo;
    protected final Fun.Function1<Void,String> notifyMissingClassInfo;
    protected final Fun.Function1<Class, String> classLoader;

    public SerializerPojo(
            Fun.Function1<String, Object> getNameForObject,
            Fun.Function1<Object, String> getNamedObject,
            Fun.Function1Int<ClassInfo> getClassInfo,
            Fun.Function0<ClassInfo[]> getClassInfos,
            Fun.Function1<Void, String> notifyMissingClassInfo,
            Fun.Function1<Class, String> classLoader,
            Engine engine){
        this.getNameForObject = getNameForObject;
        this.getNamedObject = getNamedObject;
        this.classLoader = classLoader!=null? classLoader : DEFAULT_CLASS_LOADER;
        this.engine = engine;
        this.getClassInfo = getClassInfo!=null?getClassInfo:new Fun.Function1Int<ClassInfo>() {
            @Override public ClassInfo run(int a) {
                return null;
            }
        };
        this.getClassInfos = getClassInfos!=null?getClassInfos:new Fun.Function0<ClassInfo[]>() {
            @Override
            public ClassInfo[] run() {
                return new ClassInfo[0];
            }
        };
        this.notifyMissingClassInfo = notifyMissingClassInfo;
    }

    /**
     * Stores info about single class stored in MapDB.
     * Roughly corresponds to 'java.io.ObjectStreamClass'
     */
    protected static final class ClassInfo {

        //TODO optimize deserialization cost here.

        protected final String name;
        protected final FieldInfo[] fields;
        protected final Map<String, FieldInfo> name2fieldInfo = new HashMap<String, FieldInfo>();
        protected final Map<String, Integer> name2fieldId = new HashMap<String, Integer>();
        protected ObjectStreamField[] objectStreamFields;

        protected final boolean isEnum;

        protected final boolean useObjectStream;

        public ClassInfo(final String name, final FieldInfo[] fields, final boolean isEnum, final boolean isExternalizable) {
            this.name = name;
            this.isEnum = isEnum;
            this.useObjectStream = isExternalizable;

            this.fields = fields.clone();

            //TODO constructing dictionary might be contraproductive, perhaps use linear scan for smaller sizes
            for (int i=0;i<fields.length;i++) {
                FieldInfo f = fields[i];
                this.name2fieldId.put(f.name, i);
                this.name2fieldInfo.put(f.name, f);
            }
        }

        public int getFieldId(String name) {
            Integer fieldId = name2fieldId.get(name);
            if(fieldId != null)
                return fieldId;
            return -1;
        }

        public ObjectStreamField[] getObjectStreamFields() {
            return objectStreamFields;
        }

        @Override public String toString(){
            return super.toString()+ "["+name+"]";
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            ClassInfo classInfo = (ClassInfo) o;

            if (isEnum != classInfo.isEnum) return false;
            if (useObjectStream != classInfo.useObjectStream) return false;
            if (name != null ? !name.equals(classInfo.name) : classInfo.name != null) return false;
            // Probably incorrect - comparing Object[] arrays with Arrays.equals
            return Arrays.equals(fields, classInfo.fields);

        }

        @Override
        public int hashCode() {
            int result = name != null ? name.hashCode() : 0;
            result = 31 * result + (fields != null ? Arrays.hashCode(fields) : 0);
            result = 31 * result + (isEnum ? 1 : 0);
            result = 31 * result + (useObjectStream ? 1 : 0);
            return result;
        }
    }

    /**
     * Stores info about single field stored in MapDB.
     * Roughly corresponds to 'java.io.ObjectFieldClass'
     */
    protected static class FieldInfo {
        protected final String name;
        protected final boolean primitive;
        protected final String type;
        protected Class<?> typeClass;
        // Class containing this field
        protected final Class<?> clazz;
        protected Field field;

//        FieldInfo(String name, boolean primitive, String type, Class<?> clazz) {
//            this(name, primitive, SerializerPojo.classForNameClassLoader(), type, clazz);
//        }
//
//        public FieldInfo(String name, boolean primitive, ClassLoader classLoader, String type, Class<?> clazz) {
//            this(name, type, primitive ? null : classForName(classLoader, type), clazz);
//        }
//
//        public FieldInfo(ObjectStreamField sf, ClassLoader loader, Class<?> clazz) {
//            this(sf.getName(), sf.isPrimitive(), loader, sf.getType().getName(), clazz);
//        }

        public FieldInfo(String name, String type, Class<?> typeClass, Class<?> clazz) {
            this.name = name;
            this.primitive = typeClass == null;
            this.type = type;
            this.clazz = clazz;
            this.typeClass = typeClass;

            //init field

            Class<?> aClazz = clazz;

            // iterate over class hierarchy, until root class
            while (true) {
                if(aClazz == Object.class) throw new RuntimeException("Could not set field value: "+name+" - "+clazz.toString());
                // access field directly
                try {
                    Field f = aClazz.getDeclaredField(name);
                    // security manager may not be happy about this
                    if (!f.isAccessible())
                        f.setAccessible(true);
                    field = f;
                    break;
                } catch (NoSuchFieldException e) {
                    //field does not exists
                }
                // move to superclass
                aClazz = aClazz.getSuperclass();
            }
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            FieldInfo fieldInfo = (FieldInfo) o;

            if (primitive != fieldInfo.primitive) return false;
            if (name != null ? !name.equals(fieldInfo.name) : fieldInfo.name != null) return false;
            if (type != null ? !type.equals(fieldInfo.type) : fieldInfo.type != null) return false;
            if (typeClass != null ? !typeClass.equals(fieldInfo.typeClass) : fieldInfo.typeClass != null) return false;
            if (clazz != null ? !clazz.equals(fieldInfo.clazz) : fieldInfo.clazz != null) return false;
            return !(field != null ? !field.equals(fieldInfo.field) : fieldInfo.field != null);

        }

        @Override
        public int hashCode() {
            int result = name != null ? name.hashCode() : 0;
            result = 31 * result + (primitive ? 1 : 0);
            result = 31 * result + (type != null ? type.hashCode() : 0);
            result = 31 * result + (typeClass != null ? typeClass.hashCode() : 0);
            result = 31 * result + (clazz != null ? clazz.hashCode() : 0);
            result = 31 * result + (field != null ? field.hashCode() : 0);
            return result;
        }
    }

    public ClassInfo makeClassInfo(String className){
        Class clazz = classLoader.run(className);
        final boolean advancedSer = usesAdvancedSerialization(clazz);
        ObjectStreamField[] streamFields = advancedSer ? new ObjectStreamField[0] : makeFieldsForClass(clazz);
        FieldInfo[] fields = new FieldInfo[streamFields.length];
        for (int i = 0; i < fields.length; i++) {
            ObjectStreamField sf = streamFields[i];
            String type = sf.getType().getName();
            fields[i] = new FieldInfo(
                    sf.getName(),
                    type,
                    sf.isPrimitive() ? null : classLoader.run(type),
                    clazz);
        }

        return new ClassInfo(clazz.getName(), fields, clazz.isEnum(), advancedSer);
    }

    protected static boolean usesAdvancedSerialization(Class<?> clazz) {
        if(Externalizable.class.isAssignableFrom(clazz))
            return true;
        try {
            if(clazz.getDeclaredMethod("readObject",ObjectInputStream.class)!=null)
                return true;
        } catch (NoSuchMethodException e) {
        }

        try {
            if(clazz.getDeclaredMethod("writeObject",ObjectOutputStream.class)!=null)
                return true;
        } catch (NoSuchMethodException e) {
        }

        try {
            if(clazz.getDeclaredMethod("writeReplace")!=null)
                return true;
        } catch (NoSuchMethodException e) {
        }

        try {
            if(clazz.getDeclaredMethod("readResolve")!=null)
                return true;
        } catch (NoSuchMethodException e) {
        }

        return false;
    }

    protected static ObjectStreamField[] fieldsForClass(ClassInfo[] classes, Class<?> clazz) {
        ObjectStreamField[] fields = null;
        ClassInfo classInfo = null;
        int classId = classToId(classes,clazz.getName());
        if (classId != -1) {
            classInfo = classes[classId];
            fields = classInfo.getObjectStreamFields();
        }
        if (fields == null) {
            fields = makeFieldsForClass(clazz);
        }
        return fields;
    }

    private static ObjectStreamField[] makeFieldsForClass(Class<?> clazz) {
        ObjectStreamField[] fields;ObjectStreamClass streamClass = ObjectStreamClass.lookup(clazz);
        FastArrayList<ObjectStreamField> fieldsList = new FastArrayList<ObjectStreamField>();
        while (streamClass != null) {
            for (ObjectStreamField f : streamClass.getFields()) {
                fieldsList.add(f);
            }
            clazz = clazz.getSuperclass();
            streamClass = ObjectStreamClass.lookup(clazz);
        }
        fields = new ObjectStreamField[fieldsList
                .size];
        System.arraycopy(fieldsList.data, 0, fields, 0, fields.length);
        //TODO what is StreamField? perhaps performance optim?
//        if(classInfo != null)
//            classInfo.setObjectStreamFields(fields);
        return fields;
    }

    public boolean isSerializable(Object o){
        if(super.isSerializable(o))
            return true;

        return Serializable.class.isAssignableFrom(o.getClass());
    }

    protected void assertClassSerializable(ClassInfo[] classes, Class<?> clazz) throws NotSerializableException, InvalidClassException {
        if(classToId(classes,clazz.getName())!=-1)
            return;

        if (!Serializable.class.isAssignableFrom(clazz))
            throw new NotSerializableException(clazz.getName());

    }

    public Object getFieldValue(FieldInfo fieldInfo, Object object) {

        if(fieldInfo.field==null){
            throw new NoSuchFieldError(object.getClass() + "." + fieldInfo.name);
        }

        try {
            return fieldInfo.field.get(object);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Could not get value from field", e);
        }
    }

    public void setFieldValue(FieldInfo fieldInfo, Object object, Object value) {
        if(fieldInfo.field==null)
            throw new NoSuchFieldError(object.getClass() + "." + fieldInfo.name);

        try{
           fieldInfo.field.set(object, value);
        } catch (IllegalAccessException e) {
           throw new RuntimeException("Could not set field value: ",e);
        }

    }

    public static int classToId(ClassInfo[] classes, String className) {
        for(int i=0;i<classes.length;i++){
            if(classes[i].name.equals(className))
                return i;
        }
        return -1;
    }

    @Override
    protected Engine getEngine() {
        return engine;
    }

    @Override
    protected void serializeUnknownObject(DataOutput out, Object obj, FastArrayList<Object> objectStack) throws IOException {
        if(getNameForObject!=null){
            //check for named objects
            String name = getNameForObject.run(obj);
            if(name!=null){
                out.write(Header.NAMED);
                out.writeUTF(name);
                //TODO object stack here?
                return;
            }
        }

        out.write(Header.POJO);

        ClassInfo[] classes = getClassInfos.run();
        assertClassSerializable(classes,obj.getClass());
        //write class header
        int classId = classToId(classes,obj.getClass().getName());
        if(classId==-1){
            //unknown class, fallback into object OutputOutputStream
            DataIO.packInt(out,-1);
            ObjectOutputStream2 out2 = new ObjectOutputStream2((OutputStream) out, classes);
            out2.writeObject(obj);
            //and notify listeners about missing class
            if(notifyMissingClassInfo!=null)
                notifyMissingClassInfo.run(obj.getClass().getName());
            return;
        }

        Class<?> clazz = obj.getClass();
        if( !clazz.isEnum() && clazz.getSuperclass()!=null && clazz.getSuperclass().isEnum())
            clazz = clazz.getSuperclass();

        if(clazz != Object.class)
            assertClassSerializable(classes,clazz);

        //write class header
        DataIO.packInt(out, classId);
        ClassInfo classInfo = classes[classId];

        if(classInfo.useObjectStream){
            ObjectOutputStream2 out2 = new ObjectOutputStream2((OutputStream) out, classes);
            out2.writeObject(obj);
            return;
        }

        if(classInfo.isEnum) {
            int ordinal = ((Enum<?>)obj).ordinal();
            DataIO.packInt(out, ordinal);
        }

        ObjectStreamField[] fields = fieldsForClass(classes, clazz);
        DataIO.packInt(out, fields.length);

        for (ObjectStreamField f : fields) {
            //write field ID
            int fieldId = classInfo.getFieldId(f.getName());
            if (fieldId == -1) {
                throw new AssertionError("Missing field: "+f.getName());
                //TODO class info is immutable in 2.0, so this old code can not be used
//                //field does not exists in class definition stored in db,
//                //probably new field was added so add field descriptor
//                fieldId = classInfo.addFieldInfo(new FieldInfo(f, clazz));
//                saveClassInfo();
            }
            DataIO.packInt(out, fieldId);
            //and write value
            Object fieldValue = getFieldValue(classInfo.fields[fieldId], obj);
            serialize(out, fieldValue, objectStack);
        }
    }

    @Override
    protected Object deserializeUnknownHeader(DataInput in, int head, FastArrayList<Object> objectStack) throws IOException {
        if(head == Header.NAMED){
            String name = in.readUTF();
            Object o = getNamedObject.run(name);
            if(o==null)
                throw new DBException.DataCorruption("Named object was not found: "+name);
            objectStack.add(o);
            return o;
        }

        if(head!= Header.POJO)
            throw new DBException.DataCorruption("wrong header");
        try {
            int classId = DataIO.unpackInt(in);
            ClassInfo classInfo = getClassInfo.run(classId);

            //is unknown Class or uses specialized serialization
            if (classId == -1 || classInfo.useObjectStream) {
                //deserialize using object stream
                ObjectInputStream2 in2 = new ObjectInputStream2(in, getClassInfos.run());
                Object o = in2.readObject();
                objectStack.add(o);
                return o;
            }

            Class<?> clazz = classLoader.run(classInfo.name);
            if (!Serializable.class.isAssignableFrom(clazz))
                throw new NotSerializableException(clazz.getName());

            Object o;
            if (classInfo.isEnum) {
                int ordinal = DataIO.unpackInt(in);
                o = clazz.getEnumConstants()[ordinal];
            } else {
                o = createInstanceSkippinkConstructor(clazz);
            }

            objectStack.add(o);

            int fieldCount = DataIO.unpackInt(in);
            for (int i = 0; i < fieldCount; i++) {
                int fieldId = DataIO.unpackInt(in);
                FieldInfo f = classInfo.fields[fieldId];
                Object fieldValue = deserialize(in, objectStack);
                setFieldValue(f, o, fieldValue);
            }

            return o;
        }catch(ClassNotFoundException e){
            throw new DBException.ClassNotFound(e);
        }
    }

    static protected Method sunConstructor = null;
    static protected Object sunReflFac = null;
    static protected Method androidConstructor = null;
    static private Method androidConstructorGinger = null;
    static private Method androidConstructorJelly = null;
    static private Object constructorId;

    static{
        try{
            Class<?> clazz = DEFAULT_CLASS_LOADER.run("sun.reflect.ReflectionFactory");
            if(clazz!=null){
                Method getReflectionFactory = clazz.getMethod("getReflectionFactory");
                sunReflFac = getReflectionFactory.invoke(null);
                sunConstructor = clazz.getMethod("newConstructorForSerialization",
                        java.lang.Class.class, java.lang.reflect.Constructor.class);
            }
        }catch(Exception e){
            //ignore
        }

        if(sunConstructor == null)try{
            //try android way
            Method newInstance = ObjectInputStream.class.getDeclaredMethod("newInstance", Class.class, Class.class);
            newInstance.setAccessible(true);
            androidConstructor = newInstance;

        }catch(Exception e){
            //ignore
        }

        //this method was taken from
        //http://dexmaker.googlecode.com/git-history/5a7820356e68a977711afc854d6cd71296c56391/src/mockito/java/com/google/dexmaker/mockito/UnsafeAllocator.java
        //Copyright (C) 2012 The Android Open Source Project, licenced under Apache 2 license
        if(sunConstructor == null && androidConstructor == null)try{
            //try android post ginger way
            Method getConstructorId = ObjectStreamClass.class.getDeclaredMethod("getConstructorId", Class.class);
            getConstructorId.setAccessible(true);
            constructorId = getConstructorId.invoke(null, Object.class);

            Method newInstance = ObjectStreamClass.class.getDeclaredMethod("newInstance", Class.class, getConstructorId.getReturnType());
            newInstance.setAccessible(true);
            androidConstructorGinger = newInstance;

        }catch(Exception e){
            //ignore
        }

        if(sunConstructor == null && androidConstructor == null && androidConstructorGinger == null)try{
            //try android post 4.2 way
            Method getConstructorId = ObjectStreamClass.class.getDeclaredMethod("getConstructorId", Class.class);
            getConstructorId.setAccessible(true);
            constructorId = getConstructorId.invoke(null, Object.class);

            Method newInstance = ObjectStreamClass.class.getDeclaredMethod("newInstance", Class.class, long.class);
            newInstance.setAccessible(true);
            androidConstructorJelly = newInstance;

        }catch(Exception e){
            //ignore
        }
    }

    protected static Map<Class<?>, Constructor<?>> class2constuctor = new ConcurrentHashMap<Class<?>, Constructor<?>>();

    /**
     * <p>
     * For pojo serialization we need to instantiate class without invoking its constructor.
     * There are two ways to do it:
     * </p><p>
     *   Using proprietary API on Oracle JDK and OpenJDK
     *   sun.reflect.ReflectionFactory.getReflectionFactory().newConstructorForSerialization()
     *   more at http://www.javaspecialists.eu/archive/Issue175.html
     * </p><p>
     *   Using {@code ObjectInputStream.newInstance} on Android
     *   http://stackoverflow.com/a/3448384
     * </p><p>
     *   If non of these works we fallback into usual reflection which requires an no-arg constructor
     * </p>
     */
    @SuppressWarnings("restriction")
	protected <T> T createInstanceSkippinkConstructor(Class<T> clazz) {

        try {
            if (sunConstructor != null) {
                //Sun specific way
                Constructor<?> intConstr = class2constuctor.get(clazz);

                if (intConstr == null) {
                    Constructor<?> objDef = Object.class.getDeclaredConstructor();
                    intConstr = (Constructor<?>) sunConstructor.invoke(sunReflFac, clazz, objDef);
                    class2constuctor.put(clazz, intConstr);
                }

                return (T) intConstr.newInstance();
            } else if (androidConstructor != null) {
                //android (harmony) specific way
                return (T) androidConstructor.invoke(null, clazz, Object.class);
            } else if (androidConstructorGinger != null) {
                //android (post ginger) specific way
                return (T) androidConstructorGinger.invoke(null, clazz, constructorId);
            } else if (androidConstructorJelly != null) {
                //android (post 4.2) specific way
                return (T) androidConstructorJelly.invoke(null, clazz, constructorId);
            } else {
                //try usual generic stuff which does not skip constructor
                Constructor<?> c = class2constuctor.get(clazz);
                if (c == null) {
                    c = clazz.getConstructor();
                    if (!c.isAccessible()) c.setAccessible(true);
                    class2constuctor.put(clazz, c);
                }
                return (T) c.newInstance();
            }
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        }
    }

    protected final class ObjectOutputStream2 extends ObjectOutputStream{

        private final ClassInfo[] classes;

        protected ObjectOutputStream2(OutputStream out, ClassInfo[] classes) throws IOException, SecurityException {
            super(out);
            this.classes = classes;
        }

        @Override
        protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException {
            int classId = classToId(classes,desc.getName());
            DataIO.packInt(this,classId);
            if(classId==-1){
                //unknown class, write its full name
                this.writeUTF(desc.getName());
                //and notify about unknown class
                if(notifyMissingClassInfo!=null)
                    notifyMissingClassInfo.run(desc.getName());
            }
        }
    }

    protected final class ObjectInputStream2 extends ObjectInputStream{

        private final ClassInfo[] classes;

        // One-element cache to handle the common case where we immediately resolve a descriptor to its class.
        // Unlike most ObjecTInputStream subclasses we actually have to look up the class to find the descriptor!
        private ObjectStreamClass lastDescriptor;
        private Class lastDescriptorClass;

        protected ObjectInputStream2(DataInput in, ClassInfo[] classes) throws IOException, SecurityException {
            super(new DataIO.DataInputToStream(in));
            this.classes = classes;
        }

        @Override
        protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException {
            int classId = DataIO.unpackInt(this);

            final Class clazz;
            String className;
            if(classId == -1){
                //unknown class, so read its name
                className = this.readUTF();
            }else{
                className = classes[classId].name;
            }
            clazz = classLoader.run(className);
            final ObjectStreamClass descriptor = ObjectStreamClass.lookup(clazz);

            lastDescriptor = descriptor;
            lastDescriptorClass = clazz;

            return descriptor;
        }

        @Override
        protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
            if (desc == lastDescriptor) return lastDescriptorClass;
            Class<?> clazz = classLoader.run(desc.getName());
            if (clazz != null)
                return clazz;
            return super.resolveClass(desc);
        }
    }
}


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2020 Couchbase, Inc
 *
 *   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.
 */

#include "collections_dcp_producers.h"

#include "collections/collections_types.h"
#include "item.h"
#include "tests/mock/mock_dcp_consumer.h"

#include "folly/portability/GTest.h"

/*
 * DCP callback method to push SystemEvents on to the consumer
 */
ENGINE_ERROR_CODE CollectionsDcpTestProducers::system_event(
        uint32_t opaque,
        Vbid vbucket,
        mcbp::systemevent::id event,
        uint64_t bySeqno,
        mcbp::systemevent::version version,
        cb::const_byte_buffer key,
        cb::const_byte_buffer eventData,
        cb::mcbp::DcpStreamId sid) {
    (void)vbucket; // ignored as we are connecting VBn to VBn+1
    clear_dcp_data();
    last_op = cb::mcbp::ClientOpcode::DcpSystemEvent;
    last_system_event = event;
    // Validate the provided parameters
    cb::mcbp::request::DcpSystemEventPayload extras(bySeqno, event, version);
    EXPECT_TRUE(extras.isValidVersion());
    EXPECT_TRUE(extras.isValidEvent());
    last_system_event_data.insert(
            last_system_event_data.begin(), eventData.begin(), eventData.end());
    last_system_event_version = version;
    last_stream_id = sid;

    switch (event) {
    case mcbp::systemevent::id::CreateCollection: {
        last_collection_id =
                reinterpret_cast<const Collections::CreateEventDcpData*>(
                        eventData.data())
                        ->cid.to_host();
        if (version == mcbp::systemevent::version::version0) {
            // Using the ::size directly in the EXPECT is failing to link on
            // OSX build, but copying the value works.
            const auto expectedSize = Collections::CreateEventDcpData::size;
            EXPECT_EQ(expectedSize, eventData.size());
            const auto* ev =
                    reinterpret_cast<const Collections::CreateEventDcpData*>(
                            eventData.data());
            last_collection_id = ev->cid.to_host();
            last_scope_id = ev->sid.to_host();
            last_collection_manifest_uid = ev->manifestUid.to_host();
        } else {
            const auto expectedSize =
                    Collections::CreateWithMaxTtlEventDcpData::size;
            EXPECT_EQ(expectedSize, eventData.size());
            const auto* ev = reinterpret_cast<
                    const Collections::CreateWithMaxTtlEventDcpData*>(
                    eventData.data());
            last_collection_id = ev->cid.to_host();
            last_scope_id = ev->sid.to_host();
            last_collection_manifest_uid = ev->manifestUid.to_host();
        }

        last_key.assign(reinterpret_cast<const char*>(key.data()), key.size());
        break;
    }
    case mcbp::systemevent::id::DeleteCollection: {
        const auto* ev = reinterpret_cast<const Collections::DropEventDcpData*>(
                eventData.data());
        last_collection_id = ev->cid.to_host();
        last_collection_manifest_uid = ev->manifestUid.to_host();
        // Using the ::size directly in the EXPECT is failing to link on
        // OSX build, but copying the value works.
        const auto expectedSize = Collections::DropEventDcpData::size;
        EXPECT_EQ(expectedSize, eventData.size());
        EXPECT_EQ(nullptr, key.data());
        break;
    }
    case mcbp::systemevent::id::CreateScope: {
        const auto* ev =
                reinterpret_cast<const Collections::CreateScopeEventDcpData*>(
                        eventData.data());
        last_scope_id = ev->sid.to_host();
        last_collection_manifest_uid = ev->manifestUid.to_host();

        const auto expectedSize = Collections::CreateScopeEventDcpData::size;
        EXPECT_EQ(expectedSize, eventData.size());
        last_key.assign(reinterpret_cast<const char*>(key.data()), key.size());
        break;
    }
    case mcbp::systemevent::id::DropScope: {
        const auto* ev =
                reinterpret_cast<const Collections::DropScopeEventDcpData*>(
                        eventData.data());
        last_scope_id = ev->sid.to_host();
        last_collection_manifest_uid = ev->manifestUid.to_host();

        const auto expectedSize = Collections::DropScopeEventDcpData::size;
        EXPECT_EQ(expectedSize, eventData.size());
        EXPECT_EQ(nullptr, key.data());
        break;
    }
    default:
        EXPECT_TRUE(false) << "Unsupported event " << int(event);
    }

    if (consumer) {
        auto rv = consumer->systemEvent(
                opaque, replicaVB, event, bySeqno, version, key, eventData);
        EXPECT_EQ(ENGINE_SUCCESS, rv)
                << "Failure to push system-event onto the consumer";
        return rv;
    }
    return ENGINE_SUCCESS;
}

ENGINE_ERROR_CODE CollectionsDcpTestProducers::marker(
        uint32_t opaque,
        Vbid vbucket,
        uint64_t start_seqno,
        uint64_t end_seqno,
        uint32_t flags,
        std::optional<uint64_t> high_completed_seqno,
        std::optional<uint64_t> maxVisibleSeqno,
        std::optional<uint64_t> timestamp,
        cb::mcbp::DcpStreamId sid) {
    auto ret = ENGINE_SUCCESS;
    if (consumer) {
        ret = consumer->snapshotMarker(opaque,
                                       replicaVB,
                                       start_seqno,
                                       end_seqno,
                                       flags,
                                       high_completed_seqno,
                                       maxVisibleSeqno);
        EXPECT_EQ(ENGINE_SUCCESS, ret);
    }

    MockDcpMessageProducers::marker(opaque,
                                    replicaVB,
                                    start_seqno,
                                    end_seqno,
                                    flags,
                                    high_completed_seqno,
                                    maxVisibleSeqno,
                                    timestamp,
                                    sid);

    return ret;
}

ENGINE_ERROR_CODE CollectionsDcpTestProducers::mutation(
        uint32_t opaque,
        cb::unique_item_ptr itm,
        Vbid vbucket,
        uint64_t by_seqno,
        uint64_t rev_seqno,
        uint32_t lock_time,
        uint8_t nru,
        cb::mcbp::DcpStreamId sid) {
    auto ret = ENGINE_SUCCESS;
    if (consumer) {
        auto& item = *static_cast<Item*>(itm.get());

        ret = consumer->mutation(
                opaque,
                item.getKey(),
                {reinterpret_cast<const uint8_t*>(item.getData()),
                 item.getNBytes()},
                0,
                item.getDataType(),
                item.getCas(),
                replicaVB,
                item.getFlags(),
                by_seqno,
                rev_seqno,
                item.getExptime(),
                lock_time,
                {},
                nru);
    }

    MockDcpMessageProducers::mutation(opaque,
                                      std::move(itm),
                                      vbucket,
                                      by_seqno,
                                      rev_seqno,
                                      lock_time,
                                      nru,
                                      sid);
    return ret;
}

ENGINE_ERROR_CODE CollectionsDcpTestProducers::prepare(
        uint32_t opaque,
        cb::unique_item_ptr itm,
        Vbid vbucket,
        uint64_t by_seqno,
        uint64_t rev_seqno,
        uint32_t lock_time,
        uint8_t nru,
        DocumentState document_state,
        cb::durability::Level level) {
    auto ret = ENGINE_SUCCESS;
    if (consumer) {
        auto& item = *static_cast<Item*>(itm.get());

        ret = consumer->prepare(
                opaque,
                item.getKey(),
                {reinterpret_cast<const uint8_t*>(item.getData()),
                 item.getNBytes()},
                0,
                item.getDataType(),
                item.getCas(),
                replicaVB,
                item.getFlags(),
                by_seqno,
                rev_seqno,
                item.getExptime(),
                lock_time,
                nru,
                document_state,
                level);
    }
    MockDcpMessageProducers::prepare(opaque,
                                     std::move(itm),
                                     vbucket,
                                     by_seqno,
                                     rev_seqno,
                                     lock_time,
                                     nru,
                                     document_state,
                                     level);
    return ret;
}

ENGINE_ERROR_CODE CollectionsDcpTestProducers::commit(uint32_t opaque,
                                                      Vbid vbucket,
                                                      const DocKey& key,
                                                      uint64_t prepare_seqno,
                                                      uint64_t commit_seqno) {
    auto ret = ENGINE_SUCCESS;
    if (consumer) {
        ret = consumer->commit(
                opaque, replicaVB, key, prepare_seqno, commit_seqno);
    }
    MockDcpMessageProducers::commit(
            opaque, vbucket, key, prepare_seqno, commit_seqno);
    return ret;
}


text:
from Config import Config

class Runde(object):
    def __init__(self):
        self.zuege = []
        self.strafe = 0
        self.verlierer = None
        self.besterSpieler = None

    def add_zug(self, zug):
        self.zuege.append(zug)

    def get_zug(self, spieler):
        zug = None
        for x in range(0, len(self.zuege)):
            if self.zuege[x].spieler == spieler:
                zug = self.zuege[x]
        return zug

    def get_ersten_zug(self):
        return self.zuege[0]

    def get_runden_beginner(self):
        return self.zuege[0].spieler

    def get_winning_wurf(self):
        """ TODO """
        return self.zuege[len(self.zuege)].get_last_wurf()

    def get_aktuelle_zugnummer(self):
        return len(self.zuege)

    def ermittle_strafe(self):
        hoechster_zug = self.zuege[0]
        for x in range(1, len(self.zuege)):
            """ TODO: Mit-Ist-Shit """
            if hoechster_zug is None or self.zuege[x] > hoechster_zug:
                hoechster_zug = self.zuege[x]

        if Config.LOG_RUNDEN: print("Höchster Zug: {0}".format(hoechster_zug))

        if hoechster_zug is not None:
            self.strafe = hoechster_zug.endergebnis.get_strafstein_wertigkeit()

        return self.strafe

    def ermittle_besten_spieler(self):
        hoechster_zug = self.zuege[0]
        for x in range(1, len(self.zuege)):
            """ TODO: Mit-Ist-Shit """
            if hoechster_zug is None or self.zuege[x] > hoechster_zug:
                hoechster_zug = self.zuege[x]

        if Config.LOG_RUNDEN: print("Bester Spieler der Runde: {0}".format(hoechster_zug.spieler))

        if hoechster_zug is not None:
            self.besterSpieler = hoechster_zug.spieler

        return self.besterSpieler

    def ermittle_verlierer(self):
        niedrigster_zug = self.zuege[0]

        for x in range(1, len(self.zuege)):
            """ TODO: Mit-Ist-Shit """
            if niedrigster_zug is None or self.zuege[x] < niedrigster_zug:
                niedrigster_zug = self.zuege[x]

        if niedrigster_zug is not None:
            self.verlierer = niedrigster_zug.spieler

        return self.verlierer


text:
package tlc2.tool.liveness.simulation;

import tlc2.TLC;

public class SimulationTest2 extends SuccessfulSimulationTestCase {

	public SimulationTest2() {
		super("Test2", "/", new String[] {"-simulate", "-depth", "6"});
		TLC.setTraceNum(50);
	}
}


text:
'use strict';
require('../common');
const assert = require('assert');
const { sleep } = require('internal/util');

let cntr = 0;
let first;
const t = setInterval(() => {
  cntr++;
  if (cntr === 1) {
    sleep(100);
    // Ensure that the event loop passes before the second interval
    setImmediate(() => assert.strictEqual(cntr, 1));
    first = Date.now();
  } else if (cntr === 2) {
    assert(Date.now() - first < 100);
    clearInterval(t);
  }
}, 100);
const t2 = setInterval(() => {
  if (cntr === 2) {
    clearInterval(t2);
  }
}, 100);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>org.apache.solr.analytics.plugin (Solr 6.3.0 API)</title>
<meta name="date" content="2016-11-02">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.apache.solr.analytics.plugin

Classes

AnalyticsStatisticsCollector


text:
<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>A page » First subpage | My Project</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,600,600i%7CSource+Code+Pro:400,400i,600" />
  <link rel="stylesheet" href="m-dark+documentation.compiled.css" />
  <link rel="next" href="subpage2.html" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

      My Project

          A page »
          First subpage

A page | Second subpage »


text:
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.Token;

import java.util.ArrayDeque;

public class CPPLexer extends CPPBaseLexer {
	protected ArrayDeque<Token> buffer = new ArrayDeque<Token>();

	public CPPLexer(CharStream input) { super(input); }

	@Override
	public Token nextToken() {
		if ( buffer.size()>0 ) {
			return buffer.removeFirst();
		}
		else {
			// matched rule adds at least one to buffer via emit(t)
			super.nextToken(); // ignore return value; we use buffer
			return buffer.removeFirst();
		}
	}

	@Override
	public Token getToken() {
		return buffer.peek();
	}

	@Override
	public void emit(Token token) {
		super.emit(token);
		buffer.add(token);
	}
}


text:
set -e

cd "$(dirname "$(readlink -f "$BASH_SOURCE")")"

url='git://github.com/docker-library/sentry'

echo '# maintainer: InfoSiftr <github@infosiftr.com> (@infosiftr)'

commit="$(git log -1 --format='format:%H' -- Dockerfile $(awk 'toupper($1) == "COPY" { for (i = 2; i < NF; i++) { print $i } }' Dockerfile))"
fullVersion="$(grep -m1 'ENV SENTRY_VERSION ' Dockerfile | cut -d' ' -f3)"

versionAliases=()
while [ "${fullVersion%.*}" != "$fullVersion" ]; do
	versionAliases+=( $fullVersion )
	fullVersion="${fullVersion%.*}"
done
versionAliases+=( $fullVersion latest )

echo
for va in "${versionAliases[@]}"; do
	echo "$va: ${url}@${commit}"
done


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="ro.pub.cs.systems.pdsd.lab03.examples.othercontrolssamples.OtherControlsSamplesActivity" >

    <NumberPicker
        android:id="@+id/numberPicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

    <RatingBar
        android:id="@+id/ratingBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/numberPicker1"
        android:layout_below="@id/numberPicker1"
        android:numStars="5"
        android:stepSize="0.25" />

</RelativeLayout>


text:
using System;
using Microsoft.Xna.Framework;

namespace GCS
{
    public partial class LineLike
    {
        public class LineLikeOnTwoDotsRule : ShapeRule
        {
            public LineLikeOnTwoDotsRule(LineLike line, Dot d1, Dot d2) : base(line)
            {
                d1.Childs.Add(line);
                d2.Childs.Add(line);
                line.Parents.Add(d1);
                line.Parents.Add(d2);

                Fix();
            }

            public override void OnMoved()
            {
                if (IsHandling) return;
                IsHandling = true;

                var line = Shape as LineLike;

                Shape.Parents[0].MoveTo(line.Point1);
                Shape.Parents[1].MoveTo(line.Point2);

                Fix(); // 부모 점이 도형에 의존하여 움직임이 규제된다면 다시 옮겨줘야 함
                MoveChilds();

                IsHandling = false;
            }

            public override void OnParentMoved()
            {
                if (IsHandling) return;
                Fix();
                MoveChilds();
            }

            protected override void Fix()
            {
                var line = Shape as LineLike;
                line.Point1 = (line.Parents[0] as Dot).Coord;
                line.Point2 = (line.Parents[1] as Dot).Coord;
            }
        }
    }

    public partial class Line
    {
        public class ParallelLineRule : ShapeRule
        {
            private Vector2 _last = new Vector2();
            public ParallelLineRule(Line line, LineLike original, Dot on) : base(line)
            {
                original.Childs.Add(line);
                on.Childs.Add(line);
                line.Parents.Add(original);
                line.Parents.Add(on);

                Fix();
            }

            public override void OnMoved()
            {
                if (IsHandling) return;
                IsHandling = true;

                var line = Shape as Line;
                var delta = line.Point1 - _last;

                var dot = line.Parents[1] as Dot;
                dot.Move(delta);

                Fix();
                MoveChilds();
                IsHandling = false;
            }

            public override void OnParentMoved()
            {
                if (IsHandling) return;
                Fix();
                MoveChilds();
            }

            protected override void Fix()
            {
                var line = Shape as Line;
                var parent = (line.Parents[0] as LineLike);
                var dot = (line.Parents[1] as Dot).Coord;

                var gap = new Vector2(dot.X - (parent.Point1.X + parent.Point2.X) / 2,
                                      dot.Y - (parent.Point1.Y + parent.Point2.Y) / 2);

                line.Point1 = parent.Point1 + gap;
                line.Point2 = parent.Point2 + gap;

                _last = line.Point1;
            }
        }

        public class PerpendicularLineRule : ShapeRule
        {
            private Vector2 _last = new Vector2();
            public PerpendicularLineRule(Line line, LineLike original, Dot on) : base(line)
            {
                original.Childs.Add(line);
                on.Childs.Add(line);
                line.Parents.Add(original);
                line.Parents.Add(on);

                Fix();
            }

            public override void OnMoved()
            {
                if (IsHandling) return;
                IsHandling = true;

                var line = Shape as Line;
                var delta = line.Point1 - _last;

                var dot = line.Parents[1] as Dot;
                dot.Move(delta);

                Fix();
                MoveChilds();
                IsHandling = false;
            }

            public override void OnParentMoved()
            {
                if (IsHandling) return;
                Fix();
                MoveChilds();
            }

            protected override void Fix()
            {
                var line = Shape as Line;
                var parent = (line.Parents[0] as LineLike);
                var dot = (line.Parents[1] as Dot).Coord;

                var gap = new Vector2(dot.X - (parent.Point1.X + parent.Point2.X) / 2,
                                      dot.Y - (parent.Point1.Y + parent.Point2.Y) / 2);

                var p1 = Geometry.Rotate(parent.Point1 + gap - dot, MathHelper.ToRadians(90)) + dot;
                var p2 = Geometry.Rotate(parent.Point2 + gap - dot, MathHelper.ToRadians(90)) + dot;

                line.Point1 = p1;
                line.Point2 = p2;

                _last = line.Point1;
            }
        }

        public class TangentLineRule : ShapeRule
        {
            private Vector2 _last = new Vector2();
            public TangentLineRule(Line line, Circle original, Dot on) : base(line)
            {
                original.Childs.Add(line);
                on.Childs.Add(line);
                line.Parents.Add(original);
                line.Parents.Add(on);

                Fix();
            }

            public TangentLineRule(Line line, Ellipse original, Dot on) : base(line)
            {
                original.Childs.Add(line);
                on.Childs.Add(line);
                line.Parents.Add(original);
                line.Parents.Add(on);

                Fix();
            }

            public override void OnMoved()
            {
                if (IsHandling) return;
                IsHandling = true;

                var line = Shape as Line;
                var delta = line.Point1 - _last;

                var dot = line.Parents[1] as Dot;
                dot.Move(delta);

                MoveChilds();
                Fix();
                IsHandling = false;
            }

            public override void OnParentMoved()
            {
                if (IsHandling) return;
                Fix();
                MoveChilds();
            }

            protected override void Fix()
            {
                var line = Shape as Line;
                var dot = (line.Parents[1] as Dot).Coord;
                if(line.Parents[0] is Ellipse)
                {
                    var parent = (line.Parents[0] as Ellipse);
                    Vector2 diff = parent.Focus1 - parent.Focus2;
                    float angle = (float)Math.Atan2(diff.Y, diff.X);
                    var tempcenter = Geometry.Rotate(parent.Center, -angle);
                    var tempdot = Geometry.Rotate(dot, -angle);

                    float tempgrad = (parent.Semiminor * parent.Semiminor * (tempcenter.X - tempdot.X))/
                        (parent.Semimajor * parent.Semimajor * (tempdot.Y - tempcenter.Y ) );
                    float grad = (float)((tempgrad + Math.Tan(angle)) / (1 - tempgrad * Math.Tan(angle)));
                    //tangent 덧셈 정리
                    line.Point1 = dot;
                    line.Point2 = dot + new Vector2(1, grad);

                }
                else
                {
                    var parent = (line.Parents[0] as Circle);
                    float grad = (parent.Center.X - dot.X) / (dot.Y - parent.Center.Y);
                    //float Weight = (float)Math.Sqrt(parent.Radius/(grad*grad+1));
                    line.Point1 = dot;
                    line.Point2 = dot + new Vector2(1, grad); // or (Weight, Weight * grad)
                    //Weight 는 Point1 과 Point2 사이의 거리를 Radius 로 뽑아줄 때 쓰면 됨.
                }

                _last = line.Point1;
            }

        }
    }
}


text:
module("luci.controller.adblock", package.seeall)

function index()
	if not nixio.fs.access("/etc/config/adblock") then
		return
	end

	entry({"admin", "services", "adblock"}, cbi("adblock"), _("Adblock"), 40)
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Abp.Configuration;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using Abp.Extensions;

namespace Abp.Authorization.Users
{
    /// <summary>
    /// Base class for user.
    /// </summary>
    [Table("AbpUsers")]
    public abstract class AbpUserBase : FullAuditedEntity<long>, IMayHaveTenant, IPassivable
    {
        /// <summary>
        /// Maximum length of the <see cref="UserName"/> property.
        /// </summary>
        public const int MaxUserNameLength = 32;

        /// <summary>
        /// Maximum length of the <see cref="EmailAddress"/> property.
        /// </summary>
        public const int MaxEmailAddressLength = 256;

        /// <summary>
        /// Maximum length of the <see cref="Name"/> property.
        /// </summary>
        public const int MaxNameLength = 32;

        /// <summary>
        /// Maximum length of the <see cref="Surname"/> property.
        /// </summary>
        public const int MaxSurnameLength = 32;

        /// <summary>
        /// Maximum length of the <see cref="AuthenticationSource"/> property.
        /// </summary>
        public const int MaxAuthenticationSourceLength = 64;

        /// <summary>
        /// UserName of the admin.
        /// admin can not be deleted and UserName of the admin can not be changed.
        /// </summary>
        public const string AdminUserName = "admin";

        /// <summary>
        /// Maximum length of the <see cref="Password"/> property.
        /// </summary>
        public const int MaxPasswordLength = 128;

        /// <summary>
        /// Maximum length of the <see cref="Password"/> without hashed.
        /// </summary>
        public const int MaxPlainPasswordLength = 32;

        /// <summary>
        /// Maximum length of the <see cref="EmailConfirmationCode"/> property.
        /// </summary>
        public const int MaxEmailConfirmationCodeLength = 328;

        /// <summary>
        /// Maximum length of the <see cref="PasswordResetCode"/> property.
        /// </summary>
        public const int MaxPasswordResetCodeLength = 328;

        /// <summary>
        /// Maximum length of the <see cref="PhoneNumber"/> property.
        /// </summary>
        public const int MaxPhoneNumberLength = 32;

        /// <summary>
        /// Maximum length of the <see cref="SecurityStamp"/> property.
        /// </summary>
        public const int MaxSecurityStampLength = 128;

        /// <summary>
        /// Authorization source name.
        /// It's set to external authentication source name if created by an external source.
        /// Default: null.
        /// </summary>
        [MaxLength(MaxAuthenticationSourceLength)]
        public virtual string AuthenticationSource { get; set; }

        /// <summary>
        /// User name.
        /// User name must be unique for it's tenant.
        /// </summary>
        [Required]
        [StringLength(MaxUserNameLength)]
        public virtual string UserName { get; set; }

        /// <summary>
        /// Tenant Id of this user.
        /// </summary>
        public virtual int? TenantId { get; set; }

        /// <summary>
        /// Email address of the user.
        /// Email address must be unique for it's tenant.
        /// </summary>
        [Required]
        [StringLength(MaxEmailAddressLength)]
        public virtual string EmailAddress { get; set; }

        /// <summary>
        /// Name of the user.
        /// </summary>
        [Required]
        [StringLength(MaxNameLength)]
        public virtual string Name { get; set; }

        /// <summary>
        /// Surname of the user.
        /// </summary>
        [Required]
        [StringLength(MaxSurnameLength)]
        public virtual string Surname { get; set; }

        /// <summary>
        /// Return full name (Name Surname )
        /// </summary>
        [NotMapped]
        public virtual string FullName { get { return this.Name + " " + this.Surname; } }

        /// <summary>
        /// Password of the user.
        /// </summary>
        [Required]
        [StringLength(MaxPasswordLength)]
        public virtual string Password { get; set; }

        /// <summary>
        /// Confirmation code for email.
        /// </summary>
        [StringLength(MaxEmailConfirmationCodeLength)]
        public virtual string EmailConfirmationCode { get; set; }

        /// <summary>
        /// Reset code for password.
        /// It's not valid if it's null.
        /// It's for one usage and must be set to null after reset.
        /// </summary>
        [StringLength(MaxPasswordResetCodeLength)]
        public virtual string PasswordResetCode { get; set; }

        /// <summary>
        /// Lockout end date.
        /// </summary>
        public virtual DateTime? LockoutEndDateUtc { get; set; }

        /// <summary>
        /// Gets or sets the access failed count.
        /// </summary>
        public virtual int AccessFailedCount { get; set; }

        /// <summary>
        /// Gets or sets the lockout enabled.
        /// </summary>
        public virtual bool IsLockoutEnabled { get; set; }

        /// <summary>
        /// Gets or sets the phone number.
        /// </summary>
        [StringLength(MaxPhoneNumberLength)]
        public virtual string PhoneNumber { get; set; }

        /// <summary>
        /// Is the <see cref="PhoneNumber"/> confirmed.
        /// </summary>
        public virtual bool IsPhoneNumberConfirmed { get; set; }

        /// <summary>
        /// Gets or sets the security stamp.
        /// </summary>
        [StringLength(MaxSecurityStampLength)]
        public virtual string SecurityStamp { get; set; }

        /// <summary>
        /// Is two factor auth enabled.
        /// </summary>
        public virtual bool IsTwoFactorEnabled { get; set; }

        /// <summary>
        /// Login definitions for this user.
        /// </summary>
        [ForeignKey("UserId")]
        public virtual ICollection<UserLogin> Logins { get; set; }

        /// <summary>
        /// Roles of this user.
        /// </summary>
        [ForeignKey("UserId")]
        public virtual ICollection<UserRole> Roles { get; set; }

        /// <summary>
        /// Claims of this user.
        /// </summary>
        [ForeignKey("UserId")]
        public virtual ICollection<UserClaim> Claims { get; set; }

        /// <summary>
        /// Permission definitions for this user.
        /// </summary>
        [ForeignKey("UserId")]
        public virtual ICollection<UserPermissionSetting> Permissions { get; set; }

        /// <summary>
        /// Settings for this user.
        /// </summary>
        [ForeignKey("UserId")]
        public virtual ICollection<Setting> Settings { get; set; }

        /// <summary>
        /// Is the <see cref="AbpUserBase.EmailAddress"/> confirmed.
        /// </summary>
        public virtual bool IsEmailConfirmed { get; set; }

        /// <summary>
        /// Is this user active?
        /// If as user is not active, he/she can not use the application.
        /// </summary>
        public virtual bool IsActive { get; set; }

        /// <summary>
        /// The last time this user entered to the system.
        /// </summary>
        public virtual DateTime? LastLoginTime { get; set; }

        protected AbpUserBase()
        {
            IsActive = true;
            IsLockoutEnabled = true;
            SecurityStamp = SequentialGuidGenerator.Instance.Create().ToString();
        }

        public virtual void SetNewPasswordResetCode()
        {
            PasswordResetCode = Guid.NewGuid().ToString("N").Truncate(MaxPasswordResetCodeLength);
        }

        public virtual void SetNewEmailConfirmationCode()
        {
            EmailConfirmationCode = Guid.NewGuid().ToString("N").Truncate(MaxEmailConfirmationCodeLength);
        }

        /// <summary>
        /// Creates <see cref="UserIdentifier"/> from this User.
        /// </summary>
        /// <returns></returns>
        public virtual UserIdentifier ToUserIdentifier()
        {
            return new UserIdentifier(TenantId, Id);
        }

        public override string ToString()
        {
            return $"[User {Id}] {UserName}";
        }
    }
}