コード例 #1
0
 public void ConcatWorks()
 {
     var arr = new[] { "a", "b" };
     Assert.AreEqual(arr.Concat("c"), new[] { "a", "b", "c" });
     Assert.AreEqual(arr.Concat("c", "d"), new[] { "a", "b", "c", "d" });
     Assert.AreEqual(arr, new[] { "a", "b" });
 }
コード例 #2
0
ファイル: ArrayExtensions.cs プロジェクト: pengyancai/cs-util
        public void TestConcat()
        {
            var arr1 = new[] {0, 1, 2};
              var arr2 = new[] {3, 4, 5};
              var arr3 = new[] {6, 7, 8};

              Assert.AreEqual(new[] {0, 1, 2, 3, 4, 5}, arr1.Concat(arr2));
              Assert.AreEqual(new[] {0, 1, 2, 3, 4, 5, 6, 7, 8}, arr1.Concat(arr2, arr3));
        }
コード例 #3
0
ファイル: Tree.cs プロジェクト: jamesrcounts/CS513
        public Tree Union(Tree t, Edge e)
        {
            var es = new[] { e };
            es = es.Concat(Edges).ToArray();
            es = es.Concat(t.Edges).ToArray();

            var ns = Nodes.Concat(t.Nodes);

            return new Tree(ns.ToArray(), es.ToArray());
        }
コード例 #4
0
        public void Compile(FileInfo source, FileInfo output)
        {
            IEnumerable<string> includePaths = new[] { source.Directory.FullName };
            if (!string.IsNullOrWhiteSpace(Options.CompilationIncludePaths) && Directory.Exists(Options.CompilationIncludePaths))
                includePaths = includePaths.Concat(Options.CompilationIncludePaths.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));

            var result = Compiler.CompileFile(source.FullName,
                    sourceMapPath:          Options.GenerateSourceMaps ? output.FullName + ".map" : null,
                    includeSourceComments:  Options.IncludeSourceComments,
                    precision:              Options.Precision,
                    additionalIncludePaths: includePaths,
                    outputStyle:            Options.OutputStyle
                );

            var css = result.CSS;
            var sourceMap = result.SourceMap;
            InteropHelper.CheckOut(output.FullName);

            if (Options.IncludeGeneratedCodeWarning)
                css = new StringBuilder("/* AUTOGENERATED CSS: To make changes edit ").Append(source.Name).Append(" */").AppendLine().Append(css).ToString();

            File.WriteAllText(output.FullName, css, UTF8_ENCODING);

            if (Options.GenerateSourceMaps && !string.IsNullOrEmpty(sourceMap))
            {
                InteropHelper.CheckOut(output.FullName + ".map");
                File.WriteAllText(output.FullName + ".map", sourceMap, UTF8_ENCODING);
            }
        }
コード例 #5
0
        /// <summary>
        /// Gets the additional namespaces that should be imported for queries using this driver
        /// </summary>
        /// <param name="props">the deserialized ConnectionProperties object.</param>
        /// <returns>The namespaces that should be imported as strings</returns>
        public static IEnumerable<string> GetNamespacesToAdd(ConnectionProperties props)
        {
            IEnumerable<string> ret = new[]
                {
                    "MongoDB.Driver.Builders",
                    "MongoDB.Driver",
                };

            if(!string.IsNullOrEmpty(props.SelectedDatabase))
            {
                ret = ret.Concat(
                props.CollectionTypeMappings[props.SelectedDatabase].Select(x => x.CollectionType)
                    .Where(x => !string.IsNullOrEmpty(x))
                    .Select(name =>
                    {
                        name = name.Split(',').First();
                        int lastDot = name.LastIndexOf('.');
                        if (lastDot <= -1)
                            return null;

                        return name.Substring(0, lastDot);
                    }).Where(x => !string.IsNullOrEmpty(x)));
            }

            return ret.Distinct();
        }
