Esempio n. 1
0
 public static ValueNode WinCol(
     AggregateType type,
     ValueNode aggregateParameter,
     IEnumerable <ValueNode> partitionBy     = null,
     IEnumerable <OrderByClauseNode> orderBy = null)
 {
     return(ValueNode.NewWindowedColumn(
                new Tuple <Tuple <AggregateType, ValueNode>, AST.WindowNode>(
                    new Tuple <AggregateType, ValueNode>(type, aggregateParameter),
                    new AST.WindowNode(
                        partitionBy == null ? ListModule.Empty <ValueNode>() : ListModule.OfSeq(partitionBy),
                        orderBy == null ? ListModule.Empty <OrderByClauseNode>() : ListModule.OfSeq(orderBy)))));
 }
Esempio n. 2
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            FileSystem fs     = new FileSystem();
            FormState  source = new FormState(fs);
            MenuModule menu   = new MenuModule(source);
            TreeModule tree   = new TreeModule(source);
            ListModule list   = new ListModule(source, menu);

            Application.Run(new MainForm(source, menu, tree, list));
        }
Esempio n. 3
0
 public static JoinClauseNode Join <TSource1, TSource2, TTarget>(
     ITableIdentifier <TSource1> source1,
     ITableIdentifier <TSource2> source2,
     ITableIdentifier <TTarget> target,
     JoinType type,
     ValueNode joinExpr)
 {
     return(new JoinClauseNode(
                ListModule.OfArray(new ITableIdentifier[] { source1, source2 }),
                target,
                type,
                joinExpr.ToOption()));
 }
Esempio n. 4
0
        public static NeuralNetwork fit(
            NeuralNetwork network,
            double learningRate,
            double[] inputValues,
            double[] expectedOutput)
        {
            FSharpList <double> ivs = ListModule.OfSeq(inputValues);
            FSharpList <double> eos = ListModule.OfSeq(expectedOutput);
            LazyList <LazyList <Neuron.Neuron> > _contents =
                NeuralNetworkModule.fit(network.contents, learningRate, ivs, eos);

            return(new NeuralNetwork(_contents));
        }
Esempio n. 5
0
        public static double[] errors(
            NeuralNetwork network,
            double learningRate,
            double[] inputValues,
            double[] expectedOutput)
        {
            FSharpList <double> ivs = ListModule.OfSeq(inputValues);
            FSharpList <double> eos = ListModule.OfSeq(expectedOutput);

            return(NeuralNetworkModule
                   .errors(network.contents, learningRate, ivs, eos)
                   .ToArray());
        }
Esempio n. 6
0
        public void Itself()
        {
            const bool expected             = true;
            List <Tuple <int, int> > coords = new List <Tuple <int, int> >
            {
                new Tuple <int, int>(6, 2)
            };
            FSharpList <Tuple <int, int> > input = ListModule.OfSeq(coords);

            bool result = isCorrectArrangement(input);

            Assert.AreEqual(expected, result);
        }
