Ejemplo n.º 1
0
        public void As_sequence_with_shorter_notes()
        {
            Intervals intervals = new Intervals("1 3 5").SetRoot("C");

            intervals.AsSequence = "$!i $0q $1h $2w";
            intervals.GetPattern().ToString().Should().Be("C5i E5i G5i C5q E5h G5w");
        }
Ejemplo n.º 2
0
        private int ParseInternalInterval(string s, int index, NoteContext context)
        {
            if (context.IsRest)
            {
                return(index);
            }

            // An internal interval is indicated by a single quote
            if ((index < s.Length) && (s[index] == '\''))
            {
                int intervalLength = 0;
                // Verify that index+1 is a number representing the interval.
                if (index + 1 < s.Length && IsValidIntervalChar(s[index + 1]))
                {
                    intervalLength = 1;
                }
                // We'll allow for the possibility of double-sharps and double-flats.
                if ((intervalLength == 1) && (index + 2 < s.Length) && IsValidIntervalChar(s[index + 2]))
                {
                    intervalLength = 2;
                }
                if ((intervalLength == 2) && (index + 3 < s.Length) && IsValidIntervalChar(s[index + 3]))
                {
                    intervalLength = 3;
                }
                context.InternalInterval = Intervals.GetHalfsteps(s.Substring(index + 1, intervalLength));
                context.OriginalString   = Note.ToneStringWithoutOctave((context.NoteNumber + context.InternalInterval)) + (context.IsOctaveExplicitlySet ? context.OctaveNumber.ToString() : "");
                return(index + intervalLength + 1);
            }
            return(index);
        }
Ejemplo n.º 3
0
        private void CopyRows(string where)
        {
            IsPopulatingIntervals = true;
            var selectedRows = Intervals.Where(x => x.IsSelected);
            var toCopy       = new List <Interval>();

            foreach (var interval in selectedRows)
            {
                var copy = Interval.NewInterval(string.Empty, Template.EffortType, () => RefreshTemplate());
                copy.Description      = interval.Description;
                copy.Title            = interval.Title;
                copy.IntervalLevel    = interval.IntervalLevel;
                copy.IntervalType     = interval.IntervalType;
                copy.Effort           = interval.Effort;
                copy.RecoveryInterval = interval.RecoveryInterval;
                copy.Repeats          = interval.Repeats;
                copy.IntervalDuration = interval.IntervalDuration;
                copy.ToStart          = interval.ToStart.Clone();
                copy.ToEnd            = interval.ToStart.Clone();
                toCopy.Add(copy);
            }
            var relativeTo = CurrentInterval;

            foreach (var interval in toCopy)
            {
                InsertIntervalRelativeTo(interval, relativeTo, where);
                relativeTo = interval;
            }
            IsPopulatingIntervals = false;
        }
Ejemplo n.º 4
0
 private void InsertIntervalRelativeTo(Interval toInsert, Interval relativeTo, string where)
 {
     if (relativeTo == null)
     {
         intervals.Add(toInsert);
     }
     else
     {
         var index = Intervals.IndexOf(relativeTo);
         if ("after".Equals(where))
         {
             if (index != -1)
             {
                 intervals.Insert(++index, toInsert);
             }
             else
             {
                 intervals.Add(toInsert);
             }
         }
         if ("before".Equals(where))
         {
             Intervals.Insert(index, toInsert);
         }
     }
     FirePropertyChanged("HasIntervals");
     RefreshTemplate();
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Attach transcription of audio file.
        /// </summary>
        /// <param name="filename">File name.</param>
        public void AttachTranscriptionFile(string filename)
        {
            if (!File.Exists(filename))
            {
                throw new Exception("File not found!");
            }

            int lineCount = File.ReadAllLines(filename).Length;

            m_intervals = new Intervals[lineCount];

            using (TextReader reader = File.OpenText(filename))
            {
                int    i = 0;
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    string[] item  = line.Split('\t');
                    float    start = float.Parse(item[1]) * m_SamplesPerSec;
                    float    stop  = float.Parse(item[2]) * m_SamplesPerSec;
                    m_intervals[i++] = new Intervals(item[0], (int)start, (int)stop);
                }
            }

            HasTranscription = true;
        }
