Exemplo n.º 1
0
        public override Func <Target, Equinox.Store.IStream <TEvent, TState> > Resolve <TEvent, TState>(
            IUnionEncoder <TEvent, byte[]> codec,
            Func <TState, IEnumerable <TEvent>, TState> fold,
            TState initial,
            Func <TEvent, bool> isOrigin  = null,
            Func <TState, TEvent> compact = null)
        {
            var accessStrategy =
                isOrigin == null && compact == null
                    ? null
                    : AccessStrategy <TEvent, TState> .NewSnapshot(FuncConvert.FromFunc(isOrigin), FuncConvert.FromFunc(compact));

            var cacheStrategy = _cache == null
                ? null
                : CachingStrategy.NewSlidingWindow(_cache, TimeSpan.FromMinutes(20));
            var resolver = new EqxResolver <TEvent, TState>(_store, codec, FuncConvert.FromFunc(fold), initial, accessStrategy, cacheStrategy);

            return(t => resolver.Resolve.Invoke(t));
        }
        public override Func <string, Equinox.Core.IStream <TEvent, TState> > Resolve <TEvent, TState>(
            FsCodec.IEventCodec <TEvent, byte[], object> codec,
            Func <TState, IEnumerable <TEvent>, TState> fold,
            TState initial,
            Func <TEvent, bool> isOrigin     = null,
            Func <TState, TEvent> toSnapshot = null)
        {
            var accessStrategy =
                isOrigin == null && toSnapshot == null
                    ? null
                    : AccessStrategy <TEvent, TState> .NewSnapshot(FuncConvert.FromFunc(isOrigin), FuncConvert.FromFunc(toSnapshot));

            var cacheStrategy = _cache == null
                ? null
                : CachingStrategy.NewSlidingWindow(_cache, TimeSpan.FromMinutes(20));
            var resolver = new Resolver <TEvent, TState, object>(_store, codec, FuncConvert.FromFunc(fold), initial, cacheStrategy, accessStrategy, compressUnfolds: FSharpOption <bool> .None);

            return(t => resolver.Resolve(t));
        }
Exemplo n.º 3
0
        public void FSharpFunc()
        {
            Equal(I.Module.ReturnsFunc().Invoke(3), 3);
            Equal(I.Module.ReturnsFunc2().Invoke(1).Invoke(2), 3);
            Func <int, int> f = I.Module.ReturnsFunc().Invoke;

            Equal(f(3), 3);
            Equal(I.Module.InvokeFunc(FSharpConvert.Fun((int x) => x + 1), 1), 2);
            Equal(I.Module.InvokeFunc2(FSharpConvert.Fun((int x, int y) => x + y), 1, 2), 3);
            Equal(I.Module.InvokeFunc(FuncConvert.FromFunc((int x) => x + 1), 1), 2);
            Equal(I.Module.InvokeFunc2(FuncConvert.FromFunc((int x, int y) => x + y), 1, 2), 3);
            Equal(I.Module.InvokeFunc(FuncConvert.ToFSharpFunc((int x) => x + 1), 1), 2);
            var c = FSharpFunc <int, int> .ToConverter(I.Module.ReturnsFunc());

            Equal(c(3), 3);
            var f2 = FSharpFunc <int, int> .FromConverter(c);

            Equal(f2.Invoke(3), 3);
        }
Exemplo n.º 4
0
        public override Func <string, IStream <TEvent, TState> > Resolve <TEvent, TState>(
            FsCodec.IEventCodec <TEvent, byte[], object> codec,
            Func <TState, IEnumerable <TEvent>, TState> fold,
            TState initial,
            Func <TEvent, bool> isOrigin     = null,
            Func <TState, TEvent> toSnapshot = null)
        {
            var accessStrategy =
                isOrigin == null && toSnapshot == null
                    ? null
                    : AccessStrategy <TEvent, TState> .NewRollingSnapshots(FuncConvert.FromFunc(isOrigin), FuncConvert.FromFunc(toSnapshot));

            var cacheStrategy = _cache == null
                ? null
                : CachingStrategy.NewSlidingWindow(_cache, TimeSpan.FromMinutes(20));
            var cat = new EventStoreCategory <TEvent, TState, object>(_connection, codec, FuncConvert.FromFunc(fold),
                                                                      initial, cacheStrategy, accessStrategy);

            return(t => cat.Resolve(t));
        }
Exemplo n.º 5
0
        public override Func <Target, IStream <TEvent, TState> > Resolve <TEvent, TState>(
            FsCodec.IUnionEncoder <TEvent, byte[], object> codec,
            Func <TState, IEnumerable <TEvent>, TState> fold,
            TState initial,
            Func <TEvent, bool> isOrigin  = null,
            Func <TState, TEvent> compact = null)
        {
            var accessStrategy =
                isOrigin == null && compact == null
                    ? null
                    : AccessStrategy <TEvent, TState> .NewRollingSnapshots(FuncConvert.FromFunc(isOrigin), FuncConvert.FromFunc(compact));

            var cacheStrategy = _cache == null
                ? null
                : CachingStrategy.NewSlidingWindow(_cache, TimeSpan.FromMinutes(20));
            var resolver = new Resolver <TEvent, TState, object>(_connection, codec, FuncConvert.FromFunc(fold),
                                                                 initial, cacheStrategy, accessStrategy);

            return(t => resolver.Resolve(t));
        }
Exemplo n.º 6
0
        private void init()
        {
            //FSharpFunc<string, Unit> f_set_text = FuncConvert.ToFSharpFunc((Action<string>)SetTextProc);
            FSharpFunc <string, Unit> f_set_text = FuncConvert.ToFSharpFunc(new Action <string>(SetTextProc));
            //FSharpFunc<string, Unit> f_set_text = FuncConvert.ToFSharpFunc(delegate(string text) { textBoxABC.Text = text; });
            Action close_action = new Action(CloseProc);
            //Action<Unit> close_action2 = new Action<Unit>(CloseProc);
            //Converter<Unit, Unit> close_action_2 = new Converter<Unit, Unit>(close_action);
            FSharpFunc <Unit, Unit> f_close        = FuncConvert.ToFSharpFunc(close_action);
            Action <int>            close_action_1 = new Action <int>(CloseProc1);
            FSharpFunc <int, Unit>  f_close_1      = FuncConvert.ToFSharpFunc(close_action_1);

            //FSharpFunc<Unit, Unit> f_close = FuncConvert.ToFSharpFunc(close_action);
            //FSharpFunc<Unit, Unit> f_close = (FSharpFunc<Unit, Unit>)close_action;
            //FSharpFunc<Unit, Unit> f_close = FuncConvert.ToFSharpFunc<Unit>(new Action<Unit>(new Action(CloseProc)));
            abc_editor_fs = new ABCEditorFSharp.ABCEditor(f_set_text, f_close);
            //var f_close = (FSharpFunc<Unit, Unit>)CloseProc;
            //var f = new Converter<string, Unit>(SetTextProc);
            //abc_editor_fs = new ABCEditorFSharp.ABCEditor((FSharpFunc<string, Unit>)delegate(string text) { textBoxABC.Text = text; }, (FSharpFunc<Unit, Unit>)delegate() { Close(); });
            //abc_editor_fs = new ABCEditorFSharp.ABCEditor((FSharpFunc<string, Unit>)SetTextProc, (FSharpFunc<Unit, Unit>)CloseProc);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(MenuPage), args.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            // Ensure the current window is active
            Window.Current.Activate();

            SettingsPane.GetForCurrentView().CommandsRequested += App_CommandsRequested;

            var dispatcher = Window.Current.Dispatcher;

            ObservableObject.Post = FuncConvert.ToFSharpFunc <FSharpFunc <Unit, Unit> >(
                async callback => await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, (Windows.UI.Core.DispatchedHandler)(() => { callback.Invoke((Unit)null); })));
        }
