예제 #1
0
        /// <summary>
        /// Simulate a student that is really indecisive
        /// </summary>
        public async Task RunProducer(IFdbDatabase db, CancellationToken ct)
        {
            int cnt = 0;

            var rnd = new Random();

            this.TimeLine.Start();
            while (!ct.IsCancellationRequested)
            {
                int   k      = cnt++;
                Slice taskId = STuple.EncodeKey(this.Id.GetHashCode(), k);

                string msg = "Message #" + k + " from producer " + this.Id + " (" + DateTime.UtcNow.ToString("O") + ")";

                var latency = Stopwatch.StartNew();
                await this.WorkerPool.ScheduleTaskAsync(db, taskId, Slice.FromString(msg), ct).ConfigureAwait(false);

                latency.Stop();
                Console.Write(k.ToString("N0") + "\r");

                this.TimeLine.Add(latency.Elapsed.TotalMilliseconds);

                TimeSpan delay = TimeSpan.FromTicks(rnd.Next((int)this.DelayMin.Ticks, (int)this.DelayMax.Ticks));
                await Task.Delay(delay, ct).ConfigureAwait(false);
            }
            this.TimeLine.Stop();

            ct.ThrowIfCancellationRequested();
        }
        public override Matrix Apply(Matrix input)
        {
            int    i;
            int    j;
            Matrix ret = new Matrix(input.RowCount, input.ColumnCount);
            STuple <float, float> pair;

            for (i = 0; i < input.RowCount; i++)
            {
                for (j = 0; j < input.ColumnCount; j++)
                {
                    pair = new STuple <float, float>(i / (float)input.RowCount, j / (float)input.ColumnCount);
                    pair = Modulate(pair.Value1, pair.Value2);
                    if (pair.Value1 < 0 || pair.Value1 > 1 ||
                        pair.Value2 < 0 || pair.Value2 > 1)
                    {
                        ret[i, j] = 0;
                    }
                    else
                    {
                        ret[i, j] =
                            input[
                                (int)(Math.Round(pair.Value1 * (input.RowCount - 1))),
                                (int)(Math.Round(pair.Value2 * (input.ColumnCount - 1)))];
                    }
                }
            }

            return(ret);
        }
예제 #3
0
            public int Compare(STuple <T1, T2, T3, T4, T5, T6> x, STuple <T1, T2, T3, T4, T5, T6> y)
            {
                int cmp = Comparer1.Compare(x.Item1, y.Item1);

                if (cmp == 0)
                {
                    cmp = Comparer2.Compare(x.Item2, y.Item2);
                }
                if (cmp == 0)
                {
                    cmp = Comparer3.Compare(x.Item3, y.Item3);
                }
                if (cmp == 0)
                {
                    cmp = Comparer4.Compare(x.Item4, y.Item4);
                }
                if (cmp == 0)
                {
                    cmp = Comparer5.Compare(x.Item5, y.Item5);
                }
                if (cmp == 0)
                {
                    cmp = Comparer6.Compare(x.Item6, y.Item6);
                }
                return(cmp);
            }
예제 #4
0
        public void Test_KeyRange_Test()
        {
            const int BEFORE = -1, INSIDE = 0, AFTER = +1;

            KeyRange range;

            // range: [ "A", "Z" )
            range = KeyRange.Create(Slice.FromAscii("A"), Slice.FromAscii("Z"));

            // Excluding the end: < "Z"
            Assert.That(range.Test(Slice.FromAscii("\x00"), endIncluded: false), Is.EqualTo(BEFORE));
            Assert.That(range.Test(Slice.FromAscii("@"), endIncluded: false), Is.EqualTo(BEFORE));
            Assert.That(range.Test(Slice.FromAscii("A"), endIncluded: false), Is.EqualTo(INSIDE));
            Assert.That(range.Test(Slice.FromAscii("Z"), endIncluded: false), Is.EqualTo(AFTER));
            Assert.That(range.Test(Slice.FromAscii("Z\x00"), endIncluded: false), Is.EqualTo(AFTER));
            Assert.That(range.Test(Slice.FromAscii("\xFF"), endIncluded: false), Is.EqualTo(AFTER));

            // Including the end: <= "Z"
            Assert.That(range.Test(Slice.FromAscii("\x00"), endIncluded: true), Is.EqualTo(BEFORE));
            Assert.That(range.Test(Slice.FromAscii("@"), endIncluded: true), Is.EqualTo(BEFORE));
            Assert.That(range.Test(Slice.FromAscii("A"), endIncluded: true), Is.EqualTo(INSIDE));
            Assert.That(range.Test(Slice.FromAscii("Z"), endIncluded: true), Is.EqualTo(INSIDE));
            Assert.That(range.Test(Slice.FromAscii("Z\x00"), endIncluded: true), Is.EqualTo(AFTER));
            Assert.That(range.Test(Slice.FromAscii("\xFF"), endIncluded: true), Is.EqualTo(AFTER));

            range = KeyRange.Create(STuple.EncodeKey("A"), STuple.EncodeKey("Z"));
            Assert.That(range.Test(STuple.EncodeKey("@")), Is.EqualTo((BEFORE)));
            Assert.That(range.Test(STuple.EncodeKey("A")), Is.EqualTo((INSIDE)));
            Assert.That(range.Test(STuple.EncodeKey("Z")), Is.EqualTo((AFTER)));
            Assert.That(range.Test(STuple.EncodeKey("Z"), endIncluded: true), Is.EqualTo(INSIDE));
        }
