Beispiel #1
0
        public static Cell <double> CapturePrice(
            Stream <Fuel> sStart,
            Cell <double> price1, Cell <double> price2,
            Cell <double> price3)
        {
            Stream <double> sPrice1 = sStart.Snapshot(price1,
                                                      (f, p) => f == Fuel.One ? Maybe.Some(p) : Maybe.None).FilterMaybe();
            Stream <double> sPrice2 = sStart.Snapshot(price2,
                                                      (f, p) => f == Fuel.Two ? Maybe.Some(p) : Maybe.None).FilterMaybe();
            Stream <double> sPrice3 = sStart.Snapshot(price3,
                                                      (f, p) => f == Fuel.Three ? Maybe.Some(p) : Maybe.None).FilterMaybe();

            return(sPrice1.OrElse(sPrice2.OrElse(sPrice3)).Hold(0.0));
        }
Beispiel #2
0
        public static DiscreteCell <double> CapturePrice(
            Stream <Fuel> sStart,
            DiscreteCell <double> price1, DiscreteCell <double> price2,
            DiscreteCell <double> price3)
        {
            Stream <double> sPrice1 = sStart.Snapshot(price1,
                                                      (f, p) => f == Fuel.One ? Maybe.Just(p) : Maybe.Nothing <double>()).FilterMaybe();
            Stream <double> sPrice2 = sStart.Snapshot(price2,
                                                      (f, p) => f == Fuel.Two ? Maybe.Just(p) : Maybe.Nothing <double>()).FilterMaybe();
            Stream <double> sPrice3 = sStart.Snapshot(price3,
                                                      (f, p) => f == Fuel.Three ? Maybe.Just(p) : Maybe.Nothing <double>()).FilterMaybe();

            return(sPrice1.OrElse(sPrice2.OrElse(sPrice3)).Hold(0.0));
        }
Beispiel #3
0
        public static Cell<double> CapturePrice(
            Stream<Fuel> sStart,
            Cell<double> price1, Cell<double> price2,
            Cell<double> price3)
        {
            Stream<double> sPrice1 = sStart.Snapshot(price1,
                (f, p) => f == Fuel.One ? Maybe.Just(p) : Maybe.Nothing<double>()).FilterMaybe();
            Stream<double> sPrice2 = sStart.Snapshot(price2,
                (f, p) => f == Fuel.Two ? Maybe.Just(p) : Maybe.Nothing<double>()).FilterMaybe();
            Stream<double> sPrice3 = sStart.Snapshot(price3,
                (f, p) => f == Fuel.Three ? Maybe.Just(p) : Maybe.Nothing<double>()).FilterMaybe();

            return sPrice1.OrElse(sPrice2.OrElse(sPrice3)).Hold(0.0);
        }
Beispiel #4
0
            public TestObject(Stream <bool> s, Stream <int> s1, Stream <int> s2)
            {
                var t = Transaction.Run(() =>
                {
                    var cell  = s.Map(v => v ? 1 : 0).OrElse(s1).OrElse(s2).Hold(0);
                    var cell2 = s1.Snapshot(cell.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);
                    var cell3 = s1.Snapshot(cell.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);
                    var cell4 = s1.Snapshot(cell.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);
                    var cell5 = s1.Snapshot(cell.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);
                    var cell6 = s1.Snapshot(cell.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);
                    var cell7 = s1.Snapshot(cell.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);
                    var cell8 = s1.Snapshot(cell.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);
                    var cell9 = s1.Snapshot(cell.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);

                    var l = Transaction.Run(() =>
                    {
                        this.currentValue = cell.Cell.SampleLazy();
                        return(cell.Updates.Listen(v => this.CurrentValue = v));
                    });

                    return(Tuple.Create(cell, l));
                });

                this.Cell = t.Item1;
                this.l    = t.Item2;
            }
Beispiel #5
0
            public TestObject(Stream <bool> s, Stream <int> s1, Stream <int> s2)
            {
                (DiscreteCell <int> cell, IStrongListener l) = Transaction.Run(() =>
                {
                    var cellLocal = s.Map(v => v ? 1 : 0).OrElse(s1).OrElse(s2).Hold(0);
                    var cell2     = s1.Snapshot(cellLocal.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);
                    var cell3     = s1.Snapshot(cellLocal.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);
                    var cell4     = s1.Snapshot(cellLocal.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);
                    var cell5     = s1.Snapshot(cellLocal.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);
                    var cell6     = s1.Snapshot(cellLocal.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);
                    var cell7     = s1.Snapshot(cellLocal.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);
                    var cell8     = s1.Snapshot(cellLocal.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);
                    var cell9     = s1.Snapshot(cellLocal.Cell, (left, right) => left + right).Filter(v => v > 5).OrElse(s.Snapshot(s1.Hold(0).Lift(s2.Hold(1), (left, right) => left + right).Cell).Map(v => v + 1)).Hold(3);

                    var lLocal = Transaction.Run(() =>
                    {
                        this.currentValue = cellLocal.Cell.SampleLazy();
                        return(cellLocal.Updates.Listen(v => this.CurrentValue = v));
                    });

                    return(cellLocal, lLocal);
                });

                this.Cell = cell;
                this.l    = l;
            }