Exemplo n.º 8
0
        public static void MapOne()
        {
            // define a list of names
            List <string> names = new List <string>(
                new string[] { "Stefany", "Oussama", "Sebastien", "Frederick" }
                );
            // define a predicate delegate/function
            Converter <string, bool> pred =
                delegate(string s) { return(s.StartsWith("S")); };

            // convert to a FastFunc
            FSharpFunc <string, bool> ff =
                FuncConvert.ToFSharpFunc <string, bool>(pred);
            // call the F# demo function
            IEnumerable <string> results = FuncsTakesFuncs.filterStringList(ff, names);

            // write the results to the console
            foreach (var name in results)
            {
                Console.WriteLine(name);
            }
        }
Exemplo n.º 9
0
 public static FSharpFunc <Tuple <A1, A2, A3>, Result> ToTupledFSharpFunc <A1, A2, A3, Result>(this Func <A1, A2, A3, Result> f)
 {
     return(FuncConvert.ToFSharpFunc(new Converter <Tuple <A1, A2, A3>, Result>(t => f(t.Item1, t.Item2, t.Item3))));
 }
Exemplo n.º 10
0
 public static FSharpFunc <A, Result> ToFSharpFunc <A, Result>(this Func <A, Result> f)
 {
     return(FuncConvert.ToFSharpFunc(new Converter <A, Result>(f)));
 }
        /// <summary>
        ///     Modify parameters of an FsCheck.Config.
        /// </summary>
        public static FsCheckConfig With(
            this FsCheckConfig config, List <Type> Arbitrary = null, int?EndSize           = null,
            Func <int, object[], string> Every = null, Func <object[], string> EveryShrink = null,
            int?MaxRejected = null, int?MaxTest = null, string Name = null,
            ParallelRunConfig ParallelRunConfig = null, bool?QuietOnSuccess = null,
            Tuple <ulong, ulong, int> Replay    = null, IRunner Runner      = null, int?StartSize = null)
        {
            // Create complex FSharp type
            var replay = config.Replay;

            if (Replay != null)
            {
                replay = FSharpOption <Replay> .Some(
                    new Replay(new Rnd(Replay.Item1, Replay.Item2), FSharpOption <int> .Some(Replay.Item3))
                    );
            }

            // Create complex FSharp type
            var parallelRunConfig = config.ParallelRunConfig;

            if (ParallelRunConfig != null)
            {
                parallelRunConfig = FSharpOption <ParallelRunConfig> .Some(
                    new ParallelRunConfig(ParallelRunConfig.MaxDegreeOfParallelism)
                    );
            }

            // Create complex FSharp func
            var every = config.Every;

            if (Every != null)
            {
                every = FuncConvert.FromFunc(
                    (Func <int, FSharpList <object>, string>)((numTest, list) => Every(numTest, list.ToArray()))
                    );
            }

            // Create complex FSharp func
            var everyShrink = config.EveryShrink;

            if (Every != null)
            {
                everyShrink = FuncConvert.FromFunc(
                    (Func <FSharpList <object>, string>)(list => EveryShrink(list.ToArray()))
                    );
            }

            var result = new FsCheckConfig(
                MaxTest ?? config.MaxTest, MaxRejected ?? config.MaxRejected, replay, Name ?? config.Name,
                StartSize ?? config.StartSize, EndSize ?? config.EndSize, QuietOnSuccess ?? config.QuietOnSuccess,
                every, everyShrink, ToFSharpList(Arbitrary) ?? config.Arbitrary, Runner ?? config.Runner,
                parallelRunConfig
                );

            return(result);

            FSharpList <T> ToFSharpList <T>(IEnumerable <T> elements)
            {
                return(elements?.Reverse()
                       .Aggregate(FSharpList <T> .Empty, (list, head) => FSharpList <T> .Cons(head, list)));
            }
        }
Exemplo n.º 12
0
 public static FSharpFunc <Tuple <A1, A2>, Result> ToTupledFSharpFunc <A1, A2, Result>(this Func <A1, A2, Result> f)
 => FuncConvert.ToFSharpFunc(new Converter <Tuple <A1, A2>, Result>(t => f(t.Item1, t.Item2)));
Exemplo n.º 13
0
 // Project from the synchronized state, without the possibility of adding events that Decide(Func) admits
 public async Task <T> Query <T>(Func <TState, T> project) =>
 await FSharpAsync.StartAsTask(Query(FuncConvert.FromFunc(project)), null, null);