예제 #5
0
 private void Add(STuple key, IGameEventCom gameEvenet)
 {
     Console.WriteLine("ADDING POST ID{0} TTC:{1}", key.One, gameEvenet.TimeToComplete);
     _posts.Add(key, new PostData {
         TimeToComplete = gameEvenet.TimeToComplete, GameEventID = key.One
     });
 }
예제 #6
0
 public bool Equals(STuple <T1, T2, T3, T4> x, STuple <T1, T2, T3, T4> y)
 {
     return(Comparer1.Equals(x.Item1, y.Item1) &&
            Comparer2.Equals(x.Item2, y.Item2) &&
            Comparer3.Equals(x.Item3, y.Item3) &&
            Comparer4.Equals(x.Item4, y.Item4));
 }
예제 #7
0
        public async Task Test_Vector_Fast()
        {
            using (var db = await OpenTestPartitionAsync())
            {
                var location = await GetCleanDirectory(db, "ranked_set");

                var vector = new FdbRankedSet(location);

                await db.ReadWriteAsync(async (tr) =>
                {
                    await vector.OpenAsync(tr);
                    await PrintRankedSet(vector, tr);
                }, this.Cancellation);

                Console.WriteLine();
                var rnd = new Random();
                var sw  = Stopwatch.StartNew();
                for (int i = 0; i < 100; i++)
                {
                    Console.Write("\rInserting " + i);
                    await db.ReadWriteAsync((tr) => vector.InsertAsync(tr, STuple.EncodeKey(rnd.Next())), this.Cancellation);
                }
                sw.Stop();
                Console.WriteLine("\rDone in {0:N3} sec", sw.Elapsed.TotalSeconds);

                await db.ReadAsync((tr) => PrintRankedSet(vector, tr), this.Cancellation);
            }
        }
예제 #8
0
        public async Task Test_Can_Batch_ForEach_AsyncWithContextAndState()
        {
            const int N = 50 * 1000;

            using (var db = await OpenTestPartitionAsync())
            {
                Log("Bulk inserting {0:N0} items...", N);
                var location = await GetCleanDirectory(db, "Bulk", "ForEach");

                Log("Preparing...");

                await Fdb.Bulk.WriteAsync(
                    db,
                    Enumerable.Range(1, N).Select((x) => new KeyValuePair <Slice, Slice>(location.Keys.Encode(x), Slice.FromInt32(x))),
                    this.Cancellation
                    );

                Log("Reading...");

                long total  = 0;
                long count  = 0;
                int  chunks = 0;
                var  sw     = Stopwatch.StartNew();
                await Fdb.Bulk.ForEachAsync(
                    db,
                    Enumerable.Range(1, N).Select(x => location.Keys.Encode(x)),
                    () => STuple.Create(0L, 0L),
                    async (xs, ctx, state) =>
                {
                    Interlocked.Increment(ref chunks);
                    Log("> Called with batch of {0:N0} items at offset {1:N0} of gen #{2} with step {3:N0} and cooldown {4} (generation = {5:N3} sec, total = {6:N3} sec)", xs.Length, ctx.Position, ctx.Generation, ctx.Step, ctx.Cooldown, ctx.ElapsedGeneration.TotalSeconds, ctx.ElapsedTotal.TotalSeconds);

                    var throttle = Task.Delay(TimeSpan.FromMilliseconds(10 + (xs.Length / 25) * 5));                             // magic numbers to try to last longer than 5 sec
                    var results  = await ctx.Transaction.GetValuesAsync(xs);
                    await throttle;

                    long sum = 0;
                    for (int i = 0; i < results.Length; i++)
                    {
                        sum += results[i].ToInt32();
                    }
                    return(STuple.Create(state.Item1 + sum, state.Item2 + results.Length));
                },
                    (state) =>
                {
                    Interlocked.Add(ref total, state.Item1);
                    Interlocked.Add(ref count, state.Item2);
                },
                    this.Cancellation
                    );

                sw.Stop();

                Log("Done in {0:N3} sec and {1} chunks", sw.Elapsed.TotalSeconds, chunks);
                Log("Sum of integers 1 to {0:N0} is {1:N0}", count, total);

                // cleanup because this test can produce a lot of data
                await location.RemoveAsync(db, this.Cancellation);
            }
        }