Esempio n. 7
0
        public static void PrintStickerFromMnf(string path)
        {
            FSharpOption <Tuple <FSharpOption <Bitmap>, string, FSharpList <Tuple <string, string> > > > fSharpOption  = EtiketParse(path);
            FSharpOption <Tuple <FSharpOption <Bitmap>, string, FSharpList <Tuple <string, string> > > > fSharpOption2 = fSharpOption;
            FSharpOption <Tuple <FSharpOption <Bitmap>, string, FSharpList <Tuple <string, string> > > > fSharpOption3 = fSharpOption2;

            if (fSharpOption3 != null)
            {
                FSharpOption <Tuple <FSharpOption <Bitmap>, string, FSharpList <Tuple <string, string> > > > fSharpOption4 = fSharpOption3;
                if (fSharpOption4.Value.Item1 != null)
                {
                    FSharpOption <Bitmap> item = fSharpOption4.Value.Item1;
                    FSharpList <Tuple <string, string> > lst2 = fSharpOption4.Value.Item3;
                    Bitmap bmp   = item.Value;
                    string barc2 = fSharpOption4.Value.Item2;
                    using (MemoryStream stream = new MemoryStream(File.ReadAllBytes(Path.Combine(libPath, "stickerImp.xaml"))))
                    {
                        object obg  = XamlReader.Load((Stream)stream);
                        Window win2 = (Window)obg;
                        //Window win2 = (Window)XamlReader.Load((Stream)stream);
                        Grid sticker2 = (Grid)win2.FindName("sticker");
                        System.Windows.Controls.Image barcod2 = (System.Windows.Controls.Image)win2.FindName("barcod");
                        System.Windows.Controls.Image imgWin  = (System.Windows.Controls.Image)win2.FindName("imgWin");
                        imgWin.Source = /*Bitmap.*/ get_Source(bmp);
                        ListModule.Iterate(new PrintStickerFromMnf_132_1(win2), lst2);
                        BarcodeDraw brc2 = BarcodeDrawFactory.GetSymbology(BarcodeSymbology.Code128);
                        barcod2.Source = /*Bitmap.*/ get_Source((Bitmap)brc2.Draw(barc2, 30));
                        PrintGrid(sticker2);
                        Unit unit = null;
                    }
                }
                else
                {
                    FSharpList <Tuple <string, string> > lst = fSharpOption4.Value.Item3;
                    string barc = fSharpOption4.Value.Item2;
                    using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(Path.Combine(libPath, "stickerBlk.xaml"))))
                    {
                        object obg = XamlReader.Load((Stream)ms);
                        Window win = (Window)obg;
                        //Window win = (Window)XamlReader.Load((Stream)ms);
                        Grid sticker = (Grid)win.FindName("sticker");
                        System.Windows.Controls.Image barcod = (System.Windows.Controls.Image)win.FindName("barcod");
                        ListModule.Iterate(new PrintStickerFromMnf_121(win), lst);
                        BarcodeDraw brc = BarcodeDrawFactory.GetSymbology(BarcodeSymbology.Code128);
                        barcod.Source = /*Bitmap.*/ get_Source((Bitmap)brc.Draw(barc, 30));
                        PrintGrid(sticker);
                        Unit unit2 = null;
                    }
                }
            }
        }
        private string PostRequest(string request,
                                   IHttpResponse httpResponse,
                                   ServerProperties serverProperties)
        {
            var game = ((TicTacToeGame)
                        serverProperties.ServiceSpecificObjectsWrapper);
            var data = WebUtility.UrlDecode(request.Remove(0,
                                                           request.LastIndexOf("\r\n\r\n",
                                                                               StringComparison.Ordinal) + 4));

            var move = data.Substring(0, data.IndexOf("&",
                                                      StringComparison.Ordinal))
                       .Replace("box=", "");

            if (move.StartsWith("-") &&
                move.EndsWith("-") && move.Length > 2)
            {
                move = move.Replace("-", "");
            }

            var ticTacToeBox =
                new TicTacToeBoxClass.TicTacToeBox(
                    ListModule.OfSeq(GetBoxValues(data)));

            var errorMesageCode = Game.isUserInputCorrect(ticTacToeBox,
                                                          move, game.Setting.playerGlyph, game.Setting.aIGlyph);

            if (errorMesageCode == Translate.Blank)
            {
                ticTacToeBox = (TicTacToeBoxClass.TicTacToeBox)
                               game.Play(ticTacToeBox,
                                         CleanInput.SanitizeHumanPickedPlace(move, 9));
            }

            httpResponse.SendHeaders(new List <string>
            {
                "HTTP/1.1 200 OK\r\n",
                "Cache-Control: no-cache\r\n",
                "Content-Type: text/html\r\n",
                "Content-Length: "
                + GetByteCount(GameFormPage(ticTacToeBox, game,
                                            errorMesageCode, serverProperties)) +
                "\r\n\r\n"
            });
            httpResponse
            .SendBody(GetByte(GameFormPage(ticTacToeBox, game,
                                           errorMesageCode, serverProperties)),
                      GetByteCount(GameFormPage(ticTacToeBox, game,
                                                errorMesageCode, serverProperties)));
            return("200 OK");
        }
 static void Main(string[] args)
 {
     Console.WriteLine("=====");
     foreach (var election in allElections)
     {
         List <Party> parties = Election.RunElection(ListModule.OfSeq(election), 120).ToList();
         foreach (Party party in parties)
         {
             Console.WriteLine(string.Format("{0}: {1}", party.PartyName, party.TotalSeats.ToString()));
         }
         Console.WriteLine("=====");
     }
     Console.ReadLine();
 }
