private EntityCollection GenerateRandomAccountCollection()
        {
            var collection = new List<Entity>();
            for (var i = 0; i < 10; i++)
            {
                var rgn = new Random((int)DateTime.Now.Ticks);
                var entity = new Entity("account");
                entity["accountid"] = entity.Id = Guid.NewGuid();
                entity["address1_addressid"] = Guid.NewGuid();
                entity["modifiedon"] = DateTime.Now;
                entity["lastusedincampaign"] = DateTime.Now;
                entity["donotfax"] = rgn.NextBoolean();
                entity["new_verybignumber"] = rgn.NextInt64();
                entity["exchangerate"] = rgn.NextDecimal();
                entity["address1_latitude"] = rgn.NextDouble();
                entity["numberofemployees"] = rgn.NextInt32();
                entity["primarycontactid"] = new EntityReference("contact", Guid.NewGuid());
                entity["revenue"] = new Money(rgn.NextDecimal());
                entity["ownerid"] = new EntityReference("systemuser", Guid.NewGuid());
                entity["industrycode"] = new OptionSetValue(rgn.NextInt32());
                entity["name"] = rgn.NextString(15);
                entity["description"] = rgn.NextString(300);
                entity["statecode"] = new OptionSetValue(rgn.NextInt32());
                entity["statuscode"] = new OptionSetValue(rgn.NextInt32());
                collection.Add(entity);
            }

            return new EntityCollection(collection);
        }
        public void FuzzTest()
        {
            var random = new System.Random(12345);

            for (var i = 0; i < 10000; ++i)
            {
                var count     = random.Next(1000);
                var sequence1 = Enumerable.Range(0, count).Select(_ => random.Next(count)).ToList();
                var sequence2 = sequence1.Shuffled(random).ToList();
                var equal     = random.NextBoolean();
                if (!equal)
                {
                    switch (count == 0 ? 4 : random.Next(5))
                    {
                    case 0:
                        sequence2[random.Next(count)]++;
                        break;

                    case 1:
                        var toChange = random.Next(1, count + 1);
                        for (var j = 0; j < toChange; ++j)
                        {
                            sequence2[j]++;
                        }
                        break;

                    case 2:
                        sequence2.RemoveAt(random.Next(count));
                        break;

                    case 3:
                        var toRemove = random.Next(1, count + 1);
                        sequence2 = sequence2.Skip(toRemove).ToList();
                        break;

                    case 4:
                        var toAdd = random.Next(1, count + 1);
                        sequence2.AddRange(Enumerable.Repeat(random.Next(count), toAdd));
                        break;

                    default:
                        throw new InvalidOperationException("should never get here");
                    }
                }

                var toCompare1 = random.NextBoolean() ? sequence1 : sequence1.Where(_ => true);
                var toCompare2 = random.NextBoolean() ? sequence2 : sequence2.Where(_ => true);

                try
                {
                    toCompare1.CollectionEquals(toCompare2)
                    .ShouldEqual(equal);
                }
                catch
                {
                    this.output.WriteLine($"Case {i} failed");
                    throw;
                }
            }
        }
        private IObservable<MarketData> GenerateStream(CurrencyPair currencyPair)
        {
            return Observable.Create<MarketData>(observer =>
            {
                        var spread = currencyPair.DefaultSpread;
                        var midRate = currencyPair.InitialPrice;
                        var bid = midRate - (spread * currencyPair.PipSize);
                        var offer = midRate + (spread * currencyPair.PipSize);
                        var initial = new MarketData(currencyPair.Code, bid, offer);

                        var currentPrice = initial;
                        observer.OnNext(initial);

                        var random = new Random();

                        //for a given period, move prices by up to 5 pips
                        return Observable.Interval(TimeSpan.FromSeconds(1 / (double)currencyPair.TickFrequency))
                            .Select(_ =>  random.Next(1, 5))
                            .Subscribe(pips =>
                            {
                                //move up or down between 1 and 5 pips
                                var adjustment = Math.Round(pips * currencyPair.PipSize,currencyPair.DecimalPlaces);
                                currentPrice = random.NextBoolean()
                                                ? currentPrice + adjustment
                                                : currentPrice - adjustment;
                                observer.OnNext(currentPrice);

                            });
            });
        }
Example #4
0
        public void TestNextBoolean()
        {
            var random  = new System.Random(1);
            var average = Enumerable.Range(0, 20000).Select(_ => Convert.ToInt32(random.NextBoolean()))
                          .Average();

            (Math.Abs(average - .5) < .01).ShouldEqual(true);
        }
 public void Boolean_Distribution()
 {
     Distribution(
         2,
         100_000,
         () => r.NextBoolean() ? 0 : 1
         );
 }