예제 #9
0
        public void Test_TypedKeySpace_T1()
        {
            var location = KeySubspace.CreateTyped <string>(Slice.FromString("PREFIX"));

            Assert.That(location.KeyEncoder, Is.Not.Null, "Should have a Key Encoder");
            Assert.That(location.KeyEncoder.Encoding, Is.SameAs(TuPack.Encoding), "Encoder should use Tuple type system");

            // shortcuts
            Assert.That(location[Slice.FromString("SUFFIX")].ToString(), Is.EqualTo("PREFIXSUFFIX"));
            Assert.That(location.Keys["hello"].ToString(), Is.EqualTo("PREFIX<02>hello<00>"));
            Assert.That(location.Keys[ValueTuple.Create("hello")].ToString(), Is.EqualTo("PREFIX<02>hello<00>"));

            // Encode<T...>(...)
            Assert.That(location.Keys.Encode("hello").ToString(), Is.EqualTo("PREFIX<02>hello<00>"));

            // Pack(ITuple)
            Assert.That(location.Keys.Pack((IVarTuple)STuple.Create("hello")).ToString(), Is.EqualTo("PREFIX<02>hello<00>"));

            // Pack(ValueTuple)
            Assert.That(location.Keys.Pack(ValueTuple.Create("hello")).ToString(), Is.EqualTo("PREFIX<02>hello<00>"));

            // STuple<T...> Decode(...)
            Assert.That(location.Keys.Decode(Slice.Unescape("PREFIX<02>hello<00>")), Is.EqualTo("hello"));

            // Decode(..., out T)
            location.Keys.Decode(Slice.Unescape("PREFIX<02>hello<00>"), out string x);
            Assert.That(x, Is.EqualTo("hello"));
        }
예제 #10
0
        public void Test_Simple_SelfTerms_Codecs()
        {
            // encodes a key using 3 parts: (x, y, z) => ordered_key

            string x = "abc";
            long   y = 123;
            Guid   z = Guid.NewGuid();

            var first  = TupleCodec <string> .Default;
            var second = TupleCodec <long> .Default;
            var third  = TupleCodec <Guid> .Default;

            var writer = SliceWriter.Empty;

            first.EncodeOrderedSelfTerm(ref writer, x);
            second.EncodeOrderedSelfTerm(ref writer, y);
            third.EncodeOrderedSelfTerm(ref writer, z);
            var data = writer.ToSlice();

            Assert.That(data, Is.EqualTo(STuple.EncodeKey(x, y, z)));

            var reader = new SliceReader(data);

            Assert.That(first.DecodeOrderedSelfTerm(ref reader), Is.EqualTo(x));
            Assert.That(second.DecodeOrderedSelfTerm(ref reader), Is.EqualTo(y));
            Assert.That(third.DecodeOrderedSelfTerm(ref reader), Is.EqualTo(z));
            Assert.That(reader.HasMore, Is.False);
        }
예제 #11
0
 public int GetHashCode(STuple <T1, T2> obj)
 {
     return(HashCodes.Combine(
                Comparer1.GetHashCode(obj.Item1),
                Comparer2.GetHashCode(obj.Item2)
                ));
 }
예제 #12
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            (double, double)valueTuple = ((double, double))value;
            STuple <double, double> stuple = valueTuple;

            serializer.Serialize(writer, stuple, typeof(STuple <dynamic, dynamic>));
        }
예제 #13
0
            public Preparation(int count)
            {
                // Although this appears to be "random", it is always seeded with the same value, so it always produces the same
                // sequence of keys (with uniform distribution). The perf test will use the same set of keys and therefore the
                // same code paths every time it is run. I.E. This is the most convenient way to generate a large set of test keys.
                ParkAndMiller random = new ParkAndMiller(Seed);

                inserts = new STuple <int, int, int> [count];
                int[] xExtents = new int[count];
                deletes = new int[count];
                int xExtent = 0;

                for (int i = 0; i < count; i++)
                {
                    int xStart  = random.Next() % Math.Max(1, xExtent);
                    int xLength = random.Next() % 100 + 1;
                    int yLength = random.Next() % 100 + 1;
                    inserts[i]  = new STuple <int, int, int>(xStart, xLength, yLength);
                    xExtent    += xLength;
                    xExtents[i] = xExtent;
                }
                for (int i = 0; i < count; i++)
                {
                    deletes[i] = random.Next() % xExtents[count - 1 - i];
                }
            }