コード例 #6
0
ファイル: ConcatTest.cs プロジェクト: KevinKelley/morelinq
 public void ConcatWithNonEmptyHeadSequence()
 {
     var head = new[] { "first", "second" };
     var tail = "third";
     var whole = head.Concat(tail);
     whole.AssertSequenceEqual("first", "second", "third");
 }
コード例 #7
0
 public OptChar[] AddLeadingTrailingSpace(OptChar[] input)
 {
     List<OptChar> trailing = input.ToList();
     trailing.Add(OptChar.None);                                 // add trailing empty string
     List<OptChar> leading = new[] { OptChar.None }.ToList();    // add leading empty string
     return leading.Concat(trailing).ToArray();
 }
コード例 #8
0
        private static XamlNamespaceRegistry CreateXamlNamespaceRegistry()
        {
            var xamlNamespaceRegistry = new XamlNamespaceRegistry();

            var forcedAssemblies = new[]
            {
                typeof (Control),
                typeof(Style)
            }.Select(t => t.GetTypeInfo().Assembly);

            foreach (var nsa in 
                forcedAssemblies
                    .Concat(PerspexLocator.Current.GetService<IPclPlatformWrapper>().GetLoadedAssemblies())
                    .Distinct()
                    .SelectMany(asm
                        => asm.GetCustomAttributes<XmlnsDefinitionAttribute>().Select(attr => new {asm, attr}))
                    .GroupBy(entry => entry.attr.XmlNamespace))
            {
                var def = XamlNamespace.Map(nsa.Key)
                    .With(nsa.GroupBy(x => x.asm).Select(
                        a => Route.Assembly(a.Key)
                            .WithNamespaces(a.Select(entry => entry.attr.ClrNamespace).ToList())
                        ));
                xamlNamespaceRegistry.AddNamespace(def);
            }
            xamlNamespaceRegistry.RegisterPrefix(new PrefixRegistration(string.Empty, PerspexNs));

            return xamlNamespaceRegistry;
        }
コード例 #9
0
ファイル: TestRenderers.cs プロジェクト: nabuk/NSlice
 public static IMarkdown ToMarkdown(this ITestCase testCase, CultureInfo culture)
 {
     Func<IMarkdown> renderGain = () =>
     {
         var testExecutionTime = testCase.Test.ExecutionTime;
         var benchmarkExecutionTime = testCase.Benchmark.ExecutionTime;
         if (testExecutionTime < 1.0 || benchmarkExecutionTime < 1.0)
             return Markdown.Empty;
         var gain = (testExecutionTime/benchmarkExecutionTime) - 1.0;
         gain *= 100.0;
         if (Math.Abs(gain) < 5.0)
             return Markdown.Empty;
         return
             Markdown.Empty
             .Add("  ")
             .Add(
                 Markdown.Create(() => string.Format(culture, "{0:+0.0;-0.0;0.0}%", gain))
                 .InlineCode());
     };
     return Markdown.Create(() =>
     {
         var result = testCase.Name.ToMarkdown();
         if (testCase.Benchmark != null)
             result = result.Add(renderGain());
         result = result.H3().NewLine().NewLine();
         IEnumerable<ITest> tests = new[] { testCase.Test };
         if (testCase.Benchmark != null)
             tests = tests.Concat(new[] {testCase.Benchmark});
         return result.Add(tests.Select(t => t.ToMarkdown().NewLine()).AsLines());
     });
 }