Ejemplo n.º 6
0
        public void Nth_interval_for_index_outside_of_range_should_throw()
        {
            var    intervals = new Intervals("1 3 5");
            Action act       = () => intervals.GetNthInterval(3);

            act.ShouldThrow <IndexOutOfRangeException>();
        }
 public void AddCandle(string symbol, int interval, long time, double open, double close, double high, double low, double volume, bool isAddToAll, bool isTriggerEvent)
 {
     lock (this)
     {
         if (Intervals.Contains(interval))
         {
             if (isAddToAll)
             {
                 var index   = this.Intervals.FindIndex(i => i == interval);
                 var quoteId = this.CreateQuote(symbol, interval);
                 var num     = Quotes[quoteId].AddUpdate(time, open, high, low, close, volume, isTriggerEvent);  //trigger dataadded event
                 //var num = Quotes[quoteId].AddUpdate(time, open, high, low, close, volume, false);             //do not trigger dataadded event to prevent from reducing number in buffer
                 if (num >= 0)
                 {
                     var d = this.AddToOtherQuotes(Quotes[quoteId], index + 1, isTriggerEvent);
                     //QuoteStore_OnDataAddedOrUpdated(this, this.Quotes[quoteId], num);
                     //foreach (var id in d.Keys) QuoteStore_OnDataAddedOrUpdated(this, this.Quotes[id], d[id]);
                 }
             }
             else
             {
                 var quoteId = this.CreateQuote(symbol, interval);
                 Quotes[quoteId].AddUpdate(time, open, high, low, close, volume, true);
             }
         }
     }
 }
Ejemplo n.º 8
0
 public PointFigureBars(SymbolInfo symbolInfo, long boxSize, long reversal)
 {
     this.minimumTick = symbolInfo.MinimumTick.ToLong();
     this.boxSize     = boxSize * minimumTick;
     this.reversal    = reversal;
     IntervalDefault  = Intervals.Define(BarUnit.Tick, 100);
 }
Ejemplo n.º 9
0
        private async Task _client_MessageReceived_Slowmode(SocketMessage m)
        {
            if (m.Author.Id == _client.CurrentUser.Id)
            {
                return;                                        // Ignore messages from the bot itself
            }
            if (!(m.Author is SocketGuildUser author))
            {
                return;                                        // Ignore messages that do not come from a guild
            }
            if (author.Roles.Select(r => r.Id).Any(x => _config.BypassIds.Contains(x)))
            {
                return;                                                                         // Ignore messages from privileged users
            }
            var channel = m.Channel as SocketTextChannel;

            if (!Intervals.ContainsKey(channel))
            {
                return;                                  // Ignore channels for which slowmode is not enabled
            }
            var interval = Intervals[channel];

            if (!_lastMessage.ContainsKey(author.Id))
            {
                var dictionary = new Dictionary <SocketTextChannel, DateTime>();
                dictionary.Add(channel, DateTime.UtcNow);
                _lastMessage.Add(author.Id, dictionary);
            }
            else
            {
                if (DateTime.UtcNow.Subtract(_lastMessage[author.Id][channel]).TotalSeconds >= Intervals[channel]) // If the user's message was sent after the interval was up
                {
                    _lastMessage[author.Id][channel] = DateTime.UtcNow;
                }
                else
                {
                    // Delete message and mute user
                    await m.DeleteAsync();

                    var muteRole = author.Guild.GetRole(_config.MuteRoleId);
                    await author.AddRoleAsync(muteRole);

                    // author.Guild.Id, author.Id, 0, DateTime.UtcNow, DateTime.UtcNow.Add(MuteTime), "N/A (SLOWMODE AUTO-MUTE)"
                    var mute = await _records.AddMuteAsync(new Mute
                    {
                        GuildId     = author.Guild.Id,
                        SubjectId   = author.Id,
                        ModeratorId = 0,
                        Timestamp   = DateTime.UtcNow,
                        UnmuteAt    = DateTime.UtcNow.Add(MuteTime),
                        Reason      = "N/A (SLOWMODE AUTO-MUTE)",
                        Active      = true
                    });

                    _unpunish.Mutes.Add(mute);
                    _records.DisposeContext();
                    await _log.LogModMessageAsync($"Automatically muted {author.Nickname ?? author.Username}#{author.Discriminator} ({author.Id})'s message in {channel.Mention} for {MuteTime.Humanize(5)} for violating slowmode: `{m.Content}`");
                }
            }
        }