예제 #14
0
 /// <summary>
 /// Returns the list of names of all existing classes
 /// </summary>
 public Task <List <string> > AvailableClasses(IFdbReadOnlyTransaction tr)
 {
     return(tr.GetRange(this.Subspace.Keys.ToRange(STuple.Create("class")))
            .Where(kvp => { int _; return Int32.TryParse(kvp.Value.ToStringAscii(), out _); })              // (step 3)
            .Select(kvp => this.Subspace.Keys.Decode <string>(kvp.Key))
            .ToListAsync());
 }
예제 #15
0
        private static void DumpIndex <TKey, TVal>(string label, MemoryIndex <TKey> index, Func <TKey, int, TVal> orderBy, IComparer <TVal> comparer = null, bool heatMaps = false)
        {
            comparer = comparer ?? Comparer <TVal> .Default;

            int  total       = index.Statistics.Values.Sum();
            long totalLegacy = 0;

            int[]  map = new int[100];
            double r   = (double)(map.Length - 1) / total;

            Console.WriteLine("__{0}__", label);
            Console.WriteLine("| Indexed Value           |  Count | Total % | Words |  Lit%  | 1-Bits |  Word% |   Bitmap | ratio % |   Legacy  | ratio % |" + (heatMaps ? " HeatMap |" : ""));
            Console.WriteLine("|:------------------------|-------:|--------:|------:|-------:|-------:|-------:|---------:|--------:|----------:|--------:|" + (heatMaps ? ":-----------------------------------------------------------------------|" : ""));
            foreach (var kv in index.Values.OrderBy((kv) => orderBy(kv.Key, index.Count(kv.Key)), comparer))
            {
                var t  = STuple.Create(kv.Key);
                var tk = t.ToSlice();

                int    bits, words, literals, fillers;
                double ratio;
                kv.Value.GetStatistics(out bits, out words, out literals, out fillers, out ratio);

                long legacyIndexSize = 0;                 // size estimate of a regular FDB index (..., "Value", GUID) = ""
                Array.Clear(map, 0, map.Length);
                foreach (var p in kv.Value.GetView())
                {
                    map[(int)(r * p)]++;
                    legacyIndexSize += 3 + tk.Count + 17;
                }
                totalLegacy += legacyIndexSize;

                int bytes = kv.Value.ToSlice().Count;

                Console.WriteLine(string.Format(
                                      CultureInfo.InvariantCulture,
                                      "| {0,-24}| {1,6:N0} | {2,6:N2}% | {3,5:N0} | {4,5:N1}% | {5,6:N0} | {6,6:N2} | {7,8:N0} | {8,6:N2}% | {9,9:N0} | {10,6:N2}% |" + (heatMaps ? " `{11}` |" : ""),
                                      /*0*/ t,
                                      /*1*/ index.Count(kv.Key),
                                      /*2*/ 100.0 * index.Frequency(kv.Key),
                                      /*3*/ words,
                                      /*4*/ (100.0 * literals) / words,
                                      /*5*/ bits,
                                      /*6*/ 1.0 * bits / words,
                                      /*7*/ bytes,
                                      /*8*/ 100.0 * ratio,
                                      /*9*/ legacyIndexSize,
                                      /*A*/ (100.0 * bytes) / legacyIndexSize,
                                      /*B*/ heatMaps ? MakeHeatMap(map) : ""
                                      ));
            }

            Console.WriteLine(string.Format(
                                  CultureInfo.InvariantCulture,
                                  "> {0:N0} distinct value(s), {1:N0} document(s), {2:N0} bitmap bytes, {3:N0} legacy bytes",
                                  index.Values.Count,
                                  total,
                                  index.Values.Values.Sum(x => x.ToSlice().Count),
                                  totalLegacy
                                  ));
        }
        /// <summary>Return one or more fields of an hashset</summary>
        /// <param name="trans">Transaction that will be used for this request</param>
        /// <param name="id">Unique identifier of the hashset</param>
        /// <param name="fields">List of the fields to read</param>
        /// <returns>Dictionary containing the values of the selected fields, or Slice.Empty if that particular field does not exist.</returns>
        public async Task <IDictionary <string, Slice> > GetAsync([NotNull] IFdbReadOnlyTransaction trans, [NotNull] ITuple id, [NotNull] params string[] fields)
        {
            if (trans == null)
            {
                throw new ArgumentNullException(nameof(trans));
            }
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }
            if (fields == null)
            {
                throw new ArgumentNullException(nameof(fields));
            }

            var keys = STuple.EncodePrefixedKeys(GetKey(id), fields);

            var values = await trans.GetValuesAsync(keys).ConfigureAwait(false);

            Contract.Assert(values != null && values.Length == fields.Length);

            var results = new Dictionary <string, Slice>(values.Length, StringComparer.OrdinalIgnoreCase);

            for (int i = 0; i < fields.Length; i++)
            {
                results[fields[i]] = values[i];
            }
            return(results);
        }