Example #6
0
    private Vector3 RandomSpawnPoint()
    {
        if (_randomGenerator.NextBoolean())
        {
            bool  isRight = _randomGenerator.NextBoolean();
            float x       = isRight ? SPAWN_DISTANCE_X_MIN : SPAWN_DISTANCE_X_MAX;

            float y = _randomGenerator.NextFloat(SPAWN_DISTANCE_Y_MIN, SPAWN_DISTANCE_Y_MAX);
            return(new Vector3(x, y));
        }
        else
        {
            bool  isTop = _randomGenerator.NextBoolean();
            float y     = isTop ? SPAWN_DISTANCE_Y_MAX : SPAWN_DISTANCE_Y_MIN;

            float x = _randomGenerator.NextFloat(SPAWN_DISTANCE_X_MIN, SPAWN_DISTANCE_X_MAX);
            return(new Vector3(x, y));
        }
    }
Example #7
0
        public void MultipleCreateAndDeleteTest()
        {
            //const int N = 21;

            using (var scope = new TempLinksTestScope())
            {
                var links = scope.Links;

                for (var N = 0; N < 100; N++)
                {
                    var random = new Random(N);

                    var created = 0;
                    var deleted = 0;

                    for (var i = 0; i < N; i++)
                    {
                        var linksCount = links.Count();

                        var createPoint = random.NextBoolean();

                        if (linksCount > 2 && createPoint)
                        {
                            var source = random.NextUInt64(1, linksCount);
                            var target = random.NextUInt64(1, linksCount);

                            var resultLink = links.CreateAndUpdate(source, target);
                            if (resultLink > linksCount)
                                created++;
                        }
                        else
                        {
                            links.Create();
                            created++;
                        }
                    }

                    Assert.True(created == (int)links.Count());

                    for (var i = 0; i < N; i++)
                    {
                        var link = (ulong)i + 1;
                        if (links.Exists(link))
                        {
                            links.Delete(link);
                            deleted++;
                        }
                    }

                    Assert.True(links.Count() == 0);
                }
            }
        }
Example #8
0
 protected UnitTestBase()
 {
     List<TestEntity> entities = new List<TestEntity>();
     DateTime dt = DateTime.Now;
     Random rnd = new Random();
     for (int i = 0; i < 1000; i++)
     {
         entities.Add(new TestEntity()
         {
             Id = i + 1,
             Name = "Name" + (i + 1),
             AddDate = rnd.NextDateTime(dt.AddDays(-7), dt.AddDays(7)),
             IsDeleted = rnd.NextBoolean()
         });
     }
     Entities = entities;
 }
        public static void Test(System.Random random)
        {
            const int Trials = 40000;

            foreach (var probability in new[] { .1, .3, .5, .7, .9 })
            {
                var count = 0;
                for (var i = 0; i < Trials; ++i)
                {
                    if (random.NextBoolean(probability))
                    {
                        ++count;
                    }
                }

                var observedProbability = count / (double)Trials;
                (Math.Abs(observedProbability - probability) < .05).ShouldEqual(true);
            }
        }
