public void ArraysShouldBeRoundtrippable()
        {
            new TestScheduler().With(sched =>
            {
                string path;
                var input = new[] {new UserObject {Bio = "A totally cool cat!", Name = "octocat", Blog = "http://www.github.com"}, new UserObject {Bio = "zzz", Name = "sleepy", Blog = "http://example.com"}};
                UserObject[] result;

                using (Utility.WithEmptyDirectory(out path))
                {
                    using (var fixture = CreateBlobCache(path))
                    {
                        fixture.InsertObject("key", input);
                    }
                    sched.Start();
                    using (var fixture = CreateBlobCache(path))
                    {
                        var action = fixture.GetObjectAsync<UserObject[]>("key");
                        sched.Start();
                        result = action.First();
                    }
                }

                Assert.Equal(input.First().Blog, result.First().Blog);
                Assert.Equal(input.First().Bio, result.First().Bio);
                Assert.Equal(input.First().Name, result.First().Name);
                Assert.Equal(input.Last().Blog, result.Last().Blog);
                Assert.Equal(input.Last().Bio, result.Last().Bio);
                Assert.Equal(input.Last().Name, result.Last().Name);
            });
        }
        public void ArraysShouldBeRoundtrippableUsingObjectFactory()
        {
            new TestScheduler().With(sched =>
            {
                string path;
                var input = new[] {new UserModel(new UserObject()) {Age = 123, Name = "Old"}, new UserModel(new UserObject()) {Age = 123, Name = "Old"}};
                UserModel[] result;

                using (Utility.WithEmptyDirectory(out path))
                {
                    using (var fixture = new TPersistentBlobCache(path))
                    {
                        fixture.InsertObject("key", input);
                    }
                    sched.Start();
                    using (var fixture = new TPersistentBlobCache(path))
                    {
                        var action = fixture.GetObjectAsync<UserModel[]>("key");
                        sched.Start();
                        result = action.First();
                    }
                }

                Assert.Equal(input.First().Age, result.First().Age);
                Assert.Equal(input.First().Name, result.First().Name);
                Assert.Equal(input.Last().Age, result.Last().Age);
                Assert.Equal(input.Last().Name, result.Last().Name);
            });
        }
示例#3
0
    public static void Main () {
        var emptyInts = new int[0];
        var ints = new[] { 1, 2, 3, 4 };

        Console.WriteLine(emptyInts.FirstOrDefault());
        Console.WriteLine(ints.FirstOrDefault());

        Console.WriteLine(ints.First());

        Console.WriteLine(emptyInts.FirstOrDefault((i) => i > 4));
        Console.WriteLine(ints.FirstOrDefault((i) => i > 4));

        Console.WriteLine(ints.First((i) => i > 2));
    }
示例#4
0
        public void should_get_unmatched_nodes(string name, StringComparison comparison, int count)
        {
            var results = new[] { new Node("oh"), new Node("hai") }
                .GetUnmatchedNodes(new[] { new Node(name), new Node("crap") },
                                    comparison);

            results.ShouldTotal(count);

            if (count == 1) results.First().Name.ShouldEqual("hai");
            else
            {
                results.First().Name.ShouldEqual("oh");
                results.Skip(1).First().Name.ShouldEqual("hai");
            }
        }
		public override void ExecuteWithResourceItems(System.Collections.Generic.IEnumerable<ResourceEditor.ViewModels.ResourceItem> resourceItems)
		{
			var firstSelectedItem = resourceItems.First();
			if (firstSelectedItem != null) {
				Clipboard.SetText(firstSelectedItem.Name);
			}
		}
示例#6
0
        public void Doit()
        {
            var c = new Customer
                        {
                            CustomerId = 3,
                            FirstName = "fn",
                            SecondName = "sn",
                            CustomerCountries =
                                new[] { new CustomerCountry { CountryId = 1 }, new CustomerCountry { CountryId = 2 } }
                        };

            var countries = new[]
                                {
                                    new Country {CountryId = 1, Name = "Moldova"},
                                    new Country {CountryId = 2, Name = "Japan"}
                                };

            var d = new CustomerDto();
            d.InjectFrom(c);
            Assert.AreEqual(c.CustomerId, d.CustomerId);
            Assert.AreEqual(c.FirstName, d.FirstName);
            Assert.AreEqual(c.SecondName, d.SecondName);

            d.InjectFrom(new My(countries), c);

            Assert.AreEqual(c.CustomerCountries.Count(), d.Countries.Count());
            Assert.AreEqual(countries.First().Name, d.Countries.First().Name);
        }