Beispiel #6
0
 public Keypad(Stream<Key> sKeypad, Stream<Unit> sClear)
 {
     CellLoop<int> value = new CellLoop<int>();
     this.Value = value;
     Stream<int> sKeyUpdate = sKeypad.Snapshot(value, (key, valueLocal) =>
     {
         if (key == Key.Clear)
         {
             return Maybe.Just(0);
         }
         int x10 = valueLocal * 10;
         return x10 >= 1000
             ? Maybe.Nothing<int>()
             : Maybe.Just(
                 key == Key.Zero ? x10 :
                     key == Key.One ? x10 + 1 :
                         key == Key.Two ? x10 + 2 :
                             key == Key.Three ? x10 + 3 :
                                 key == Key.Four ? x10 + 4 :
                                     key == Key.Five ? x10 + 5 :
                                         key == Key.Six ? x10 + 6 :
                                             key == Key.Seven ? x10 + 7 :
                                                 key == Key.Eight ? x10 + 8 :
                                                     x10 + 9);
     }).FilterMaybe();
     value.Loop(sKeyUpdate.OrElse(sClear.Map(u => 0)).Hold(0));
     this.SBeep = sKeyUpdate.Map(_ => Unit.Value);
 }
Beispiel #7
0
        public MainWindow()
        {
            this.InitializeComponent();

            Transaction.RunVoid(() =>
            {
                // 책의 자바 예제와 다른점은 CellLoop를 사용
                CellLoop <int> value = new CellLoop <int>();

                // UI요소 생성 및 등록 부분
                SLabel lblValue = new SLabel(value.Map(i => i.ToString()));
                SButton plus    = new SButton {
                    Content = "+", Width = 25, Margin = new Thickness(5, 0, 0, 0)
                };
                SButton minus = new SButton {
                    Content = "-", Width = 25, Margin = new Thickness(5, 0, 0, 0)
                };

                this.Container.Children.Add(lblValue);
                this.Container.Children.Add(plus);
                this.Container.Children.Add(minus);

                // 각 버튼의 기능 스트림과 표시에 대한 스냅샷 연결
                Stream <int> sPlusDelta  = plus.SClicked.Map(_ => 1);
                Stream <int> sMinusDelta = minus.SClicked.Map(_ => - 1);
                Stream <int> sDelta      = sPlusDelta.OrElse(sMinusDelta);
                Stream <int> sUpdate     = sDelta.Snapshot(value, (d, v) => v + d);
                value.Loop(sUpdate.Hold(0));
            });
        }
Beispiel #8
0
        public MainWindow()
        {
            this.InitializeComponent();

            Transaction.RunVoid(() =>
            {
                DiscreteCellLoop <int> value = new DiscreteCellLoop <int>();
                SLabel lblValue = new SLabel(value.Map(i => i.ToString()));
                SButton plus    = new SButton {
                    Content = "+", Width = 25, Margin = new Thickness(5, 0, 0, 0)
                };
                SButton minus = new SButton {
                    Content = "-", Width = 25, Margin = new Thickness(5, 0, 0, 0)
                };

                this.Container.Children.Add(lblValue);
                this.Container.Children.Add(plus);
                this.Container.Children.Add(minus);

                Stream <int> sPlusDelta  = plus.SClicked.Map(_ => 1);
                Stream <int> sMinusDelta = minus.SClicked.Map(_ => - 1);
                Stream <int> sDelta      = sPlusDelta.OrElse(sMinusDelta);
                Stream <int> sUpdate     = sDelta.Snapshot(value, (d, v) => v + d).Filter(n => n >= 0);
                value.Loop(sUpdate.Hold(0));
            });
        }