Example #10
0
        /// <summary>
        /// create a new index writer config with random defaults using the specified random </summary>
        public static IndexWriterConfig NewIndexWriterConfig(Random r, LuceneVersion v, Analyzer a)
        {
            IndexWriterConfig c = new IndexWriterConfig(v, a);
            c.SetSimilarity(ClassEnvRule.Similarity);
            if (VERBOSE)
            {
                // Even though TestRuleSetupAndRestoreClassEnv calls
                // InfoStream.setDefault, we do it again here so that
                // the PrintStreamInfoStream.messageID increments so
                // that when there are separate instances of
                // IndexWriter created we see "IW 0", "IW 1", "IW 2",
                // ... instead of just always "IW 0":
                c.InfoStream = new TestRuleSetupAndRestoreClassEnv.ThreadNameFixingPrintStreamInfoStream(Console.Out);
            }

            if (r.NextBoolean())
            {
                c.SetMergeScheduler(new SerialMergeScheduler());
            }
            else if (Rarely(r))
            {
                int maxThreadCount = TestUtil.NextInt(Random(), 1, 4);
                int maxMergeCount = TestUtil.NextInt(Random(), maxThreadCount, maxThreadCount + 4);
                ConcurrentMergeScheduler cms = new ConcurrentMergeScheduler();
                cms.SetMaxMergesAndThreads(maxMergeCount, maxThreadCount);
                c.SetMergeScheduler(cms);
            }
            if (r.NextBoolean())
            {
                if (Rarely(r))
                {
                    // crazy value
                    c.SetMaxBufferedDocs(TestUtil.NextInt(r, 2, 15));
                }
                else
                {
                    // reasonable value
                    c.SetMaxBufferedDocs(TestUtil.NextInt(r, 16, 1000));
                }
            }
            if (r.NextBoolean())
            {
                if (Rarely(r))
                {
                    // crazy value
                    c.SetTermIndexInterval(r.NextBoolean() ? TestUtil.NextInt(r, 1, 31) : TestUtil.NextInt(r, 129, 1000));
                }
                else
                {
                    // reasonable value
                    c.SetTermIndexInterval(TestUtil.NextInt(r, 32, 128));
                }
            }
            if (r.NextBoolean())
            {
                int maxNumThreadStates = Rarely(r) ? TestUtil.NextInt(r, 5, 20) : TestUtil.NextInt(r, 1, 4); // reasonable value -  crazy value

                if (Rarely(r))
                {
                    // Retrieve the package-private setIndexerThreadPool
                    // method:
                    MethodInfo setIndexerThreadPoolMethod = typeof(IndexWriterConfig).GetMethod("SetIndexerThreadPool", new Type[] { typeof(DocumentsWriterPerThreadPool) });
                    //setIndexerThreadPoolMethod.setAccessible(true);
                    Type clazz = typeof(RandomDocumentsWriterPerThreadPool);
                    ConstructorInfo ctor = clazz.GetConstructor(new[] { typeof(int), typeof(Random) });
                    //ctor.Accessible = true;
                    // random thread pool
                    setIndexerThreadPoolMethod.Invoke(c, new[] { ctor.Invoke(new object[] { maxNumThreadStates, r }) });
                }
                else
                {
                    // random thread pool
                    c.SetMaxThreadStates(maxNumThreadStates);
                }
            }

            c.SetMergePolicy(NewMergePolicy(r));

            if (Rarely(r))
            {
                c.SetMergedSegmentWarmer(new SimpleMergedSegmentWarmer(c.InfoStream));
            }
            c.SetUseCompoundFile(r.NextBoolean());
            c.SetReaderPooling(r.NextBoolean());
            c.SetReaderTermsIndexDivisor(TestUtil.NextInt(r, 1, 4));
            c.SetCheckIntegrityAtMerge(r.NextBoolean());
            return c;
        }