예제 #17
0
        public async Task Test_Can_MergeSort()
        {
            int K = 3;
            int N = 100;

            using (var db = await OpenTestPartitionAsync())
            {
                var location = await GetCleanDirectory(db, "Queries", "MergeSort");

                // clear!
                await db.ClearRangeAsync(location, this.Cancellation);

                // create K lists
                var lists = Enumerable.Range(0, K).Select(i => location.Partition.ByKey(i)).ToArray();

                // lists[0] contains all multiples of K ([0, 0], [K, 1], [2K, 2], ...)
                // lists[1] contains all multiples of K, offset by 1 ([1, 0], [K+1, 1], [2K+1, 2], ...)
                // lists[k-1] contains all multiples of K, offset by k-1 ([K-1, 0], [2K-1, 1], [3K-1, 2], ...)

                // more generally: lists[k][i] = (..., MergeSort, k, (i * K) + k) = (k, i)

                for (int k = 0; k < K; k++)
                {
                    using (var tr = db.BeginTransaction(this.Cancellation))
                    {
                        for (int i = 0; i < N; i++)
                        {
                            tr.Set(lists[k].Keys.Encode((i * K) + k), STuple.EncodeKey(k, i));
                        }
                        await tr.CommitAsync();
                    }
                }

                // MergeSorting all lists together should produce all integers from 0 to (K*N)-1, in order
                // we use the last part of the key for sorting

                using (var tr = db.BeginTransaction(this.Cancellation))
                {
                    var merge = tr.MergeSort(
                        lists.Select(list => KeySelectorPair.Create(list.Keys.ToRange())),
                        kvp => location.Keys.DecodeLast <int>(kvp.Key)
                        );

                    Assert.That(merge, Is.Not.Null);
                    Assert.That(merge, Is.InstanceOf <FdbMergeSortIterator <KeyValuePair <Slice, Slice>, int, KeyValuePair <Slice, Slice> > >());

                    var results = await merge.ToListAsync();

                    Assert.That(results, Is.Not.Null);
                    Assert.That(results.Count, Is.EqualTo(K * N));

                    for (int i = 0; i < K * N; i++)
                    {
                        Assert.That(location.ExtractKey(results[i].Key), Is.EqualTo(STuple.EncodeKey(i % K, i)));
                        Assert.That(results[i].Value, Is.EqualTo(STuple.EncodeKey(i % K, i / K)));
                    }
                }
            }
        }
예제 #18
0
        public static STuple <float, float> ConvertPolarToEuclidean(float r, float theta)
        {
            STuple <float, float> pair = new STuple <float, float>();

            pair.Value1 = (float)(r * Math.Cos(theta));
            pair.Value2 = (float)(r * Math.Sin(theta));
            return(pair);
        }
        protected override STuple <float, float> Modulate(float x, float y)
        {
            STuple <float, float> pair = AcuityEngine.ConvertZeroOneToNegOneOne(x, y);

            pair = InternalModulate(pair);

            return(AcuityEngine.ConvertNegOneOneToZeroOne(pair.Value1, pair.Value2));
        }
예제 #20
0
        public static STuple <float, float> ConvertEuclideanToPolar(float x, float y)
        {
            STuple <float, float> pair = new STuple <float, float>();

            pair.Value1 = (float)Math.Sqrt(x * x + y * y);
            pair.Value2 = (float)Math.Atan2(y, x);
            return(pair);
        }
 public T DecodeValue(Slice encoded)
 {
     if (encoded.IsNullOrEmpty)
     {
         return(default(T));                                           //BUGBUG
     }
     return(STuple.DecodeKey <T>(encoded));
 }
 public int GetHashCode(STuple <T1, T2, T3, T4> obj)
 {
     return(HashCodes.Combine(
                Comparer1.GetHashCode(obj.Item1),
                Comparer2.GetHashCode(obj.Item2),
                Comparer3.GetHashCode(obj.Item3),
                Comparer4.GetHashCode(obj.Item4)
                ));
 }
        //public FishEyeMatrixFilter()
        //    : base(Modulate)
        //{
        //}

        //protected override Pair<float> Modulate(float x, float y)
        //{
        //    Pair<float> pair = SolusEngine.ConvertZeroOneToNegOneOne(x, y);
        //
        //    pair = SolusEngine.ConvertEuclideanToPolar(pair.Value1, pair.Value2);
        //
        //    //r /= Math.Sqrt(2);
        //
        //    if (pair.Value1 >= -1 && pair.Value1 <= 1)
        //    {
        //        pair.Value1 = (float)(2 * Math.Asin(pair.Value1) / Math.PI);
        //    }
        //
        //    //r *= Math.Sqrt(2);
        //
        //    pair = SolusEngine.ConvertPolarToEuclidean(pair.Value1, pair.Value2);
        //
        //    pair = SolusEngine.ConvertNegOneOneToZeroOne(pair.Value1, pair.Value2);
        //
        //    return pair;
        //}

        protected override bool CheckCoordinates(STuple <float, float> pair)
        {
            if (pair.Value1 >= -1 && pair.Value1 <= 1)
            {
                return(true);
            }

            return(false);
        }