Beispiel #9
0
        public Sspinner(int initVal)
        {
            Transaction.RunVoid(() =>
            {
                StreamLoop <int> sSetValue = new StreamLoop <int>();
                STextBox textBox           = new STextBox(
                    sSetValue.Map(v => v.ToString()),
                    initVal.ToString(),
                    Cell.Constant(true));

                this.Value = textBox.CText.Map(txt => int.TryParse(txt, out int val) ? val : 0);

                //initializeComponent
                InitializeComponent();
                textBox.HorizontalContentAlignment = HorizontalAlignment.Center;
                textBox.VerticalAlignment          = VerticalAlignment.Center;
                this.valueTextBoxPlaceHolder.Children.Add(textBox);

                Stream <int> sPlusDelta  = this.plusButton.SClicked.Map(u => 1);
                Stream <int> sMinusDelta = this.minusButton.SClicked.Map(u => - 1);
                Stream <int> sDelta      = sPlusDelta.OrElse(sMinusDelta);
                sSetValue.Loop(
                    sDelta.Snapshot(
                        this.Value,
                        (delta, value) => delta + value));
            });
        }
Beispiel #10
0
        public Keypad(Stream <Key> sKeypad, Stream <Unit> sClear)
        {
            CellLoop <int> value = new CellLoop <int>();

            this.Value = value;
            Stream <int> sKeyUpdate = sKeypad.Snapshot(value, (key, valueLocal) =>
            {
                if (key == Key.Clear)
                {
                    return(Maybe.Some(0));
                }
                int x10 = valueLocal * 10;
                return(x10 >= 1000
                    ? Maybe.None
                    : Maybe.Some(
                           key == Key.Zero ? x10 :
                           key == Key.One ? x10 + 1 :
                           key == Key.Two ? x10 + 2 :
                           key == Key.Three ? x10 + 3 :
                           key == Key.Four ? x10 + 4 :
                           key == Key.Five ? x10 + 5 :
                           key == Key.Six ? x10 + 6 :
                           key == Key.Seven ? x10 + 7 :
                           key == Key.Eight ? x10 + 8 :
                           x10 + 9));
            }).FilterMaybe();

            value.Loop(sKeyUpdate.OrElse(sClear.Map(u => 0)).Hold(0));
            this.SBeep = sKeyUpdate.Map(_ => Unit.Value);
        }
Beispiel #11
0
        public void Issue151_PoolDoubleSubtraction_Fixed()
        {
            CellSink <int>   threshold   = new CellSink <int>(10);
            StreamSink <int> addPoolSink = new StreamSink <int>();

            (Stream <int> input, Cell <int> pool) = Transaction.Run(() =>
            {
                StreamLoop <int> submitPooledAmount = new StreamLoop <int>();

                // Ways that the pool is modified.
                Stream <Func <int, int> > poolAddByInput    = addPoolSink.Map <Func <int, int> >(i => x => x + i);
                Stream <Func <int, int> > poolRemoveByUsage = Operational.Defer(submitPooledAmount.Map <Func <int, int> >(i => x => x - i));

                // The current level of the pool
                Cell <int> poolLocal = poolAddByInput
                                       .Merge(poolRemoveByUsage, (f, g) => x => g(f(x)))
                                       .Accum(0, (f, x) => f(x));

                // The current input changes combined with the pool as a stream
                Stream <int> inputByAdded =
                    poolAddByInput
                    .Snapshot(
                        poolLocal,
                        threshold,
                        (f, x, t) => f(x) >= t
                                ? Maybe.Some(f(x))
                                : Maybe.None)
                    .FilterMaybe();

                // Simple rising edge on pool threshold satisfaction.
                Stream <int> inputBySatisfaction =
                    poolLocal.Updates
                    .Snapshot(
                        poolLocal,
                        threshold,
                        (neu, alt, t) => neu >= t && alt < t
                                ? Maybe.Some(neu)
                                : Maybe.None)
                    .FilterMaybe();

                submitPooledAmount.Loop(inputByAdded.Merge(inputBySatisfaction, Math.Max));

                return(submitPooledAmount, poolLocal);
            });

            List <int> submissions = new List <int>();

            using (input.Listen(submissions.Add))
            {
                // Add amount which can be immediately used based on threshold.
                // Pool should remain zero after the transaction is complete.
                addPoolSink.Send(10);
            }

            Assert.AreEqual(1, submissions.Count);
            Assert.AreEqual(10, submissions[0]);
            Assert.AreEqual(0, pool.Sample());
        }