Example #11
0
        /// <summary>
        /// TODO: javadoc </summary>
        public static IOContext NewIOContext(Random random, IOContext oldContext)
        {
            int randomNumDocs = random.Next(4192);
            int size = random.Next(512) * randomNumDocs;
            if (oldContext.FlushInfo != null)
            {
                // Always return at least the estimatedSegmentSize of
                // the incoming IOContext:
                return new IOContext(new FlushInfo(randomNumDocs, (long)Math.Max(oldContext.FlushInfo.EstimatedSegmentSize, size)));
            }
            else if (oldContext.MergeInfo != null)
            {
                // Always return at least the estimatedMergeBytes of
                // the incoming IOContext:
                return new IOContext(new MergeInfo(randomNumDocs, Math.Max(oldContext.MergeInfo.EstimatedMergeBytes, size), random.NextBoolean(), TestUtil.NextInt(random, 1, 100)));
            }
            else
            {
                // Make a totally random IOContext:
                IOContext context;
                switch (random.Next(5))
                {
                    case 0:
                        context = IOContext.DEFAULT;
                        break;

                    case 1:
                        context = IOContext.READ;
                        break;

                    case 2:
                        context = IOContext.READONCE;
                        break;

                    case 3:
                        context = new IOContext(new MergeInfo(randomNumDocs, size, true, -1));
                        break;

                    case 4:
                        context = new IOContext(new FlushInfo(randomNumDocs, size));
                        break;

                    default:
                        context = IOContext.DEFAULT;
                        break;
                }
                return context;
            }
        }
        public TestRuleSetupAndRestoreClassEnv()
        {
            /*// if verbose: print some debugging stuff about which codecs are loaded.
            if (LuceneTestCase.VERBOSE)
            {
                ISet<string> codecs = Codec.AvailableCodecs();
                foreach (string codec in codecs)
                {
                    Console.WriteLine("Loaded codec: '" + codec + "': " + Codec.ForName(codec).GetType().Name);
                }

                ISet<string> postingsFormats = PostingsFormat.AvailablePostingsFormats();
                foreach (string postingsFormat in postingsFormats)
                {
                    Console.WriteLine("Loaded postingsFormat: '" + postingsFormat + "': " + PostingsFormat.ForName(postingsFormat).GetType().Name);
                }
            }

            SavedInfoStream = InfoStream.Default;
            Random random = RandomizedContext.Current.Random;
            bool v = random.NextBoolean();
            if (LuceneTestCase.INFOSTREAM)
            {
                InfoStream.Default = new ThreadNameFixingPrintStreamInfoStream(Console.Out);
            }
            else if (v)
            {
                InfoStream.Default = new NullInfoStream();
            }

            Type targetClass = RandomizedContext.Current.GetTargetType;
            AvoidCodecs = new HashSet<string>();

            // set back to default
            LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = false;

            SavedCodec = Codec.Default;
            int randomVal = random.Next(10);
            if ("Lucene3x".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT) && randomVal == 3 && !ShouldAvoidCodec("Lucene3x"))) // preflex-only setup
            {
                Codec = Codec.ForName("Lucene3x");
                Debug.Assert((Codec is PreFlexRWCodec), "fix your classpath to have tests-framework.jar before lucene-core.jar");
                LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true;
            }
            else if ("Lucene40".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) && randomVal == 0 && !ShouldAvoidCodec("Lucene40"))) // 4.0 setup
            {
                Codec = Codec.ForName("Lucene40");
                LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true;
                Debug.Assert(Codec is Lucene40RWCodec, "fix your classpath to have tests-framework.jar before lucene-core.jar");
                Debug.Assert((PostingsFormat.ForName("Lucene40") is Lucene40RWPostingsFormat), "fix your classpath to have tests-framework.jar before lucene-core.jar");
            }
            else if ("Lucene41".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT) && randomVal == 1 && !ShouldAvoidCodec("Lucene41")))
            {
                Codec = Codec.ForName("Lucene41");
                LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true;
                Debug.Assert(Codec is Lucene41RWCodec, "fix your classpath to have tests-framework.jar before lucene-core.jar");
            }
            else if ("Lucene42".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT) && randomVal == 2 && !ShouldAvoidCodec("Lucene42")))
            {
                Codec = Codec.ForName("Lucene42");
                LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true;
                Debug.Assert(Codec is Lucene42RWCodec, "fix your classpath to have tests-framework.jar before lucene-core.jar");
            }
            else if ("Lucene45".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT) && randomVal == 5 && !ShouldAvoidCodec("Lucene45")))
            {
                Codec = Codec.ForName("Lucene45");
                LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true;
                Debug.Assert(Codec is Lucene45RWCodec, "fix your classpath to have tests-framework.jar before lucene-core.jar");
            }
            else if (("random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) == false) || ("random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT) == false))
            {
                // the user wired postings or DV: this is messy
                // refactor into RandomCodec....

                PostingsFormat format;
                if ("random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT))
                {
                    format = PostingsFormat.ForName("Lucene41");
                }
                else
                {
                    format = PostingsFormat.ForName(LuceneTestCase.TEST_POSTINGSFORMAT);
                }

                DocValuesFormat dvFormat;
                if ("random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT))
                {
                    dvFormat = DocValuesFormat.ForName("Lucene45");
                }
                else
                {
                    dvFormat = DocValuesFormat.ForName(LuceneTestCase.TEST_DOCVALUESFORMAT);
                }

                Codec = new Lucene46CodecAnonymousInnerClassHelper(this, format, dvFormat);
            }
            else if ("Asserting".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && randomVal == 6 && !ShouldAvoidCodec("Asserting")))
            {
                Codec = new AssertingCodec();
            }
            else if ("Compressing".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && randomVal == 5 && !ShouldAvoidCodec("Compressing")))
            {
                Codec = CompressingCodec.RandomInstance(random);
            }
            else if (!"random".Equals(LuceneTestCase.TEST_CODEC))
            {
                Codec = Codec.ForName(LuceneTestCase.TEST_CODEC);
            }
            else if ("random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT))
            {
                Codec = new RandomCodec(random, AvoidCodecs);
            }
            else
            {
                Debug.Assert(false);
            }
            Codec.Default = Codec;
            */
            Random random = new Random(1);
            Similarity = random.NextBoolean() ? (Similarity)new DefaultSimilarity() : new RandomSimilarityProvider(new Random(1));
            /*
            // Check codec restrictions once at class level.
            try
            {
                CheckCodecRestrictions(Codec);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("NOTE: " + e.Message + " Suppressed codecs: " + Arrays.ToString(AvoidCodecs.ToArray()));
                throw e;
            }*/
        }