コード例 #10
0
        public static IEnumerable<FakeSourceData> GetData()
        {
            var handMadeData = new[]
            {
                new FakeSourceData { Data = "Today", Time = "15.00", Address = "221b Baker Street" },
                new FakeSourceData { Data = "Today", Time = "15.00", Address = "32 Windsor Gardens" },
                new FakeSourceData { Data = "Today", Time = "15.00", Address = "Buckingham Palace" },
                new FakeSourceData { Data = "Today", Time = "15.00", Address = "29 Acacia Road" },

                new FakeSourceData { Data = "Tomorrow", Time = "16.00", Address = "15 Jubilee Terrace" },
                new FakeSourceData { Data = "Tomorrow", Time = "16.30", Address = "13 Coronation Street" },

                new FakeSourceData { Data = "25th october", Time = "16.00", Address = "890 Fifth Avenue" },
                new FakeSourceData { Data = "25th october", Time = "16.40", Address = "Apartment 5E, 129 West 81st Street" },

            };

            var r = new Random(1);
            var generatedData =
                from i in Enumerable.Range(0, 1000)
                select new FakeSourceData
                {
                    Data = "Data " + r.Next(1, 9),
                    Time = "Time " + r.Next(1, 9),
                    Address = "Address " + i
                };

            return handMadeData.Concat(generatedData);
        }
コード例 #11
0
        static PrimitiveTypes()
        {
            var types = new[]
                        {
                            typeof(Enum),
                            typeof(string),
                            typeof(char),
                            typeof(Guid),
                            typeof(bool),
                            typeof(byte),
                            typeof(short),
                            typeof(int),
                            typeof(long),
                            typeof(float),
                            typeof(double),
                            typeof(decimal),
                            typeof(sbyte),
                            typeof(ushort),
                            typeof(uint),
                            typeof(ulong),
                            typeof(DateTime),
                            typeof(DateTimeOffset),
                            typeof(TimeSpan)
                        };

            var nullableTypes = from t in types
                                where t.IsValueType
                                select typeof(Nullable<>).MakeGenericType(t);

            _list = types.Concat(nullableTypes).ToArray();
        }
コード例 #12
0
        public void TestMultipleZones()
        {
            var miz001 = new[] { "49805", "49901", "49918", "49950" };
            var miz004 = new[] { "49908", "49919", "49946", "49962", "49970" };

            Assert.IsTrue(_zoneLookup.GetZipCodes("MIZ001 - 004").Select(z => z.Code).SequenceEqual(miz001.Concat(miz004)));
        }
コード例 #13
0
        static PrimitiveTypes()
        {
            var types = new[]
                          {
                              typeof (Enum),
                              typeof (String),
                              typeof (Char),

                              typeof (Boolean),
                              typeof (Byte),
                              typeof (Int16),
                              typeof (Int32),
                              typeof (Int64),
                              typeof (Single),
                              typeof (Double),
                              typeof (Decimal),

                              typeof (SByte),
                              typeof (UInt16),
                              typeof (UInt32),
                              typeof (UInt64),

                              typeof (DateTime),
                              typeof (DateTimeOffset),
                              typeof (TimeSpan),
                          };

            var nullTypes = from t in types
                            where t.IsValueType
                            select typeof(Nullable<>).MakeGenericType(t);

            List = types.Concat(nullTypes).ToArray();
        }
コード例 #14
0
ファイル: SmartParser.cs プロジェクト: rte-se/emul8
        public object Parse(string input, Type outputType)
        {
            if(input.GetType() == outputType)
            {
                return input;
            }

            NumberStyles style;
            if(input.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                style = NumberStyles.HexNumber;
                input = input.Substring(2);
            }
            else
            {
                style = NumberStyles.Integer;
            }

            Delegate parser;
            if(!cache.TryGetValue(outputType, out parser))
            {
                var types = new[] { typeof(string), typeof(NumberStyles) };
                var method = outputType.GetMethod("Parse", types);
                if(method == null)
                {
                    throw new ArgumentException(string.Format("Type \"{0}\" does not have a \"Parse\" method", outputType.Name));
                }

                var delegateType = Expression.GetDelegateType(types.Concat(new[] { method.ReturnType }).ToArray());
                parser = method.CreateDelegate(delegateType);
                cache.Add(outputType, parser);
            }

            return parser.DynamicInvoke(input, style);
        }