Beispiel #12
0
        private SSpinner(int initialValue)
        {
            StreamLoop <int> sSetValue = new StreamLoop <int>();
            STextBox         textField = new STextBox(sSetValue.Map(v => v.ToString()), initialValue.ToString())
            {
                VerticalContentAlignment = VerticalAlignment.Center
            };

            this.Value = textField.Text.Map(t =>
            {
                int result;
                if (int.TryParse(t, out result))
                {
                    return(result);
                }

                return(0);
            });
            SButton plus = new SButton {
                Content = "+", Width = 25
            };
            SButton minus = new SButton {
                Content = "-", Width = 25
            };

            this.RowDefinitions.Add(new RowDefinition {
                Height = GridLength.Auto
            });
            this.RowDefinitions.Add(new RowDefinition {
                Height = GridLength.Auto
            });
            this.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(1, GridUnitType.Star)
            });
            this.ColumnDefinitions.Add(new ColumnDefinition {
                Width = GridLength.Auto
            });

            SetRow(textField, 0);
            SetColumn(textField, 0);
            SetRowSpan(textField, 2);
            this.Children.Add(textField);

            SetRow(plus, 0);
            SetColumn(plus, 1);
            this.Children.Add(plus);

            SetRow(minus, 1);
            SetColumn(minus, 1);
            this.Children.Add(minus);

            Stream <int> sPlusDelta  = plus.SClicked.Map(_ => 1);
            Stream <int> sMinusDelta = minus.SClicked.Map(_ => - 1);
            Stream <int> sDelta      = sPlusDelta.OrElse(sMinusDelta);

            sSetValue.Loop(sDelta.Snapshot(this.Value, (d, v) => v + d));
        }
Beispiel #13
0
        public void Issue151_PoolDoubleSubtraction_Broken()
        {
            Exception actual = null;

            try
            {
                CellSink <int>   threshold   = new CellSink <int>(10);
                StreamSink <int> addPoolSink = new StreamSink <int>();

                Transaction.Run(() =>
                {
                    StreamLoop <int> submitPooledAmount = new StreamLoop <int>();

                    // Ways that the pool is modified.
                    Stream <Func <int, int> > poolAddByInput    = addPoolSink.Map <Func <int, int> >(i => x => x + i);
                    Stream <Func <int, int> > poolRemoveByUsage = submitPooledAmount.Map <Func <int, int> >(i => x => x - i);

                    // The current level of the pool
                    Cell <int> poolLocal = poolAddByInput
                                           .Merge(poolRemoveByUsage, (f, g) => x => g(f(x)))
                                           .Accum(0, (f, x) => f(x));

                    // The current input changes combined with the pool as a stream
                    Stream <int> inputByAdded =
                        poolAddByInput
                        .Snapshot(
                            poolLocal,
                            threshold,
                            (f, x, t) => f(x) >= t
                                    ? Maybe.Some(f(x))
                                    : Maybe.None)
                        .FilterMaybe();

                    // Simple rising edge on pool threshold satisfaction.
                    Stream <int> inputBySatisfaction =
                        poolLocal.Updates
                        .Snapshot(
                            poolLocal,
                            threshold,
                            (neu, alt, t) => neu >= t && alt < t
                                    ? Maybe.Some(neu)
                                    : Maybe.None)
                        .FilterMaybe();

                    submitPooledAmount.Loop(inputByAdded.Merge(inputBySatisfaction, Math.Max));

                    return(submitPooledAmount, poolLocal);
                });
            }
            catch (Exception e)
            {
                actual = e;
            }

            Assert.IsNotNull(actual);
            Assert.AreEqual("A dependency cycle was detected.", actual.Message);
        }
Beispiel #14
0
        private Cell <bool> GetFlag(int target, Stream <int> sFlag)
        {
            Stream <int>    sMark   = sFlag.Filter(target.Equals);
            CellLoop <bool> flag    = new CellLoop <bool>();
            Stream <bool>   sInvert = sMark.Snapshot(flag, (_, value) => !value);

            flag.Loop(sInvert.Hold(true));

            return(flag);
        }
Beispiel #15
0
            private static Cell <double> PausableClock(Stream <Unit> sPause, Stream <Unit> sResume, Cell <double> clock)
            {
                Cell <IMaybe <double> > pauseTime = sPause.Snapshot(clock, (_, t) => Maybe.Just(t)).OrElse(sResume.Map(_ => Maybe.Nothing <double>())).Hold(Maybe.Nothing <double>());
                Cell <double>           lostTime  = sResume.Accum(0.0, (_, total) =>
                {
                    double tPause = pauseTime.Sample().Match(v => v, () => 0);
                    double now    = clock.Sample();
                    return(total + (now - tPause));
                });

                return(pauseTime.Lift(clock, lostTime, (otPause, tClk, tLost) => otPause.Match(v => v, () => tClk) - tLost));
            }
 public static Cell<double> Accumulate(
     Stream<Unit> sClearAccumulator,
     Stream<int> sPulses,
     Cell<double> calibration)
 {
     CellLoop<int> total = new CellLoop<int>();
     total.Loop(sClearAccumulator.Map(u => 0)
         .OrElse(sPulses.Snapshot(total, (pulsesLocal, totalLocal) => pulsesLocal + totalLocal))
         .Hold(0));
     return total.Lift(
         calibration,
         (totalLocal, calibrationLocal) => totalLocal * calibrationLocal);
 }