Example #13
0
        public static Field NewField(Random random, string name, string value, FieldType type)
        {
            name = new string(name.ToCharArray());
            if (Usually(random) || !type.Indexed)
            {
                // most of the time, don't modify the params
                return new Field(name, value, type);
            }

            // TODO: once all core & test codecs can index
            // offsets, sometimes randomly turn on offsets if we are
            // already indexing positions...

            FieldType newType = new FieldType(type);
            if (!newType.Stored && random.NextBoolean())
            {
                newType.Stored = true; // randomly store it
            }

            if (!newType.StoreTermVectors && random.NextBoolean())
            {
                newType.StoreTermVectors = true;
                if (!newType.StoreTermVectorOffsets)
                {
                    newType.StoreTermVectorOffsets = random.NextBoolean();
                }
                if (!newType.StoreTermVectorPositions)
                {
                    newType.StoreTermVectorPositions = random.NextBoolean();

                    if (newType.StoreTermVectorPositions && !newType.StoreTermVectorPayloads && !OLD_FORMAT_IMPERSONATION_IS_ACTIVE)
                    {
                        newType.StoreTermVectorPayloads = random.NextBoolean();
                    }
                }
            }

            // TODO: we need to do this, but smarter, ie, most of
            // the time we set the same value for a given field but
            // sometimes (rarely) we change it up:
            /*
                if (newType.OmitsNorms()) {
                  newType.setOmitNorms(random.NextBoolean());
                }
            */

            return new Field(name, value, newType);
        }
        private void CheckRandomData(Random random, Analyzer a, int iterations, int maxWordLength, bool useCharFilter, bool simple, bool offsetsAreCorrect, RandomIndexWriter iw)
        {
            LineFileDocs docs = new LineFileDocs(random);
            Document doc = null;
            Field field = null, currentField = null;
            StringReader bogus = new StringReader("");
            if (iw != null)
            {
                doc = new Document();
                FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
                if (random.NextBoolean())
                {
                    ft.StoreTermVectors = true;
                    ft.StoreTermVectorOffsets = random.NextBoolean();
                    ft.StoreTermVectorPositions = random.NextBoolean();
                    if (ft.StoreTermVectorPositions && !OLD_FORMAT_IMPERSONATION_IS_ACTIVE)
                    {
                        ft.StoreTermVectorPayloads = random.NextBoolean();
                    }
                }
                if (random.NextBoolean())
                {
                    ft.OmitNorms = true;
                }
                string pf = TestUtil.GetPostingsFormat("dummy");
                bool supportsOffsets = !DoesntSupportOffsets.Contains(pf);
                switch (random.Next(4))
                {
                    case 0:
                        ft.IndexOptions = FieldInfo.IndexOptions.DOCS_ONLY;
                        break;

                    case 1:
                        ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS;
                        break;

                    case 2:
                        ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS;
                        break;

                    default:
                        if (supportsOffsets && offsetsAreCorrect)
                        {
                            ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
                        }
                        else
                        {
                            ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS;
                        }
                        break;
                }
                currentField = field = new Field("dummy", bogus, ft);
                doc.Add(currentField);
            }

            try
            {
                for (int i = 0; i < iterations; i++)
                {
                    string text;

                    if (random.Next(10) == 7)
                    {
                        // real data from linedocs
                        text = docs.NextDoc().Get("body");
                        if (text.Length > maxWordLength)
                        {
                            // Take a random slice from the text...:
                            int startPos = random.Next(text.Length - maxWordLength);
                            if (startPos > 0 && char.IsLowSurrogate(text[startPos]))
                            {
                                // Take care not to split up a surrogate pair:
                                startPos--;
                                Assert.True(char.IsHighSurrogate(text[startPos]));
                            }
                            int endPos = startPos + maxWordLength - 1;
                            if (char.IsHighSurrogate(text[endPos]))
                            {
                                // Take care not to split up a surrogate pair:
                                endPos--;
                            }
                            text = text.Substring(startPos, 1 + endPos - startPos);
                        }
                    }
                    else
                    {
                        // synthetic
                        text = TestUtil.RandomAnalysisString(random, maxWordLength, simple);
                    }

                    try
                    {
                        CheckAnalysisConsistency(random, a, useCharFilter, text, offsetsAreCorrect, currentField);
                        if (iw != null)
                        {
                            if (random.Next(7) == 0)
                            {
                                // pile up a multivalued field
                                var ft = (FieldType)field.FieldType;
                                currentField = new Field("dummy", bogus, ft);
                                doc.Add(currentField);
                            }
                            else
                            {
                                iw.AddDocument(doc);
                                if (doc.Fields.Count > 1)
                                {
                                    // back to 1 field
                                    currentField = field;
                                    doc.RemoveFields("dummy");
                                    doc.Add(currentField);
                                }
                            }
                        }
                    }
                    catch (Exception t)
                    {
                        // TODO: really we should pass a random seed to
                        // checkAnalysisConsistency then print it here too:
                        Console.Error.WriteLine("TEST FAIL: useCharFilter=" + useCharFilter + " text='" + Escape(text) + "'");
                        throw;
                    }
                }
            }
            finally
            {
                IOUtils.CloseWhileHandlingException(docs);
            }
        }
        private long RandomLong(Random random)
        {
            long val;
            switch (random.Next(4))
            {
                case 0:
                    val = 1L << (random.Next(63)); //  patterns like 0x000000100000 (-1 yields patterns like 0x0000fff)
                    break;

                case 1:
                    val = -1L << (random.Next(63)); // patterns like 0xfffff00000
                    break;

                default:
                    val = random.NextLong();
                    break;
            }

            val += random.Next(5) - 2;

            if (random.NextBoolean())
            {
                if (random.NextBoolean())
                {
                    val += random.Next(100) - 50;
                }
                if (random.NextBoolean())
                {
                    val = ~val;
                }
                if (random.NextBoolean())
                {
                    val = val << 1;
                }
                if (random.NextBoolean())
                {
                    val = (long)((ulong)val >> 1);
                }
            }

            return val;
        }