Esempio n. 10
0
        public static Types.Block GetBlock(Types.Block parent, Double difficulty)
        {
            UInt32 pdiff = Convert.ToUInt32(difficulty);

            byte[] parentKey = parent == null ? new byte[] {} : Merkle.blockHeaderHasher.Invoke(parent.header);

            Types.BlockHeader newBlockHeader = new Types.BlockHeader(1, parentKey, 0, new byte[] { }, new byte[] { }, new byte[] { }, ListModule.OfSeq(new List <byte[]>()), 0, pdiff, null);
            var transactions = new List <Types.Transaction>();
            FSharpList <Types.Transaction> newBlockTransactions = ListModule.OfSeq(transactions);

            Types.Block newBlock = new Types.Block(newBlockHeader, newBlockTransactions);

            return(newBlock);
        }
Esempio n. 11
0
        public void AQuickSortOnARangeOfValues_FSharp()
        {
            var targetFSharp = new fsharpForFunAndProfitNotes.QuickSortFSharp();

            targetFSharp
            .DoQuickSortOn(ListModule.OfSeq(new List <int> {
                1, 7, 3, 15, 54, 12, 2, 5, 9
            }))
            .ToList()
            .Should()
            .BeEquivalentTo(new List <int> {
                1, 2, 3, 5, 7, 9, 12, 15, 54
            });
        }
Esempio n. 12
0
        public static void Main(string[] args)
        {
            string header    = "Advent of Code 2020";
            string separator = new string('=', header.Length);

            Console.WriteLine(header);
            Console.WriteLine(separator);
            Console.WriteLine();

            for (int i = 0; i < Solutions.Count; i++)
            {
                Type         solution = Solutions[i];
                PropertyInfo describe = solution.GetProperty("describe");
                string       name     = describe?.GetValue(null) as string;

                Console.WriteLine($"{(i + 1).ToString(CultureInfo.InvariantCulture).PadLeft(2, '0')}: {(!string.IsNullOrEmpty(name) ? name : "(no description)")}");
            }

            Console.WriteLine();
            Console.Write("Please select a puzzle or type 0 to exit: ");

            string selection = Console.ReadLine();

            if (!TryParseDay(selection, out int puzzle))
            {
                Console.WriteLine("Your selection is invalid");
                return;
            }

            Console.WriteLine();
            Console.WriteLine(separator);
            Console.WriteLine();

            string ident = puzzle.ToString().PadLeft(2, '0');
            string input = $"App_Data{Path.DirectorySeparatorChar}day{ident}.txt";

            Type       target  = Solutions[puzzle - 1];
            MethodInfo execute = target.GetMethod("execute");

            if (execute == null)
            {
                Console.WriteLine("Unable to find puzzle entrypoint");
                return;
            }

            object[] parameters = { ListModule.OfSeq(new[] { input }) };
            execute.Invoke(null, parameters);

            Console.WriteLine();
        }
Esempio n. 13
0
 public IntT IndexOf <TListSource>(TListSource source, IntT start, IntT count)
     where TListSource : IReadOnlyList <T>
 {
     if (null != source)
     {
         if (ListModule.CheckSegment <T, TListSource>(source, start, count))
         {
             return(IndexOfInternal(source, start, count));
         }
         // TODO
         throw new ArgumentException();
     }
     throw new ArgumentNullException("source");
 }
Esempio n. 14
0
        public static c.Chart FromPlots(IEnumerable <PlotInfo> plots, ChartLayout layout = ChartLayout.Chubby, Axis xAxis = null, Axis yAxis = null)
        {
            var chart = c.Chart.ofList(ListModule.OfSeq(plots));

            if (xAxis != null)
            {
                chart = Chart.setXAxis(xAxis, chart);
            }
            if (yAxis != null)
            {
                chart = Chart.setYAxis(yAxis, chart);
            }
            return(Chart.setLayout(layout, chart));
        }
    public static void MyGPULaunch <T1, T2, T3>(
        this ILGPUModule module,
        Action <T1, T2, T3> kernelD, LaunchParam lp,
        T1 arg1, T2 arg2, T3 arg3)
    {
        // get the kernel object by method name
        var kernel = module.GPUEntities.GetKernel(kernelD.Method.Name).Kernel;
        // create parameter list (which is FSharpList)
        var parameterArray = new object[] { arg1, arg2, arg3 };
        var parameterList  = ListModule.OfArray(parameterArray);

        // use untyped LaunchRaw to launch the kernel
        kernel.LaunchRaw(lp, parameterList);
    }