Exemplo n.º 14
0
    static int Main()
    {
        // Some typical code

        {
            Microsoft.FSharp.Core.FSharpOption <int> x = Microsoft.FSharp.Core.FSharpOption <int> .Some(3);

            System.Console.WriteLine("{0}", x.Value);
            Microsoft.FSharp.Collections.FSharpList <int> x2 =
                Microsoft.FSharp.Collections.FSharpList <int> .Cons(3, Microsoft.FSharp.Collections.FSharpList <int> .Empty);

            System.Console.WriteLine("{0}", x2.Head);
        }
        {
            FSharpList <int> x = FSharpList <int> .Cons(3, (FSharpList <int> .Empty));

            Console.WriteLine("x - IsCons = {0}", x != null);
            Console.WriteLine("x - IsNil = {0}", x == null);
            Console.WriteLine("x.Head = {0}", x.Head);
            Console.WriteLine("x.Tail = {0}", x.Tail);
            Console.WriteLine("x.Tail - IsNil = {0}", x.Tail);
            switch (x.Tag)
            {
            case FSharpList <int> .Tags.Cons:
                Console.WriteLine("Cons({0},{1})", x.Head, x.Tail);
                break;

            case FSharpList <int> .Tags.Empty:
                Console.WriteLine("[]");
                break;
            }
        }

        {
            FSharpList <int> x = FSharpList <int> .Cons(3, (FSharpList <int> .Empty));

            foreach (int i in x)
            {
                Console.WriteLine("i = {0}", i);
            }
        }


        {
            FSharpList <int> myList = ListModule.OfArray(new int[] { 4, 5, 6 });

            ListModule.Iterate
                (FuncConvert.ToFSharpFunc((Action <int>) delegate(int i)
                                          { Console.WriteLine("i = {0}", i); }),
                myList);

            // tests op_Implicit
            ListModule.Iterate <int>
                ((Converter <int, Unit>) delegate(int i) { Console.WriteLine("i = {0} (2nd technique)", i); return(null); },
                myList);

            // tests op_Implicit
            FSharpList <string> myList2 =
                ListModule.Map
                    (FuncConvert.ToFSharpFunc((Converter <int, string>) delegate(int i)
                                              { return(i.ToString() + i.ToString()); }),
                    myList);

            // tests op_Implicit
            ListModule.Iterate
                (FuncConvert.ToFSharpFunc((Action <string>) delegate(string s)
                                          { Console.WriteLine("i after duplication = {0}", s); }),
                myList2);

            // tests op_Implicit
            myList2 =
                ListModule.Map <int, string>
                    ((Converter <int, string>) delegate(int i) { return(i.ToString() + i.ToString()); },
                    myList);

            ListModule.Iterate <string>
                (FuncConvert.ToFSharpFunc((Action <string>) delegate(string s)
                                          { Console.WriteLine("i after duplication (2nd technique) = {0}", s); }),
                myList2);

            myList2 =
                ListModule.Map <int, string>
                    (FuncConvert.ToFSharpFunc(delegate(int i) { return(i.ToString() + i.ToString()); }),
                    myList);

            myList2 =
                ListModule.Map <int, string>
                    (FuncConvert.FromFunc((Func <int, string>) delegate(int i) { return(i.ToString() + i.ToString()); }),
                    myList);

            ListModule.Iterate <string>(FuncConvert.ToFSharpFunc <string>(s => { Console.WriteLine("s = {0}", s); }), myList2);
            ListModule.Iterate <string>(FuncConvert.FromAction <string>(s => { Console.WriteLine("s = {0}", s); }), myList2);
            ListModule.Iterate <string>(FuncConvert.FromFunc <string, Microsoft.FSharp.Core.Unit>(s => null), myList2);

            myList2 = ListModule.Map <int, string>(FuncConvert.ToFSharpFunc <int, string>(i => i.ToString() + i.ToString()), myList);
            myList2 = ListModule.Map <int, string>(FuncConvert.FromFunc <int, string>(i => i.ToString() + i.ToString()), myList);
            myList2 = ListModule.MapIndexed <int, string>(FuncConvert.FromFunc <int, int, string>((i, j) => i.ToString() + j), myList);

            var trans3 = FuncConvert.FromFunc <int, int, int, int>((i, j, k) => i + j + k);
            var trans4 = FuncConvert.FromFunc <int, int, int, int, int>((i, j, k, l) => i + j + k + l);
            var trans5 = FuncConvert.FromFunc <int, int, int, int, int, int>((i, j, k, l, m) => i + j + k + l + m);

            var action3 = FuncConvert.FromAction <int, int, int>((i, j, k) => System.Console.WriteLine("action! {0}", i + j + k));
            var action4 = FuncConvert.FromAction <int, int, int, int>((i, j, k, l) => System.Console.WriteLine("action! {0}", i + j + k + l));
            var action5 = FuncConvert.FromAction <int, int, int, int, int>((i, j, k, l, m) => System.Console.WriteLine("action! {0}", i + j + k + l + m));
            ListModule.Iterate <string>(FuncConvert.ToFSharpFunc <string>(s => { Console.WriteLine("i after duplication (2nd technique) = {0}", s); }), myList2);
            ListModule.Iterate <string>(FuncConvert.FromAction <string>(s => { Console.WriteLine("i after duplication (2nd technique) = {0}", s); }), myList2);
        }

        // Construct a value of each type from the library

        Lib.Recd1          r1  = new Lib.Recd1(3);
        Lib.Recd2          r2  = new Lib.Recd2(3, "a");
        Lib.RevRecd2       rr2 = new Lib.RevRecd2("a", 3);
        Lib.Recd3 <string> r3  = new Lib.Recd3 <string>(4, "c", null);
        r3.recd3field3 = r3;

        Lib.One     d10a = Lib.One.One;
        Lib.Int     d11a = Lib.Int.NewInt(3);
        Lib.IntPair ip   = Lib.IntPair.NewIntPair(3, 4);
        Console.WriteLine("{0}", ip.Item1);
        Console.WriteLine("{0}", ip.Item2);

        Lib.IntPear ip2 = Lib.IntPear.NewIntPear(3, 4);
        Console.WriteLine("{0}", ip2.Fst);
        Console.WriteLine("{0}", ip2.Snd);

        Lib.Bool b = Lib.Bool.True;
        Console.WriteLine("{0}", Lib.Bool.True);
        Console.WriteLine("{0}", Lib.Bool.False);
        //Console.WriteLine("{0}", Lib.Bool.IsTrue(b));
        //Console.WriteLine("{0}", Lib.Bool.IsFalse(b));
        switch (b.Tag)
        {
        case Lib.Bool.Tags.True:
            Console.WriteLine("True");
            break;

        case Lib.Bool.Tags.False:
            Console.WriteLine("False");
            break;
        }

        Lib.OptionalInt oint = Lib.OptionalInt.NewSOME(3);
        Console.WriteLine("oint - IsSOME = {0}", oint != null);
        Console.WriteLine("oint - IsNONE = {0}", oint == null);
        Console.WriteLine("{0}", (oint as Lib.OptionalInt.SOME).Item);
        switch (oint.Tag)
        {
        case Lib.OptionalInt.Tags.SOME:
            var c = oint as Lib.OptionalInt.SOME;
            Console.WriteLine("SOME({0})", c.Item);
            break;

        case Lib.OptionalInt.Tags.NONE:
            Console.WriteLine("NONE");
            break;
        }

        Lib.IntOption iopt = Lib.IntOption.Nothing;
        Console.WriteLine("iopt - IsSomething = {0}", iopt != null);
        Console.WriteLine("iopt - IsNothing = {0}", iopt == null);
        switch (iopt.Tag)
        {
        case Lib.IntOption.Tags.Something:
            Console.WriteLine("Something({0})", (iopt as Lib.IntOption.Something).Item);
            break;

        case Lib.IntOption.Tags.Nothing:
            Console.WriteLine("Nothing");
            break;
        }

        Lib.GenericUnion <int, string> gu1 = Lib.GenericUnion <int, string> .Nothing;
        Lib.GenericUnion <int, string> gu2 = Lib.GenericUnion <int, string> .NewSomething(3, "4");

        Lib.GenericUnion <int, string> gu3 = Lib.GenericUnion <int, string> .NewSomethingElse(3);

        Lib.GenericUnion <int, string> gu4 = Lib.GenericUnion <int, string> .NewSomethingElseAgain(4);

        //Console.WriteLine("{0}", (gu1 as Lib.GenericUnion<int,string>.Cases.Nothing));
        Console.WriteLine("{0}", (gu2 as Lib.GenericUnion <int, string> .Something).Item1);
        Console.WriteLine("{0}", (gu3 as Lib.GenericUnion <int, string> .SomethingElse).Item);
        Console.WriteLine("{0}", (gu4 as Lib.GenericUnion <int, string> .SomethingElseAgain).Item);
        switch (gu1.Tag)
        {
        case Lib.GenericUnion <int, string> .Tags.Nothing:
            Console.WriteLine("OK");
            break;

        case Lib.GenericUnion <int, string> .Tags.Something:
        case Lib.GenericUnion <int, string> .Tags.SomethingElse:
        case Lib.GenericUnion <int, string> .Tags.SomethingElseAgain:
            Console.WriteLine("NOT OK");
            throw (new System.Exception("ERROR - INCORRECT CASE TAG"));
        }

        switch (gu2.Tag)
        {
        case Lib.GenericUnion <int, string> .Tags.Something:
            Console.WriteLine("OK");
            break;

        case Lib.GenericUnion <int, string> .Tags.Nothing:
        case Lib.GenericUnion <int, string> .Tags.SomethingElse:
        case Lib.GenericUnion <int, string> .Tags.SomethingElseAgain:
            Console.WriteLine("NOT OK");
            throw (new System.Exception("ERROR - INCORRECT CASE TAG"));
        }

        Lib.BigUnion bu1 = Lib.BigUnion.NewA1(3);
        Lib.BigUnion bu2 = Lib.BigUnion.NewA2(3);
        Lib.BigUnion bu3 = Lib.BigUnion.NewA3(3);
        Lib.BigUnion bu4 = Lib.BigUnion.NewA4(3);
        Lib.BigUnion bu5 = Lib.BigUnion.NewA5(3);
        Lib.BigUnion bu6 = Lib.BigUnion.NewA6(3);
        Lib.BigUnion bu7 = Lib.BigUnion.NewA7(3);
        Lib.BigUnion bu8 = Lib.BigUnion.NewA8(3);
        Lib.BigUnion bu9 = Lib.BigUnion.NewA9(3);
        switch (bu1.Tag)
        {
        case Lib.BigUnion.Tags.A1:
            Console.WriteLine("OK");
            break;

        case Lib.BigUnion.Tags.A2:
        case Lib.BigUnion.Tags.A3:
        case Lib.BigUnion.Tags.A4:
        case Lib.BigUnion.Tags.A5:
        case Lib.BigUnion.Tags.A6:
        case Lib.BigUnion.Tags.A7:
        case Lib.BigUnion.Tags.A8:
        case Lib.BigUnion.Tags.A9:
            Console.WriteLine("NOT OK");
            throw (new System.Exception("ERROR - INCORRECT CASE TAG"));
        }


        Lib.BigEnum be1 = Lib.BigEnum.E1;
        Lib.BigEnum be2 = Lib.BigEnum.E2;
        Lib.BigEnum be3 = Lib.BigEnum.E3;
        Lib.BigEnum be4 = Lib.BigEnum.E4;
        Lib.BigEnum be5 = Lib.BigEnum.E5;
        Lib.BigEnum be6 = Lib.BigEnum.E6;
        Lib.BigEnum be7 = Lib.BigEnum.E7;
        Lib.BigEnum be8 = Lib.BigEnum.E8;
        Lib.BigEnum be9 = Lib.BigEnum.E9;
        switch (be1.Tag)
        {
        case Lib.BigEnum.Tags.E1:
            Console.WriteLine("OK");
            break;

        case Lib.BigEnum.Tags.E2:
        case Lib.BigEnum.Tags.E3:
        case Lib.BigEnum.Tags.E4:
        case Lib.BigEnum.Tags.E5:
        case Lib.BigEnum.Tags.E6:
        case Lib.BigEnum.Tags.E7:
        case Lib.BigEnum.Tags.E8:
        case Lib.BigEnum.Tags.E9:
            Console.WriteLine("NOT OK");
            throw (new System.Exception("ERROR - INCORRECT CASE TAG"));
        }

        Lib.Index d211a = Lib.Index.NewIndex_A(3);

        Lib.Bool        d200b = Lib.Bool.False;
        Lib.OptionalInt d210b = Lib.OptionalInt.NONE;
        Lib.IntOption   d201b = Lib.IntOption.NewSomething(3);
        Lib.Index       d211b = Lib.Index.NewIndex_B(4);

/*
 *
 * type discr2_0_0 = True | False
 * type discr2_0_1 = Nothing | Something of int
 * type discr2_1_0 = SOME of int | NONE
 * type discr2_1_1 = Index_A of int | Index_B of int
 *
 * type discr3_0_0_0 = Discr3_0_0_0_A | Discr3_0_0_0_B | Discr3_0_0_0_C
 * type discr3_0_1_0 = Discr3_0_1_0_A | Discr3_0_1_0_B of int | Discr3_0_0_0_C
 * type discr3_1_0_0 = Discr3_1_0_0_A of int | Discr3_1_0_0_B | Discr3_0_0_0_C
 * type discr3_1_1_0 = Discr3_1_1_0_A of int | Discr3_1_1_0_B of int | Discr3_0_0_0_C
 * type discr3_0_0_1 = Discr3_0_0_0_A | Discr3_0_0_0_B | Discr3_0_0_0_C of string
 * type discr3_0_1_1 = Discr3_0_1_0_A | Discr3_0_1_0_B of int | Discr3_0_0_0_C of string
 * type discr3_1_0_1 = Discr3_1_0_0_A of int | Discr3_1_0_0_B | Discr3_0_0_0_C of string
 * type discr3_1_1_1 = Discr3_1_1_0_A of int | Discr3_1_1_0_B of int | Discr3_0_0_0_C of string
 */

// Toplevel functions *
        int f_1         = Lib.f_1(1);
        int f_1_1       = Lib.f_1_1(1, 2);
        int f_1_1_1     = Lib.f_1_1_1(1, 2, 3);
        int f_1_1_1_1   = Lib.f_1_1_1_1(1, 2, 3, 4);
        int f_1_1_1_1_1 = Lib.f_1_1_1_1_1(1, 2, 3, 4, 5);

#if DELEGATES
        int f_1_effect_1 = Lib.f_1_effect_1(1)(2);
#else
        int f_1_effect_1 = Lib.f_1_effect_1(1).Invoke(2);
#endif

        //let f_2 x y = x+y
        //let f_3 x y z = x+y+z
        //let f_4 x1 x2 x3 x4 = x1+x2+x3+x4
        //let f_5 x1 x2 x3 x4 x5 = x1+x2+x3+x4+x5

        // Function returning a function
        //let f_1_1 x = let x = ref 1 in fun y -> !x+y+1

        // Tuple value
        //let tup2 = (2,3)
        //let tup3 = (2,3,4)
        //let tup4 = (2,3,4,5)

        System.Console.WriteLine("Test Passed.");

        return(0);
    }