Example #16
0
 public static Parameter GetOne(System.Random rnd)
 {
     return
         (new Parameter
     {
         ItemType = "Parameter",
         Key = rnd.Next(),
         Name = rnd.NextString(),
         Revision = rnd.Next(),
         SequenceId = rnd.Next(),
         Description = rnd.NextString(),
         Units = rnd.NextString(),
         Prop1 = rnd.NextBoolean(),
         Prop2 = rnd.NextBoolean(),
         Prop3 = rnd.NextBoolean(),
         Prop4 = rnd.NextBoolean(),
         Prop5 = rnd.NextBoolean(),
         Prop6 = rnd.NextString(),
         Prop7 = rnd.NextBoolean(),
         Prop8 = rnd.NextDouble(),
         Prop9 = rnd.NextString(),
         Prop10 = rnd.NextString(),
         Prop11 = rnd.NextBoolean(),
         Prop12 = rnd.Next(),
         Prop13 = rnd.NextString(),
         Prop14 = rnd.Next(),
         Prop15 = rnd.NextString(),
         Prop16 = rnd.NextString(),
         Prop17 = rnd.NextString(),
         Prop18 = rnd.NextString(),
         Prop19 = rnd.NextString(),
         Prop20 = rnd.NextString(),
         Prop21 = rnd.NextString(),
         Prop22 = rnd.NextString(),
         Prop23 = rnd.NextBoolean(),
         Prop24 = rnd.NextBoolean(),
         Prop25 = rnd.NextBoolean(),
         Prop26 = rnd.NextBoolean(),
         Prop27 = rnd.NextBoolean(),
         Prop28 = rnd.NextBoolean(),
         Prop29 = rnd.NextBoolean(),
         Prop30 = rnd.NextBoolean(),
         Prop31 = rnd.NextDouble(),
         Prop32 = rnd.NextDouble(),
         Prop33 = rnd.NextBoolean(),
         Prop34 = rnd.NextBoolean(),
         Prop35 = rnd.NextBoolean(),
         Prop36 = rnd.NextString(),
         Prop37 = rnd.NextBoolean(),
         Prop38 = rnd.NextBoolean(),
         Prop39 = rnd.NextBoolean(),
         Prop40 = rnd.NextBoolean(),
         Prop45 = rnd.NextString(),
         Prop46 = rnd.NextBoolean(),
         Prop47 = rnd.NextBoolean(),
         Prop48 = rnd.NextBoolean(),
         Prop49 = rnd.NextBoolean(),
         Prop50 = rnd.Next()
     });
 }
Example #17
0
        private static void ConfigureRandom(Random r, MergePolicy mergePolicy)
        {
            if (r.NextBoolean())
            {
                mergePolicy.NoCFSRatio = 0.1 + r.NextDouble() * 0.8;
            }
            else
            {
                mergePolicy.NoCFSRatio = r.NextBoolean() ? 1.0 : 0.0;
            }

            if (Rarely())
            {
                mergePolicy.MaxCFSSegmentSizeMB = 0.2 + r.NextDouble() * 2.0;
            }
            else
            {
                mergePolicy.MaxCFSSegmentSizeMB = double.PositiveInfinity;
            }
        }