Ejemplo n.º 10
0
        protected override void DoWhenAllDataIsReady()
        {
            //if (Res.DebuggingSignalFlag)
            //    Log.Debug(_tag, $"DoWhenAll: {LoggedData.Count} data pts.");
            if (AllowDataUpdates) //base.DoWhenAllDataIsReady();
            {
                LoggedData.Add(Provider.Data);
                //Timestamps.Add(Timestamps.LastOrDefault() + Provider.Interval);
                Timestamps.Add(Provider.RunTime + AccumulatedRuntime);
                Intervals.Add(Provider.Interval);
            }
            //if (SessionCTS != null && SessionCTS.IsCancellationRequested)
            //{
            //    if (DeactivationCounter == 0)
            //    {
            //        SessionCTS = null;
            //        DeactivationCounter = 10;
            //        AdditionalPointsSignal.Set();
            //    }
            //    else DeactivationCounter--;
            //}

            if (InitialInterval == TimeSpan.Zero)
            {
                InitialInterval = Provider.Interval;
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Prepares the <see cref="CpSolver"/>. Indirectly also prepares the
        /// <see cref="CpModel"/>, which is really the focus of the Sat based approach.
        /// </summary>
        /// <returns></returns>
        protected virtual Tuple <CpSolver, CpModel> PrepareProblemSolver()
        {
            IEnumerable <CpSolver> GetDefaultSolver(string stringParameters)
            {
                stringParameters = stringParameters?.Trim() ?? Empty;

                // Only relay the StringParameters when we actually have them.
                if (!IsNullOrEmpty(stringParameters))
                {
                    yield return(new CpSolver {
                        StringParameters = stringParameters
                    });
                }
            }

            Solver = GetDefaultSolver(ParametersString).SingleOrDefault() ?? new CpSolver();

            /* Truly there is nothing to convey to any Monitors, Search Agents, etc, for the Sat
             * approach. Once they are New created or Added, they are registered with the Model
             * forever and ever AMEN. */

            // ReSharper disable once UnusedVariable
            var variables = Variables.ToList();
            // ReSharper disable once UnusedVariable
            var intervals = Intervals.ToList();
            // ReSharper disable once UnusedVariable
            var constraints = Constraints.ToArray();

            // TODO: TBD: any other aspects of Solver/Model that need to be obtained?

            return(Tuple.Create(Solver, Source));
        }
Ejemplo n.º 12
0
        public void Test_rotate()
        {
            var intervals = new Intervals("1 3 5");

            intervals.Rotate(1);
            intervals.ToString().Should().Be("3 5 1");
        }
Ejemplo n.º 13
0
        public void As_sequence_with_longer_notes()
        {
            Intervals intervals = new Intervals("1 3 5").SetRoot("C");

            intervals.AsSequence = "$0q. $1q $2h";
            intervals.GetPattern().ToString().Should().Be("C5q. E5q G5h");
        }
Ejemplo n.º 14
0
 public void Disable(SocketTextChannel channel)
 {
     if (Intervals.ContainsKey(channel))
     {
         Intervals.Remove(channel);
     }
 }
Ejemplo n.º 15
0
 protected override void DoWhenAllDataIsReady()
 {
     LoggedData.Add(Provider.Data);
     //Timestamps.Add(Timestamps.LastOrDefault() + Provider.Interval);
     Timestamps.Add(Provider.RunTime);
     Intervals.Add(Provider.Interval);
 }
 public void AddQuoteBasic(IQuoteBasicBase qb, bool isAddToAll, bool isTriggerEvent)
 {
     lock (this)
     {
         if (qb != null && qb.Count > 0 && Intervals.Contains(qb.Interval))
         {
             if (isAddToAll)
             {
                 var index    = this.Intervals.FindIndex(i => i == qb.Interval);
                 var interval = this.Intervals[index];
                 var quoteId  = this.CreateQuote(qb.Symbol, interval);
                 var num      = Quotes[quoteId].Append(qb, isTriggerEvent);                                                    //trigger OnQuoteBasicDataAddedOrUpdated
                 //var num = Quotes[quoteId].Append(qb, false);                                                      //do not trigger OnQuoteBasicDataAddedOrUpdated until we add to all quotes
                 if (num >= 0)
                 {
                     var d = this.AddToOtherQuotes(Quotes[quoteId], index + 1, isTriggerEvent);
                     //QuoteStore_OnDataAddedOrUpdated(this, this.Quotes[quoteId], num);
                     //foreach (var qId in d.Keys) QuoteStore_OnDataAddedOrUpdated(this, this.Quotes[qId], d[qId]);
                 }
             }
             else
             {
                 var quoteId = this.CreateQuote(qb.Symbol, qb.Interval);
                 var num     = Quotes[quoteId].Append(qb, isTriggerEvent);
             }
         }
     }
 }
Ejemplo n.º 17
0
        public static void Run()
        {
            // initialize matrix.
            Matrix <double> matrix = new[, ]
            {
                { 5.7, 6.7, 6.2, 7 },
                { 6.7, 7.7, 7.2, 11 },
                { 7.7, 8.7, 8.2, 6 },
                { 8.7, 9.7, 9.2, 4 },
                { 9.7, 10.7, 10.2, 2 }
            };

            // choose column which will be mark.
            TableIntervals[] table = { TableIntervals.Xi, TableIntervals.Ni };

            // sets configuration for intervals
            var configIntervals = new ConfigIntervals <double>(matrix, table);

            // calculate matrix with intervals.
            var intervals = new Intervals <double>(configIntervals);

            // gets interval row mean
            intervals.GetIntervalRowMean();

            // gets modal interval
            double modal = intervals.ModalInterval;

            // gets median interval
            double median = intervals.MedianInterval;
        }
Ejemplo n.º 18
0
        public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            PhotoCalibratedBoreIntervalVM[] intervalsArray = Intervals.Where(i => !(double.IsNaN(i.LowerDepth) && double.IsNaN(i.UpperDepth))).Select(i => (PhotoCalibratedBoreIntervalVM)i).ToArray();
            info.AddValue("Intervals", intervalsArray);

            //TODO: avoid usage of explicit derived type here
            info.AddValue(nameof(imageStorage), (Persistence.FolderImageStorage)imageStorage);
        }
Ejemplo n.º 19
0
        public void Test_pattern_with_root()
        {
            var intervals = new Intervals("1 3 5");

            intervals.SetRoot("C");

            intervals.GetPattern().ToString().Should().Be("C5 E5 G5");
        }
        public void TestThatWhenValueDoesNotStartWith01IsInTheSecondQuarterReturnsFalse()
        {
            var value = Convert.ToUInt32("10101101000111001001000011000011", 2);

            var result = Intervals.IsInTheSecondQuarter(value);

            Assert.IsFalse(result);
        }
Ejemplo n.º 21
0
        public void Test_has()
        {
            var intervals = new Intervals("1 3 5");

            intervals.SetRoot("C");
            intervals.Has("E").Should().BeTrue();
            intervals.Has("F").Should().BeFalse();
        }
Ejemplo n.º 22
0
        public void Test_Nth_interval()
        {
            var intervals = new Intervals("1 3 5");

            intervals.GetNthInterval(0).Should().Be("1");
            intervals.GetNthInterval(1).Should().Be("3");
            intervals.GetNthInterval(2).Should().Be("5");
        }
        public void TestThatWhenValueStartsWith10IsInTheThirdQuarterReturnsTrue()
        {
            var value = Convert.ToUInt32("10101101000111001001000011000011", 2);

            var result = Intervals.IsInTheThirdQuarter(value);

            Assert.IsTrue(result);
        }
Ejemplo n.º 24
0
        public void Test_has_with_octaves()
        {
            var intervals = new Intervals("1 3 5");

            intervals.SetRoot("D5");
            intervals.Has("F#2").Should().BeTrue();
            intervals.Has("G5").Should().BeFalse();
        }
        public void TestThatWhenValueStartsWith0IsInTheSecondHalfReturnsFalse()
        {
            var value = Convert.ToUInt32("01101101000111001001000011000011", 2);

            var result = Intervals.IsInTheSecondHalf(value);

            Assert.IsFalse(result);
        }
Ejemplo n.º 26
0
        public void Flatten(List <Interval <int> > input, List <Interval <int> > expectedOutput)
        {
            var output = Intervals.Flatten(input);

            // Comparison is done on the string representation of intervals in order to handle infinity cases which are
            // not comparable.
            Assert.Equal(expectedOutput.Select(i => i.ToString()), output.Select(i => i.ToString()));
        }
Ejemplo n.º 27
0
 /// <summary>
 /// 判断计划时间是否处于某个时间段内
 /// </summary>
 /// <param name="beginTime">开始时间</param>
 /// <param name="endTime">结束时间</param>
 /// <param name="intervals">取值区间值</param>
 /// <returns>如果处于某个时间段内返回true,否则返回false。</returns>
 public Boolean IsInRange(PlanTime beginTime, PlanTime endTime, Intervals intervals)
 {
     if (this.Type != beginTime.Type || this.Type != endTime.Type)
     {
         throw new ArgumentException("Plan time type mismatch.");
     }
     return(this.ToDateTime().IsInRange(beginTime.ToDateTime(), endTime.ToDateTime(), intervals));
 }
Ejemplo n.º 28
0
 public TimeIntervals Intersect(TimeIntervals other)
 {
     using (var myIntervals = Intervals.GetEnumerator())
         using (var otherIntervals = other.Intervals.GetEnumerator())
         {
             return(FromIntervalsSorted(Intersect(myIntervals, otherIntervals)));
         }
 }
Ejemplo n.º 29
0
        public PhiAccrualModel NextInterval(long interval)
        {
            if (Intervals.Count == SampleSize)
            {
                return(new PhiAccrualModel(SampleSize, Intervals.Skip(1).ToImmutableList().Add(interval)));
            }

            return(new PhiAccrualModel(SampleSize, Intervals.Add(interval)));
        }
Ejemplo n.º 30
0
 private void butUncheckAll_Click(object sender, EventArgs e)
 {
     foreach (DataRow row in dataSet1.Tables[0].Rows)
     {
         try { row["Otm"] = false; }
         catch { }
     }
     Intervals.Update();
 }
Ejemplo n.º 31
0
        public void PerfectFill()
        {
            var a = new Intervals<float>();
            a.Add(0, 5);
            Assert.That(a.Contains(-float.Epsilon), Is.False);
            Assert.That(a.Contains(0));
            Assert.That(a.Contains(4.999f));
            Assert.That(a.Contains(5), Is.False);
            a.Add(6, 10);
            Assert.That(a.Contains(6));
            Assert.That(a.Contains(9.999f));
            Assert.That(a.Contains(10), Is.False);

            Assert.That(a.Count(), Is.EqualTo(2));
            a.Add(5, 6);
            Assert.That(a.Count(), Is.EqualTo(1));
        }
Ejemplo n.º 32
0
 public void AddingWithoutOverlap()
 {
     var a = new Intervals<int>();
     a.Add(0, 5);
     Assert.That(a.Contains(-1), Is.False);
     Assert.That(a.Contains(0));
     Assert.That(a.Contains(1));
     Assert.That(a.Contains(2));
     Assert.That(a.Contains(3));
     Assert.That(a.Contains(4));
     Assert.That(a.Contains(5), Is.False);
     a.Add(6, 10);
     Assert.That(a.Contains(6));
     Assert.That(a.Contains(7));
     Assert.That(a.Contains(8));
     Assert.That(a.Contains(9));
     Assert.That(a.Contains(10), Is.False);
     a.Add(-2, -1);
     Assert.That(a.Contains(-3), Is.False);
     Assert.That(a.Contains(2));
     Assert.That(a.Contains(-1), Is.False);
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Attach transcription of audio file.
        /// </summary>
        /// <param name="filename">File name.</param>
        public void AttachTranscription(string transcription)
        {
            if (transcription == "")
                return;

            string[] line = transcription.Split('\n');
            m_intervals = new Intervals[line.Length];
            for (int i = 0; i < line.Length; i++)
            {
                string[] item = line[i].Split('\t');
                float start = float.Parse(item[1]) * m_SamplesPerSec;
                float stop = float.Parse(item[2]) * m_SamplesPerSec;
                m_intervals[i] = new Intervals(item[0], (int)start, (int)stop);
            }

            HasTranscription = true;
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Разбивает график на интервалы непрерывных значений (анализ тайм-аутов по NaN)
        /// </summary>
        /// <param name="pts">Анализируемый массив</param>
        /// <returns>Массив интервалов, где [][1] - индекс первой точки интервала, [][2] - индекс последней</returns>
        private List<Intervals> getIntervals(PointF[] pts)
        {
            if (pts.Length == 0) return null;

            List<Intervals> tmpIntrv = new List<Intervals>();
            bool first = true;
            int ind = -1;

            for (int j = 0; j < pts.Length; j++)
            {
                if (float.IsNaN(pts[j].X))
                {
                    first = true;
                }
                else
                {
                    if (first)
                    {
                        Intervals Interval = new Intervals();
                        Interval.beg = j;
                        Interval.end = j;
                        tmpIntrv.Add(Interval);
                        ind++;
                        first = false;
                    }
                    else
                    {
                        tmpIntrv[ind].end = j;
                    }
                }
            }
            return tmpIntrv;
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Attach transcription of audio file.
        /// </summary>
        /// <param name="filename">File name.</param>
        public void AttachTranscriptionFile(string filename)
        {
            if (!File.Exists(filename))
                throw new Exception("File not found!");

            int lineCount = File.ReadAllLines(filename).Length;
            m_intervals = new Intervals[lineCount];

            using (TextReader reader = File.OpenText(filename))
            {
                int i = 0;
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    string[] item = line.Split('\t');
                    float start = float.Parse(item[1]) * m_SamplesPerSec;
                    float stop = float.Parse(item[2]) * m_SamplesPerSec;
                    m_intervals[i++] = new Intervals(item[0], (int)start, (int)stop);
                }
            }

            HasTranscription = true;
        }
Ejemplo n.º 36
0
 /// <summary>
 /// This makes the following tree.
 /// <para><code>
 ///                25/29
 ///             /         \
 ///          0/5          42/49
 ///       /       \
 /// -100/-50     10/12
 /// </code></para>
 /// </summary>
 /// <returns></returns>
 private static Intervals<double> MakeTree()
 {
     var a = new Intervals<double>();
     a.Add(0, 5);
     a.Add(-100, -50);
     a.Add(25, 29);
     a.Add(10, 12);
     a.Add(42, 49);
     Assert.That(a.Count(), Is.EqualTo(5));
     return a;
 }