Esempio n. 16
0
        public void Uncorrect_Two_Diagonal()
        {
            const bool expected             = false;
            List <Tuple <int, int> > coords = new List <Tuple <int, int> >
            {
                new Tuple <int, int>(6, 2),
                new Tuple <int, int>(5, 1)
            };
            FSharpList <Tuple <int, int> > input = ListModule.OfSeq(coords);

            bool result = isCorrectArrangement(input);

            Assert.AreEqual(expected, result);
        }
        public async Task <FSharpOption <StoredPreferenceInfo> > GetUserPreferences()
        {
            using (var context = this.CreateContext()) {
                var user = await GetUser(context);

                var isDefaultModeUnset =
                    user.OtrMode == Model.OtrMode.NotSet && user.SaveMode == Model.SaveMode.NotSet && user.Expire == null;

                var isAnyArchivingModeUnset =
                    user.LocalPreference == Model.ArchivingMode.NotSet ||
                    user.ManualPreference == Model.ArchivingMode.NotSet ||
                    user.AutoPreference == Model.ArchivingMode.NotSet;

                var isAllUnset =
                    isDefaultModeUnset &&
                    user.ItemPreferences.Count == 0 && isAnyArchivingModeUnset && user.AutomaticArchiving == null;
                if (isAllUnset)
                {
                    return(FSharpOption <StoredPreferenceInfo> .None);
                }

                var archivingModePrefs =
                    !isAnyArchivingModeUnset
                                        ? FSharpOption <AllMethodSettings> .Some(
                        new AllMethodSettings (
                            ToFSharp(user.AutoPreference),
                            ToFSharp(user.LocalPreference),
                            ToFSharp(user.ManualPreference)))
                                        : FSharpOption <AllMethodSettings> .None;

                var result = new StoredPreferenceInfo(
                    FSharpHelper.ToFSharpS(user.AutomaticArchiving),
                    new OtrSaveMode(
                        FSharpHelper.ToFSharpS <Int64> (user.Expire),
                        ToFSharp(user.OtrMode),
                        ToFSharp(user.SaveMode)),
                    ListModule.OfSeq <Tuple <JabberId, OtrSaveMode> >
                        (user.ItemPreferences.Select(item =>
                                                     Tuple.Create(
                                                         JabberId.Parse(item.Jid),
                                                         new OtrSaveMode(
                                                             FSharpHelper.ToFSharpS <Int64> (item.Expire),
                                                             ToFSharp(item.OtrMode),
                                                             ToFSharp(item.SaveMode))))),
                    archivingModePrefs
                    );
                return(FSharpOption <StoredPreferenceInfo> .Some(result));
            }
        }
Esempio n. 18
0
        Tuple <IIndex <K>, VectorConstruction> IIndexBuilder.Merge <K>(FSharpList <Tuple <IIndex <K>, VectorConstruction> > constructions, VectorListTransform transform)
        {
            bool flag = ListModule.ForAll <Tuple <IIndex <K>, VectorConstruction> >((Func <M0, bool>) new LinearIndex.allOrdered <K>(), (FSharpList <M0>)constructions);
            Func <IComparer <K>, Tuple <Tuple <K[], FSharpList <Tuple <long, long>[]> >, FSharpOption <bool> > > Func1 = (Func <IComparer <K>, Tuple <Tuple <K[], FSharpList <Tuple <long, long>[]> >, FSharpOption <bool> > >) new LinearIndex.mergeOrdered <K>(constructions);
            Func <Unit, Tuple <Tuple <K[], FSharpList <Tuple <long, long>[]> >, FSharpOption <bool> > >          Func2 = (Func <Unit, Tuple <Tuple <K[], FSharpList <Tuple <long, long>[]> >, FSharpOption <bool> > >) new LinearIndex.mergeUnordered <K>(constructions);
            Tuple <Tuple <K[], FSharpList <Tuple <long, long>[]> >, FSharpOption <bool> > tuple1;

            if (flag)
            {
                Comparer <K> comparer = ((Tuple <IIndex <K>, VectorConstruction>)ListModule.Head <Tuple <IIndex <K>, VectorConstruction> >((FSharpList <M0>)constructions)).Item1.Comparer;
                Tuple <Tuple <K[], FSharpList <Tuple <long, long>[]> >, FSharpOption <bool> > tuple2;
                try
                {
                    tuple2 = Func1.Invoke((IComparer <K>)comparer);
                }
                catch (object ex)
                {
                    if ((Exception)ex is ComparisonFailedException)
                    {
                        tuple2 = Func2.Invoke((Unit)null);
                    }
                    else
                    {
                        throw;
                    }
                }
                tuple1 = tuple2;
            }
            else
            {
                tuple1 = Func2.Invoke((Unit)null);
            }
            Tuple <Tuple <K[], FSharpList <Tuple <long, long>[]> >, FSharpOption <bool> > tuple3 = tuple1;
            FSharpOption <bool> fsharpOption = tuple3.Item2;
            Tuple <K[], FSharpList <Tuple <long, long>[]> > tuple4 = tuple3.Item1;
            IEnumerable <VectorConstruction> fsharpList1           = (IEnumerable <VectorConstruction>)ListModule.Map <Tuple <IIndex <K>, VectorConstruction>, VectorConstruction>((Func <M0, M1>) new LinearIndex.vectors <K>(), (FSharpList <M0>)constructions);
            LinearIndexBuilder linearIndexBuilder = this;
            Tuple <K[], FSharpList <Tuple <long, long>[]> > tuple5 = tuple4;
            IEnumerable <VectorConstruction> vectors = fsharpList1;
            FSharpOption <bool> ordered = fsharpOption;

            K[] keys = tuple5.Item1;
            FSharpList <Tuple <long, long>[]> relocations = tuple5.Item2;
            Tuple <IIndex <K>, IEnumerable <VectorConstruction> > tuple6 = linearIndexBuilder.makeSeriesConstructions <K>(keys, relocations, vectors, ordered);
            IEnumerable <VectorConstruction> fsharpList2 = tuple6.Item2;
            IIndex <K> newIndex = tuple6.Item1;

            return(new Tuple <IIndex <K>, VectorConstruction>(newIndex, VectorConstruction.NewCombine((Lazy <long>)LazyExtensions.Create <long>((Func <Unit, M0>) new LinearIndex.DeedleIndicesIIndexBuilderMerge <K>(newIndex)), fsharpList2, transform)));
        }