Exemplo n.º 15
0
        public IViewBuilder Subscribe <TValue>(AvaloniaProperty <TValue> property, Action <TValue> action, SubPatchOptions?patchOptions = null)
        {
            var option = patchOptions.HasValue ? patchOptions.Value : SubPatchOptions.Never;

            Attrs.Add(Avalonia.FuncUI.Builder.AttrBuilder <TView> .CreateSubscription <TValue>(property, FuncConvert.FromAction(action), FSharpOption <SubPatchOptions> .Some(option)));
            return(this);
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            var fullFilePath = Path.Combine(Directory.GetCurrentDirectory(), "test.md");
            var data         = File.ReadAllText(fullFilePath);

            var metadata = MarkdownParser.ParseMetadata(data);
            var res      = MarkdownParser.ParseString(data);
            //var renderer = new TextRenderer();
            IRenderer <string> renderer = new TextRenderer();

            var lookup = FuncConvert.ToFSharpFunc <string, FSharpFunc <string, string> >(action => FuncConvert.ToFSharpFunc <string, string>(args => "Hello"));
            var result = renderer.Render(res, lookup);

            Console.WriteLine("Hello World!");
        }
Exemplo n.º 17
0
 public static void Execute <TEvent, TState>(this Accumulator <TEvent, TState> that, Func <TState, IEnumerable <TEvent> > f) =>
 that.Transact(FuncConvert.FromFunc <TState, FSharpList <TEvent> >(s => ListModule.OfSeq(f(s))));