示例#7
0
		public override object CreateMultiResolutionImage (System.Collections.Generic.IEnumerable<object> images)
		{
			var refImg = (WpfImage)images.First ();
			var f = refImg.Frames[0];
			var frames = images.Cast<WpfImage> ().Select (img => new WpfImage.ImageFrame (img.Frames[0].ImageSource, f.Width, f.Height));
			return new WpfImage (frames);
		}
示例#8
0
        public void Execute(string workingDirectory)
        {
            var possibleSqlCmdExePaths = new[]
            {
                Environment.ExpandEnvironmentVariables(@"%ProgramFiles%\Microsoft SQL Server\110\Tools\Binn\SQLCMD.EXE"),
                Environment.ExpandEnvironmentVariables(@"%ProgramW6432%\Microsoft SQL Server\110\Tools\Binn\SQLCMD.EXE"),
                Environment.ExpandEnvironmentVariables(@"%ProgramFiles%\Microsoft SQL Server\120\Tools\Binn\SQLCMD.EXE"),
                Environment.ExpandEnvironmentVariables(@"%ProgramW6432%\Microsoft SQL Server\120\Tools\Binn\SQLCMD.EXE"),
            };

            var sqlCmdExePath = possibleSqlCmdExePaths.First(File.Exists);
            var argumentStringBuilder = new StringBuilder();
            foreach (var option in _options)
            {
                argumentStringBuilder.Append(string.Format("{0} {1} ", option.Key, option.Value));
            }

            var start = new ProcessStartInfo()
            {
                FileName = sqlCmdExePath,
                WorkingDirectory = workingDirectory,
                Arguments = argumentStringBuilder.ToString(),
                UseShellExecute = false
            };

            Process.Start(start).WaitForExit();
        }
        public void ItShouldParsePathToProcessFromArgumentsArray()
        {
            var args = new[] {"path/to/app.exe"};
            var spec = GetSpecWithArgs(args);

            Assert.That(spec.PathToProcess, Is.EqualTo(args.First()));
        }
        public async Task GetMemberUploadDataHandler_WithSeveralErrors_MappedCorrectly()
        {
            var memberUploadsWithSeveralErrors = new[]
            {
                new MemberUpload(
                    pcsId,
                    "FAKE DATA",
                    new List<MemberUploadError>
                        {
                            new MemberUploadError(ErrorLevel.Warning, UploadErrorType.Schema, "FAKE WARNING"),
                            new MemberUploadError(ErrorLevel.Error, UploadErrorType.Business, "FAKE ERROR"),
                            new MemberUploadError(ErrorLevel.Error, UploadErrorType.Schema, "FAKE ERROR"),
                            new MemberUploadError(ErrorLevel.Fatal, UploadErrorType.Business, "FAKE FATAL"),
                            new MemberUploadError(ErrorLevel.Fatal, UploadErrorType.Schema, "FAKE FATAL"),
                            new MemberUploadError(ErrorLevel.Fatal, UploadErrorType.Business, "FAKE FATAL")
                        },
                    0,
                    2016,
                    A.Dummy<Scheme>(),
                    "File name")
            };

            var handler = GetPreparedHandler(memberUploadsWithSeveralErrors);

            var memberUploadErrorDataList =
                await handler.HandleAsync(new GetMemberUploadData(pcsId, memberUploadsWithSeveralErrors.First().Id));

            Assert.True(memberUploadErrorDataList.Count(me => me.ErrorLevel == Core.Shared.ErrorLevel.Warning) == 1);
            Assert.True(memberUploadErrorDataList.Count(me => me.ErrorLevel == Core.Shared.ErrorLevel.Error) == 2);
            Assert.True(memberUploadErrorDataList.Count(me => me.ErrorLevel == Core.Shared.ErrorLevel.Fatal) == 3);
        }
