Esempio n. 1
0
        public IIntervalCollection <TKey, TValue> GetIntervalCollection <TKey, TValue>(string name, Mode mode)
            where TKey : IComparable <TKey>
        {
            if (!_collectionsByName.TryGetValue(name, out var collection))
            {
                ThrowIfCannotCreate(name, mode);
                ThrowIfNotRegistered <TKey>();
                ThrowIfNotRegistered <TValue>();

                IntervalCollection <TKey, TValue> .ThrowIfInvalidKey();

                var tableName = AddTable(name, CollectionType.IntervalCollection, typeof(TKey), typeof(TValue));
                collection = CreateIntervalCollection <TKey, TValue>(name, tableName);
                AddCollection(name, collection);
            }
            else
            {
                ThrowIfMustCreate(mode);
            }

            EnsureTypeSafety(collection, CollectionType.IntervalCollection, typeof(TKey), typeof(TValue));

            if (!(collection is IIntervalCollection <TKey, TValue> target))
            {
                throw new
                      ArgumentException(string.Format("The dictionary '{0}' has a value type of '{1}': If your intent was to create a new dictionary, you have to pick a new name!",
                                                      name,
                                                      collection.ValueType.FullName));
            }

            return(target);
        }
        public void GetBetween_PerformanceTest()
        {
            const int itemCount    = 100000;
            const int requestCount = 10000;
            var       random       = new Random(42);

            var collection = new IntervalCollection <int>();

            {
                int start;
                int end;
                for (var i = 0; i < itemCount; i++)
                {
                    start = random.Next(1000);
                    end   = start + random.Next(1, 50);
                    collection.Add(new TestInterval(start, end));
                }
            }

            var stopwatch     = Stopwatch.StartNew();
            var selectedCount = 0;

            for (var i = 0; i < requestCount; i++)
            {
                var start = random.Next(1000);
                var end   = start + random.Next(50);

                var result = collection.GetBetween(start, end);
                selectedCount += result.Count;
            }

            stopwatch.Stop();

            Assert.Inconclusive($"Executed {nameof(collection.GetBetween)}() {requestCount} times to select {selectedCount} results from {itemCount} items in {stopwatch.Elapsed}");
        }
 public void TestSetUp()
 {
     intervalCollection = new IntervalCollection();
     foreach (var interval in intervals)
     {
         intervalCollection.Insert(interval.Start, interval.Length);
     }
 }
        public void GetBetween_NoItems_ReturnsEmptyCollection()
        {
            var collection = new IntervalCollection <int>();

            var result = collection.GetBetween(0, 8);

            Assert.AreEqual(0, result.Count);
        }
Esempio n. 5
0
 public void PropertiesShouldBeSet()
 {
     int lower = 2;
     int upper = 8;
     var interval = new IntervalCollection<int>(lower, upper);
     Assert.AreEqual(lower, interval.Lower);
     Assert.AreEqual(upper, interval.Upper);
     Assert.IsFalse(interval.IsLowerUnbounded);
     Assert.IsFalse(interval.IsUpperUnbounded);
 }
Esempio n. 6
0
        public CharacterClass(bool negate, bool ignore)
        {
            this.negate = negate;
            this.ignore = ignore;
            intervals   = new IntervalCollection();
            int length = 144;

            pos_cats = new BitArray(length);
            neg_cats = new BitArray(length);
        }
Esempio n. 7
0
        public void PropertiesShouldBeSet()
        {
            int lower    = 2;
            int upper    = 8;
            var interval = new IntervalCollection <int>(lower, upper);

            Assert.AreEqual(lower, interval.Lower);
            Assert.AreEqual(upper, interval.Upper);
            Assert.IsFalse(interval.IsLowerUnbounded);
            Assert.IsFalse(interval.IsUpperUnbounded);
        }
Esempio n. 8
0
 private void AddTempbasalToTimeline(IntervalCollection <TempBasal> timeline, TempBasal tempBasal)
 {
     if (tempBasal.Duration == 0)
     {
         timeline.Crop(tempBasal.Time);
     }
     else
     {
         timeline.Add(tempBasal.Time, tempBasal.Time.AddMinutes(tempBasal.Duration), tempBasal);
     }
 }