Exemplo n.º 18
0
        void explorer_BeforeItemPaste_safe(ref object clipboardContent, MAPIFolder Target, ref bool Cancel)
        {
            try
            {
                if (!this.trackItemMove) //prevent infinite loop
                {
                    return;
                }

                if (clipboardContent is Selection)
                {
                    var mailsToMove = new List <MailItem>();

                    var selection = (Selection)clipboardContent;
                    foreach (object itemObj in selection)
                    {
                        var obj = itemObj as MailItem;
                        if (obj != null)
                        {
                            mailsToMove.Add(obj);
                        }
                    }

                    if (mailsToMove.Count == 0)
                    {
                        return;
                    }


                    try
                    {
                        bool mailMovedToDifferentStore = u.c(() =>
                        {
                            foreach (MailItem mail in mailsToMove)
                            {
                                if (string.IsNullOrEmpty(mail.Categories))
                                {
                                    continue;
                                }

                                if (mail.Parent is Folder)
                                {
                                    var parent = (Folder)mail.Parent;
                                    if (parent.StoreID != Target.StoreID)
                                    {
                                        return(true);
                                    }
                                }
                            }
                            return(false);
                        });

                        if (!mailMovedToDifferentStore)
                        {
                            return;
                        }


                        Cancel             = true; // because I am doing the move myself with mail.Move()
                        this.trackItemMove = false;

                        var pairs = new List <EntryIdChange>();
                        foreach (MailItem mail in mailsToMove)
                        {
                            var mailAfterMove = (MailItem)mail.Move(Target);
                            Log.log("moved mail. old id = " + ThisAddIn.getEntryIdDebug(mail, "bljbkghjrhje") + " ---- new id = " + mailAfterMove.EntryID);
                            pairs.Add(new EntryIdChange {
                                OldId = ThisAddIn.getEntryIdDebug(mail, "gflibfkhjdsbnmdbfjdhjg"), NewId = mailAfterMove.EntryID, Subject = mail.Subject ?? ""
                            });
                            Utils.ReleaseComObject(mailAfterMove);
                        }
                        this.trackItemMove = true;



                        CrashReportFsharp.execInThreadForceNewThreadDur(false, logError, FuncConvert.ToFSharpFunc <Unit>(aa =>
                        {
                            try
                            {
                                var emails = (from m in pairs
                                              let atSubj = new XAttribute("subject", m.Subject ?? "")
                                                           let atOldId = new XAttribute("old_cmd_line", outlookPrefix + m.OldId)
                                                                         let atNewId = new XAttribute("new_cmd_line", outlookPrefix + m.NewId)
                                                                                       let ats = new[] { atSubj, atOldId, atNewId }
                                              select new XElement("id_change", ats)).ToArray();
                                var xelRoot           = new XElement("update_email_ids", emails);
                                var xdoc              = new XDocument(xelRoot);
                                var tabblesWasRunning = sendXmlToTabbles(xdoc);
                                if (!tabblesWasRunning)
                                {
                                    Utils.appendToXml(xelRoot);
                                }
                            }
                            catch (Exception ecc)
                            {
                                try
                                {
                                    var crashId    = "outlook-addin: error in explorer before item paste subthread";
                                    var stackTrace = ThisAddIn.AssemblyVer_safe() + CrashReportFsharp.stringOfException(ecc);
                                    var str        = crashId + stackTrace;
                                    Log.log(str);
                                }
                                catch
                                {
                                }
                            }
                        }));
                    }
                    finally
                    {
                        foreach (MailItem mail in mailsToMove)
                        {
                            Utils.ReleaseComObject(mail);
                        }
                    }
                }
            }
            catch (Exception eOuter)
            {
                try
                {
                    var crashId    = "outlook-addin: error before item paste ";
                    var stackTrace = ThisAddIn.AssemblyVer_safe() + CrashReportFsharp.stringOfException(eOuter);
                    var str        = crashId + stackTrace;
                    Log.log(str);
                }
                catch
                {
                }
            }
        }