Esempio n. 19
0
        public void DeepCopyTests_FSharp_Collections()
        {
            // F# list
            {
                var original = FSharpList <int> .Empty;
                var copy     = (FSharpList <int>) this.fixture.SerializationManager.DeepCopy(original);
                Assert.Equal(original, copy);
            }
            {
                var original = ListModule.OfSeq(new List <int> {
                    0, 1, 2
                });
                var copy = (FSharpList <int>) this.fixture.SerializationManager.DeepCopy(original);
                Assert.Equal(original, copy);
            }

            // F# set
            {
                var original = new FSharpSet <int>(new List <int>());
                var copy     = (FSharpSet <int>) this.fixture.SerializationManager.DeepCopy(original);
                Assert.Equal(original, copy);
            }
            {
                var elements = new List <int>()
                {
                    0, 1, 2
                };
                var original = SetModule.OfSeq(elements);
                var copy     = (FSharpSet <int>) this.fixture.SerializationManager.DeepCopy(original);
                Assert.Equal(original, copy);
            }

            // F# map
            {
                var original = new FSharpMap <int, string>(new List <Tuple <int, string> >());
                var copy     = (FSharpMap <int, string>) this.fixture.SerializationManager.DeepCopy(original);
                Assert.Equal(original, copy);
            }
            {
                var elements = new List <Tuple <int, string> >()
                {
                    new Tuple <int, string>(0, "zero"),
                    new Tuple <int, string>(1, "one")
                };
                var original = MapModule.OfSeq(elements);
                var copy     = (FSharpMap <int, string>) this.fixture.SerializationManager.DeepCopy(original);
                Assert.Equal(original, copy);
            }
        }
 public IWorkflow Complete()
 {
     return(new Workflow(
                Domain,
                Name,
                Description,
                Version,
                TaskList.AsOption(string.IsNullOrWhiteSpace),
                ListModule.OfSeq(stages).AsOption(),
                TaskStartToCloseTimeout.AsOption(),
                ExecutionStartToCloseTimeout.AsOption(),
                GetChildPolicy(ChildPolicy).AsOption(),
                Identity.AsOption(string.IsNullOrWhiteSpace),
                MaxAttempts.AsOption()));
 }