Example #18
0
        public void NextBoolean_NullAsRandom_ExceptionThrown()
        {
            System.Random random            = null;
            string        expectedParamName = "random";

            ArgumentNullException actualException = Assert.Throws <ArgumentNullException>(() => random.NextBoolean());

            Assert.NotNull(actualException);
            Assert.Equal(expectedParamName, actualException.ParamName);
        }
            public SeedPostings(long seed, int minDocFreq, int maxDocFreq, Bits liveDocs, FieldInfo.IndexOptions options)
            {
                Random = new Random((int)seed);
                DocRandom = new Random(Random.Next());
                DocFreq = TestUtil.NextInt(Random, minDocFreq, maxDocFreq);
                this.LiveDocs = liveDocs;

                // TODO: more realistic to inversely tie this to numDocs:
                MaxDocSpacing = TestUtil.NextInt(Random, 1, 100);

                if (Random.Next(10) == 7)
                {
                    // 10% of the time create big payloads:
                    PayloadSize = 1 + Random.Next(3);
                }
                else
                {
                    PayloadSize = 1 + Random.Next(1);
                }

                FixedPayloads = Random.NextBoolean();
                var payloadBytes = new byte[PayloadSize];
                Payload_Renamed = new BytesRef(payloadBytes);
                this.Options = options;
                DoPositions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS.CompareTo(options) <= 0;
            }
 public RandomSimilarityProvider(Random random)
 {
     PerFieldSeed = random.Next();
     CoordType = random.Next(3);
     ShouldQueryNorm = random.NextBoolean();
     KnownSims = new List<Similarity>(AllSims);
     KnownSims = CollectionsHelper.Shuffle(KnownSims);
     //Collections.shuffle(KnownSims, random);
 }
Example #21
0
 internal AssertingWeight(Random random, Weight @in)
 {
     this.Random = random;
     this.@in = @in;
     ScoresDocsOutOfOrder_Renamed = @in.ScoresDocsOutOfOrder() || random.NextBoolean();
 }
Example #22
0
 public void NextBooleanTest()
 {
     Random rnd = new Random();
     bool value = rnd.NextBoolean();
     Assert.IsTrue(new[] { true, false }.Contains(value));
 }
Example #23
0
        public static LogMergePolicy NewLogMergePolicy(Random r)
        {
            LogMergePolicy logmp = r.NextBoolean() ? (LogMergePolicy)new LogDocMergePolicy() : new LogByteSizeMergePolicy();

            logmp.CalibrateSizeByDeletes = r.NextBoolean();
            if (Rarely(r))
            {
                logmp.MergeFactor = TestUtil.NextInt(r, 2, 9);
            }
            else
            {
                logmp.MergeFactor = TestUtil.NextInt(r, 10, 50);
            }
            ConfigureRandom(r, logmp);
            return logmp;
        }
        /// <summary>
        /// return a random NFA/DFA for testing </summary>
        public static Automaton RandomAutomaton(Random random)
        {
            // get two random Automata from regexps
            Automaton a1 = (new RegExp(AutomatonTestUtil.RandomRegexp(random), RegExp.NONE)).ToAutomaton();
            if (random.NextBoolean())
            {
                a1 = BasicOperations.Complement(a1);
            }

            Automaton a2 = (new RegExp(AutomatonTestUtil.RandomRegexp(random), RegExp.NONE)).ToAutomaton();
            if (random.NextBoolean())
            {
                a2 = BasicOperations.Complement(a2);
            }

            // combine them in random ways
            switch (random.Next(4))
            {
                case 0:
                    return BasicOperations.Concatenate(a1, a2);

                case 1:
                    return BasicOperations.Union(a1, a2);

                case 2:
                    return BasicOperations.Intersection(a1, a2);

                default:
                    return BasicOperations.Minus(a1, a2);
            }
        }