Exemplo n.º 19
0
 static void Main(string[] args)
 {
     var proclist     = Process.GetProcesses();
     int index_devenv = FuncInterop.GetRowIndex(proclist, FuncConvert.ToFSharpFunc((Process p) => p.ProcessName.Equals("explorer.exe")));
 }
Exemplo n.º 20
0
 public IViewBuilder Property <TValue>(AvaloniaProperty property, TValue value, Func <TValue, TValue, bool> comparer)
 {
     Attrs.Add(Avalonia.FuncUI.Builder.AttrBuilder <TView> .CreateProperty(property, value, FSharpValueOption <FSharpFunc <Tuple <object, object>, bool> > .Some(FuncConvert.FromFunc <Tuple <object, object>, bool>(t => comparer((TValue)t.Item1, (TValue)t.Item2)))));
     return(this);
 }
Exemplo n.º 21
0
        public IViewBuilder Property <TValue>(string property, TValue value, Func <TView, TValue> getter, Action <TView, TValue> setter, Func <TValue, TValue, bool> comparer)
        {
            var cmp = comparer == null
                ? FSharpValueOption <FSharpFunc <Tuple <object, object>, bool> > .None
                : FSharpValueOption <FSharpFunc <Tuple <object, object>, bool> > .Some(FuncConvert.FromFunc <Tuple <object, object>, bool>(t => comparer((TValue)t.Item1, (TValue)t.Item2)));

            var get = getter == null
                ? FSharpValueOption <FSharpFunc <TView, TValue> > .None
                : FSharpValueOption <FSharpFunc <TView, TValue> > .Some(FuncConvert.FromFunc(getter));

            var set = setter == null
                ? FSharpValueOption <FSharpFunc <Tuple <TView, TValue>, Unit> > .None
                : FSharpValueOption <FSharpFunc <Tuple <TView, TValue>, Unit> > .Some(FuncConvert.FromAction <Tuple <TView, TValue> >(tup => setter(tup.Item1, tup.Item2)));

            Attrs.Add(Avalonia.FuncUI.Builder.AttrBuilder <TView> .CreateProperty(property, value, get, set, cmp));
            return(this);
        }
Exemplo n.º 22
0
 // Run the decision method, letting it decide whether or not the Command's intent should manifest as Events
 public async Task <Unit> Execute(Action <Context <TEvent, TState> > decide) =>
 await FSharpAsync.StartAsTask(Decide(FuncConvert.ToFSharpFunc(decide)), null, null);
Exemplo n.º 23
0
        public IViewBuilder Subscribe <TValue>(RoutedEvent <TValue> @event, Action <TValue> action, SubPatchOptions?patchOptions = null)
            where TValue : RoutedEventArgs
        {
            var option = patchOptions.HasValue ? patchOptions.Value : SubPatchOptions.Never;

            Attrs.Add(Avalonia.FuncUI.Builder.AttrBuilder <TView> .CreateSubscription <TValue>(@event, FuncConvert.FromAction(action), FSharpOption <SubPatchOptions> .Some(option)));
            return(this);
        }
        protected override async Task <double[]> EvaluateCellsBatchAsync(IRequestContext context, ComputationalContext computationalContext, IEnumerable <GeoCellTuple> cells)
        {
            await SaveObservationsAndDalanayDiagsForCells(context, computationalContext, cells);

            VariogramModule.IVariogramFitter variogramFitter = new LMDotNetVariogramFitter.Fitter();

            Dictionary <ITimeSegment, VariogramModule.IVariogram> variograms = new Dictionary <ITimeSegment, VariogramModule.IVariogram>();

            Dictionary <ITimeSegment, IObservationsInformation> observations = (Dictionary <ITimeSegment, IObservationsInformation>)computationalContext["observations"];

            LimitedConcurrencyLevelTaskScheduler lclts = new LimitedConcurrencyLevelTaskScheduler(Environment.ProcessorCount);
            TaskFactory taskFactory = new TaskFactory(lclts);

            var variogramTasks = observations.Select(pair => taskFactory.StartNew(() =>
            {
                ITimeSegment ts = pair.Key;
                TraceVerbose(string.Format("Fitting variogram for {0} ({1} observations)", ts, pair.Value.Observations.Length));
                Stopwatch sw1 = Stopwatch.StartNew();
                var lats      = pair.Value.Observations.Select(o => o.Latitude).ToArray();
                var lons      = pair.Value.Observations.Select(o => o.Longitude).ToArray();
                var vals      = pair.Value.Observations.Select(o => o.Value).ToArray();
                var pointSet  = new EmpVariogramBuilder.PointSet(lats, lons, vals);

                var dist = FuncConvert.ToFSharpFunc(new Converter <Tuple <double, double>, FSharpFunc <Tuple <double, double>, double> >(t1 =>
                                                                                                                                         FuncConvert.ToFSharpFunc(new Converter <Tuple <double, double>, double>(t2 => SphereMath.GetDistance(t1.Item1, t1.Item2, t2.Item1, t2.Item2)))));

                var empVar           = EmpVariogramBuilder.EmpiricalVariogramBuilder.BuildEmpiricalVariogram(pointSet, dist);
                var fitted_variogram = variogramFitter.Fit(empVar);
                VariogramModule.IVariogram effectiveVariogram = null;
                sw1.Stop();

                if (FSharpOption <VariogramModule.IDescribedVariogram> .get_IsSome(fitted_variogram))
                {
                    effectiveVariogram = fitted_variogram.Value;
                    TraceVerbose(string.Format("Variogram fited for {0} ({1} observations) in {2}", ts, pair.Value.Observations.Length, sw1.Elapsed));
                }
                else
                {
                    TraceWarning(string.Format("Variogram fitting failed for {0} ({1} observations) in {2}. Using fallback variogram", ts, pair.Value.Observations.Length, sw1.Elapsed));
                    effectiveVariogram = variogramFitter.GetFallback(empVar);
                }
                lock ("saving_variograms")
                {
                    variograms.Add(ts, effectiveVariogram);
                }
            }));

            TraceVerbose(string.Format("Starting calculations of linear weights for all cells"));
            Stopwatch sw2     = Stopwatch.StartNew();
            var       weigths = CalcLinearWeights(computationalContext, cells);

            sw2.Stop();
            TraceVerbose(string.Format("calculations of linear weights for all cells ended in {0}", sw2.Elapsed));

            TraceVerbose(string.Format("Waiting for all variograms to be computed"));
            await Task.WhenAll(variogramTasks);

            TraceVerbose(string.Format("All variograms are computed. Calculating variances and values"));

            Stopwatch sw3          = Stopwatch.StartNew();
            var       resultValues = cells.Zip(weigths, (cell, weightTuple) =>
            {
                ITimeSegment ts = cell.Time;
                var weight      = weightTuple.Item2;
                VariogramModule.IVariogram variogram = variograms[ts];
                var observation = observations[ts].Observations;

                Debug.Assert(Math.Abs(weight.Sum(w => w.Weight) - 1.0) < 1e-10);

                double sill = variogram.Sill;

                double cellLat = (cell.LatMax + cell.LatMin) * 0.5;
                double cellLon = (cell.LonMax + cell.LonMin) * 0.5;
                //var = cov(0)+ sum sum (w[i]*w[j]*cov(i,j))-2.0*sum(w[i]*cov(x,i))
                double cov_at_0 = sill;

                double acc = cov_at_0;     //cov(0)
                for (int i = 0; i < weight.Length; i++)
                {
                    double w    = weight[i].Weight;
                    int idx1    = weight[i].DataIndex;
                    double lat1 = observation[idx1].Latitude;
                    double lon1 = observation[idx1].Longitude;
                    for (int j = 0; j < i; j++)
                    {
                        int idx2    = weight[j].DataIndex;
                        double lat2 = observation[idx2].Latitude;
                        double lon2 = observation[idx2].Longitude;
                        double dist = SphereMath.GetDistance(lat1, lon1, lat2, lon2);
                        double cov  = sill - variogram.GetGamma(dist);
                        acc        += 2.0 * w * weight[j].Weight * cov;
                    }
                    acc         += w * w * cov_at_0; //diagonal elements
                    double dist2 = SphereMath.GetDistance(lat1, lon1, cellLat, cellLon);
                    double cov2  = sill - variogram.GetGamma(dist2);
                    acc         -= 2.0 * w * cov2;
                }
                return(Tuple.Create(cell, Math.Sqrt(acc), weight.Sum(w => observation[w.DataIndex].Value * w.Weight)));
            }).ToArray();

            sw3.Stop();
            TraceVerbose(string.Format("All sigmas calulated in {0}", sw3.Elapsed));
            computationalContext.Add("results", resultValues);
            return(resultValues.Select(r => r.Item2).ToArray());
        }