Esempio n. 9
0
 private void AddProfileToTimeline(IntervalCollection <BasalProfile> timeline, BasalProfile profile)
 {
     if (profile.Duration == 0)
     {
         timeline.Add(profile.Time, null, profile);
     }
     else
     {
         timeline.Add(profile.Time, profile.Time.AddMinutes(profile.Duration), profile);
     }
 }
Esempio n. 10
0
        public CharacterClass(bool negate, bool ignore)
        {
            this.negate = negate;
            this.ignore = ignore;

            intervals = new IntervalCollection();

            // initialize pos/neg category arrays

            int cat_size = (int)Category.LastValue;

            pos_cats = new BitArray(cat_size);
            neg_cats = new BitArray(cat_size);
        }
        public void Contains()
        {
            var now = DateTime.UtcNow;

            var intervals = new IntervalCollection();

            intervals.Add(new Interval(now, TimeSpan.FromHours(1)));
            intervals.Add(new Interval(now.AddDays(10), TimeSpan.FromHours(1)));

            Assert.IsTrue(intervals.Contains(now));
            Assert.IsTrue(intervals.Contains(now.AddMinutes(10)));
            Assert.IsFalse(intervals.Contains(now.AddMinutes(-10)));
            Assert.IsFalse(intervals.Contains(now.AddDays(5)));
            Assert.IsFalse(intervals.Contains(now.AddDays(11)));
        }
Esempio n. 12
0
 private void AnalyzeType(TypeDefinition type)
 {
     foreach (var innerType in type.NestedTypes)
     {
         AnalyzeType(innerType);
     }
     // we're only interested in methods that are not abstract
     foreach (var method in type.Methods.Where(x => x.HasBody))
     {
         var intervalCollection = new IntervalCollection();
         AnalyzeBlockFrom(method, method.Body.Instructions[0], intervalCollection);
         foreach (var interval in intervalCollection)
         {
             blocks.Add(nextBlockId++, new BlockEntry(new AssemblyEntry(method.Module.Assembly),
                                                      method.Module, method, interval.Start, interval.Length, method.MetadataToken.ToInt32()));
         }
     }
 }
        public void Intersections()
        {
            var now = DateTime.UtcNow;

            var intervals = new IntervalCollection();

            intervals.Add(new Interval(now, TimeSpan.FromHours(1)));
            intervals.Add(new Interval(now.AddDays(10), TimeSpan.FromHours(1)));

            Assert.IsTrue(intervals.GetIntersections().Count() == 0);

            intervals.Clear();
            intervals.Add(new Interval(now, TimeSpan.FromHours(2)));
            intervals.Add(new Interval(now.AddHours(-0.5), TimeSpan.FromHours(1)));

            var intersection = intervals.GetIntersections().Single();

            Assert.AreEqual(now, intersection.Start);
            Assert.AreEqual(TimeSpan.FromHours(0.5), intersection.Length);
        }
        public void FromUnordered_PerformanceTest()
        {
            const int itemCount = 100000;
            var       random    = new Random(42);

            int start;
            int end;
            var items = Enumerable.Range(0, itemCount).Select(i =>
            {
                start = random.Next(1000);
                end   = start + random.Next(1, 50);
                return(new TestInterval(start, end));
            }).ToList();

            var stopwatch  = Stopwatch.StartNew();
            var collection = IntervalCollection <int> .FromUnordered(items);

            stopwatch.Stop();

            Assert.Inconclusive($"Added {itemCount} items in {stopwatch.Elapsed}");
        }
        public void Add_PerformanceTest()
        {
            const int itemCount = 100000;
            var       random    = new Random(42);

            var stopwatch = Stopwatch.StartNew();

            var collection = new IntervalCollection <int>();
            int start;
            int end;

            for (var i = 0; i < itemCount; i++)
            {
                start = random.Next(1000);
                end   = start + random.Next(1, 50);
                collection.Add(new TestInterval(start, end));
            }

            stopwatch.Stop();

            Assert.Inconclusive($"Added {itemCount} items in {stopwatch.Elapsed}");
        }