Beispiel #17
0
        public static DiscreteCell <double> Accumulate(
            Stream <Unit> sClearAccumulator,
            Stream <int> sPulses,
            DiscreteCell <double> calibration)
        {
            DiscreteCellLoop <int> total = new DiscreteCellLoop <int>();

            total.Loop(sClearAccumulator.Map(u => 0)
                       .OrElse(sPulses.Snapshot(total, (pulsesLocal, totalLocal) => pulsesLocal + totalLocal))
                       .Hold(0));
            return(total.Lift(
                       calibration,
                       (totalLocal, calibrationLocal) => totalLocal * calibrationLocal));
        }
Beispiel #18
0
 public Frp(Action <string> addMessage)
 {
     this.listener = Transaction.Run(() =>
     {
         Cell <Maybe <DragInfo> > dragInfo =
             this.sMouseDown.Map(me => Maybe.Some(new DragInfo(me, Canvas.GetLeft(me.Element.Polygon).ZeroIfNaN(), Canvas.GetTop(me.Element.Polygon).ZeroIfNaN())))
             .OrElse(this.sMouseUp.Map(_ => Maybe <DragInfo> .None)).Hold(Maybe.None);
         Stream <MouseEvt> mouseMoveWhileDragging = dragInfo.Map(md => md.Match(d => this.sMouseMove, Stream.Never <MouseEvt>)).SwitchS();
         IListener listener1 = dragInfo.Values().FilterMaybe().Listen(d => addMessage("FRP dragging " + d.Me.Element.Name));
         IListener listener2 = mouseMoveWhileDragging.Snapshot(dragInfo, (me, md) => md.Match(d => Maybe.Some(new Reposition(d, me)), () => Maybe.None)).FilterMaybe().Listen(p =>
         {
             Canvas.SetLeft(p.Polygon, p.Left);
             Canvas.SetTop(p.Polygon, p.Top);
         });
         return(Listener.CreateComposite(new[] { listener1, listener2 }));
     });
 }
Beispiel #19
0
        public void Test_Snapshot_TestCase()
        {
            Tuple <Stream <char>, Dictionary <int, Action> > s1T = MkStream(new Dictionary <int, char> {
                { 0, 'a' }, { 3, 'b' }, { 5, 'c' }
            });
            Stream <char>            s1  = s1T.Item1;
            Dictionary <int, Action> s1F = s1T.Item2;
            Tuple <Stream <int>, Dictionary <int, Action> > s2T = MkStream(new Dictionary <int, int> {
                { 1, 4 }, { 5, 7 }
            });
            Stream <int>             s2  = s2T.Item1;
            Dictionary <int, Action> s2F = s2T.Item2;
            DiscreteCell <int>       c   = s2.Hold(3);
            List <int> @out = RunSimulation <int>(s1.Snapshot(c.Cell).Listen, new[] { s1F, s2F });

            CollectionAssert.AreEqual(new[] { 3, 4, 4 }, @out);
        }
Beispiel #20
0
        public LifeCycle(Stream <UpDown> sNozzle1, Stream <UpDown> sNozzle2, Stream <UpDown> sNozzle3)
        {
            Stream <Fuel> sLiftNozzle =
                WhenLifted(sNozzle1, Fuel.One).OrElse(
                    WhenLifted(sNozzle2, Fuel.Two).OrElse(
                        WhenLifted(sNozzle3, Fuel.Three)));
            CellLoop <Maybe <Fuel> > fillActive = new CellLoop <Maybe <Fuel> >();

            this.FillActive = fillActive;
            this.SStart     = sLiftNozzle.Snapshot(fillActive, (newFuel, fillActiveLocal) => fillActiveLocal.Match(_ => Maybe.None, () => Maybe.Some(newFuel))).FilterMaybe();
            this.SEnd       = WhenSetDown(sNozzle1, Fuel.One, fillActive).OrElse(
                WhenSetDown(sNozzle2, Fuel.Two, fillActive).OrElse(
                    WhenSetDown(sNozzle3, Fuel.Three, fillActive)));
            fillActive.Loop(
                this.SEnd.Map(e => Maybe <Fuel> .None)
                .OrElse(this.SStart.Map(Maybe.Some))
                .Hold(Maybe.None));
        }