Esempio n. 21
0
    public static object CreateOrder(bool isBomb, bool isBombard, bool isConquer, bool isDirectAttack, bool isDockAt, bool isLandAt, HexTiling.HexCoords coords, HexTiling.HexCoords[] path)
    {
        PexAssume.IsNotNull(coords);
        PexAssume.IsNotNull(path);
        PexAssume.AreElementsNotNull(path);

        return
            (isBomb ? Orders.Order.NewBomb(coords, ListModule.OfArray(path)) :
             isBombard?Orders.Order.NewBombard(coords) :
                 isConquer?Orders.Order.NewConquer(ListModule.OfArray(path)) :
                     isDirectAttack?Orders.Order.NewDirectAttack(coords, ListModule.OfArray(path)) :
                         isDockAt?Orders.Order.NewDockAt(ListModule.OfArray(path)) :
                             isLandAt?Orders.Order.NewLandAt(ListModule.OfArray(path)) :
                                 Orders.Order.NewUnload(ListModule.OfArray(path), coords));
    }
Esempio n. 22
0
        public Deedle.Ranges.Ranges <T> MergeWith(IEnumerable <Deedle.Ranges.Ranges <T> > ranges)
        {
            IEnumerable <Deedle.Ranges.Ranges <T> > list = (IEnumerable <Deedle.Ranges.Ranges <T> >)SeqModule.ToList <Deedle.Ranges.Ranges <T> >((IEnumerable <M0>) new Ranges.MergeWith <T>(this, ranges, 0, (Deedle.Ranges.Ranges <T>)null));

            if (SeqModule.IsEmpty <Deedle.Ranges.Ranges <T> >((IEnumerable <M0>)list))
            {
                throw new ArgumentException("Range cannot be empty", nameof(ranges));
            }
            IRangeKeyOperations <T>    operations = ((Deedle.Ranges.Ranges <T>)SeqModule.Head <Deedle.Ranges.Ranges <T> >((IEnumerable <M0>)list)).Operations;
            FSharpList <Tuple <T, T> > fsharpList = (FSharpList <Tuple <T, T> >)ListModule.SortWith <Tuple <T, T> >((FSharpFunc <M0, FSharpFunc <M0, int> >) new Ranges.MergeWith <T>(operations), SeqModule.ToList <Tuple <T, T> >((IEnumerable <M0>) new Ranges.MergeWith <T>(list, (Deedle.Ranges.Ranges <T>)null, (IEnumerator <Deedle.Ranges.Ranges <T> >)null, (Tuple <T, T>)null, (IEnumerator <Tuple <T, T> >)null, 0, (Tuple <T, T>)null)));
            FSharpFunc <Tuple <T, T>, FSharpFunc <FSharpList <Tuple <T, T> >, IEnumerable <Tuple <T, T> > > > fsharpFunc = (FSharpFunc <Tuple <T, T>, FSharpFunc <FSharpList <Tuple <T, T> >, IEnumerable <Tuple <T, T> > > >) new Ranges.MergeWith <T>(operations);
            IRangeKeyOperations <T> ops = operations;

            return(new Deedle.Ranges.Ranges <T>((IEnumerable <Tuple <T, T> >)FSharpFunc <Tuple <T, T>, FSharpList <Tuple <T, T> > > .InvokeFast <IEnumerable <Tuple <T, T> > >((FSharpFunc <Tuple <T, T>, FSharpFunc <FSharpList <Tuple <T, T> >, M0> >)fsharpFunc, (Tuple <T, T>)ListModule.Head <Tuple <T, T> >((FSharpList <M0>)fsharpList), (FSharpList <Tuple <T, T> >)ListModule.Tail <Tuple <T, T> >((FSharpList <M0>)fsharpList)), ops));
        }
Esempio n. 23
0
        public static NeuralNetwork customizedInit(
            int[] layers,
            Func <int, ActivationFunction> activationF,
            Func <int, Double> weightInitF)
        {
            FSharpList <int> ls = ListModule.OfSeq(layers);
            FSharpFunc <int, Activation.Function> actF =
                (Converter <int, Activation.Function>)(x => activationF(x).contents);
            FSharpFunc <int, Double> weightF =
                (Converter <int, Double>)(x => weightInitF(x));
            LazyList <LazyList <Neuron.Neuron> > _contents =
                NeuralNetworkModule.customizedInit(ls, actF, weightF);

            return(new NeuralNetwork(_contents));
        }
Esempio n. 24
0
        public void ItCanVisitAMultipleColumnSelector()
        {
            Expression <Func <Person, object> > func = (Person p) => new { p.Age, p.Name };
            var tableRef = Types.TableReferenceFromType <Person>();
            var ev       = ExpressionVisitor.Visit(
                ExpressionVisitor.VisitableExpression.NewLinqExpression(func),
                new[] { tableRef }.ToContext()
                );

            var expected =
                ValueNode.NewValueList(
                    ListModule.OfArray(new[] { S.Col <Person>("Age"), S.Col <Person>("Name") })).ToOption();

            Assert.That(ev, Is.EqualTo(expected));
        }