示例#11
0
        public void OldRequestIsThrownAwayIfNewOneArrives()
        {
            var networkStatus = Substitute.For<INetworkStatus>();
            networkStatus.IsAvailable.Returns(Observable.Return(true));

            using (var library = Helpers.CreateLibrary())
            {
                new TestScheduler().With(scheduler =>
                {
                    var songs = new[] { new YoutubeSong("http://blabla.com", TimeSpan.Zero) };

                    // Define that the old request takes longer than the new request
                    var firstReturn = Observable.Timer(TimeSpan.FromSeconds(2000), scheduler).Select(x => (IReadOnlyList<YoutubeSong>)new List<YoutubeSong>()).ToTask();
                    var secondReturn = Task.FromResult((IReadOnlyList<YoutubeSong>)new List<YoutubeSong>(songs));

                    var songFinder = Substitute.For<IYoutubeSongFinder>();
                    songFinder.GetSongsAsync(Arg.Any<string>()).Returns(firstReturn, secondReturn);

                    Guid token = library.LocalAccessControl.RegisterLocalAccessToken();
                    var vm = new YoutubeViewModel(library, new ViewSettings(), new CoreSettings(), token, networkStatus, songFinder);

                    vm.SearchText = "Request1";

                    scheduler.AdvanceByMs(501);

                    vm.SearchText = "Request2";

                    scheduler.AdvanceByMs(501);

                    scheduler.AdvanceByMs(2000);

                    Assert.Equal(songs.First().OriginalPath, vm.SelectableSongs.First().Path);
                });
            }
        }
示例#12
0
        public void Start()
        {
            var sp = Stopwatch.StartNew();
            var reader = Task.Factory.StartNew(ReadFile);
            var parser = Task.Factory.StartNew(ParseEntries);
            var processer = Task.Factory.StartNew(ProcessDisks);

            while (true)
            {
                var tasks = new[] { reader, parser, processer, Task.Delay(1000) };
                var array = tasks
                    .Where(x => x.IsCompleted == false)
                    .ToArray();
                if (tasks.Any(x => x.IsFaulted))
                {
                    tasks.First(x => x.IsFaulted).Wait();
                }
                if (array.Length <= 1)
                    break;
                Task.WaitAny(array);
                Console.Write("\r{0,10:#,#} sec reads: {1,10:#,#} parsed: {2,10:#,#} written: {3,10:#,#}", sp.Elapsed.TotalSeconds, reads,
                    parsed, writtern);
            }
            Console.WriteLine();
            Console.WriteLine("Total");
            Console.WriteLine("{0,10:#,#} reads: {1:10:#,#} parsed: {2:10:#,#} written: {3:10:#,#}", sp.ElapsedMilliseconds, reads,
                    parsed, writtern);
        }
示例#13
0
        public virtual IEnumerable<INodeFactory> ResolvePath(IContext context, string path)
        {
            Regex re = new Regex(@"^[-_a-z0-9:]+:/?");
            path = path.ToLowerInvariant().Replace('\\', '/');
            path = re.Replace(path, "");

            var factory = Root;

            var nodeMonikers = path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            IEnumerable<INodeFactory> factories = new[] {factory};

            foreach (var nodeMoniker in nodeMonikers )
            {
                factories = factory.Resolve(context, nodeMoniker);
                if (null == factories || !factories.Any())
                {
                    return null;
                }

                factory = factories.First();
            }

            return factories;
        }