コード例 #15
0
        public static Type[] GetLanguageNeutralTypes()
        {
            var types = new[]
            {
                // ROSLYN
                typeof(Microsoft.CodeAnalysis.Editor.Implementation.Workspaces.WorkspaceTaskSchedulerFactoryFactory),
                typeof(Microsoft.CodeAnalysis.Host.WorkspaceTaskSchedulerFactoryFactory),
                typeof(Microsoft.CodeAnalysis.Formatting.Rules.DefaultFormattingRuleFactoryServiceFactory),
                typeof(Microsoft.CodeAnalysis.Host.PersistentStorageServiceFactory),
                typeof(Microsoft.CodeAnalysis.Text.Implementation.TextBufferFactoryService.TextBufferCloneServiceFactory),
                typeof(Microsoft.CodeAnalysis.Host.MetadataServiceFactory),
                typeof(Microsoft.CodeAnalysis.Host.TemporaryStorageServiceFactory),
                typeof(Microsoft.CodeAnalysis.Host.TextFactoryService),
                typeof(Microsoft.CodeAnalysis.Editor.Implementation.Workspaces.ProjectCacheHostServiceFactory),
                typeof(Solution), // ServicesCore
                typeof(Microsoft.CodeAnalysis.Options.OptionService), // Service
                typeof(Microsoft.CodeAnalysis.Options.OptionsServiceFactory),
                typeof(Microsoft.CodeAnalysis.Options.Providers.ExportedOptionProvider),
                typeof(Microsoft.CodeAnalysis.Editor.Implementation.SmartIndent.SmartIndentProvider),
                typeof(Microsoft.CodeAnalysis.Editor.Implementation.ForegroundNotification.ForegroundNotificationService),
                typeof(Microsoft.CodeAnalysis.Editor.UnitTests.TestOptionsServiceFactory),
                typeof(TestWaitIndicator),
                typeof(TestExtensionErrorHandler),
                typeof(TestExportProvider)
            };

            return types.Concat(TestHelpers.GetAllTypesWithStaticFieldsImplementingType(typeof(InternalSolutionCrawlerOptions).Assembly, typeof(Microsoft.CodeAnalysis.Options.IOption)))
                        .Concat(TestHelpers.GetAllTypesWithStaticFieldsImplementingType(typeof(EditorComponentOnOffOptions).Assembly, typeof(Microsoft.CodeAnalysis.Options.IOption)))
                        .Concat(TestHelpers.GetAllTypesWithStaticFieldsImplementingType(typeof(ServiceComponentOnOffOptions).Assembly, typeof(Microsoft.CodeAnalysis.Options.IOption)))
                        .Concat(TestHelpers.GetAllTypesWithStaticFieldsImplementingType(typeof(Microsoft.CodeAnalysis.Formatting.FormattingOptions).Assembly, typeof(Microsoft.CodeAnalysis.Options.IOption)))
                        .Distinct()
                        .ToArray();
        }
コード例 #16
0
        public void TestZoneLocationReturned()
        {
            var date = new DateTime(2008, 12, 19);
            var events = _ncdc.GetEvents(new State("MI"), "Ingham", date, date, null);
            var e = events.Single();
            var miz051Zips = new[]
                                 {
                                     "48811", "48812", "48818", "48829", "48834", "48838", "48850", "48852", "48884",
                                     "48885", "48886", "48888", "48891", "49322", "49326", "49329", "49339", "49347"
                                 };
            var miz059Zips = new[]
                                 {
                                     "48808", "48820", "48822", "48831", "48833", "48835", "48853", "48866", "48879",
                                     "48894"
                                 };
            var miz067Zips = new[]
                                 {
                                     "48805", "48819", "48823", "48824", "48825", "48826", "48840", "48842", "48854",
                                     "48864", "48892", "48895", "48901", "48906", "48909", "48910", "48911", "48912",
                                     "48913", "48915", "48916", "48918", "48919", "48921", "48922", "48924", "48929",
                                     "48930", "48933", "48937", "48950", "48956", "48980", "49251", "49264", "49285"
                                 };

            var allZips = miz051Zips.Concat(miz059Zips).Concat(miz067Zips).ToList();
            var locatedZipCodes = e.Locations.Select(l => l.ZipCode.Code).ToList();
            allZips.Sort();
            locatedZipCodes.Sort();
            Assert.IsTrue(allZips.SequenceEqual(locatedZipCodes));
        }