Esempio n. 25
0
        private static CNFify.Term NotAllEqual(List <CNFify.Term> input)
        {
            //we now have a list of all squares that should not be equal, make a
            //not - and combi of them:

            // voor in de slides: gekut met types kan wel wat beter Microsoft
            //eerste poging ipv ListModule.OfSeq was: (Microsoft.FSharp.Collections.FSharpList<CNFify.Term>)AllAnds;

            CNFify.Term NotAllSame =
                CNFify.Term.NewNot(
                    CNFify.createAndClauseFromList(ListModule.OfSeq(input))
                    );

            return(NotAllSame);
        }
Esempio n. 26
0
        static void Main(string[] args)
        {
            var pList = InitList();

            var helloFsharp = FSharp.Say.hello("C#");

            Console.WriteLine(helloFsharp);

            var fsharpAvg = FSharp.Say.avgHeight(ListModule.OfSeq(pList));

            Console.WriteLine($"F# Avg. Height: {fsharpAvg}");
            Console.WriteLine($"C# Avg. Height: {pList.Average(x => x.Height)}");

            Console.ReadKey();
        }
Esempio n. 27
0
        public static async Task RunAsync(
            IReadOnlyList <string> organizations,
            string githubLogin,
            string githubPassword,
            bool includePrivateRepositories,
            bool includeUngroupedRepositories)
        {
            var committerGroups = organizations.SelectMany(CrappyCommitterGroupService.Get).ToList();

            var client = GitHubClientFactory.Create(typeof(Program).Namespace, githubLogin, githubPassword);

            var repositoryService     = new RepositoryService(client);
            var ungroupedRepositories = (await Task.WhenAll(committerGroups
                                                            .SelectMany(@group => @group.RepositoryList.Select(id => id.Owner))
                                                            .Concat(organizations)
                                                            .Distinct()
                                                            .Select(owner => repositoryService.Get(owner))))
                                        .SelectMany(_ => _)
                                        .Where(repository => includePrivateRepositories || !repository.IsPrivate)
                                        .Where(repository => !committerGroups.Any(group => group.RepositoryList.Contains(repository.Id)))
                                        .ToList();

            foreach (var repository in ungroupedRepositories.OrderBy(_ => _))
            {
                log.WarnFormat("{@Repository} is not grouped.", repository);
            }

            if (includeUngroupedRepositories)
            {
                committerGroups = committerGroups
                                  .Concat(ungroupedRepositories
                                          .GroupBy(repository => repository.Id.Owner)
                                          .Select(group => new CommitterGroup(
                                                      $"{group.Key}-ungrouped", ListModule.OfSeq(group.Select(repository => repository.Id)))))
                                  .ToList();
            }

            var contributions = (await Task.WhenAll(
                                     ContributionService.Get(committerGroups, new CommitService(client)),
                                     ContributionService.Get(committerGroups, new IssueService(client)),
                                     ContributionService.Get(committerGroups, new PullRequestService(client))))
                                .SelectMany(_ => _)
                                .GroupBy(contribution => new { contribution.Group, contribution.Login })
                                .Select(group => new Contribution(group.Key.Group, group.Key.Login, group.Sum(contribution => contribution.Score)))
                                .ToList();

            TsvContributionsRepository.Save(contributions);
        }
        public void Ai_Moves()
        {
            var correctOutPut = new List <string>
            {
                "@",
                "@",
                "x",
                "x",
                "@",
                "x",
                "@",
                "x",
                "@"
            };

            var ticTacToeBox = new List <string>
            {
                "-1-",
                "@",
                "x",
                "x",
                "@",
                "x",
                "@",
                "x",
                "@"
            };

            var user = new MockUser().StubMove(
                new TicTacToeBoxClass.TicTacToeBox(
                    ListModule.OfSeq(ticTacToeBox)));
            var aI   = new Ai();
            var game = new TicTacToeGame(
                user,
                aI,
                new GameSettings.gameSetting(3, "x", "@"
                                             , (int)PlayerValues.playerVals.Human
                                             , false, false, false)
                );

            var outputBox = game.Play(new TicTacToeBoxClass.TicTacToeBox(
                                          ListModule.OfSeq(ticTacToeBox)), 1);

            for (var i = 0; i < outputBox.cellCount(); i++)
            {
                Assert.Equal(correctOutPut[i], outputBox.getGlyphAtLocation(i));
            }
        }