예제 #24
0
 public bool Equals(STuple <T1, T2, T3, T4, T5, T6> x, STuple <T1, T2, T3, T4, T5, T6> y)
 {
     return(Comparer1.Equals(x.Item1, y.Item1) &&
            Comparer2.Equals(x.Item2, y.Item2) &&
            Comparer3.Equals(x.Item3, y.Item3) &&
            Comparer4.Equals(x.Item4, y.Item4) &&
            Comparer5.Equals(x.Item5, y.Item5) &&
            Comparer6.Equals(x.Item6, y.Item6));
 }
예제 #25
0
        private static LambdaExpression CreateDynamicSelect <TInput>(IQueryable <TInput> query, ParameterExpression param, IEnumerable <LambdaExpression> propertySelectors)
        {
            var selectors = propertySelectors.ToList();
            var tupleType = STuple.GetTupleType(selectors.Select(x => x.ReturnType).ToArray());
            var binds     = selectors.Select((x, i) => Expression.Bind(tupleType.GetTypeInfo().GetProperty($"Item{i + 1}"), x.Body)).ToList();
            var init      = Expression.MemberInit(Expression.New(tupleType), binds);

            return(Expression.Lambda(init, param));
        }
예제 #26
0
 private static void LoadTree(IRange2Map <int> tree, int count, STuple <int, int, int>[] inserts)
 {
     for (int i = 0; i < count; i++)
     {
         STuple <int, int, int> insert = inserts[i];
         int start = insert.Item1;
         tree.NearestLessOrEqual(start, Side.X, out start);
         tree.Insert(start, Side.X, insert.Item2, insert.Item3, insert.Item1);
     }
 }
예제 #27
0
            public int Compare(STuple <T1, T2> x, STuple <T1, T2> y)
            {
                int cmp = Comparer1.Compare(x.Item1, y.Item1);

                if (cmp == 0)
                {
                    cmp = Comparer2.Compare(x.Item2, y.Item2);
                }
                return(cmp);
            }