Beispiel #21
0
 public Frp(Action <string> addMessage)
 {
     this.listener = Transaction.Run(() =>
     {
         DiscreteCell <IMaybe <DragInfo> > dragInfo =
             this.sMouseDown.Map(me => Maybe.Just(new DragInfo(me, Canvas.GetLeft(me.Element.Polygon).ZeroIfNaN(), Canvas.GetTop(me.Element.Polygon).ZeroIfNaN())))
             .OrElse(this.sMouseUp.Map(_ => Maybe.Nothing <DragInfo>())).Hold(Maybe.Nothing <DragInfo>());
         DiscreteCell <bool> axisLock             = this.sShift.Hold(false);
         Stream <MouseEvt> mouseMoveWhileDragging = dragInfo.Cell.Map(md => md.Match(d => this.sMouseMove, Stream.Never <MouseEvt>)).SwitchS();
         IListener listener1 = dragInfo.Updates.FilterMaybe().Listen(d => addMessage("FRP dragging " + d.Me.Element.Name));
         IListener listener2 = mouseMoveWhileDragging.Snapshot(dragInfo, axisLock, (me, md, a) => md.Match(
                                                                   d => Maybe.Just(new Reposition(d, me, a)),
                                                                   Maybe.Nothing <Reposition>)).FilterMaybe().Listen(p =>
         {
             Canvas.SetLeft(p.Polygon, p.Left);
             Canvas.SetTop(p.Polygon, p.Top);
         });
         return(new CompositeListener(new[] { listener1, listener2 }));
     });
 }
Beispiel #22
0
 private static Stream <End> WhenSetDown(Stream <UpDown> sNozzle, Fuel nozzleFuel, Cell <Maybe <Fuel> > fillActive) =>
 sNozzle.Snapshot(fillActive, (u, f) => u == UpDown.Down && f.Equals(Maybe.Some(nozzleFuel)) ? Maybe.Some(End.Value) : Maybe.None).FilterMaybe();
Beispiel #23
0
 private static Stream<End> WhenSetDown(Stream<UpDown> sNozzle, Fuel nozzleFuel, Cell<IMaybe<Fuel>> fillActive)
 {
     return sNozzle.Snapshot(fillActive, (u, f) => u == UpDown.Down && f.Equals(Maybe.Just(nozzleFuel)) ? Maybe.Just(End.Value) : Maybe.Nothing<End>()).FilterMaybe();
 }