Esempio n. 16
0
        public override AnchorInfo GetAnchorInfo(bool reverse)
        {
            int                fixedWidth         = base.GetFixedWidth();
            ArrayList          arrayList          = new ArrayList();
            IntervalCollection intervalCollection = new IntervalCollection();
            int                num   = 0;
            int                count = base.Expressions.Count;

            for (int i = 0; i < count; i++)
            {
                Expression expression;
                if (reverse)
                {
                    expression = base.Expressions[count - i - 1];
                }
                else
                {
                    expression = base.Expressions[i];
                }
                AnchorInfo anchorInfo = expression.GetAnchorInfo(reverse);
                arrayList.Add(anchorInfo);
                if (anchorInfo.IsPosition)
                {
                    return(new AnchorInfo(this, num + anchorInfo.Offset, fixedWidth, anchorInfo.Position));
                }
                if (anchorInfo.IsSubstring)
                {
                    intervalCollection.Add(anchorInfo.GetInterval(num));
                }
                if (anchorInfo.IsUnknownWidth)
                {
                    break;
                }
                num += anchorInfo.Width;
            }
            intervalCollection.Normalize();
            Interval interval = Interval.Empty;

            foreach (object obj in intervalCollection)
            {
                Interval interval2 = (Interval)obj;
                if (interval2.Size > interval.Size)
                {
                    interval = interval2;
                }
            }
            if (interval.IsEmpty)
            {
                return(new AnchorInfo(this, fixedWidth));
            }
            bool flag = false;
            int  num2 = 0;

            num = 0;
            for (int j = 0; j < arrayList.Count; j++)
            {
                AnchorInfo anchorInfo2 = (AnchorInfo)arrayList[j];
                if (anchorInfo2.IsSubstring && interval.Contains(anchorInfo2.GetInterval(num)))
                {
                    flag |= anchorInfo2.IgnoreCase;
                    arrayList[num2++] = anchorInfo2;
                }
                if (anchorInfo2.IsUnknownWidth)
                {
                    break;
                }
                num += anchorInfo2.Width;
            }
            StringBuilder stringBuilder = new StringBuilder();

            for (int k = 0; k < num2; k++)
            {
                AnchorInfo anchorInfo3;
                if (reverse)
                {
                    anchorInfo3 = (AnchorInfo)arrayList[num2 - k - 1];
                }
                else
                {
                    anchorInfo3 = (AnchorInfo)arrayList[k];
                }
                stringBuilder.Append(anchorInfo3.Substring);
            }
            if (stringBuilder.Length == interval.Size)
            {
                return(new AnchorInfo(this, interval.low, fixedWidth, stringBuilder.ToString(), flag));
            }
            if (stringBuilder.Length > interval.Size)
            {
                Console.Error.WriteLine("overlapping?");
                return(new AnchorInfo(this, fixedWidth));
            }
            throw new SystemException("Shouldn't happen");
        }
Esempio n. 17
0
        public override AnchorInfo GetAnchorInfo(bool reverse)
        {
            int ptr;
            int width = GetFixedWidth();

            ArrayList          infos    = new ArrayList();
            IntervalCollection segments = new IntervalCollection();

            // accumulate segments
            ptr = 0;
            int count = Expressions.Count;

            for (int i = 0; i < count; ++i)
            {
                Expression e;
                if (reverse)
                {
                    e = Expressions [count - i - 1];
                }
                else
                {
                    e = Expressions [i];
                }

                AnchorInfo info = e.GetAnchorInfo(reverse);
                infos.Add(info);

                if (info.IsPosition)
                {
                    return(new AnchorInfo(this, ptr + info.Offset, width, info.Position));
                }

                if (info.IsSubstring)
                {
                    segments.Add(info.GetInterval(ptr));
                }

                if (info.IsUnknownWidth)
                {
                    break;
                }

                ptr += info.Width;
            }

            // normalize and find the longest segment
            segments.Normalize();

            Interval longest = Interval.Empty;

            foreach (Interval segment in segments)
            {
                if (segment.Size > longest.Size)
                {
                    longest = segment;
                }
            }

            if (longest.IsEmpty)
            {
                return(new AnchorInfo(this, width));
            }

            // now chain the substrings that made this segment together
            bool ignore    = false;
            int  n_strings = 0;

            ptr = 0;
            for (int i = 0; i < infos.Count; ++i)
            {
                AnchorInfo info = (AnchorInfo)infos [i];

                if (info.IsSubstring && longest.Contains(info.GetInterval(ptr)))
                {
                    ignore |= info.IgnoreCase;
                    infos [n_strings++] = info;
                }

                if (info.IsUnknownWidth)
                {
                    break;
                }

                ptr += info.Width;
            }

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < n_strings; ++i)
            {
                AnchorInfo info;
                if (reverse)
                {
                    info = (AnchorInfo)infos [n_strings - i - 1];
                }
                else
                {
                    info = (AnchorInfo)infos [i];
                }
                sb.Append(info.Substring);
            }

            if (sb.Length == longest.Size)
            {
                return(new AnchorInfo(this, longest.low, width, sb.ToString(), ignore));
            }
            // were the string segments overlapping?
            if (sb.Length > longest.Size)
            {
                Console.Error.WriteLine("overlapping?");
                return(new AnchorInfo(this, width));
            }
            throw new SystemException("Shouldn't happen");
        }