示例#14
0
        public virtual IEnumerable<IPathNode> ResolvePath(IProviderContext providerContext, string path)
        {
            if (string.IsNullOrEmpty(path))
                throw new ArgumentNullException(nameof(path));

            Regex re = new Regex(@"^[-_a-z0-9:]+:/?");
            path = path.ToLowerInvariant().Replace('\\', '/');
            path = re.Replace(path, "");

            var factory = Root;

            var nodeMonikers = path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            IEnumerable<IPathNode> factories = new[] { factory };

            foreach (var nodeMoniker in nodeMonikers)
            {
                factories = factory.Resolve(providerContext, nodeMoniker);
                if (null == factories || !factories.Any())
                {
                    return null;
                }

                factory = factories.First();
            }

            return factories;
        }
		public static void PathEquals(this Uri u, string pathAndQueryString)
		{
			var paths = (pathAndQueryString ?? "").Split(new[] { '?' }, 2);

			string path = paths.First(), query = string.Empty;
			if (paths.Length > 1)
				query = paths.Last();

			var expectedUri = new UriBuilder("http", "localhost", u.Port, path, "?" + query).Uri;

			u.AbsolutePath.Should().Be(expectedUri.AbsolutePath);
			u = new UriBuilder(u.Scheme, u.Host, u.Port, u.AbsolutePath, u.Query.Replace("pretty=true&", "").Replace("pretty=true", "")).Uri;

			var queries = new[] { u.Query, expectedUri.Query };
			if (queries.All(string.IsNullOrWhiteSpace)) return;
			if (queries.Any(string.IsNullOrWhiteSpace))
			{
				queries.Last().Should().Be(queries.First());
				return;
			}

			var clientKeyValues = u.Query.Substring(1).Split('&')
				.Select(v => v.Split('='))
				.Where(k => !string.IsNullOrWhiteSpace(k[0]))
				.ToDictionary(k => k[0], v => v.Last());
			var expectedKeyValues = expectedUri.Query.Substring(1).Split('&')
				.Select(v => v.Split('='))
				.Where(k => !string.IsNullOrWhiteSpace(k[0]))
				.ToDictionary(k => k[0], v => v.Last());

			clientKeyValues.Count.Should().Be(expectedKeyValues.Count);
			clientKeyValues.Should().ContainKeys(expectedKeyValues.Keys.ToArray());
			clientKeyValues.Should().Equal(expectedKeyValues);
		}
示例#16
0
        public void DontBreakPresentation()
        {
            //class and collection initializers
            var magnus = new Person {Name = "Magnus Lidbom"};
            IEnumerable<string> names = new[] {"Calle", "Oscar"};

            //extension methods
            var first = names.First();

            //inf
            var alsoNames = names;

            //Anonymous types
            var address = new {Street = "AStreet", Zip = "111111"};

            //lambda
            var upperCaseNames = names.Select(name => name.ToUpper());

            //expr
            Expression<Func<string, bool>> isUpperCased = test => test == test.ToUpper();

            //comprehension syntax
            var lowerCaseNames = from name in names
                                 select name.ToLower();
        }
        private void PrepareView()
        {
            _view.OldMethodName = _model.SourceMember.IdentifierName;
            _view.MethodName = _model.SourceMember.IdentifierName + "_1";
            _view.Inputs = _model.Inputs;
            _view.Outputs = _model.Outputs;
            _view.Locals =
                _model.Locals.Select(
                    variable =>
                        new ExtractedParameter(variable.AsTypeName, ExtractedParameter.PassedBy.ByVal, variable.IdentifierName))
                    .ToList();

            var returnValues = new[] {new ExtractedParameter(string.Empty, ExtractedParameter.PassedBy.ByVal)}
                .Union(_view.Outputs)
                .Union(_view.Inputs)
                .ToList();

            _view.ReturnValues = returnValues;
            _view.ReturnValue = (_model.Outputs.Any() && !_model.Outputs.Skip(1).Any())
                ? _model.Outputs.Single()
                : returnValues.First();

            _view.RefreshPreview += _view_RefreshPreview;
            _view.OnRefreshPreview();
        }
示例#18
0
    public static void DataBind_ByEventType_Count(
        System.Data.DataTable dt, 
        System.Collections.Generic.List<string> event_ids,
        System.Collections.Generic.Dictionary<string, string> Data_CrimeType,
        System.Web.UI.DataVisualization.Charting.Chart Chart1)
    {
        List<double> yValues = new List<double>();
        List<String> xValues = new List<string>();
        
        foreach (string crimetype_id in event_ids)
        {
            string event_type_name = Data_CrimeType.First((i) => { return i.Value == crimetype_id; }).Key;

            int count = 0;
            foreach (DataRow r in dt.Rows)
            {
                if (Convert.ToString(r["EVENT_TYPE_NAME"]) == event_type_name)
                { count++; }
            }

            if (count > 0)
            {
                xValues.Add(event_type_name + "[" + count + "]");
                yValues.Add(count);
            }
        }

        Chart1.Series["Default"].Points.DataBindXY(xValues, yValues);
        Chart1.Series["Default"].ChartType = SeriesChartType.Pie;
        Chart1.Series["Default"]["PieLabelStyle"] = "Enabled";
        Chart1.Legends[0].Enabled = true;
    }