Esempio n. 29
0
        static JSON()
        {
            var number = Terminal.Create("Number", (position, data) => ToDecimal(data),
                                         Join(
                                             Literal('-').Optional(),
                                             Literal('0').Or(OneOf("123456789").And(OneOf(PredefinedSets.Number).ZeroOrMore())),
                                             Literal('.').And(OneOf(PredefinedSets.Number).AtLeast(1)).Optional(),
                                             Join(
                                                 OneOf("eE"),
                                                 OneOf("+-").Optional(),
                                                 OneOf(PredefinedSets.Number).AtLeast(1)).Optional()));
            var jsonString = Terminals.StringEx("/bfnrt", true, false, '"', "String");
            var jsonObject = Nonterminal.Create <Json>("Object");
            var jsonArray  = Nonterminal.Create <Json>("Array");
            var value      = Nonterminal.Create("Value",
                                                jsonString.Finish(Json.NewString),
                                                number.AsIs(),
                                                jsonObject.AsIs(),
                                                jsonArray.AsIs(),
                                                "true".FinishConstant(Json.NewBool(true)),
                                                "false".FinishConstant(Json.NewBool(false)),
                                                "null".FinishConstant(Json.NewNull(null)));
            var arrayReversed = Nonterminal.Create <FSharpList <Json> >("Array Reversed");

            arrayReversed.SetProductions(
                arrayReversed.Extended().Append(",").Extend(value).Finish((xs, x) => FSharpList <Json> .Cons(x, xs)),
                value.Finish(ListModule.Singleton));
            var arrayOptional = Nonterminal.Create("Array Optional",
                                                   arrayReversed.Finish(ListModule.Reverse),
                                                   ProductionBuilder.Empty.FinishConstant(FSharpList <Json> .Empty));

            jsonArray.SetProductions("[".Appended().Extend(arrayOptional).Append("]").Finish(Json.NewArray));

            var objectElement = Nonterminal.Create <FSharpList <Tuple <string, Json> > >("Object Element");

            objectElement.SetProductions(
                objectElement.Extended().Append(",").Extend(jsonString).Append(":").Extend(value)
                .Finish((xs, k, v) => FSharpList <Tuple <string, Json> > .Cons(Tuple.Create(k, v), xs)),
                jsonString.Extended().Append(":").Extend(value).Finish((k, v) => ListModule.Singleton(Tuple.Create(k, v))));
            var objectOptional = Nonterminal.Create("Object Optional",
                                                    objectElement.Finish(x => Json.NewObject(MapModule.OfList(x))),
                                                    ProductionBuilder.Empty.FinishConstant(Json.NewObject(MapModule.Empty <string, Json>())));

            jsonObject.SetProductions("{".Appended().Extend(objectOptional).Append("}").AsIs());

            Designtime = value.CaseSensitive().UseDynamicCodeGen();
            Runtime    = Designtime.Build();
        }
Esempio n. 30
0
        static void Main(string[] args)
        {
            var original = new List <int>();
            var random   = new Random();

            for (int i = 0; i < 20; i++)
            {
                original.Add(random.Next() % 25);
            }
            PrintEnumerable <int>(original);

            var toSort = ListModule.OfSeq(original);
            var sorted = QSort.sort <int>(toSort);

            PrintEnumerable <int>(sorted);
        }
        private void UpdateModule(ListModule module, FormCollection collection)
        {
            var listOfKeys = (from y in collection.AllKeys
                              where y.StartsWith("frm_list_key_")
                              select y);

            foreach (string formKey in listOfKeys)
            {
                string key = formKey.Replace("frm_list_key_", String.Empty).UrlDecodeSeo();
                string valueFormKey = formKey.Replace("frm_list_key", "frm_list_value");
                string value = collection[valueFormKey];
                bool isExistingField = !key.EndsWith("newField");

                if (!isExistingField)
                {
                    key = collection[formKey];
                }

                if (!String.IsNullOrEmpty(key) && !module.ListItems.ContainsKey(key))
                {
                    module.ListItems.Add(key, collection[valueFormKey]);
                }
                else if (isExistingField || !String.IsNullOrEmpty(value))
                {

                    if (value == "{delete}")
                    {
                        module.ListItems.Remove(key);
                    }
                    else
                    {
                        module.ListItems[key] = value;
                    }
                }
            }
        }