Esempio n. 18
0
        public override void Compile(ICompiler cmp, bool reverse)
        {
            // create the meta-collection
            IntervalCollection meta =
                intervals.GetMetaCollection(new IntervalCollection.CostDelegate(GetIntervalCost));

            // count ops
            int count = meta.Count;

            for (int i = 0; i < pos_cats.Length; ++i)
            {
                if (pos_cats[i] || neg_cats [i])
                {
                    ++count;
                }
            }

            if (count == 0)
            {
                return;
            }

            // emit in op for |meta| > 1
            LinkRef tail = cmp.NewLink();

            if (count > 1)
            {
                cmp.EmitIn(tail);
            }

            // emit character/range/sets from meta-collection
            // we emit these first so that any 'ignore' flags will be noticed by the evaluator
            foreach (Interval a in meta)
            {
                if (a.IsDiscontiguous)                                          // Set
                {
                    BitArray bits = new BitArray(a.Size);
                    foreach (Interval b in intervals)
                    {
                        if (a.Contains(b))
                        {
                            for (int i = b.low; i <= b.high; ++i)
                            {
                                bits[i - a.low] = true;
                            }
                        }
                    }

                    cmp.EmitSet((char)a.low, bits, negate, ignore, reverse);
                }
                else if (a.IsSingleton)                                         // Character
                {
                    cmp.EmitCharacter((char)a.low, negate, ignore, reverse);
                }
                else                                                            // Range
                {
                    cmp.EmitRange((char)a.low, (char)a.high, negate, ignore, reverse);
                }
            }

            // emit categories
            for (int i = 0; i < pos_cats.Length; ++i)
            {
                if (pos_cats[i])
                {
                    if (neg_cats [i])
                    {
                        cmp.EmitCategory(Category.AnySingleline, negate, reverse);
                    }
                    else
                    {
                        cmp.EmitCategory((Category)i, negate, reverse);
                    }
                }
                else if (neg_cats[i])
                {
                    cmp.EmitNotCategory((Category)i, negate, reverse);
                }
            }

            // finish up
            if (count > 1)
            {
                if (negate)
                {
                    cmp.EmitTrue();
                }
                else
                {
                    cmp.EmitFalse();
                }

                cmp.ResolveLink(tail);
            }
        }
Esempio n. 19
0
		public CharacterClass (bool negate, bool ignore) {
			this.negate = negate;
			this.ignore = ignore;

			intervals = new IntervalCollection ();

			// initialize pos/neg category arrays

			int cat_size = (int) Category.LastValue;
			pos_cats = new BitArray (cat_size);
			neg_cats = new BitArray (cat_size);
		}