示例#19
0
        static int CalculateRibbon(Package package)
        {
            IEnumerable<int> smallest = new[] { package.Length, package.Width, package.Height }.OrderBy(x => x).Take(2);

            int ribbon = (smallest.First() * 2) + (smallest.Last() * 2) + (package.Length * package.Width * package.Height);

            return ribbon;
        }
示例#20
0
 public void DataChunk_WithTwoItems_SetsFirstItem()
 {
     //Arrange
     var input = new[] { "Johnson", "Controls" };
     //Act;
     var actual = new DataChunk<string>(input, isEnd: true);
     //Assert
     Assert.AreEqual(input.First(), actual.FirstElement, "Failed to set first item of enumeration.");
 }
        public async Task GetMemberUploadByIdHandler_MemberUploadNotOwnedByOrganisation_ThrowsArgumentException()
        {
            var memberUploads = new[]
            {
                new MemberUpload(pcsId, "Test data", new List<MemberUploadError>(), 0, 2016, A.Dummy<Scheme>(), "File name")
            };

            var otherPcsId = Guid.NewGuid();

            var handler = GetPreparedHandler(memberUploads);
            var message = new GetMemberUploadById(otherPcsId, memberUploads.First().Id);

            var exception = await Assert.ThrowsAsync<ArgumentException>(async () => await handler.HandleAsync(message));

            Assert.True(exception.Message.ToUpperInvariant().Contains("MEMBER UPLOAD"));
            Assert.True(exception.Message.Contains(otherPcsId.ToString()));
            Assert.True(exception.Message.Contains(memberUploads.First().Id.ToString()));
        }
示例#22
0
 private void ViewEditorOnPropertyPathActivate(object sender, PropertyPathEventArgs eventArgs)
 {
     IEnumerable<PropertyPath> propertyPaths = new []{eventArgs.PropertyPath};
     if (UseTransformedView && ViewEditor.ViewTransformer != null)
     {
         propertyPaths = ViewEditor.ViewTransformer.TransformView(ViewInfo, propertyPaths).Value;
     }
     OnActivatePropertyPath(propertyPaths.First());
 }
 public static SummaryProcessStat ProcessCompetitionPack(LoggerWrapper logger, BrokerData brokerData, GatherBehaviorMode algoMode, BrokerCompetitionSettings brokerSettings, Action<SummaryProcessStat, BrokerType, SportType, CompetitionItemRawTransport, MatchParsed> actionForMatchedItem)
 {
     var stat = new SummaryProcessStat();
     var competitorProvider = ProjectProvider.Instance.CompetitorProvider;
     var competitionProvider = ProjectProvider.Instance.CompetitionProvider;
     foreach (var competitionParsed in brokerData.Competitions) {
         var competition = competitionProvider.GetCompetitionSpecify(stat[ProcessStatType.CompetitionFromRaw], stat[ProcessStatType.CompetitionSpecifyFromRaw], brokerData.Broker, brokerData.Language, competitionParsed.Type, competitionParsed.Name, competitionParsed, algoMode);
         foreach (var matchParsed in competitionParsed.Matches) {
             var competitorStat = stat[ProcessStatType.CompetitorFromRaw];
             var competitors = new[] {
                 competitorProvider
                 .GetCompetitor(competitorStat, brokerData.Broker, brokerData.Language, competitionParsed.Type, competition.Object.GenderType, matchParsed.CompetitorName1, algoMode),
                 competitorProvider
                 .GetCompetitor(competitorStat, brokerData.Broker, brokerData.Language, competitionParsed.Type, competition.Object.GenderType, matchParsed.CompetitorName2, algoMode)
             };
             if (competitors.Any(c => c.RawObject.ID == default(int))) {
                 continue;
             }
             if (competitors.Any(c => c.Object.ID == default(int)) && competitors.Any(c => c.Object.ID != default(int))) {
                 var linker = new SystemStateProvder();
                 linker.ApplyLinker(competitors.First(c => c.Object.ID != default(int)).RawObject.ID, BrokerEntityType.Competitor);
                 var unlikedCompetitor = competitors.First(c => c.Object.ID == default(int));
                 unlikedCompetitor.Object.ID = RawCompetitor.DataSource.GetByKey(unlikedCompetitor.RawObject.ID).CompetitoruniqueID;
             }
             var creationCiMode = (matchParsed.Odds.SafeAny() || matchParsed.Result != null) ? algoMode : algoMode.FlagDrop(GatherBehaviorMode.CreateOriginalIfMatchedAll);
             var competitionItemRawTransport = competitionProvider.GetCompetitionItem(stat[ProcessStatType.CompetitionItemFromRaw], brokerData.Broker, competitors, competition, matchParsed.DateUtc, creationCiMode, brokerSettings);
             if (competitionItemRawTransport != null && competitionItemRawTransport.CompetitionItemID != default(int)) {
                 if (competitionItemRawTransport.CompetitionItemID < default(int)) {
                     competitionItemRawTransport.CompetitionItemID = -competitionItemRawTransport.CompetitionItemID;
                     logger.Info("Inverse data for ID = {0} {1} {2}", competitionItemRawTransport.CompetitionItemID, brokerData.Broker, brokerData.Language);
                     ReverseAllDataInMatch(matchParsed);
                 }
                 actionForMatchedItem(stat, brokerData.Broker, competitionParsed.Type, competitionItemRawTransport, matchParsed);
             }
         }
     }
     logger.Info("SaveResults: {0} {1} {2} {3}: Competitions: {4}/{5} CompetitionItems: {6}/{7} Competitors {8}/{9} {10}", brokerData.Competitions.FirstOrDefault(c => c.Matches.Any())?.Matches.FirstOrDefault()?.DateUtc.Date.ToString("yyyy MMMM dd"),
         brokerData.Broker, brokerData.Language, algoMode,
         stat[ProcessStatType.CompetitionSpecifyFromRaw].FinallySuccessCount, stat[ProcessStatType.CompetitionSpecifyFromRaw].TotalCount,
         stat[ProcessStatType.CompetitionItemFromRaw].FinallySuccessCount, stat[ProcessStatType.CompetitionItemFromRaw].TotalCount,
         stat[ProcessStatType.CompetitorFromRaw].FinallySuccessCount, stat[ProcessStatType.CompetitorFromRaw].TotalCount,
         brokerData.Competitions.GroupBy(c => c.Type).Select(g => string.Format("{0}={1}", g.Key, g.Count())).StrJoin(", "));
     return stat;
 }