Beispiel #24
0
        private FrTextField(string initText, CellLoop <string> text)
            : base((size, sMouse, sKey, focus, idSupply) =>
        {
            Stream <double> sPressed = sMouse.Snapshot(size, (e, mSize) =>
                                                       mSize.Match(
                                                           s =>
            {
                MouseButtonEventArgs b = e.Args as MouseButtonEventArgs;
                Point p = e.GetPosition();
                return(b != null && b.ChangedButton == MouseButton.Left && b.ButtonState == MouseButtonState.Pressed &&
                       p.X >= 2 && p.X < s.Width - 2 && p.Y >= 2 && p.Y < s.Height - 2
                                ? Maybe.Just(p.X - 2)
                                : Maybe.Nothing <double>());
            },
                                                           Maybe.Nothing <double>)).FilterMaybe();
            CellLoop <int> x                = new CellLoop <int>();
            long myId                       = idSupply.Get();
            Cell <bool> haveFocus           = focus.Map(fId => fId == myId);
            Typeface typeface               = new Typeface(new FontFamily("Helvetica"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
            Stream <TextUpdate> sTextUpdate = sKey.Gate(haveFocus).Snapshot(text, (key, txt) =>
            {
                int xValue = x.Sample();
                if (key is BackspaceKeyEvent)
                {
                    return(xValue > 0 ? Maybe.Just(new TextUpdate(
                                                       txt.Substring(0, xValue - 1) +
                                                       txt.Substring(xValue),
                                                       xValue - 1)) : Maybe.Nothing <TextUpdate>());
                }

                StringKeyEvent stringKey = key as StringKeyEvent;
                if (stringKey == null)
                {
                    throw new InvalidOperationException("Unexpected type encountered for " + typeof(KeyEvent).FullName + ": " + key.GetType().FullName + ".");
                }

                string keyString = stringKey.String;
                return(keyString == "\b" ? Maybe.Nothing <TextUpdate>() :
                       Maybe.Just(new TextUpdate(
                                      txt.Substring(0, xValue) +
                                      keyString +
                                      txt.Substring(xValue),
                                      xValue + 1)));
            }).FilterMaybe();
            x.Loop(sPressed.Snapshot(text,
                                     (xCoord, txt) =>
            {
                for (int i = 1; i <= txt.Length; i++)
                {
                    if (xCoord < FontUtilities.MeasureString(txt.Substring(0, i), typeface, 13).Width)
                    {
                        return(i - 1);
                    }
                }
                return(txt.Length);
            })
                   .OrElse(sTextUpdate.Map(tu => tu.NewX))
                   .Hold(0));
            text.Loop(sTextUpdate.Map(tu => tu.Txt).Hold(initText));
            Cell <Size> desiredSize = text.Map(txt =>
            {
                Size s = FontUtilities.MeasureString(txt, typeface, 13);
                return(new Size(s.Width + 14, s.Height + 10));
            });
            return(new Output(
                       text.Lift(
                           x, haveFocus, size,
                           (txt, xValue, haveFocusValue, mSize) => new DrawableDelegate(d =>
            {
                mSize.Match(
                    sz =>
                {
                    d.DrawRectangle(Brushes.White, new Pen(Brushes.Black, 1), new Rect(new Point(2, 2), new Size(sz.Width - 5, sz.Height - 5)));
                    FormattedText t = FontUtilities.GetStandardFormattedText(txt, typeface, 13, Brushes.Black);
                    FormattedText tCursor = FontUtilities.GetStandardFormattedText(txt.Substring(0, xValue), typeface, 13, Brushes.Black);
                    d.DrawText(t, new Point(4, (sz.Height - t.Height) / 2));
                    if (haveFocusValue)
                    {
                        double cursorX = tCursor.Width;
                        d.DrawLine(new Pen(Brushes.Red, 1), new Point(4 + cursorX, 4), new Point(4 + cursorX, sz.Height - 5));
                    }
                },
                    () => { });
            })),
                       desiredSize,
                       sPressed.Map(_ => myId)));
        })
        {
            this.Text = text;
        }
Beispiel #25
0
 private static Stream <End> WhenSetDown(Stream <UpDown> sNozzle, Fuel nozzleFuel, DiscreteCell <IMaybe <Fuel> > fillActive)
 {
     return(sNozzle.Snapshot(fillActive, (u, f) => u == UpDown.Down && f.Equals(Maybe.Just(nozzleFuel)) ? Maybe.Just(End.Value) : Maybe.Nothing <End>()).FilterMaybe());
 }
Beispiel #26
0
        public static void TestStream(string streamid)
        {
            Stream stream      = null;
            var    credentials = new Credentials(AccessKey, SecretKey); // Credentials Object
            var    hub         = new Hub(credentials, HubName);

            //get a stream
            try
            {
                stream = hub.GetStream(streamid);
                Console.WriteLine("hub.getStream:");
                Console.WriteLine(stream.ToJsonString());

                /*
                 * {
                 *    "id": "z1.liuhanlin.562f2b35d409d2aa48001102",
                 *    "createdAt": "2015-10-27T07:43:49.756Z",
                 *    "updatedAt": "2015-10-27T07:43:49.756Z",
                 *    "title": "562f2b35d409d2aa48001102",
                 *    "hub": "liuhanlin",
                 *    "disabled": false,
                 *    "publishKey": "9654c11a01b7b941",
                 *    "publishSecurity": "static",
                 *    "hosts": {
                 *      "publish": {
                 *        "rtmp": "100000p.publish.z1.pili.qiniup.com"
                 *      },
                 *      "live": {
                 *        "hdl": "100000p.live1-hdl.z1.pili.qiniucdn.com",
                 *        "hls": "100000p.live1-hls.z1.pili.qiniucdn.com",
                 *        "http": "100000p.live1-hls.z1.pili.qiniucdn.com",
                 *        "rtmp": "100000p.live1-rtmp.z1.pili.qiniucdn.com"
                 *      },
                 *      "playback": {
                 *        "hls": "100000p.playback1.z1.pili.qiniucdn.com",
                 *        "http": "100000p.playback1.z1.pili.qiniucdn.com"
                 *      },
                 *      "play": {
                 *        "http": "100000p.live1-hls.z1.pili.qiniucdn.com",
                 *        "rtmp": "100000p.live1-rtmp.z1.pili.qiniucdn.com"
                 *      }
                 *    }
                 *  }
                 */
            }
            catch (PiliException e)
            {
                // TODO Auto-generated catch block
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }
            //// Get Stream segments
            try
            {
                long start       = 0; // optional, in second, unix timestamp
                long end         = 0; // optional, in second, unix timestamp
                var  limit       = 0; // optional, int
                var  segmentList = stream.Segments(start, end, limit);

                Console.WriteLine("Stream segments()");
                foreach (var segment in segmentList.GetSegmentList())
                {
                    Console.WriteLine("start:" + segment.Start + ",end:" + segment.End);
                }

                /*
                 *   start:1440315411,end:1440315435
                 */
            }
            catch (PiliException e)
            {
                // TODO Auto-generated catch block
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }

            // Snapshot Stream
            var    format    = "jpg";                      // required
            var    name      = "imageName" + "." + format; // required
            long   time      = 1440315411;                 // optional, in second, unix timestamp
            string notifyUrl = null;                       // optional

            try
            {
                var response = stream.Snapshot(name, format, time, notifyUrl);
                Console.WriteLine("Stream snapshot()");
                Console.WriteLine(response.ToString());

                /*
                 * {
                 *   "targetUrl":"http://ey636h.static1.z0.pili.qiniucdn.com/snapshots/z1.test-hub.55d81a72e3ba5723280000ec/imageName.jpg",
                 *   "persistentId":"z1.55d81c247823de5a49ad729c"
                 * }
                 */
            }
            catch (PiliException e)
            {
                // TODO Auto-generated catch block
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }

            // Save Stream as a file
            var    saveAsFormat    = "mp4";                            // required
            var    saveAsName      = "videoName" + "." + saveAsFormat; // required
            long   saveAsStart     = 1444897613;                       // required, in second, unix timestampstart:1444897613,end:1444897973
            long   saveAsEnd       = 1444897973;                       // required, in second, unix timestamp
            string saveAsNotifyUrl = null;                             // optional
            string pipleline       = null;

            try
            {
                var response = stream.SaveAs(saveAsName, saveAsFormat, saveAsStart, saveAsEnd, saveAsNotifyUrl, pipleline);
                Console.WriteLine("Stream saveAs()");
                Console.WriteLine(response.ToString());

                /*
                 * {
                 *   "url":"http://ey636h.vod1.z1.pili.qiniucdn.com/recordings/z1.test-hub.55d81a72e3ba5723280000ec/videoName.m3u8",
                 *   "targetUrl":"http://ey636h.vod1.z1.pili.qiniucdn.com/recordings/z1.test-hub.55d81a72e3ba5723280000ec/videoName.mp4",
                 *   "persistentId":"z1.55d81c6c7823de5a49ad77b3"
                 * }
                 */
            }
            catch (PiliException e)
            {
                // TODO Auto-generated catch block
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }

            // Delete a Stream
            try
            {
                var res = stream.Delete();
                Console.WriteLine("Stream delete()");
                Console.WriteLine(res);
                // No Content
            }
            catch (PiliException e)
            {
                // TODO Auto-generated catch block
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }
            //////////////////////////////////////////////////////////////////////////////////////////
            // Stream end

            //get a stream
            try
            {
                stream = hub.GetStream(streamid);
                Console.WriteLine("hub.getStream:");
                Console.WriteLine(stream.ToJsonString());

                /*
                 * {
                 *    "id": "z1.liuhanlin.562f2b35d409d2aa48001102",
                 *    "createdAt": "2015-10-27T07:43:49.756Z",
                 *    "updatedAt": "2015-10-27T07:43:49.756Z",
                 *    "title": "562f2b35d409d2aa48001102",
                 *    "hub": "liuhanlin",
                 *    "disabled": false,
                 *    "publishKey": "9654c11a01b7b941",
                 *    "publishSecurity": "static",
                 *    "hosts": {
                 *      "publish": {
                 *        "rtmp": "100000p.publish.z1.pili.qiniup.com"
                 *      },
                 *      "live": {
                 *        "hdl": "100000p.live1-hdl.z1.pili.qiniucdn.com",
                 *        "hls": "100000p.live1-hls.z1.pili.qiniucdn.com",
                 *        "http": "100000p.live1-hls.z1.pili.qiniucdn.com",
                 *        "rtmp": "100000p.live1-rtmp.z1.pili.qiniucdn.com"
                 *      },
                 *      "playback": {
                 *        "hls": "100000p.playback1.z1.pili.qiniucdn.com",
                 *        "http": "100000p.playback1.z1.pili.qiniucdn.com"
                 *      },
                 *      "play": {
                 *        "http": "100000p.live1-hls.z1.pili.qiniucdn.com",
                 *        "rtmp": "100000p.live1-rtmp.z1.pili.qiniucdn.com"
                 *      }
                 *    }
                 *  }
                 */
            }
            catch (PiliException e)
            {
                // TODO Auto-generated catch block
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }
        }