Esempio n. 20
0
		public override AnchorInfo GetAnchorInfo (bool reverse)
		{
			int ptr;
			int width = GetFixedWidth ();

			ArrayList infos = new ArrayList ();
			IntervalCollection segments = new IntervalCollection ();

			// accumulate segments
			ptr = 0;
			int count = Expressions.Count;
			for (int i = 0; i < count; ++ i) {
				Expression e;
				if (reverse)
					e = Expressions [count - i - 1];
				else
					e = Expressions [i];

				AnchorInfo info = e.GetAnchorInfo (reverse);
				infos.Add (info);

				if (info.IsPosition)
					return new AnchorInfo (this, ptr + info.Offset, width, info.Position);

				if (info.IsSubstring)
					segments.Add (info.GetInterval (ptr));

				if (info.IsUnknownWidth)
					break;

				ptr += info.Width;
			}

			// normalize and find the longest segment
			segments.Normalize ();

			Interval longest = Interval.Empty;
			foreach (Interval segment in segments) {
				if (segment.Size > longest.Size)
					longest = segment;
			}

			if (longest.IsEmpty)
				return new AnchorInfo (this, width);

			// now chain the substrings that made this segment together
			bool ignore = false;
			int n_strings = 0;

			ptr = 0;
			for (int i = 0; i < infos.Count; ++i) {
				AnchorInfo info = (AnchorInfo) infos [i];

				if (info.IsSubstring && longest.Contains (info.GetInterval (ptr))) {
					ignore |= info.IgnoreCase;
					infos [n_strings ++] = info;
				}

				if (info.IsUnknownWidth)
					break;

				ptr += info.Width;
			}

			StringBuilder sb = new StringBuilder ();
			for (int i = 0; i < n_strings; ++i) {
				AnchorInfo info;
				if (reverse)
					info = (AnchorInfo) infos [n_strings - i - 1];
				else
					info = (AnchorInfo) infos [i];
				sb.Append (info.Substring);
			}

			if (sb.Length == longest.Size)
				return new AnchorInfo (this, longest.low, width, sb.ToString (), ignore);
			// were the string segments overlapping?
			if (sb.Length > longest.Size) {
				Console.Error.WriteLine ("overlapping?");
				return new AnchorInfo (this, width);
			}
			throw new SystemException ("Shouldn't happen");
		}
Esempio n. 21
0
        public override AnchorInfo GetAnchorInfo(bool reverse)
        {
            int ptr;
            int width = GetFixedWidth();

            ArrayList          infos    = new ArrayList();
            IntervalCollection segments = new IntervalCollection();

            // accumulate segments

            ptr = 0;
            //foreach (Expression e in Expressions) {
            int count = Expressions.Count;

            for (int i = 0; i < count; ++i)
            {
                Expression e;
                if (reverse)
                {
                    e = Expressions [count - i - 1];
                }
                else
                {
                    e = Expressions [i];
                }

                AnchorInfo info = e.GetAnchorInfo(reverse);
                infos.Add(info);

                if (info.IsPosition)
                {
                    return(new AnchorInfo(this, ptr + info.Offset, width, info.Position));
                }

                if (info.IsSubstring)
                {
                    segments.Add(info.GetInterval(ptr));
                }

                if (info.IsUnknownWidth)
                {
                    break;
                }

                ptr += info.Width;
            }

            // normalize and find the longest segment

            segments.Normalize();

            Interval longest = Interval.Empty;

            foreach (Interval segment in segments)
            {
                if (segment.Size > longest.Size)
                {
                    longest = segment;
                }
            }

            // now chain the substrings that made this segment together

            if (!longest.IsEmpty)
            {
                string    str    = "";
                ArrayList strs   = new ArrayList();
                bool      ignore = false;

                ptr = 0;

                //foreach (AnchorInfo info in infos) {
                for (int i = 0; i < infos.Count; ++i)
                {
                    AnchorInfo info;

                    info = (AnchorInfo)infos[i];

                    if (info.IsSubstring && longest.Contains(info.GetInterval(ptr)))
                    {
                        //str += info.Substring;	// TODO mark subexpressions
                        strs.Add(info.Substring);
                        ignore |= info.IgnoreCase;
                    }


                    if (info.IsUnknownWidth)
                    {
                        break;
                    }

                    ptr += info.Width;
                }

                for (int i = 0; i < strs.Count; ++i)
                {
                    if (reverse)
                    {
                        str += strs [strs.Count - i - 1];
                    }
                    else
                    {
                        str += strs [i];
                    }
                }


                return(new AnchorInfo(this, longest.low, width, str, ignore));
            }

            return(new AnchorInfo(this, width));
        }