Exemplo n.º 25
0
 public static void Execute <TEvent, TState>(this Context <TEvent, TState> that, Func <TState, IEnumerable <TEvent> > f) =>
 that.Execute(FuncConvert.FromFunc <TState, FSharpList <TEvent> >(s => ListModule.OfSeq(f(s))));
Exemplo n.º 26
0
        public void TestTrendingManagerHosting()
        {
            var repository =
                new VolatileRepository <int, SiteTrendingSeries>(
                    FuncConvert.ToFSharpFunc <SiteTrendingSeries, int>(sts => sts.Id))
                as IRepository <int, SiteTrendingSeries>;

            int seriesId = 1;
            var matrix   = new double[]
            { 1.0, 0.0, 0.0, 0.0,
              0.0, 1.0, 0.0, 0.0,
              0.0, 0.0, 1.0, 0.0,
              0.0, 0.0, 0.0, 1.0 };

            repository.Create(
                new SiteTrendingSeries()
            {
                Id       = seriesId,
                Label    = seriesId.ToString(),
                Protocol = new TrendingProtocol()
                {
                    Algorithm = "trend",
                    Tolerance = 1.0,
                },
                SeriesItems = ListModule.OfSeq(
                    new List <TrendingSeriesItem>
                {
                    new TrendingSeriesItem(
                        allResults: FSharpList <RegistrationResult> .Empty,
                        selectedResult: new RegistrationResult(matrix: matrix, label: ""))
                }),
                Shift = new double[] { 1.0, 2.0, 3.0 }
            });


            var container = Hosting.createHostContainer();

            ComponentRegistration.registerService_(typeof(ITrendingManager), typeof(TrendingManagerService), container);
            ComponentRegistration.registerService_(typeof(ITrendingEngine), typeof(TrendingEngineService), container);
            ComponentRegistration.registerService_(typeof(ITrendingDataAccess), typeof(TrendingDataAccess), container);
            ComponentRegistration.registerFunction <ITrendCalculationFunction, TrendCalculation>(container);
            ComponentRegistration.registerRepositoryInstance(repository, container);

            Hosting.startServices(container);

            var ipm = container.Resolve <IProxyManager>();

            using (var proxyContext = ipm.GetTransientContext())
            {
                var proxy  = ipm.GetProxy <ITrendingManager>();
                var series = proxy.GetSeries(seriesId);
                Assert.IsTrue(series != null);
                var updatedSeries = proxy.UpdateSeries(series);
                Assert.IsTrue(updatedSeries.Id == series.Id);
            }

            using (var proxyContext = ipm.GetTransientContext())
            {
                var proxy  = ipm.GetProxy <ITrendingManager>();
                var series = proxy.GetSeries(seriesId);
                Assert.IsTrue(series != null);
                var updatedSeries = proxy.UpdateSeries(series);
                Assert.IsTrue(updatedSeries.Id == series.Id);
            }

            Hosting.stopServices(container);
        }
Exemplo n.º 27
0
 // Execute a command, as Decide(Action) does, but also yield an outcome from the decision
 public async Task <T> Decide <T>(Func <Context <TEvent, TState>, T> interpret) =>
 await FSharpAsync.StartAsTask <T>(Decide(FuncConvert.FromFunc(interpret)), null, null);