예제 #28
0
        public void Test_FdbKey_PrettyPrint()
        {
            // verify that the pretty printing of keys produce a user friendly output

            Assert.That(FdbKey.Dump(Slice.Nil), Is.EqualTo("<null>"));
            Assert.That(FdbKey.Dump(Slice.Empty), Is.EqualTo("<empty>"));

            Assert.That(FdbKey.Dump(Slice.FromByte(0)), Is.EqualTo("<00>"));
            Assert.That(FdbKey.Dump(Slice.FromByte(255)), Is.EqualTo("<FF>"));

            Assert.That(FdbKey.Dump(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }.AsSlice()), Is.EqualTo("<00><01><02><03><04><05><06><07>"));
            Assert.That(FdbKey.Dump(new byte[] { 255, 254, 253, 252, 251, 250, 249, 248 }.AsSlice()), Is.EqualTo("<FF><FE><FD><FC><FB><FA><F9><F8>"));

            Assert.That(FdbKey.Dump(Slice.FromString("hello")), Is.EqualTo("hello"));
            Assert.That(FdbKey.Dump(Slice.FromString("héllø")), Is.EqualTo("h<C3><A9>ll<C3><B8>"));

            // tuples should be decoded properly

            Assert.That(FdbKey.Dump(TuPack.EncodeKey(123)), Is.EqualTo("(123,)"), "Singleton tuples should end with a ','");
            Assert.That(FdbKey.Dump(TuPack.EncodeKey(Slice.FromByteString("hello"))), Is.EqualTo("(`hello`,)"), "ASCII strings should use single back quotes");
            Assert.That(FdbKey.Dump(TuPack.EncodeKey("héllø")), Is.EqualTo("(\"héllø\",)"), "Unicode strings should use double quotes");
            Assert.That(FdbKey.Dump(TuPack.EncodeKey(new byte[] { 1, 2, 3 }.AsSlice())), Is.EqualTo("(`<01><02><03>`,)"));
            Assert.That(FdbKey.Dump(TuPack.EncodeKey(123, 456)), Is.EqualTo("(123, 456)"), "Elements should be separated with a space, and not end up with ','");
            Assert.That(FdbKey.Dump(TuPack.EncodeKey(default(object), true, false)), Is.EqualTo("(null, true, false)"), "Booleans should be displayed as numbers, and null should be in lowercase");             //note: even though it's tempting to using Python's "Nil", it's not very ".NETty"
            //note: the string representation of double is not identical between NetFx and .NET Core! So we cannot used a constant literal here
            Assert.That(FdbKey.Dump(TuPack.EncodeKey(1.0d, Math.PI, Math.E)), Is.EqualTo("(1, " + Math.PI.ToString("R", CultureInfo.InvariantCulture) + ", " + Math.E.ToString("R", CultureInfo.InvariantCulture) + ")"), "Doubles should used dot and have full precision (17 digits)");
            Assert.That(FdbKey.Dump(TuPack.EncodeKey(1.0f, (float)Math.PI, (float)Math.E)), Is.EqualTo("(1, " + ((float)Math.PI).ToString("R", CultureInfo.InvariantCulture) + ", " + ((float)Math.E).ToString("R", CultureInfo.InvariantCulture) + ")"), "Singles should used dot and have full precision (10 digits)");
            var guid = Guid.NewGuid();

            Assert.That(FdbKey.Dump(TuPack.EncodeKey(guid)), Is.EqualTo($"({guid:B},)"), "GUIDs should be displayed as a string literal, surrounded by {{...}}, and without quotes");
            var uuid128 = Uuid128.NewUuid();

            Assert.That(FdbKey.Dump(TuPack.EncodeKey(uuid128)), Is.EqualTo($"({uuid128:B},)"), "Uuid128s should be displayed as a string literal, surrounded by {{...}}, and without quotes");
            var uuid64 = Uuid64.NewUuid();

            Assert.That(FdbKey.Dump(TuPack.EncodeKey(uuid64)), Is.EqualTo($"({uuid64:B},)"), "Uuid64s should be displayed as a string literal, surrounded by {{...}}, and without quotes");

            // ranges should be decoded when possible
            var key = TuPack.ToRange(STuple.Create("hello"));

            // "<02>hello<00><00>" .. "<02>hello<00><FF>"
            Assert.That(FdbKey.PrettyPrint(key.Begin, FdbKey.PrettyPrintMode.Begin), Is.EqualTo("(\"hello\",).<00>"));
            Assert.That(FdbKey.PrettyPrint(key.End, FdbKey.PrettyPrintMode.End), Is.EqualTo("(\"hello\",).<FF>"));

            key = KeyRange.StartsWith(TuPack.EncodeKey("hello"));
            // "<02>hello<00>" .. "<02>hello<01>"
            Assert.That(FdbKey.PrettyPrint(key.Begin, FdbKey.PrettyPrintMode.Begin), Is.EqualTo("(\"hello\",)"));
            Assert.That(FdbKey.PrettyPrint(key.End, FdbKey.PrettyPrintMode.End), Is.EqualTo("(\"hello\",) + 1"));

            var t = TuPack.EncodeKey(123);

            Assert.That(FdbKey.PrettyPrint(t, FdbKey.PrettyPrintMode.Single), Is.EqualTo("(123,)"));
            Assert.That(FdbKey.PrettyPrint(TuPack.ToRange(t).Begin, FdbKey.PrettyPrintMode.Begin), Is.EqualTo("(123,).<00>"));
            Assert.That(FdbKey.PrettyPrint(TuPack.ToRange(t).End, FdbKey.PrettyPrintMode.End), Is.EqualTo("(123,).<FF>"));
        }