Esempio n. 22
0
        public override void Compile(ICompiler cmp, bool reverse)
        {
            // create the meta-collection
            IntervalCollection meta =
                intervals.GetMetaCollection(new IntervalCollection.CostDelegate(GetIntervalCost));

            // count ops

            int count = meta.Count;

            for (int i = 0; i < pos_cats.Length; ++i)
            {
                // use BitArray.Get instead of indexer for speedups
                //if (pos_cats[i]) ++ count;
                //if (neg_cats[i]) ++ count;
                if (pos_cats.Get(i))
                {
                    ++count;
                }
                if (neg_cats.Get(i))
                {
                    ++count;
                }
            }

            if (count == 0)
            {
                return;
            }

            // emit in op for |meta| > 1

            LinkRef tail = cmp.NewLink();

            if (count > 1)
            {
                cmp.EmitIn(tail);
            }


            // emit categories

            for (int i = 0; i < pos_cats.Length; ++i)
            {
                // use BitArray.Get instead of indexer for speedups
                //if (pos_cats[i]) {
                if (pos_cats.Get(i))
                {
                    //if (neg_cats [i])
                    if (neg_cats.Get(i))
                    {
                        cmp.EmitCategory(Category.AnySingleline, negate, reverse);
                    }
                    else
                    {
                        cmp.EmitCategory((Category)i, negate, reverse);
                    }
//				} else if (neg_cats[i]) {
                }
                else if (neg_cats.Get(i))
                {
                    cmp.EmitCategory((Category)i, !negate, reverse);
                }
            }

            // emit character/range/sets from meta-collection

            foreach (Interval a in meta)
            {
                if (a.IsDiscontiguous)                                          // Set
                {
                    BitArray bits = new BitArray(a.Size);
                    foreach (Interval b in intervals)
                    {
                        if (a.Contains(b))
                        {
                            for (int i = b.low; i <= b.high; ++i)
                            {
                                // use BitArray.Get instead of indexer for speedups : bits[i - a.low] = true;
                                bits.Set(i - a.low, true);
                            }
                        }
                    }

                    cmp.EmitSet((char)a.low, bits, negate, ignore, reverse);
                }
                else if (a.IsSingleton)                                         // Character
                {
                    cmp.EmitCharacter((char)a.low, negate, ignore, reverse);
                }
                else                                                            // Range
                {
                    cmp.EmitRange((char)a.low, (char)a.high, negate, ignore, reverse);
                }
            }

            // finish up

            if (count > 1)
            {
                if (negate)
                {
                    cmp.EmitTrue();
                }
                else
                {
                    cmp.EmitFalse();
                }

                cmp.ResolveLink(tail);
            }
        }
Esempio n. 23
0
        public override void Compile(ICompiler cmp, bool reverse)
        {
            IntervalCollection metaCollection = intervals.GetMetaCollection(GetIntervalCost);
            int num = metaCollection.Count;

            for (int i = 0; i < pos_cats.Length; i++)
            {
                if (pos_cats[i] || neg_cats[i])
                {
                    num++;
                }
            }
            if (num == 0)
            {
                return;
            }
            LinkRef linkRef = cmp.NewLink();

            if (num > 1)
            {
                cmp.EmitIn(linkRef);
            }
            foreach (Interval item in metaCollection)
            {
                Interval interval = item;
                if (interval.IsDiscontiguous)
                {
                    BitArray bitArray = new BitArray(interval.Size);
                    foreach (Interval interval2 in intervals)
                    {
                        Interval i2 = interval2;
                        if (interval.Contains(i2))
                        {
                            for (int j = i2.low; j <= i2.high; j++)
                            {
                                bitArray[j - interval.low] = true;
                            }
                        }
                    }
                    cmp.EmitSet((char)interval.low, bitArray, negate, ignore, reverse);
                }
                else if (interval.IsSingleton)
                {
                    cmp.EmitCharacter((char)interval.low, negate, ignore, reverse);
                }
                else
                {
                    cmp.EmitRange((char)interval.low, (char)interval.high, negate, ignore, reverse);
                }
            }
            for (int k = 0; k < pos_cats.Length; k++)
            {
                if (pos_cats[k])
                {
                    if (neg_cats[k])
                    {
                        cmp.EmitCategory(Category.AnySingleline, negate, reverse);
                    }
                    else
                    {
                        cmp.EmitCategory((Category)k, negate, reverse);
                    }
                }
                else if (neg_cats[k])
                {
                    cmp.EmitNotCategory((Category)k, negate, reverse);
                }
            }
            if (num > 1)
            {
                if (negate)
                {
                    cmp.EmitTrue();
                }
                else
                {
                    cmp.EmitFalse();
                }
                cmp.ResolveLink(linkRef);
            }
        }