Exemplo n.º 28
0
        private HomeItemViewModel Parse(string source, long timer, bool generateAssembly = false)
        {
            string error = null;

            var vm = new HomeItemViewModel {
                Source = source, Timer = timer
            };
            var input = InputModule.create(vm.Source);

            var tokensResult = Lexer.tokenize(input);

            if (tokensResult.IsError)
            {
                error = tokensResult.ErrorValue;
                goto End;
            }

            var tokens = tokensResult.ResultValue;

            var programResult = Parser.parse(tokens);

            if (programResult.IsError)
            {
                error = programResult.ErrorValue;
                goto End;
            }

            var program = programResult.ResultValue;

            vm.Ast = JsonConvert.SerializeObject(_astBuilder.Build(program));

            var symbolTableResult = SymbolCollector.create(program);

            if (symbolTableResult.IsError)
            {
                error = symbolTableResult.ErrorValue;
                goto End;
            }

            var symbolTable = symbolTableResult.ResultValue;

            var typeCheckerResult = TypeChecker.check(symbolTable, program);

            if (typeCheckerResult.IsError)
            {
                error = typeCheckerResult.ErrorValue;
                goto End;
            }

            var variableInitializationCheckerResult = VariableInitializationChecker.check(program);

            if (variableInitializationCheckerResult.IsError)
            {
                error = variableInitializationCheckerResult.ErrorValue;
                goto End;
            }

            var writeLineFunc = FuncConvert.ToFSharpFunc <int>(i => vm.PrintfnLog += i + "\n");
            var environment   = EnvironmentModule.create(symbolTable, program, writeLineFunc, vm.Timer);

            var interpreterResult = Interpreter.interpret(environment);

            if (interpreterResult.IsError)
            {
                error = interpreterResult.ErrorValue;
                goto End;
            }

            var assemblyResult = ILBuilder.build(symbolTable, program);

            if (assemblyResult.IsError)
            {
                error = assemblyResult.ErrorValue;
                goto End;
            }

            var assembly = assemblyResult.ResultValue;

            vm.Il = JsonConvert.SerializeObject(_ilBuilder.Build(assembly));

            if (generateAssembly)
            {
                var applicationResult = CodeGenerator.generate(assembly);
                if (applicationResult.IsError)
                {
                    error = applicationResult.ErrorValue;
                    goto End;
                }

                vm.Application = applicationResult.ResultValue;
            }

End:
            if (error != null)
            {
                vm.Error = error;
            }

            return(vm);
        }
        public async Task <Response <SunarpDto.SunarpMtcResponseModel> > ConsultaPlaca(string sPlaca)
        {
            try
            {
                var oResponse = new Response <SunarpDto.SunarpMtcResponseModel>();
                oResponse.IsSuccess = false;

                if (string.IsNullOrEmpty(sPlaca))
                {
                    oResponse.Message = "El valor de la Placa no puede estar vacio.";
                    return(oResponse);
                }

                var wsSunarp = new wsSoapSUNARP.WSVehicularMtcDelegateClient();
                var oResult  = await wsSunarp.getConsultaxPlacaMTCAsync(sPlaca.Replace("-", ""));

                if (oResult == null)
                {
                    oResponse.Message = "No se encontro información de la PLACA ingresada.";
                    return(oResponse);
                }
                if (oResult.Body == null)
                {
                    oResponse.Message = "No se encontro información de la PLACA ingresada.";
                    return(oResponse);
                }
                if (string.IsNullOrEmpty(oResult.Body.@return))
                {
                    oResponse.Message = "No se encontro información de la PLACA ingresada.";
                    return(oResponse);
                }

                var sJson = FuncConvert.XmlToJson(oResult.Body.@return);

                // DEBIDO A QUE EL SERVICIO RESPONDE DE DOS MANERAS SE ESTA USANDO UN METODO QUE NOS AYUDA A CONVERTIR DE JSON A OBJETO
                var oData = FuncConvert.TryParseJsonToObject <SunarpDto.ConsultaxPLaca, SunarpDto.ConsultaxPlacav2>(sJson);

                var oInfo = new SunarpDto.SunarpMtcResponseModel();

                // VALIDAMOS QUE TIPO DE DATO RESPONDIO
                if (oData is SunarpDto.ConsultaxPLaca)
                {
                    // SE LLENA LA INFORMACION CUANDO TRAE SOLO UN PROPIETARIO
                    var oValue = (SunarpDto.ConsultaxPLaca)oData;
                    if (oValue != null)
                    {
                        oInfo.Propietarios.Add(this._mapper.Map <SunarpDto.Propietario, SunarpDto.PropietarioSunarpMtcModel>(oValue.placa_vigente.vehiculo.Propietarios.Propietario));
                        oInfo.Vehiculo = this._mapper.Map <SunarpDto.Vehiculo, SunarpDto.VehiculoSunarpMtcModel>(oValue.placa_vigente.vehiculo);
                    }
                }
                else if (oData is SunarpDto.ConsultaxPlacav2)
                {
                    // SE LLENA LA INFORMACION CUANDO TRAE MAS DE UN PROPIETARIO
                    var oValue = (SunarpDto.ConsultaxPlacav2)oData;
                    if (oValue != null)
                    {
                        oInfo.Vehiculo = this._mapper.Map <SunarpDto.Vehiculo, SunarpDto.VehiculoSunarpMtcModel>(oValue.placa_vigente.vehiculo[0]);
                        for (var i = 0; i < oValue.placa_vigente.vehiculo.Count; i++)
                        {
                            oInfo.Propietarios.Add(this._mapper.Map <SunarpDto.Propietario, SunarpDto.PropietarioSunarpMtcModel>(oValue.placa_vigente.vehiculo[i].Propietarios.Propietario));
                        }
                    }
                }

                oResponse.IsSuccess = true;
                oResponse.Data      = oInfo;
                return(oResponse);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 30
0
        public Task <VariogramModule.IVariogram> GetSpatialVariogramAsync(LinearCombination.RealValueNodes nodes)
        {
            var task = taskFactory.StartNew(new Func <object, VariogramModule.IVariogram>(obj =>
            {
                Stopwatch sw = Stopwatch.StartNew();
                LinearCombination.RealValueNodes localNodes = (LinearCombination.RealValueNodes)obj;
                var variogramFitter = new LMDotNetVariogramFitter.Fitter() as VariogramModule.IVariogramFitter;

                traceSource.TraceEvent(TraceEventType.Start, 1, "Starting build of emperical variogram");
                var pointSet = new EmpVariogramBuilder.PointSet(localNodes.Lats, localNodes.Lons, localNodes.Values);

                var dist = FuncConvert.ToFSharpFunc(new Converter <Tuple <double, double>, FSharpFunc <Tuple <double, double>, double> >(t1 =>
                                                                                                                                         FuncConvert.ToFSharpFunc(new Converter <Tuple <double, double>, double>(t2 => SphereMath.GetDistance(t1.Item1, t1.Item2, t2.Item1, t2.Item2)))));

                var empVar = EmpVariogramBuilder.EmpiricalVariogramBuilder.BuildEmpiricalVariogram(pointSet, dist);
                sw.Stop();
                traceSource.TraceEvent(TraceEventType.Stop, 1, string.Format("Emperical variogram is build in {0}", sw.Elapsed));
                sw = Stopwatch.StartNew();
                traceSource.TraceEvent(TraceEventType.Start, 2, "Starting variogram fitting");
                var variogramRes = variogramFitter.Fit(empVar);
                sw.Stop();
                traceSource.TraceEvent(TraceEventType.Stop, 2, string.Format("Emperical variogram is build in {0}", sw.Elapsed));
                if (FSharpOption <VariogramModule.IDescribedVariogram> .get_IsNone(variogramRes))
                {
                    traceSource.TraceEvent(TraceEventType.Error, 3, "Fariogram fitting failed. Falling back to coarse variogram approximation");
                    return(variogramFitter.GetFallback(empVar));
                }
                else
                {
                    return(variogramRes.Value);
                }
            }), nodes);

            return(task);
        }