コード例 #17
0
        public void Activated()
        {
            // Let's make sure that the basic set of features is enabled.  If there are any that are not enabled, then let's enable them first.
            var theseFeaturesShouldAlwaysBeActive = new[] {
                "Settings"
            };

            theseFeaturesShouldAlwaysBeActive = theseFeaturesShouldAlwaysBeActive.Concat(
                _featureManager.GetAvailableFeatures().Where(f=>f.Id != "Coevery.Setup").Select(f => f.Id)).ToArray();

            var enabledFeatures = _featureManager.GetEnabledFeatures().Select(f => f.Id).ToList();
            var featuresToEnable = theseFeaturesShouldAlwaysBeActive.Where(shouldBeActive => !enabledFeatures.Contains(shouldBeActive)).ToList();
            if (featuresToEnable.Any()) {
                _featureManager.EnableFeatures(featuresToEnable, true);
            }

            foreach (var feature in _dataMigrationManager.GetFeaturesThatNeedUpdate()) {
                try {
                    _dataMigrationManager.Update(feature);
                }
                catch (Exception e) {
                    Logger.Error("Could not run migrations automatically on " + feature, e);
                }
            }
        }
コード例 #18
0
        private static CalculationExpectation[] GenerateTestData(int maxBit)
        {
            //Create array of +ve numbers in the 'maxBit' bit range (i.e. 32 bit or 64bit)
            var smallValues = new[]
            {
                new CalculationExpectation(1L, 63),
                new CalculationExpectation(2L, 62),
                new CalculationExpectation(3L, 62),
                new CalculationExpectation(4L, 61),
                new CalculationExpectation(5L, 61),
            };
            var largeValues = Enumerable.Range(3, maxBit - 3)
                .Select(exp => new { Value = 1L << exp, LZC = 63 - exp })
                .SelectMany(x => new[]
                {
                    new CalculationExpectation(x.Value-1, x.LZC+1),
                    new CalculationExpectation(x.Value, x.LZC),
                    new CalculationExpectation(x.Value+1, x.LZC),
                })
                .Where(x => x.Value > 0)
                .Distinct()
                .ToArray();

            return smallValues.Concat(largeValues).ToArray();
        }
コード例 #19
0
 public override void SendPacket(MinecraftServer server, MinecraftClient client)
 {
     byte[] payload = new[] { PacketId, (byte)EntityIds.Length };
     foreach (int id in EntityIds)
         payload = payload.Concat(DataUtility.CreateInt32(id)).ToArray();
     client.SendData(payload);
 }
コード例 #20
0
 private static string[] GetDelimiters(string input)
 {
     var delimitersPart = ExtractDelimitersPart(input);
     var customDelimiters = ExtractCustomDelimiters(delimitersPart);
     var defaultDelimiters = new[] {",", "\n"};
     var delimiters = defaultDelimiters.Concat(customDelimiters).ToArray();
     return delimiters;
 }
コード例 #21
0
ファイル: ConcatTests.cs プロジェクト: kawillia/LinqToObjects
        public void ReturnsAllOriginalElementsInTheInputSequences()
        {
            var first = new[] { 1, 2 };
            var result = first.Concat(new[] { 3, 4 });
            var expected = new[] { 1, 2, 3, 4 };

            Assert.That(result, Is.EqualTo(expected));
        }