示例#24
0
		public override void ExecuteWithResourceItems(System.Collections.Generic.IEnumerable<ResourceEditor.ViewModels.ResourceItem> resourceItems)
		{
			var selectedItem = resourceItems.First();
			string newValue = SD.MessageService.ShowInputBox("${res:ResourceEditor.ResourceEdit.ContextMenu.EditComment}",
				                   "${res:ResourceEditor.ResourceEdit.ContextMenu.EditCommentText}",
				                   selectedItem.Comment);
			if (newValue != null && newValue != selectedItem.Comment) {
				selectedItem.Comment = newValue;
			}
		}
 private static void CheckIsRightTriangle(double a, double b, double c)
 {
     var orderedSide = new[] {a, b, c}.OrderBy(x => x);
     var hypotenuse = orderedSide.First();
     var legs1 = orderedSide.ElementAt(1);
     var legs2 = orderedSide.ElementAt(2);
     if (hypotenuse*hypotenuse != legs1*legs1 + legs2*legs2)
     {
         throw new ArithmeticException("Треугольник не является прямоугольным");
     }
 }
示例#26
0
文件: Reduce.cs 项目: miklund/holf
 private void Example()
 {
     var input = new[] { 1, 2, 3, 4, 5 };
     var result = input.First();
     foreach (var item in input.Skip(1))
     {
         if (result < item)
         {
             result = item;
         }
     }
 }
示例#27
0
        static void Main(string[] args)
        {
            var startingTags = new[]
            {
                "trip-hop"
            }
            .Select(t => new Node(t, FSharpOption<IDictionary<Node, int>>.None));

            var q = new Algo("ff03f5b2e6d5c55b4c0b74b8e203bb7c", "64804b95f74e40b3b968304c59d97c08", 5);

            q.fillGraphAsync(startingTags.First(), 3).Wait();
            Console.ReadLine();
        }