예제 #29
0
        public void Test_FdbKey_PrettyPrint()
        {
            // verify that the pretty printing of keys produce a user friendly output

            Assert.That(FdbKey.Dump(Slice.Nil), Is.EqualTo("<null>"));
            Assert.That(FdbKey.Dump(Slice.Empty), Is.EqualTo("<empty>"));

            Assert.That(FdbKey.Dump(Slice.FromByte(0)), Is.EqualTo("<00>"));
            Assert.That(FdbKey.Dump(Slice.FromByte(255)), Is.EqualTo("<FF>"));

            Assert.That(FdbKey.Dump(Slice.Create(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 })), Is.EqualTo("<00><01><02><03><04><05><06><07>"));
            Assert.That(FdbKey.Dump(Slice.Create(new byte[] { 255, 254, 253, 252, 251, 250, 249, 248 })), Is.EqualTo("<FF><FE><FD><FC><FB><FA><F9><F8>"));

            Assert.That(FdbKey.Dump(Slice.FromString("hello")), Is.EqualTo("hello"));
            Assert.That(FdbKey.Dump(Slice.FromString("héllø")), Is.EqualTo("h<C3><A9>ll<C3><B8>"));

            // tuples should be decoded properly

            Assert.That(FdbKey.Dump(STuple.EncodeKey(123)), Is.EqualTo("(123,)"), "Singleton tuples should end with a ','");
            Assert.That(FdbKey.Dump(STuple.EncodeKey(Slice.FromAscii("hello"))), Is.EqualTo("('hello',)"), "ASCII strings should use single quotes");
            Assert.That(FdbKey.Dump(STuple.EncodeKey("héllø")), Is.EqualTo("(\"héllø\",)"), "Unicode strings should use double quotes");
            Assert.That(FdbKey.Dump(STuple.EncodeKey(Slice.Create(new byte[] { 1, 2, 3 }))), Is.EqualTo("(<01 02 03>,)"));
            Assert.That(FdbKey.Dump(STuple.EncodeKey(123, 456)), Is.EqualTo("(123, 456)"), "Elements should be separated with a space, and not end up with ','");
            Assert.That(FdbKey.Dump(STuple.EncodeKey(true, false, default(object))), Is.EqualTo("(1, 0, null)"), "Booleans should be displayed as numbers, and null should be in lowercase");             //note: even though it's tempting to using Python's "Nil", it's not very ".NETty"
            Assert.That(FdbKey.Dump(STuple.EncodeKey(1.0d, Math.PI, Math.E)), Is.EqualTo("(1, 3.1415926535897931, 2.7182818284590451)"), "Doubles should used dot and have full precision (17 digits)");
            Assert.That(FdbKey.Dump(STuple.EncodeKey(1.0f, (float)Math.PI, (float)Math.E)), Is.EqualTo("(1, 3.14159274, 2.71828175)"), "Singles should used dot and have full precision (10 digits)");
            var guid = Guid.NewGuid();

            Assert.That(FdbKey.Dump(STuple.EncodeKey(guid)), Is.EqualTo(String.Format("({0},)", guid.ToString("B"))), "GUIDs should be displayed as a string literal, surrounded by {...}, and without quotes");
            var uuid128 = Uuid128.NewUuid();

            Assert.That(FdbKey.Dump(STuple.EncodeKey(uuid128)), Is.EqualTo(String.Format("({0},)", uuid128.ToString("B"))), "Uuid128s should be displayed as a string literal, surrounded by {...}, and without quotes");
            var uuid64 = Uuid64.NewUuid();

            Assert.That(FdbKey.Dump(STuple.EncodeKey(uuid64)), Is.EqualTo(String.Format("({0},)", uuid64.ToString("B"))), "Uuid64s should be displayed as a string literal, surrounded by {...}, and without quotes");

            // ranges should be decoded when possible
            var key = STuple.ToRange(STuple.Create("hello"));

            // "<02>hello<00><00>" .. "<02>hello<00><FF>"
            Assert.That(FdbKey.PrettyPrint(key.Begin, FdbKey.PrettyPrintMode.Begin), Is.EqualTo("(\"hello\",).<00>"));
            Assert.That(FdbKey.PrettyPrint(key.End, FdbKey.PrettyPrintMode.End), Is.EqualTo("(\"hello\",).<FF>"));

            key = KeyRange.StartsWith(STuple.EncodeKey("hello"));
            // "<02>hello<00>" .. "<02>hello<01>"
            Assert.That(FdbKey.PrettyPrint(key.Begin, FdbKey.PrettyPrintMode.Begin), Is.EqualTo("(\"hello\",)"));
            Assert.That(FdbKey.PrettyPrint(key.End, FdbKey.PrettyPrintMode.End), Is.EqualTo("(\"hello\",) + 1"));

            var t = STuple.EncodeKey(123);

            Assert.That(FdbKey.PrettyPrint(t, FdbKey.PrettyPrintMode.Single), Is.EqualTo("(123,)"));
            Assert.That(FdbKey.PrettyPrint(STuple.ToRange(t).Begin, FdbKey.PrettyPrintMode.Begin), Is.EqualTo("(123,).<00>"));
            Assert.That(FdbKey.PrettyPrint(STuple.ToRange(t).End, FdbKey.PrettyPrintMode.End), Is.EqualTo("(123,).<FF>"));
        }
예제 #30
0
    void Update()
    {
        var action   = ActionClosure.Create((a, b) => UDebug.Print(a + b), 1, 2);
        var function = FuncClosure.Create((a, b) => a + b, 1, 2);

        action.Invoke();
        var c = function.Invoke <int>();

        var function2 = FuncClosure.Create(ctx => ctx.Item1 + ctx.Item2, STuple.Create(1, 2));
        var c2        = function2.Invoke <int>();
    }