Esempio n. 24
0
        public async IAsyncEnumerable <TimeValue> BasalRates(DateTimeOffset start, DateTimeOffset end)
        {
            using var nsql = await NightSql.GetInstance(Configuration);

            var zeroBasalSchedule = (UtcOffset : 0, Rates : new double[48]);

            var basalTimeline     = new IntervalCollection <BasalProfile>();
            var tempBasalTimeline = new IntervalCollection <TempBasal>();

            var bpStart = start;

            var sql = "SELECT * FROM basal WHERE duration = 0 AND time <= @t1 ORDER BY time DESC LIMIT 1";

            await foreach (var bpr in nsql.ExecuteQuery(sql, new [] { nsql.GetParameter("t1", start) }))
            {
                var earlyProfile = await ReadProfile(bpr);

                AddProfileToTimeline(basalTimeline, earlyProfile);
                bpStart = earlyProfile.Time;
            }

            sql = "SELECT * FROM basal WHERE time > @t1 AND time < @t2 ORDER BY time";
            await foreach (var bpr in nsql.ExecuteQuery(sql, new [] { nsql.GetParameter("t1", bpStart), nsql.GetParameter("t2", end) }))
            {
                var profile = await ReadProfile(bpr);

                AddProfileToTimeline(basalTimeline, profile);
            }

            sql = "SELECT * FROM tempbasal WHERE time <= @t1 ORDER BY time DESC LIMIT 1";
            await foreach (var tbr in nsql.ExecuteQuery(sql, new [] { nsql.GetParameter("t1", start) }))
            {
                var earlyTempBasal = await ReadTempBasal(tbr);

                AddTempbasalToTimeline(tempBasalTimeline, earlyTempBasal);
            }

            sql = "SELECT * FROM tempbasal WHERE time > @t1 AND time < @t2 ORDER BY time";
            await foreach (var tbr in nsql.ExecuteQuery(sql, new [] { nsql.GetParameter("t1", start), nsql.GetParameter("t2", end) }))
            {
                AddTempbasalToTimeline(tempBasalTimeline, await ReadTempBasal(tbr));
            }

            var    pointOfInterest  = start;
            double?lastRate         = null;
            var    activeBasalRates = new double[48];
            var    activeUtcOffset  = 0;

            while (pointOfInterest < end)
            {
                var activeBasalInterval     = basalTimeline[pointOfInterest];
                var activeBasal             = activeBasalInterval?.Value;
                var activeTempBasalInterval = tempBasalTimeline[pointOfInterest];
                var activeTempBasal         = activeTempBasalInterval?.Value;

                if (activeBasal.HasValue)
                {
                    for (int i = 0; i < 48; i++)
                    {
                        activeBasalRates[i] = activeBasal.Value.BasalRates[i];
                    }
                    activeUtcOffset = activeBasal.Value.UtcOffsetInMinutes;
                }

                if (activeTempBasal.HasValue)
                {
                    if (activeTempBasal.Value.AbsoluteRate.HasValue)
                    {
                        for (int i = 0; i < 48; i++)
                        {
                            activeBasalRates[i] = activeTempBasal.Value.AbsoluteRate.Value;
                        }
                    }
                    else if (activeTempBasal.Value.Percentage.HasValue)
                    {
                        for (int i = 0; i < 48; i++)
                        {
                            activeBasalRates[i] *= activeTempBasal.Value.Percentage.Value;
                            activeBasalRates[i] /= 100;
                        }
                    }
                }

                var scheduleOffset = pointOfInterest.AddMinutes(activeUtcOffset);
                var scheduleIndex  = scheduleOffset.Hour * 2;
                if (scheduleOffset.Minute > 30)
                {
                    scheduleIndex++;
                }

                var scheduledRate = activeBasalRates[scheduleIndex];

                if (lastRate != scheduledRate)
                {
                    yield return(new TimeValue
                    {
                        Time = pointOfInterest,
                        Value = scheduledRate
                    });

                    lastRate = scheduledRate;
                }

                pointOfInterest = GetNextHalfHourMark(pointOfInterest);

                if (activeBasalInterval?.End < pointOfInterest)
                {
                    pointOfInterest = activeBasalInterval.End;
                }

                if (activeTempBasalInterval?.End < pointOfInterest)
                {
                    pointOfInterest = activeTempBasalInterval.End;
                }
            }
        }