示例#28
0
        public override void Run()
        {
            var inputs = new[]
            {
                JoinArrays(GetColorAttributeArray(Color.Blue), GetShapeAttributeArray(Shapes.Rectangle), new double[] { 10 }),
                JoinArrays(GetColorAttributeArray(Color.Red), GetShapeAttributeArray(Shapes.Rectangle), new double[] { 10 }),
                JoinArrays(GetColorAttributeArray(Color.Blue), GetShapeAttributeArray(Shapes.Star), new double[] { 10 }),
                JoinArrays(GetColorAttributeArray(Color.Blue), GetShapeAttributeArray(Shapes.Ring), new double[] { 15 }),
                JoinArrays(GetColorAttributeArray(Color.Green), GetShapeAttributeArray(Shapes.Circle), new double[] { 10 }),
                JoinArrays(GetColorAttributeArray(Color.Yellow), GetShapeAttributeArray(Shapes.Circle), new double[] { 10 }),
                JoinArrays(GetColorAttributeArray(Color.Yellow), GetShapeAttributeArray(Shapes.Circle), new double[] { 10 }),
                JoinArrays(GetColorAttributeArray(Color.Blue), GetShapeAttributeArray(Shapes.Rectangle), new double[] { 15 }),

                JoinArrays(GetColorAttributeArray(Color.Yellow), GetShapeAttributeArray(Shapes.Star), new double[] { 10 }),
                JoinArrays(GetColorAttributeArray(Color.Red), GetShapeAttributeArray(Shapes.Arrow), new double[] { 10 }),
                JoinArrays(GetColorAttributeArray(Color.Green), GetShapeAttributeArray(Shapes.Trapezium), new double[] { 15 }),
                JoinArrays(GetColorAttributeArray(Color.Green), GetShapeAttributeArray(Shapes.Diamond), new double[] { 15 }),
                JoinArrays(GetColorAttributeArray(Color.Yellow), GetShapeAttributeArray(Shapes.Triangle), new double[] { 15 }),
                JoinArrays(GetColorAttributeArray(Color.Red), GetShapeAttributeArray(Shapes.Ring), new double[] { 15 }),
                JoinArrays(GetColorAttributeArray(Color.Yellow), GetShapeAttributeArray(Shapes.Circle), new double[] { 15 }),
                JoinArrays(GetColorAttributeArray(Color.Red), GetShapeAttributeArray(Shapes.Ellipse), new double[] { 15 }),
            };

            var outputs = new bool[] { true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false };

            var j = new Range(inputs.Length);
            var noise = Variable.GammaFromMeanAndVariance(1, 1);
            var X = Variable.Observed(inputs.Select(i => Vector.FromArray(i)).ToArray(), j).Named("X");
            var Y = Variable.Observed(outputs, j).Named("Y");
            var weights = Variable.VectorGaussianFromMeanAndPrecision(Vector.Zero(inputs.First().Length), PositiveDefiniteMatrix.Identity(inputs.First().Length))
                .Named("weights");
            Y[j] = Variable.GaussianFromMeanAndPrecision(Variable.InnerProduct(X[j], weights), noise) > 0;
            var engine = new InferenceEngine();
            var posteriorWeightsDist = engine.Infer<VectorGaussian>(weights);
            var posteriorNoiseDist = engine.Infer<Gamma>(noise);
            weights = Variable.Random(posteriorWeightsDist);
            var testCase = JoinArrays(GetColorAttributeArray(Color.Red), GetShapeAttributeArray(Shapes.Trapezium), new double[] { 15 });
            var testClassification = engine.Infer<Bernoulli>(Variable.InnerProduct(Vector.FromArray(testCase), weights) > 0);
        }
示例#29
0
    static void Main(String[] args)
    {
        Console.ReadLine(); //skip first line;

        var h1 = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
        var h2 = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
        var h3 = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

        var stacks = new[]{ h1, h2, h3}.Select(_=> new MyStack(_)).ToArray();
        MyStack.PopAll(stacks);

        Console.WriteLine(stacks.First().Sum);
    }
示例#30
0
 public void OrderBy_DoesNotSort_WhenExpressionsIsNull()
 {
     var data = new[]
     {
         new User { Name = "user2" },
         new User { Name = "user3" },
         new User { Name = "user1" },
     };
     var orderedQueryable = data.AsQueryable().OrderBy(null);
     orderedQueryable.Count().ShouldEqual(3);
     orderedQueryable.First().ShouldEqual(data.First());
     orderedQueryable.Skip(1).First().ShouldEqual(data.Skip(1).First());
     orderedQueryable.Last().ShouldEqual(data.Last());
 }