コード例 #22
0
ファイル: LexicalTests.cs プロジェクト: rafaellincoln/roslyn
 public LexicalTests()
 {
     _options = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp3);
     var binaryLiterals = new[] { new KeyValuePair<string, string>("binaryLiterals", "true") };
     var digitSeparators = new[] { new KeyValuePair<string, string>("digitSeparators", "true") };
     _binaryOptions = _options.WithFeatures(binaryLiterals);
     _underscoreOptions = _options.WithFeatures(digitSeparators);
     _binaryUnderscoreOptions = _options.WithFeatures(binaryLiterals.Concat(digitSeparators));
 }
コード例 #23
0
        public void ConcatTest()
        {
            var a1 = new[] { 1, 2 };
            var a2 = new[] { 3, 4 };

            var actual = a1.Concat(a2);

            CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4 }, actual);
        }
コード例 #24
0
 private static string getFormItemGetterSummary( ModificationField field, string controlType, IEnumerable<string> additionalSentences )
 {
     var sentences = new[]
         {
             "Creates a " + field.PropertyName + controlType.PrependDelimiter( " " ) + " form item, which includes a label, a control, and a validation.",
             controlType.Any() ? "" : "This is a generic form-item getter; use it only if there is no specific getter for the control type that you need.",
             "You almost certainly should not call this method from a deferred block of code since this could cause validations to be added to the data modification in the wrong order."
         };
     return StringTools.ConcatenateWithDelimiter( " ", sentences.Concat( additionalSentences ).ToArray() );
 }
コード例 #25
0
 private bool append_category(string val)
 {
   if (val == first_or_default_category())
   {
     return false;
   }
   var n = new[] { val };
   _.categories = n.Concat(_.categories).ToArray();
   return true;
 }
コード例 #26
0
		public static int[] ToSerializable(this ShortcutKey shortcutKey)
		{
			if (shortcutKey.Key == VirtualKey.None) return Array.Empty<int>();

			var key = new[] { (int)shortcutKey.Key, };

			return shortcutKey.Modifiers.Length == 0
				? key
				: key.Concat(shortcutKey.Modifiers.Select(x => (int)x)).ToArray();
		}
コード例 #27
0
ファイル: Reflector.cs プロジェクト: jcowart/Symbiote
        public static IEnumerable<Type> GetInheritenceChain(Type type)
        {
            var baseType = type.BaseType;
            if (baseType == null || baseType == typeof(object))
                return null;

            var types = new[] { baseType };
            var enumerable = GetInheritenceChain(baseType);
            return enumerable == null ? types : types.Concat(enumerable);
        }
コード例 #28
0
ファイル: TestError.cs プロジェクト: stasi009/TestDrivenLearn
        public static void TestCatch_OnlySwitchOnError()
        {
            IObservable<int> stream1 = new[] { 1, 2 }.ToObservable();
            IObservable<int> stream2 = new[] { 3, 4 }.ToObservable();

            IObservable<int> errored = stream1.Concat(Observable.Throw<int>(new Exception("test"))).Catch(stream2);
            CollectionAssert.AreEqual(new[] { 1, 2, 3, 4 }, errored.ToEnumerable());

            IObservable<int> noerror = stream1.Catch(stream2);
            CollectionAssert.AreEqual(new[] { 1, 2 }, noerror.ToEnumerable());
        }
コード例 #29
0
ファイル: OpenAlSoundEngine.cs プロジェクト: Roger-luo/OpenRA
		public SoundDevice[] AvailableDevices()
		{
			var defaultDevices = new[]
			{
				new SoundDevice("Default", null, "Default Output"),
				new SoundDevice("Null", null, "Output Disabled")
			};

			var physicalDevices = PhysicalDevices().Select(d => new SoundDevice("Default", d, d));
			return defaultDevices.Concat(physicalDevices).ToArray();
		}
コード例 #30
0
        static IEnumerable<int> PrimeFactors(int number)
        {
            int smallestPrimeFactor = Primes().First(p => number % p == 0);
              var justThisFactor = new[] { smallestPrimeFactor };

              if (smallestPrimeFactor == number)
              {
            return justThisFactor;
              }
              return justThisFactor.Concat(PrimeFactors(number / smallestPrimeFactor));
        }