Esempio n. 25
0
        private void AnalyzeBlockFrom(MethodDefinition method, Instruction instruction, IntervalCollection methodBlocks)
        {
            int nextIntervalStart;
            var startingOffset = instruction.Offset;

            // if our entry point can be found in some existing block
            // we have to divide that block
            if (methodBlocks.DivideIfNecessary(startingOffset, out nextIntervalStart))
            {
                return;
            }
            if (nextIntervalStart == -1)
            {
                nextIntervalStart = int.MaxValue;
            }

            while (NextInstructionShouldBeReached(instruction) &&
                   (instruction.Offset + instruction.GetSize()) < nextIntervalStart)
            {
                instruction = instruction.Next;
                if (instruction == null)
                {
                    throw new InvalidOperationException("Invalid IL code.");
                }
            }

            var instructionSize = instruction.GetSize();

            methodBlocks.Insert(startingOffset, instruction.Offset - startingOffset + instructionSize);

            switch (instruction.OpCode.FlowControl)
            {
            case FlowControl.Return:
            case FlowControl.Throw:
                return;

            case FlowControl.Branch:
                AnalyzeBlockFrom(method, ((Instruction)instruction.Operand), methodBlocks);
                break;

            case FlowControl.Cond_Branch:
                var operandAsInstruction      = instruction.Operand as Instruction;
                var operandAsInstructionArray = instruction.Operand as Instruction[];

                if (operandAsInstruction != null)
                {
                    AnalyzeBlockFrom(method, operandAsInstruction, methodBlocks);
                }
                else if (operandAsInstructionArray != null)
                {
                    foreach (var operandInstruction in operandAsInstructionArray)
                    {
                        AnalyzeBlockFrom(method, operandInstruction, methodBlocks);
                    }
                }
                AnalyzeBlockFrom(method, instruction.Next, methodBlocks);
                break;

            case FlowControl.Break:
            case FlowControl.Meta:
            case FlowControl.Phi:
                throw new NotImplementedException();

            case FlowControl.Call:
            case FlowControl.Next:
                // we've reached here due to the nextIntervalStart that finished our scan prematurely
                return;
            }
        }
Esempio n. 26
0
		public override AnchorInfo GetAnchorInfo (bool reverse) {
			int ptr;
			int width = GetFixedWidth ();

			ArrayList infos = new ArrayList ();
			IntervalCollection segments = new IntervalCollection ();

			// accumulate segments

			ptr = 0;
			//foreach (Expression e in Expressions) {
			int count = Expressions.Count;
			for (int i = 0; i < count; ++ i) {
				Expression e;
				if (reverse)
					e = Expressions [count - i - 1];
				else
					e = Expressions [i];		
				
				AnchorInfo info = e.GetAnchorInfo (reverse);
				infos.Add (info);

				if (info.IsPosition)
					return new AnchorInfo (this, ptr + info.Offset, width, info.Position);

				if (info.IsSubstring)
					segments.Add (info.GetInterval (ptr));

				if (info.IsUnknownWidth)
					break;

				ptr += info.Width;
			}

			// normalize and find the longest segment

			segments.Normalize ();

			Interval longest = Interval.Empty;
			foreach (Interval segment in segments) {
				if (segment.Size > longest.Size)
					longest = segment;
			}

			// now chain the substrings that made this segment together

			if (!longest.IsEmpty) {
				string str = "";
				ArrayList strs = new ArrayList();
				bool ignore = false;

				ptr = 0;
				
				//foreach (AnchorInfo info in infos) {
				for (int i = 0; i < infos.Count; ++ i) {
					AnchorInfo info;

					info = (AnchorInfo)infos[i];		
					
					if (info.IsSubstring && longest.Contains (info.GetInterval (ptr))) {
						//str += info.Substring;	// TODO mark subexpressions
						strs.Add(info.Substring);
						ignore |= info.IgnoreCase;
					}

					
					 	if (info.IsUnknownWidth)					 		
							break;
					
						ptr += info.Width;
				}	
					
				for (int i = 0; i< strs.Count; ++i)
				{
					if (reverse)
						str += strs [strs.Count - i - 1];
					else
						str += strs [i];
							
					
				}
			

				return new AnchorInfo (this, longest.low, width, str, ignore);
			}

			return new AnchorInfo (this, width);
		}