Example #25
0
 public static MergePolicy NewMergePolicy(Random r)
 {
     if (Rarely(r))
     {
         return new MockRandomMergePolicy(r);
     }
     else if (r.NextBoolean())
     {
         return NewTieredMergePolicy(r);
     }
     else if (r.Next(5) == 0)
     {
         return NewAlcoholicMergePolicy(r, ClassEnvRule.TimeZone);
     }
     return NewLogMergePolicy(r);
 }
            public int[] GetRandomAcceptedString(Random r)
            {
                IList<int?> soFar = new List<int?>();
                if (a.IsSingleton)
                {
                    // accepts only one
                    var s = a.Singleton;

                    int charUpto = 0;
                    while (charUpto < s.Length)
                    {
                        int cp = Character.CodePointAt(s, charUpto);
                        charUpto += Character.CharCount(cp);
                        soFar.Add(cp);
                    }
                }
                else
                {
                    var s = a.InitialState;

                    while (true)
                    {
                        if (s.Accept)
                        {
                            if (s.numTransitions == 0)
                            {
                                // stop now
                                break;
                            }
                            else
                            {
                                if (r.NextBoolean())
                                {
                                    break;
                                }
                            }
                        }

                        if (s.numTransitions == 0)
                        {
                            throw new Exception("this automaton has dead states");
                        }

                        bool cheat = r.NextBoolean();

                        Transition t;
                        if (cheat)
                        {
                            // pick a transition that we know is the fastest
                            // path to an accept state
                            IList<Transition> toAccept = new List<Transition>();
                            for (int i = 0; i < s.numTransitions; i++)
                            {
                                Transition t0 = s.TransitionsArray[i];
                                if (LeadsToAccept.ContainsKey(t0))
                                {
                                    toAccept.Add(t0);
                                }
                            }
                            if (toAccept.Count == 0)
                            {
                                // this is OK -- it means we jumped into a cycle
                                t = s.TransitionsArray[r.Next(s.numTransitions)];
                            }
                            else
                            {
                                t = toAccept[r.Next(toAccept.Count)];
                            }
                        }
                        else
                        {
                            t = s.TransitionsArray[r.Next(s.numTransitions)];
                        }
                        soFar.Add(GetRandomCodePoint(r, t));
                        s = t.Dest;
                    }
                }

                return ArrayUtil.ToIntArray(soFar);
            }
Example #27
0
        private static double AbsDiffOfMeans(double[] A, double[] B, bool randomize)
        {
            Random random = new Random();
            double aTotal = 0.0;
            double bTotal = 0.0;
            for (int i = 0; i < A.Length; i++)
            {
                if (randomize && random.NextBoolean())
                {
                    aTotal += B[i];
                    bTotal += A[i];
                }
                else
                {
                    aTotal += A[i];
                    bTotal += B[i];
                }
            }

            double aMean = aTotal / A.Length;
            double bMean = bTotal / B.Length;
            return System.Math.Abs(aMean - bMean);
        }
        public void CheckRandomData(Random random, Analyzer a, int iterations, int maxWordLength, bool simple, bool offsetsAreCorrect)
        {
            CheckResetException(a, "best effort");
            long seed = random.Next();
            bool useCharFilter = random.NextBoolean();
            Directory dir = null;
            RandomIndexWriter iw = null;
            string postingsFormat = TestUtil.GetPostingsFormat("dummy");
            bool codecOk = iterations * maxWordLength < 100000
                || !(postingsFormat.Equals("Memory") || postingsFormat.Equals("SimpleText"));
            if (Rarely(random) && codecOk)
            {
                dir = NewFSDirectory(CreateTempDir("bttc"));
                iw = new RandomIndexWriter(new Random((int)seed), dir, a, ClassEnvRule.Similarity, ClassEnvRule.TimeZone);
            }

            bool success = false;
            try
            {
                CheckRandomData(new Random((int)seed), a, iterations, maxWordLength, useCharFilter, simple, offsetsAreCorrect, iw);
                // now test with multiple threads: note we do the EXACT same thing we did before in each thread,
                // so this should only really fail from another thread if its an actual thread problem
                int numThreads = TestUtil.NextInt(random, 2, 4);
                var startingGun = new CountdownEvent(1);
                var threads = new AnalysisThread[numThreads];
                for (int i = 0; i < threads.Length; i++)
                {
                    threads[i] = new AnalysisThread(seed, /*startingGun,*/ a, iterations, maxWordLength, useCharFilter, simple, offsetsAreCorrect, iw, this);
                }
                
                Array.ForEach(threads, thread => thread.Start());                

                startingGun.Signal();
                
                foreach (var t in threads)
                {
                    try
                    {
                        t.Join();
                    }
                    catch (ThreadInterruptedException e)
                    {
                        Fail("Thread interrupted");
                    }
                }

                if (threads.Any(x => x.Failed))
                    Fail("Thread interrupted");

                success = true;
            }
            finally
            {
                if (success)
                {
                    IOUtils.Close(iw, dir);
                }
                else
                {
                    IOUtils.CloseWhileHandlingException(iw, dir); // checkindex
                }
            }
        }