System.Linq.Enumerable.Range(int, int)

Here are the examples of the csharp api System.Linq.Enumerable.Range(int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

6950 Examples 7

19 View Source File : FileSystemRepoBuilderBenchmark.cs
License : Apache License 2.0
Project Creator : acblog

[IterationSetup]
        public void Setup()
        {
            RootPath = Path.Join(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location), Guid.NewGuid().ToString());
            FSStaticBuilder.EnsureDirectoryExists(RootPath);

            PostData = Enumerable.Range(0, Length).Select(x => Generator.GetPost()).ToArray();
            LayoutData = Enumerable.Range(0, Length).Select(x => Generator.GetLayout()).ToArray();
            PageData = Enumerable.Range(0, Length).Select(x => Generator.GetPage()).ToArray();
            FileData = Enumerable.Range(0, Length).Select(x => Generator.GetFile()).ToArray();

            Builder = new BlogBuilder(new BlogOptions(), RootPath);
        }

19 View Source File : EventHost.cs
License : MIT License
Project Creator : ad313

private async Task sample_publish_queue_all3_big()
        {
            var key = "sample_publish_queue_all3";
            var key2 = "sample_publish_queue_all4";

            var index1 = 0;
            var index2 = 0;
            var index3 = 0;


            var queue = new ConcurrentQueue<int>();

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------11");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  11");
                    //index1 = 0;
                    await Task.CompletedTask;
                });

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------12");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  12");
                    //index1 = 0;
                    await Task.CompletedTask;
                });

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------13");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  13");
                    //index1 = 0;
                    await Task.CompletedTask;
                });






            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key2, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------21");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  21");
                    //index1 = 0;
                    await Task.CompletedTask;
                });

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key2, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------22");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  22");
                    //index1 = 0;
                    await Task.CompletedTask;
                });

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key2, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------23");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  23");
                    //index1 = 0;
                    await Task.CompletedTask;
                });


            await Task.Delay(2000);



            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(0, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(100, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(200, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(300, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(400, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(500, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(600, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(700, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());


            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1000, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1100, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1200, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1300, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1400, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1500, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1600, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1700, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

            await Task.Delay(20000);
        }

19 View Source File : UserStatsGetter.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<List<UserMonthlyCountStats>> GetUsersCountOverMonth()
        {
            var startDate = DateTime.UtcNow.AddDays(-31);
            var endDate = DateTime.UtcNow;

            var users = (from u in _usersRepo.Table.Where(uu => uu.CreatedAt >= startDate && uu.CreatedAt <= endDate)
                         group u by u.CreatedAt.Date into g
                         orderby g.Key
                         select new UserMonthlyCountStats
                         {
                             Count = g.Count(),
                             Day = g.Key
                         }).ToList();
            var days = Enumerable.Range(0, 31).Select(offset => endDate.AddDays(-offset)).ToList();

            days.ForEach(day =>
            {
                if (!users.Any(u => u.Day.Date == day.Date))
                {
                    users.Add(new UserMonthlyCountStats
                    {
                        Day = day.Date,
                        Count = 0
                    });
                }
            });

            users = users.OrderBy(u => u.Day.Date).ToList();

            return users;
        }

19 View Source File : SeriesWithMetadata.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void OnSeriesWithMetadataLoaded(object sender, RoutedEventArgs e)
        {
            var startDate = new DateTime(1995, 1, 1);

            // Budget data
            var yearsData = Enumerable.Range(0, 18).Select(startDate.AddYears).ToArray();
            var gainLossData = new [] {0, -20.5, -30.06, -70.1, -100.22, 10.34, 30.00, 60.12, 50.1, 70.4, 40.55, 30.76, -50.2, -60.00, -20.01, 50.01, 60.32, 60.44};

            // Metadata
            var executivesData = new [] {"Emerson Irwin", "Reynold Harding", "Carl Carpenter", "Merle Godfrey", "Karl Atterberry"};
            var checkPointIndicies = new []{0, 4, 9, 13, 16};

            var ceo = executivesData[0];
            var budgetMetadata = gainLossData.Select((value, index) =>
            {
                var metadata = new BudgetPointMetadata(value);

                if (checkPointIndicies.Contains(index))
                {
                    metadata.IsCheckPoint = true;

                    var ceoIndex = checkPointIndicies.IndexOf(index);
                    ceo = executivesData[ceoIndex];
                }

                metadata.CEO = ceo;

                return metadata;
            }).ToArray();

            var budgetDataSeries = new XyDataSeries<DateTime, double>();

            budgetDataSeries.Append(yearsData, gainLossData, budgetMetadata);

            lineSeries.DataSeries = budgetDataSeries;

            sciChart.ZoomExtents();
        }

19 View Source File : TransactionStatsQueriesHandler.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<List<TransactionMonthlyStatsDto>> Handle(TransactionStatsOverMonthQuery request, CancellationToken cancellationToken)
        {
            var startDate = DateTime.UtcNow.Date.AddDays(-31);
            var endDate = DateTime.UtcNow.Date;

            var transes = (from r in _receivingsRepo.Table
                           where
                              r.ReceivedAtUtc.Date >= startDate && r.ReceivedAtUtc.Date <= endDate
                           group r by r.ReceivedAtUtc.Date into g
                           orderby g.Key
                           select new TransactionMonthlyStatsDto
                           {
                               Count = g.Count(),
                               Day = g.Key
                           }).ToList();
            var days = Enumerable.Range(0, 31).Select(offset => endDate.AddDays(-offset)).ToList();

            days.ForEach(day =>
            {
                if (!transes.Any(t => t.Day.Date == day.Date))
                {
                    transes.Add(new TransactionMonthlyStatsDto
                    {
                        Count = 0,
                        Day = day.Date,
                    });
                }
            });

            return transes.OrderBy(t => t.Day.Date).ToList();
        }

19 View Source File : FileTransferProgressBar.cs
License : MIT License
Project Creator : a-luna

string GetProgressBarText(double currentProgress)
		{
			const string singleSpace = " ";

			var numBlocksCompleted = (int)(currentProgress * NumberOfBlocks);

			var completedBlocks =
				Enumerable.Range(0, numBlocksCompleted).Aggregate(
					string.Empty,
					(current, _) => current + CompletedBlock);

			var incompleteBlocks =
				Enumerable.Range(0, NumberOfBlocks - numBlocksCompleted).Aggregate(
					string.Empty,
					(current, _) => current + IncompleteBlock);

			var progressBar = $"{StartBracket}{completedBlocks}{incompleteBlocks}{EndBracket}";
			var percent = $"{currentProgress:P0}".PadLeft(4, '\u00a0');

			var fileSizeInBytes = FileHelper.FileSizeToString(FileSizeInBytes);
			var padLength = fileSizeInBytes.Length;
			var bytesReceived = FileHelper.FileSizeToString(BytesReceived).PadLeft(padLength, '\u00a0');
			var bytes = $"{bytesReceived} of {fileSizeInBytes}";

			var animationFrame = AnimationSequence[AnimationIndex++ % AnimationSequence.Length];
			var animation = $"{animationFrame}";

		    progressBar = DisplayBar
		        ? progressBar + singleSpace
		        : string.Empty;

		    percent = DisplayPercentComplete
		        ? percent + singleSpace
		        : string.Empty;

		    bytes = DisplayBytes
		        ? bytes + singleSpace
		        : string.Empty;

			if (!DisplayAnimation || currentProgress is 1)
			{
				animation = string.Empty;
			}

			return progressBar + bytes + percent + animation;
		}

19 View Source File : WeatherForecastController.cs
License : MIT License
Project Creator : ad313

[HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }

19 View Source File : NoDuplicationFuzzersShould.cs
License : Apache License 2.0
Project Creator : 42skillz

[Test]
        public void Be_able_to_pick_always_different_values_from_a_medium_size_list_of_int()
        {
            var fuzzer = new Fuzzer(noDuplication: true);

            var candidates = Enumerable.Range(-10000, 10000).ToArray();

            CheckThatNoDuplicationIsMadeWhileGenerating(fuzzer, candidates.LongLength, () =>
            {
                return fuzzer.PickOneFrom(candidates);
            });
        }

19 View Source File : ImageParser.cs
License : MIT License
Project Creator : adainrivers

public async Task<List<RawPriceData>> Parse(string language, Image image)
        {

            await InitializeTesseract(language);
            using var adjustedImage = image.AdjustSize(out var sizeModifier);
            _sizeModifier = sizeModifier;
            var result = Enumerable.Range(0, 9).Select(i => new RawPriceData
            {
                ItemName = GereplacedemName(adjustedImage, i),
                Price = GereplacedemPrice(adjustedImage, i),
                GearScore = GetGearScore(adjustedImage, i),
                Tier = GetTier(adjustedImage, i),
                Availability = GetAvailability(adjustedImage, i),
                Location = GetLocation(adjustedImage, i)
            }).ToList();

            if (!_highPerformanceMode)
            {
                using var debugImage = adjustedImage.ConvertToBlackAndWhite();
                debugImage.Save(DebugFilePath, ImageFormat.Png);
            }

            return result;
        }

19 View Source File : GradientGenerator.cs
License : MIT License
Project Creator : 5argon

[ContextMenu("Generate")]
    public void Generate()
    {
        var gradients = new List<Gradient>();
        for (int k = 0; k < gradientSpecs.Length; k++)
        {
            var spec = gradientSpecs[k];

            var eightRainbow = Enumerable.Range(0, 9).Select(x => Mathf.InverseLerp(0, 9, x)).Take(8).Select(x =>
            Color.HSVToRGB(spec.hProgression.Evaluate(x), spec.sProgression.Evaluate(x), spec.vProgression.Evaluate(x))).ToArray();

            for (int mode = 0; mode < 2; mode++)
            {
                GradientMode gm = (GradientMode)mode;
                var modePlus = gm == GradientMode.Fixed ? 1 : 0;
                for (int i = 1; i < 8; i++)
                {
                    var timeRange = Enumerable.Range(0, i + 1).Select(x => Mathf.InverseLerp(0, i + modePlus, x + modePlus)).ToArray();
                    var g = new Gradient();
                    g.mode = gm;
                    var colorKeys = new GradientColorKey[i + 1];
                    var alphaKeys = new GradientAlphaKey[i + 1];
                    for (int j = 0; j < i + 1; j++)
                    {
                        colorKeys[j].color = eightRainbow[j];
                        colorKeys[j].time = spec.timeRemap.Evaluate(timeRange[j]);
                        alphaKeys[j].alpha = spec.aProgression.Evaluate(timeRange[j]);
                        alphaKeys[j].time = spec.timeRemap.Evaluate(timeRange[j]);
                    }
                    g.SetKeys(colorKeys, alphaKeys);
                    gradients.Add(g);
                }
            }

        }
        generatedGradients = gradients.ToArray();
#if UNITY_EDITOR
        EditorUtility.SetDirty(this);
        replacedetDatabase.Savereplacedets();
#endif
    }

19 View Source File : PointMarkersSelectionExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void PointMarkersSelectionExampleView_OnLoaded(object sender, RoutedEventArgs e)
        {
            // Create a DataSeries of type X=double, Y=double
            var dataSeries1 = new UniformXyDataSeries<double>(0d, 0.05) { SeriesName = "Green" };
            var dataSeries2 = new UniformXyDataSeries<double>(0d, 0.05) { SeriesName = "Blue" };
            var dataSeries3 = new UniformXyDataSeries<double>(0d, 0.05) { SeriesName = "Yellow" };

            // Attach DataSeries to RenderableSeries
            lineRenderSeries1.DataSeries = dataSeries1;
            lineRenderSeries2.DataSeries = dataSeries2;
            lineRenderSeries3.DataSeries = dataSeries3;

            // Generate data
            var count = 200;
            var data1 = DataManager.Instance.GetSinewaveYData(100, 55, count);
            var data3 = DataManager.Instance.GetSinewaveYData(50, 20, count);
            
            // Append data to series
            using (sciChart.SuspendUpdates())
            {
                dataSeries1.Append(data1, Enumerable.Range(0, count).Select(i => new MyMetadata()));
                dataSeries3.Append(data3, Enumerable.Range(0, count).Select(i => new MyMetadata()));

                for (int i = 0; i < count; i += 4)
                {
                    dataSeries2.Append(i++, new MyMetadata());
                }
            }

            // Zoom out to the extents of data
            sciChart.ZoomExtents();
        }

19 View Source File : FdbKey.cs
License : MIT License
Project Creator : abdullin

public static IEnumerable<IEnumerable<int>> BatchedRange(int offset, int count, int batchSize)
		{
			while (count > 0)
			{
				int chunk = Math.Min(count, batchSize);
				yield return Enumerable.Range(offset, chunk);
				offset += chunk;
				count -= chunk;
			}
		}

19 View Source File : ConsoleProgressBar.cs
License : MIT License
Project Creator : a-luna

private string GetProgressBarText(double currentProgress)
        {
            const string singleSpace = " ";

            var numBlocksCompleted = (int) (currentProgress * NumberOfBlocks);

            var completedBlocks =
                Enumerable.Range(0, numBlocksCompleted).Aggregate(
                    string.Empty,
                    (current, _) => current + CompletedBlock);

            var incompleteBlocks =
                Enumerable.Range(0, NumberOfBlocks - numBlocksCompleted).Aggregate(
                    string.Empty,
                    (current, _) => current + IncompleteBlock);

            var progressBar = $"{StartBracket}{completedBlocks}{incompleteBlocks}{EndBracket}";
            var percent = $"{currentProgress:P0}".PadLeft(4, '\u00a0');
            var animationFrame = AnimationSequence[AnimationIndex++ % AnimationSequence.Length];
            var animation = $"{animationFrame}";

            progressBar = DisplayBar
                ? progressBar + singleSpace
                : string.Empty;

            percent = DisplayPercentComplete
                ? percent + singleSpace
                : string.Empty;

            if (!DisplayAnimation || currentProgress is 1)
            {
                animation = string.Empty;
            }

            return (progressBar + percent + animation).TrimEnd();
        }

19 View Source File : AscReader.cs
License : MIT License
Project Creator : ABTSoftware

private static AscData ReadFromStream(StreamReader stream, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
        {
            var result = new AscData
            {
                XValues = new List<float>(),
                YValues = new List<float>(),
                ZValues = new List<float>(),
                ColorValues = new List<Color>(),
                NumberColumns = ReadInt(stream, "ncols"),
                NumberRows = ReadInt(stream, "nrows"),
                XllCorner = ReadInt(stream, "xllcorner"),
                YllCorner = ReadInt(stream, "yllcorner"),
                CellSize = ReadInt(stream, "cellsize"),
                NoDataValue = ReadInt(stream, "NODATA_value"),
            };

            // Load the ASC file format 

            // Generate X-values based off cell position 
            float[] xValuesRow = Enumerable.Range(0, result.NumberColumns).Select(x => (float)x * result.CellSize).ToArray();

            for (int i = 0; i < result.NumberRows; i++)
            {
                // Read heights from the ASC file and generate Z-cell values
                float[] heightValuesRow = ReadFloats(stream, " ", result.NoDataValue);
                float[] zValuesRow = Enumerable.Repeat(0 + i * result.CellSize, result.NumberRows).Select(x => (float)x).ToArray();

                result.XValues.AddRange(xValuesRow);
                result.YValues.AddRange(heightValuesRow);
                result.ZValues.AddRange(zValuesRow);

                if (colorMapFunction != null)
                {
                    // Optional color-mapping of points based on height 
                    Color[] colorValuesRow = heightValuesRow
                        .Select(colorMapFunction)
                        .ToArray();
                    result.ColorValues.AddRange(colorValuesRow);
                }

                // Optional report loading progress 0-100%
                reportProgress?.Invoke((int)(100.0f * i / result.NumberRows));
            }

            return result;
        }

19 View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private static Maybe<int> LastChanceToFindNotAlreadyProvidedInteger(SortedSet<object> alreadyProvidedValues, int? minValue, int? maxValue, IFuzz fuzzer)
        {
            minValue = minValue ?? int.MinValue;
            maxValue = maxValue ?? int.MaxValue;

            var allPossibleValues = Enumerable.Range(minValue.Value, maxValue.Value).ToArray();

            var remainingCandidates = allPossibleValues.Except<int>(alreadyProvidedValues.Cast<int>()).ToArray();

            if (remainingCandidates.Any())
            {
                var pickOneFrom = fuzzer.PickOneFrom<int>(remainingCandidates);
                return new Maybe<int>(pickOneFrom);
            }

            return new Maybe<int>();
        }

19 View Source File : LootGenerationFactory_Magic.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static bool replacedignMagic_Spells(WorldObject wo, TreasureDeath profile, bool isArmor, out int numSpells, out int epicCantrips, out int legendaryCantrips)
        {
            SpellId[][] spells;
            SpellId[][] cantrips;

            int lowSpellTier = GetLowSpellTier(profile.Tier);
            int highSpellTier = GetHighSpellTier(profile.Tier);

            switch (wo.WeenieType)
            {
                case WeenieType.Clothing:
                    spells = ArmorSpells.Table;
                    cantrips = ArmorCantrips.Table;
                    break;
                case WeenieType.Caster:
                    spells = WandSpells.Table;
                    cantrips = WandCantrips.Table;
                    break;
                case WeenieType.Generic:
                    spells = JewelrySpells.Table;
                    cantrips = JewelryCantrips.Table;
                    break;
                case WeenieType.MeleeWeapon:
                    spells = MeleeSpells.Table;
                    cantrips = MeleeCantrips.Table;
                    break;
                case WeenieType.MissileLauncher:
                    spells = MissileSpells.Table;
                    cantrips = MissileCantrips.Table;
                    break;
                default:
                    spells = null;
                    cantrips = null;
                    break;
            }

            if (wo.IsShield)
            {
                spells = ArmorSpells.Table;
                cantrips = ArmorCantrips.Table;
            }

            numSpells = 0;
            epicCantrips = 0;
            legendaryCantrips = 0;

            if (spells == null || cantrips == null)
                return false;

            // Refactor 3/2/2020 - HQ
            // Magic stats
            numSpells = GetSpellDistribution(profile, out int minorCantrips, out int majorCantrips, out epicCantrips, out legendaryCantrips);
            int numCantrips = minorCantrips + majorCantrips + epicCantrips + legendaryCantrips;

            if (numSpells - numCantrips > 0)
            {
                var indices = Enumerable.Range(0, spells.Length).ToList();

                for (int i = 0; i < numSpells - numCantrips; i++)
                {
                    var idx = ThreadSafeRandom.Next(0, indices.Count - 1);
                    int col = ThreadSafeRandom.Next(lowSpellTier - 1, highSpellTier - 1);
                    SpellId spellID = spells[indices[idx]][col];
                    indices.RemoveAt(idx);
                    wo.Biota.GetOrAddKnownSpell((int)spellID, wo.BiotaDatabaseLock, out _);
                }
            }

            // Per discord discussions: ALL armor/shields if it had any spells, had an Impen spell
            if (isArmor)
            {
                var impenSpells = SpellLevelProgression.Impenetrability;

                // Ensure that one of the Impen spells was not already added
                bool impenFound = false;
                for (int i = 0; i < 8; i++)
                {
                    if (wo.Biota.SpellIsKnown((int)impenSpells[i], wo.BiotaDatabaseLock))
                    {
                        impenFound = true;
                        break;
                    }
                }
                if (!impenFound)
                {
                    int col = ThreadSafeRandom.Next(lowSpellTier - 1, highSpellTier - 1);
                    SpellId spellID = impenSpells[col];
                    wo.Biota.GetOrAddKnownSpell((int)spellID, wo.BiotaDatabaseLock, out _);
                }
            }

            if (numCantrips > 0)
            {
                var indices = Enumerable.Range(0, cantrips.Length).ToList();

                // minor cantrips
                for (var i = 0; i < minorCantrips; i++)
                {
                    var idx = ThreadSafeRandom.Next(0, indices.Count - 1);
                    SpellId spellID = cantrips[indices[idx]][0];
                    indices.RemoveAt(idx);
                    wo.Biota.GetOrAddKnownSpell((int)spellID, wo.BiotaDatabaseLock, out _);
                }
                // major cantrips
                for (var i = 0; i < majorCantrips; i++)
                {
                    var idx = ThreadSafeRandom.Next(0, indices.Count - 1);
                    SpellId spellID = cantrips[indices[idx]][1];
                    indices.RemoveAt(idx);
                    wo.Biota.GetOrAddKnownSpell((int)spellID, wo.BiotaDatabaseLock, out _);
                }
                // epic cantrips
                for (var i = 0; i < epicCantrips; i++)
                {
                    var idx = ThreadSafeRandom.Next(0, indices.Count - 1);
                    SpellId spellID = cantrips[indices[idx]][2];
                    indices.RemoveAt(idx);
                    wo.Biota.GetOrAddKnownSpell((int)spellID, wo.BiotaDatabaseLock, out _);
                }
                // legendary cantrips
                for (var i = 0; i < legendaryCantrips; i++)
                {
                    var idx = ThreadSafeRandom.Next(0, indices.Count - 1);
                    SpellId spellID = cantrips[indices[idx]][3];
                    indices.RemoveAt(idx);
                    wo.Biota.GetOrAddKnownSpell((int)spellID, wo.BiotaDatabaseLock, out _);
                }
            }
            return true;
        }

19 View Source File : SimpleLatencyBenchmark.cs
License : MIT License
Project Creator : Abc-Arbitrage

public static void PrintSummary(string replacedle, params (string name, SimpleLatencyBenchmarkResult result)[] results)
        {
            Console.WriteLine(replacedle);
            Console.WriteLine(String.Join("", Enumerable.Range(0, replacedle.Length).Select(_ => "=")));
            Console.WriteLine();

            Console.WriteLine("+------------+--------+--------+--------+------------+------------+------------+------------+------------+------------+------------+");
            Console.WriteLine("| Test       |   Mean | Median |    P90 |        P95 |        P99 |      P99.9 |     P99.99 |    P99.999 |        Max |   GC Count |");
            Console.WriteLine("+------------+--------+--------+--------+------------+------------+------------+------------+------------+------------+------------+");

            foreach (var (name, result) in results)
            {
                var histo = Concatenate(result.ExecutionTimes);

                Console.WriteLine($"| {name,-10} | {histo.GetMean(),6:N0} | {histo.GetValueAtPercentile(50),6:N0} | {histo.GetValueAtPercentile(90),6:N0} | {histo.GetValueAtPercentile(95),10:N0} | {histo.GetValueAtPercentile(99),10:N0} | {histo.GetValueAtPercentile(99.9),10:N0} | {histo.GetValueAtPercentile(99.99),10:N0} | {histo.GetValueAtPercentile(99.999),10:N0} | {histo.GetMaxValue(),10:N0} | {result.CollectionCount,10:N0} |");
            }

            Console.WriteLine("+------------+--------+--------+--------+------------+------------+------------+------------+------------+------------+------------+");
        }

19 View Source File : EventHost.cs
License : MIT License
Project Creator : ad313

private async Task sample_publish_queue_all()
        {
            var key = "sample_publish_queue_all";

            var index1 = 0;
            var index2 = 0;
            _eventBusProvider.SubscribeQueue<int>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        Console.WriteLine($"--------------------------------------{v}-----------------1");
                    }

                    index1 += data.Count;
                    await Task.CompletedTask;
                },completed: async () =>
                {
                    Console.WriteLine($"{index1}  1");
                    index1 = 0;
                    await Task.CompletedTask;
                });

            _eventBusProvider.SubscribeQueue<int>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        Console.WriteLine($"--------------------------------------{v}-----------------2");
                    }
                    index2 += data.Count;
                    await Task.CompletedTask;
                }, completed: async () =>
                {

                    Console.WriteLine($"{index2}  2");
                    index2 = 0;
                    await Task.CompletedTask;
                });

            //    //Enumerable.Range(0, 100).AsParallel().ForAll(i =>
            //    //{
            //    //    Console.WriteLine($"{i}");
            //    //    _eventBusProvider.PublishAsync("testevent", new EventMessageModel<string>($"{i}")).GetAwaiter().GetResult();
            //    //});

            //await _eventBusProvider.PublishQueueAsync(key, new List<int>());


            await Task.Delay(2000);

            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(0, 100).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(100, 100).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(200, 100).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(300, 100).ToList());
        }

19 View Source File : KeysTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void Del()
        {
            var keys = Enumerable.Range(0, 10).Select(a => Guid.NewGuid().ToString()).ToArray();
            cli.MSet(keys.ToDictionary(a => a, a => (object)a));
            replacedert.Equal(10, cli.Del(keys));
        }

19 View Source File : WeatherForecastController.cs
License : MIT License
Project Creator : ad313

[HttpGet]
        [RpcServer("rpc-test1")]
        public IEnumerable<WeatherForecast> Get()
        {
            //var v = _testClreplaced.Get();
            //v = _testClreplaced.Get();
            //var ss = AopCacheProviderInstance.Get<Guid>("aaaaa","b").GetAwaiter().GetResult();

            //AopCacheProviderInstance.Remove("aaaaa","b");

            //v = _testClreplaced.Get();

            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }

19 View Source File : UserStatsGetter.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<UserYearlyCountListStats> GetUsersCountOverTwoYears()
        {
            // end Date 6/4/ 2020
            // start date 1/1/2019
            // the stats will
            // CurrentYear : 1/1/20, 1/2/20, 1/3/20, 1/4/20, 1/5/20 = 0, 1/6/20 = 0, 1/7/20 = 0, ...
            // PreviousYear: 1/1/19, 1/2/19, 1/3/19, 1/4/19, 1/5/19 = x, 1/6/20 = y, 1/7/19 = z, ...
            var startDate = DateTime.UtcNow.AddYears(-1).AddMonths(-DateTime.UtcNow.Month + 1).AddDays(-DateTime.UtcNow.Day + 1).Date;
            var endDate = DateTime.UtcNow.Date;

            var usersMonthly = (from u in _usersRepo.Table
                                where u.CreatedAt >= startDate && u.CreatedAt <= endDate
                                group u by new
                                {
                                    u.CreatedAt.Year,
                                    u.CreatedAt.Month
                                } into g
                                select new
                                {
                                    Count = g.Count(),
                                    MonthYear = new DateTime(g.Key.Year, g.Key.Month, 1)
                                }).ToList();

            var months = Enumerable.Range(0, 24).Select(offset => startDate.AddMonths(offset)).ToList();

            months.ForEach(month =>
            {
                if (!usersMonthly.Any(u => u.MonthYear.Year == month.Year && u.MonthYear.Month == month.Month))
                {
                    usersMonthly.Add(new
                    {
                        Count = 0,
                        MonthYear = month,
                    });
                }
            });

            return new UserYearlyCountListStats()
            {
                CurrentYear = usersMonthly.Where(um => um.MonthYear.Year == DateTime.UtcNow.Year).OrderBy(c => c.MonthYear).Select(c => c.Count).ToList(),
                PreviousYear = usersMonthly.Where(um => um.MonthYear.Year == DateTime.UtcNow.Year - 1).OrderBy(c => c.MonthYear).Select(c => c.Count).ToList()
            };
        }

19 View Source File : TransactionStatsQueriesHandler.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<TransactionTodayStatsDto> Handle(TransactionStatsOverTodayQuery request, CancellationToken cancellationToken)
        {
            // This will resolve to MM/DD/YYYY 00:00:00
            var startDate = DateTime.UtcNow.Date;

            // This will resolve to MM/DD+1/YYYY 00:00:00
            var endDate = DateTime.UtcNow.Date.AddDays(1);

            var transesHourly = (from r in _receivingsRepo.Table
                                 where r.ReceivedAtUtc >= startDate && r.ReceivedAtUtc <= endDate
                                 group r by new
                                 {
                                     r.ReceivedAtUtc.Date,
                                     r.ReceivedAtUtc.Hour,
                                 } into g
                                 select new
                                 {
                                     Count = g.Count(),
                                     Date = g.Key.Date,
                                     Hour = g.Key.Hour
                                 });
            var transesHourlyFormated = transesHourly.Select(r => new
            {
                r.Count,
                DateTime = new DateTime(r.Date.Year, r.Date.Month, r.Date.Day, r.Hour, 0, 0)
            }).ToList();

            var hours = Enumerable.Range(0, 24).Select(offset =>
            {

                var dateTime = startDate.AddHours(offset);
                return dateTime;
            }).ToList();

            hours.ForEach(hour =>
            {
                if (!transesHourlyFormated.Any(t => t.DateTime == hour))
                {
                    transesHourlyFormated.Add(new
                    {
                        Count = 0,
                        DateTime = hour
                    });
                }
            });

            transesHourlyFormated = transesHourlyFormated.OrderBy(t => t.DateTime).ToList();
            var stats = transesHourlyFormated.Select(t => t.Count).ToList();

            var transactions = from r in _registrationsRepo.Table
                               where r.ShouldReturnItAfter.HasValue && r.Status == ObjectRegistrationStatus.OK
                               select r;
            var late = transactions
                .AsEnumerable()
                .Count(r => r.ObjectReceiving != null &&
                    r.ObjectReceiving.ObjectReturning != null &&
                    (r.ObjectReceiving.ReceivedAtUtc + r.ShouldReturnItAfter.Value) > r.ObjectReceiving.ObjectReturning.ReturnedAtUtc.AddMinutes(30));
            var notReturned = transactions.Count(r => r.ObjectReceiving != null && r.ObjectReceiving.ObjectReturning == null);
            var onTime = transactions
                .AsEnumerable()
                .Count(r => r.ObjectReceiving != null &&
                    r.ObjectReceiving.ObjectReturning != null &&
                    r.ObjectReceiving.ReceivedAtUtc.Add(r.ShouldReturnItAfter.Value) <= r.ObjectReceiving.ObjectReturning.ReturnedAtUtc.AddMinutes(30));

            return new TransactionTodayStatsDto
            {
                LateReturn = late,
                NotReturnedYet = notReturned,
                OnTimeReturn = onTime,
                TransactionsOverToday = stats
            };
        }

19 View Source File : ValuesController.cs
License : MIT License
Project Creator : 2881099

[HttpGet]
		async public Task<string> Get() {

			long id = 0;

			try {

				var repos2Song = _orm.GetRepository<Song, int>();
				repos2Song.Where(a => a.Id > 10).ToList();
				//查询结果,进入 states

				var song = new Song { };
				repos2Song.Insert(song);
				id = song.Id;

				var adds = Enumerable.Range(0, 100)
					.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, replacedle = "xxxx" + a, Url = "url222" })
					.ToList();
				//创建一堆无主键值

				repos2Song.Insert(adds);

				for (var a = 0; a < 10; a++)
					adds[a].replacedle = "dkdkdkdk" + a;

				repos2Song.Update(adds);
				//批量修改

				repos2Song.Delete(adds.Skip(10).Take(20).ToList());
				//批量删除,10-20 元素的主键值会被清除

				adds.Last().Url = "skldfjlksdjglkjjcccc";
				repos2Song.Update(adds.Last());

				adds.First().Url = "skldfjlksdjglkjjcccc";
				repos2Song.Update(adds.First());


				var ctx = _songContext;
				var tag = new Tag {
					Name = "testaddsublist",
					Tags = new[] {
							new Tag { Name = "sub1" },
							new Tag { Name = "sub2" },
							new Tag {
								Name = "sub3",
								Tags = new[] {
									new Tag { Name = "sub3_01" }
								}
							}
						}
				};
				ctx.Tags.Add(tag);


				ctx.UnitOfWork.GetOrBeginTransaction();

				var tagAsync = new Tag {
					Name = "testaddsublist",
					Tags = new[] {
							new Tag { Name = "sub1" },
							new Tag { Name = "sub2" },
							new Tag {
								Name = "sub3",
								Tags = new[] {
									new Tag { Name = "sub3_01" }
								}
							}
						}
				};
				await ctx.Tags.AddAsync(tagAsync);


				ctx.Songs.Select.Where(a => a.Id > 10).ToList();
				//查询结果,进入 states

				song = new Song { };
				//可插入的 song

				ctx.Songs.Add(song);
				id = song.Id;
				//因有自增类型,立即开启事务执行SQL,返回自增值

				adds = Enumerable.Range(0, 100)
					.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, replacedle = "xxxx" + a, Url = "url222" })
					.ToList();
				//创建一堆无主键值

				ctx.Songs.AddRange(adds);
				//立即执行,将自增值赋给 adds 所有元素,因为有自增类型,如果其他类型,指定传入主键值,不会立即执行

				for (var a = 0; a < 10; a++)
					adds[a].replacedle = "dkdkdkdk" + a;

				ctx.Songs.UpdateRange(adds);
				//批量修改,进入队列

				ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList());
				//批量删除,进入队列,完成时 10-20 元素的主键值会被清除

				//ctx.Songs.Update(adds.First());

				adds.Last().Url = "skldfjlksdjglkjjcccc";
				ctx.Songs.Update(adds.Last());

				adds.First().Url = "skldfjlksdjglkjjcccc";
				ctx.Songs.Update(adds.First());

				//单条修改 urls 的值,进入队列

				//throw new Exception("回滚");

				//ctx.Songs.Select.First();
				//这里做一个查询,会立即打包【执行队列】,避免没有提交的数据,影响查询结果

				ctx.SaveChanges();
				//打包【执行队列】,提交事务


				using (var uow = _orm.CreateUnitOfWork()) {

					var reposSong = uow.GetRepository<Song, int>();
					reposSong.Where(a => a.Id > 10).ToList();
					//查询结果,进入 states

					song = new Song { };
					reposSong.Insert(song);
					id = song.Id;

					adds = Enumerable.Range(0, 100)
						.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, replacedle = "xxxx" + a, Url = "url222" })
						.ToList();
					//创建一堆无主键值

					reposSong.Insert(adds);

					for (var a = 0; a < 10; a++)
						adds[a].replacedle = "dkdkdkdk" + a;

					reposSong.Update(adds);
					//批量修改

					reposSong.Delete(adds.Skip(10).Take(20).ToList());
					//批量删除,10-20 元素的主键值会被清除

					adds.Last().Url = "skldfjlksdjglkjjcccc";
					reposSong.Update(adds.Last());

					adds.First().Url = "skldfjlksdjglkjjcccc";
					reposSong.Update(adds.First());

					uow.Commit();
				}



				//using (var ctx = new SongContext()) {

				//	var song = new Song { };
				//	await ctx.Songs.AddAsync(song);
				//	id = song.Id;

				//	var adds = Enumerable.Range(0, 100)
				//		.Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, replacedle = "xxxx" + a, Url = "url222" })
				//		.ToList();
				//	await ctx.Songs.AddRangeAsync(adds);

				//	for (var a = 0; a < adds.Count; a++)
				//		adds[a].replacedle = "dkdkdkdk" + a;

				//	ctx.Songs.UpdateRange(adds);

				//	ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList());

				//	//ctx.Songs.Update(adds.First());

				//	adds.Last().Url = "skldfjlksdjglkjjcccc";
				//	ctx.Songs.Update(adds.Last());

				//	//throw new Exception("回滚");

				//	await ctx.SaveChangesAsync();
				//}
			} catch {
				var item = await _orm.Select<Song>().Where(a => a.Id == id).FirstAsync();

				throw;
			}

			var item22 = await _orm.Select<Song>().Where(a => a.Id == id).FirstAsync();
			var item33 = await _orm.Select<Song>().Where(a => a.Id > id).ToListAsync();

			return item22.Id.ToString();
		}

19 View Source File : TransactionStatsQueriesHandler.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<List<int>> Handle(TransactionStatsOverYearQuery request, CancellationToken cancellationToken)
        {
            // end Date 6/4/ 2020
            // start date 1/1/2019
            // the stats will
            // CurrentYear : 1/1/20, 1/2/20, 1/3/20, 1/4/20, 1/5/20 = 0, 1/6/20 = 0, 1/7/20 = 0, ...
            var startDate = DateTime.UtcNow.AddMonths(-DateTime.UtcNow.Month + 1).AddDays(-DateTime.UtcNow.Day + 1).Date;
            var endDate = DateTime.UtcNow.Date.AddDays(1);

            var transesMonthly = (from r in _receivingsRepo.Table
                                  where
                                     r.ReceivedAtUtc >= startDate && r.ReceivedAtUtc <= endDate
                                  group r by new
                                  {
                                      r.ReceivedAtUtc.Year,
                                      r.ReceivedAtUtc.Month
                                  } into g
                                  select new
                                  {
                                      Count = g.Count(),
                                      MonthYear = new DateTime(g.Key.Year, g.Key.Month, 1)
                                  }).ToList();

            var months = Enumerable.Range(0, 12).Select(offset => startDate.AddMonths(offset)).ToList();

            months.ForEach(month =>
            {
                if (!transesMonthly.Any(u => u.MonthYear.Year == month.Year && u.MonthYear.Month == month.Month))
                {
                    transesMonthly.Add(new
                    {
                        Count = 0,
                        MonthYear = month,
                    });
                }
            });

            return transesMonthly.Select(m => m.Count).ToList();
        }

19 View Source File : StateMachines.cs
License : MIT License
Project Creator : 71

[Fact]
        public void ShouldCreateComplexIterator()
        {
            ParameterExpression i = Expression.Parameter(typeof(int), "i");

            IteratorExpression enumerable = X.Enumerable(
                X.While(Expression.LessThan(i, 20.AsExpression()),
                    X.Yield(Expression.PostIncrementreplacedign(i))
                )
            );

            enumerable
                .Compile<int>()
                .SequenceEqual(Enumerable.Range(0, 20))
                .ShouldBeTrue();
        }

19 View Source File : BoxPlotExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private IEnumerable<BoxPoint> GetBoxPlotData(int count)
        {
            var dates = Enumerable.Range(0, count).Select(i => new DateTime(2011, 01, 01).AddMonths(i)).ToArray();
            var medianValues = new RandomWalkGenerator(0).GetRandomWalkSeries(count).YData;

            var random = new Random(0);
            for (int i = 0; i < count; i++)
            {
                double med = medianValues[i];

                double min = med - random.NextDouble();
                double max = med + random.NextDouble();

                double lower = (med - min)*random.NextDouble() + min;
                double upper = (max - med)*random.NextDouble() + med;

                yield return new BoxPoint(dates[i], min, lower, med, upper, max);
            }
        }

19 View Source File : PolarChartViewModelFactory.cs
License : MIT License
Project Creator : ABTSoftware

public static PolarChartViewModel New<T>() where T : IRenderableSeriesViewModel
        {
            var type = typeof(T);
            var data = Enumerable.Range(0, PointAmount).Select(x => (double) x).ToList();

            if (type == typeof(LineRenderableSeriesViewModel))
            {
                return new PolarChartViewModel(new LineRenderableSeriesViewModel {DataSeries = GetXyDataSeries(data)});
            }

            if (type == typeof(XyScatterRenderableSeriesViewModel))
            {
                return new PolarChartViewModel(new XyScatterRenderableSeriesViewModel
                {
                    DataSeries = GetXyDataSeries(data),
                    PointMarker = new EllipsePointMarker
                    {
                        Width = 10,
                        Height = 10,
                        Fill = Color.FromArgb(255, 71, 187, 255),
                        Stroke = Colors.Black
                    }
                });
            }

            if (type == typeof(MountainRenderableSeriesViewModel))
            {
                return new PolarChartViewModel(new MountainRenderableSeriesViewModel
                    {DataSeries = GetXyDataSeries(data)});
            }

            if (type == typeof(ColumnRenderableSeriesViewModel))
            {
                return new PolarChartViewModel(new ColumnRenderableSeriesViewModel
                    {DataSeries = GetXyDataSeries(data)});
            }

            if (type == typeof(ImpulseRenderableSeriesViewModel))
            {
                return new PolarChartViewModel(new ImpulseRenderableSeriesViewModel
                    {DataSeries = GetHlcDataSeries(data)});
            }

            if (type == typeof(CandlestickRenderableSeriesViewModel))
            {
                return new PolarChartViewModel(new CandlestickRenderableSeriesViewModel
                    {DataSeries = GetOhlcDataSeries(data)});
            }

            if (type == typeof(OhlcRenderableSeriesViewModel))
            {
                return new PolarChartViewModel(new OhlcRenderableSeriesViewModel
                    {DataSeries = GetOhlcDataSeries(data)});
            }

            if (type == typeof(BoxPlotRenderableSeriesViewModel))
            {
                return new PolarChartViewModel(new BoxPlotRenderableSeriesViewModel {DataSeries = GetBoxSeries(data)});
            }

            if (type == typeof(ErrorBarsRenderableSeriesViewModel))
            {
                return new PolarChartViewModel(new ErrorBarsRenderableSeriesViewModel
                    {DataSeries = GetHlcDataSeries(data)});
            }

            if (type == typeof(BubbleRenderableSeriesViewModel))
            {
                return new PolarChartViewModel(new BubbleRenderableSeriesViewModel
                {
                    DataSeries = GetXyzDataSeries(data),
                    BubbleColor = Color.FromArgb(255, 110, 0, 255),
                    AutoZRange = false,
                });
            }

            if (type == typeof(BandRenderableSeriesViewModel))
            {
                return new PolarChartViewModel(new BandRenderableSeriesViewModel {DataSeries = GetXyyDataSeries(data)});
            }

            if (type == typeof(StackedColumnRenderableSeriesViewModel))
            {
                return new PolarChartViewModel(
                    new StackedColumnRenderableSeriesViewModel
                    {
                        DataSeries = GetXyDataSeries(data),
                        Fill = new SolidColorBrush(Color.FromArgb(255, 0, 2, 195)),
                        StackedGroupId = "stackedColumns"
                    },
                    new StackedColumnRenderableSeriesViewModel
                    {
                        DataSeries = GetXyDataSeries(data),
                        Fill = new SolidColorBrush(Color.FromArgb(255, 0, 143, 255)),
                        StackedGroupId = "stackedColumns"
                    },
                    new StackedColumnRenderableSeriesViewModel
                    {
                        DataSeries = GetXyDataSeries(data),
                        Fill = new SolidColorBrush(Color.FromArgb(255, 0, 255, 84)),
                        StackedGroupId = "stackedColumns"
                    });
            }

            if (type == typeof(StackedMountainRenderableSeriesViewModel))
            {
                return new PolarChartViewModel(
                    new StackedMountainRenderableSeriesViewModel
                    {
                        DataSeries = GetXyDataSeries(data),
                        Fill = new SolidColorBrush(Color.FromArgb(255, 57, 255, 0)),
                        StackedGroupId = "stackedMountains",
                    },
                    new StackedMountainRenderableSeriesViewModel
                    {
                        DataSeries = GetXyDataSeries(data),
                        Fill = new SolidColorBrush(Color.FromArgb(255, 251, 255, 0)),
                        StackedGroupId = "stackedMountains",
                    },
                    new StackedMountainRenderableSeriesViewModel
                    {
                        DataSeries = GetXyDataSeries(data),
                        Fill = new SolidColorBrush(Color.FromArgb(255, 0, 90, 255)),
                        StackedGroupId = "stackedMountains",
                    });
            }

            throw new NotImplementedException("Unsupported Series Type");
        }

19 View Source File : LINQ.cs
License : MIT License
Project Creator : 71

[Fact]
        public void ShouldTransformComplexQuery()
        {
            IEnumerable<int> positives = Enumerable.Range(0, 100);
            IEnumerable<int> negatives = Enumerable.Range(-100, 0);

            Expression body = X.Express(() => from p in positives
                                              from n in negatives
                                              let sum = p + n
                                              where sum == 0
                                              let product = p * n
                                              orderby product descending
                                              select sum.ToString());

            QueryExpression query = X.Query(body);
            string[] result = query.Compile<Func<IEnumerable<string>>>()().ToArray();
        }

19 View Source File : SeriesBindingViewModel.cs
License : MIT License
Project Creator : ABTSoftware

private IEnumerable<BoxPoint> GetBoxPlotData()
        {
            var dates = Enumerable.Range(0, PointsCount).Select(i => i).ToArray();
            var medianValues = new RandomWalkGenerator(0).GetRandomWalkSeries(PointsCount).YData;
            var random = new Random(0);

            for (int i = 0; i < PointsCount; i++)
            {
                double med = medianValues[i];
                double min = med - random.NextDouble();
                double max = med + random.NextDouble();
                double lower = (med - min)*random.NextDouble() + min;
                double upper = (max - med)*random.NextDouble() + med;

                yield return new BoxPoint(dates[i], min, lower, med, upper, max);
            }
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public static byte[] StringToByteArray(string hex)
        {
            return Enumerable.Range(0, hex.Length)
                             .Where(x => x % 2 == 0)
                             .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                             .ToArray();
        }

19 View Source File : ViewModelsFactory.cs
License : MIT License
Project Creator : ABTSoftware

private static IEnumerable<double> GetXValues(double[] data)
        {
            return Enumerable.Range(0, data.Length).Select(x => (double) x);
        }

19 View Source File : FileTransferProgressBar.cs
License : MIT License
Project Creator : a-luna

string GetProgressBarText(double currentProgress)
		{
			const string singleSpace = " ";

			var numBlocksCompleted = (int)(currentProgress * NumberOfBlocks);

			var completedBlocks =
				Enumerable.Range(0, numBlocksCompleted).Aggregate(
					string.Empty,
					(current, _) => current + CompletedBlock);

			var incompleteBlocks =
				Enumerable.Range(0, NumberOfBlocks - numBlocksCompleted).Aggregate(
					string.Empty,
					(current, _) => current + IncompleteBlock);

			var progressBar = $"{StartBracket}{completedBlocks}{incompleteBlocks}{EndBracket}";
			var percent = $"{currentProgress:P0}".PadLeft(4, '\u00a0');

			var fileSizeInBytes = FileHelper.FileSizeToString(FileSizeInBytes);
			var padLength = fileSizeInBytes.Length;
			var bytesReceived = FileHelper.FileSizeToString(BytesReceived).PadLeft(padLength, '\u00a0');
			var bytes = $"{bytesReceived} of {fileSizeInBytes}";

			var animationFrame = AnimationSequence[AnimationIndex++ % AnimationSequence.Length];
			var animation = $"{animationFrame}";

		    progressBar = DisplayBar
		        ? progressBar + singleSpace
		        : string.Empty;

		    percent = DisplayPercentComplete
		        ? percent + singleSpace
		        : string.Empty;

		    bytes = DisplayBytes
		        ? bytes + singleSpace
		        : string.Empty;

			if (!DisplayAnimation || currentProgress is 1)
			{
				animation = string.Empty;
			}

			return progressBar + bytes + percent + animation;
		}

19 View Source File : AscReader.cs
License : MIT License
Project Creator : ABTSoftware

public static async Task<AscData> ReadFileToAscData(
            string filename, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
        {
            AscData result = new AscData()
            {
                XValues = new List<float>(),
                YValues = new List<float>(),
                ZValues = new List<float>(),
                ColorValues = new List<Color>(),
            };

            await Task.Run(() =>
            {
                using (var file = File.OpenText(filename))
                {
                    // Load the ASC file format 
                    result.NumberColumns = ReadInt(file, "ncols");
                    result.NumberRows = ReadInt(file, "nrows");
                    result.XllCorner = ReadInt(file, "xllcorner");
                    result.YllCorner = ReadInt(file, "yllcorner");
                    result.CellSize = ReadInt(file, "cellsize");
                    result.NoDataValue = ReadInt(file, "NODATA_value");

                    // Generate X-values based off cell position 
                    float[] xValuesRow = Enumerable.Range(0, result.NumberColumns).Select(x => (float)x * result.CellSize).ToArray();

                    for (int i = 0; i < result.NumberRows; i++)
                    {
                        // Read heights from the ASC file and generate Z-cell values
                        float[] heightValuesRow = ReadFloats(file, " ", result.NoDataValue);
                        float[] zValuesRow = Enumerable.Repeat(0 + i * result.CellSize, result.NumberRows).Select(x => (float)x).ToArray();

                        result.XValues.AddRange(xValuesRow);
                        result.YValues.AddRange(heightValuesRow);
                        result.ZValues.AddRange(zValuesRow);

                        if (colorMapFunction != null)
                        {
                            // Optional color-mapping of points based on height 
                            Color[] colorValuesRow = heightValuesRow
                                .Select(colorMapFunction)
                                .ToArray();
                            result.ColorValues.AddRange(colorValuesRow);
                        }

                        // Optional report loading progress 0-100%
                        reportProgress?.Invoke((int)(100.0f * i / result.NumberRows));
                    }
                }
            });

            return result;
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

private void UpdateClientCount()
        {
            if (null == EndingNumber) { return; }
            if (null == NumberOfClients) { return; }
            if (StartingNumber.Text.Length.Equals(0) || EndingNumber.Text.Length.Equals(0))
            {
                return;
            }
            int StartingNo = Int32.Parse(StartingNumber.Text);
            int EndingNo = Int32.Parse(EndingNumber.Text);
            CalculatedClientsCount = Enumerable.Range(StartingNo, EndingNo).ToList().Count.ToString();

            NumberOfClients.Text = CalculatedClientsCount;

            Console.WriteLine("Generating " + CalculatedClientsCount + " new clients");
        }

19 View Source File : FileSystemTest.cs
License : Apache License 2.0
Project Creator : acblog

[TestInitialize]
        public async Task Setup()
        {
            RootPath = Path.Join(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location), "fstest");
            FSStaticBuilder.EnsureDirectoryExists(RootPath);

            PostData = Enumerable.Range(0, 100).Select(x => Generator.GetPost()).ToArray();
            LayoutData = Enumerable.Range(0, 100).Select(x => Generator.GetLayout()).ToArray();
            PageData = Enumerable.Range(0, 100).Select(x => Generator.GetPage()).ToArray();
            FileData = Enumerable.Range(0, 100).Select(x => Generator.GetFile()).ToArray();
            BlogOptionsData = new BlogOptions();

            BlogBuilder builder = new BlogBuilder(BlogOptionsData, RootPath);
            await builder.Build();
            await builder.BuildPosts(PostData);
            await builder.BuildLayouts(LayoutData);
            await builder.BuildPages(PageData);
            await builder.BuildFiles(FileData);

            BlogService = new FileSystemBlogService(new PhysicalFileProvider(RootPath).AsFileProvider());
        }

19 View Source File : ProgressAnimations.cs
License : MIT License
Project Creator : a-luna

public static string RandomBrailleSequence()
        {
            var rand = new Random();
            var sequence = string.Empty;
            foreach(int i in Enumerable.Range(0, 40))
            {
                var charIndex = rand.Next(10241, 10496);
                var randChar = Strings.ChrW(charIndex);
                sequence +=  randChar;
            }

            return sequence;
        }

19 View Source File : EnumerableExtensions.cs
License : MIT License
Project Creator : actions

public static MultiParreplacedionResults<T> Parreplacedion<T>(this IEnumerable<T> source, params Predicate<T>[] predicates)
        {
            ArgumentUtility.CheckForNull(source, nameof(source));
            ArgumentUtility.CheckForNull(predicates, nameof(predicates));

            var range = Enumerable.Range(0, predicates.Length).ToList();

            var results = new MultiParreplacedionResults<T>();
            results.MatchingParreplacedions.AddRange(range.Select(_ => new List<T>()));

            foreach (var item in source)
            {
                bool added = false;

                foreach (var predicateIndex in range.Where(predicateIndex => predicates[predicateIndex](item)))
                {
                    results.MatchingParreplacedions[predicateIndex].Add(item);
                    added = true;
                    break;
                }

                if (!added)
                {
                    results.NonMatchingParreplacedion.Add(item);
                }
            }

            return results;
        }

19 View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private static Maybe<int> LastChanceToFindAge(SortedSet<object> alreadyProvidedValues, int minAge, int maxAge, IFuzz fuzzer)
        {
            var allPossibleValues = Enumerable.Range(minAge, maxAge - minAge).ToArray();

            var remainingCandidates = allPossibleValues.Except(alreadyProvidedValues.Cast<int>()).ToArray();

            if (remainingCandidates.Any())
            {
                var pickOneFrom = fuzzer.PickOneFrom<int>(remainingCandidates);
                return new Maybe<int>(pickOneFrom);
            }

            return new Maybe<int>();
        }

19 View Source File : EventHost.cs
License : MIT License
Project Creator : ad313

private async Task sample_publish_queue()
        {
            var key = "sample_publish_queue";

            _eventBusProvider.SubscribeQueue<int>(key, async func =>
            {
                var data = await func(1000);
                foreach (var v in data)
                {
                    queue.Enqueue(v);
                    Console.WriteLine($"--------------------------------------{v}-----------------1");
                }

                Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  11");

                await Task.CompletedTask;
            });

            _eventBusProvider.SubscribeQueue<int>(key, async func =>
            {
                var data = await func(1000);
                foreach (var v in data)
                {
                    queue.Enqueue(v);
                    Console.WriteLine($"--------------------------------------{v}-----------------2");
                }

                Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  12");

                await Task.CompletedTask;
            });

            Enumerable.Range(0, 1000).AsParallel().ForAll(i =>
            {
                //Console.WriteLine($"{i}");
                _eventBusProvider.PublishQueueAsync(key, new List<int>() { i }).GetAwaiter().GetResult();
            });

            //await _eventBusProvider.PublishQueueAsync(key, new List<int>());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(0, 200).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(200, 200).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(400, 200).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(600, 200).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(800, 200).ToList());
        }

19 View Source File : SimpleLatencyBenchmark.cs
License : MIT License
Project Creator : Abc-Arbitrage

public static SimpleLatencyBenchmarkResult RunBench(int producingThreadCount, Func<HistogramBase> produce, ManualResetEventSlim signal)
        {
            var tasks = Enumerable.Range(0, producingThreadCount).Select(_ => new Task<HistogramBase>(produce, TaskCreationOptions.LongRunning)).ToList();

            GC.Collect(2);
            GC.WaitForPendingFinalizers();
            GC.Collect(2);
            var collectionsBefore = GC.CollectionCount(0);

            foreach (var task in tasks)
            {
                task.Start();
            }

            signal.Wait(TimeSpan.FromSeconds(30));

            var collectionsAfter = GC.CollectionCount(0);
            var result = new SimpleLatencyBenchmarkResult { ExecutionTimes = tasks.Select(x => x.Result).ToList(), CollectionCount = collectionsAfter - collectionsBefore };
            return result;
        }

19 View Source File : EventHost.cs
License : MIT License
Project Creator : ad313

private async Task sample_publish_queue_all2()
        {
            var key = "sample_publish_queue_all3";

            //var queue = new ConcurrentQueue<int>();

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------11");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  11");
                    //index1 = 0;
                    await Task.CompletedTask;
                });

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------12");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  12");
                    //index1 = 0;
                    await Task.CompletedTask;
                });

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------13");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  13");
                    //index1 = 0;
                    await Task.CompletedTask;
                });


            //await Task.Delay(2000);

            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(0, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(100, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(200, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(300, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(400, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(500, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(600, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(700, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

        }

19 View Source File : Encrypter.cs
License : MIT License
Project Creator : 1y0n

private static byte[] EncryptInitalize(byte[] key)
        {
            byte[] s = Enumerable.Range(0, 256)
              .Select(i => (byte)i)
              .ToArray();
            for (int i = 0, j = 0; i < 256; i++)
            {
                j = (j + key[i % key.Length] + s[i]) & 255;
                Swap(s, i, j);
            }
            return s;
        }

19 View Source File : RpcTestController.cs
License : MIT License
Project Creator : ad313

[HttpGet]
        public async Task<IActionResult> Get()
        {
            //Parallel.For(0, 100, i =>
            //{
            //    var str = _eventBusProvider.RpcClientAsync<string>("rpc-test1").GetAwaiter().GetResult();
            //    Console.WriteLine(i + "-----" + str);
            //});


            var tasks = Enumerable.Range(0, 10).Select(d => _eventBusProvider.RpcClientAsync<string>("rpc-test1")).ToArray();
            await Task.WhenAll(tasks);

            var str = await _eventBusProvider.RpcClientAsync<string>("rpc-test1");

            return string.IsNullOrWhiteSpace(str.Data) ? BadRequest() : Ok(str.Data);

            return Ok();
        }

19 View Source File : UserStatsGetter.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<List<int>> GetUsersCountOverToday()
        {
            // This will resolve to MM/DD/YYYY 00:00:00
            var startDate = DateTime.UtcNow.Date;

            // This will resolve to MM/DD+1/YYYY 00:00:00
            var endDate = DateTime.UtcNow.Date.AddDays(1);

            var usersHourly = (from u in _usersRepo.Table
                               where u.CreatedAt >= startDate && u.CreatedAt <= endDate
                               group u by new
                               {
                                   u.CreatedAt.Date,
                                   u.CreatedAt.Hour
                               } into g
                               select new
                               {
                                   Count = g.Count(),
                                   Date = g.Key.Date,
                                   Hour = g.Key.Hour
                               }).ToList();
            var usersHourlyFormated = usersHourly.Select(u => new
            {
                Count = u.Count,
                DateTime = new DateTime(u.Date.Year, u.Date.Month, u.Date.Day, u.Hour, 0, 0)
            }).ToList();

            var hours = Enumerable.Range(0, 24).Select(offset =>
            {

                var dateTime = startDate.AddHours(offset);
                return dateTime;
            }).ToList();

            hours.ForEach(hour =>
            {
                if (!usersHourlyFormated.Any(u => u.DateTime == hour))
                {
                    usersHourlyFormated.Add(new
                    {
                        Count = 0,
                        DateTime = hour
                    });
                }
            });
            usersHourlyFormated = usersHourlyFormated.OrderBy(u => u.DateTime).ToList();

            var stats = usersHourlyFormated.Select(u => u.Count).ToList();
            return stats;
        }

19 View Source File : Tlv.cs
License : MIT License
Project Creator : 499116344

private static byte[] GetBytes(string hexString)
        {
            return Enumerable
                .Range(0, hexString.Length)
                .Where(x => x % 2 == 0)
                .Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
                .ToArray();
        }

19 View Source File : ScCreateOrders.cs
License : MIT License
Project Creator : 0x1000000

public async Task Exec(IScenarioContext context)
        {
            var tOrder = AllTables.GereplacedOrder();
            var tOrderSub2 = AllTables.GereplacedOrder();
            var vwCustomer = new CustomerName();

            var numbers = Values(Enumerable.Range(1, 10).Select(Literal).ToList()).AsColumns("Num");

            var getNum = numbers.Column(context.Dialect == SqlDialect.MySql ? "1" : "Num");
            await InsertInto(tOrder, tOrder.CustomerId, tOrder.Notes)
                .From(
                    Select(vwCustomer.CustomerId, ("Notes for " + vwCustomer.Name + " No:" + Cast(getNum, SqlType.String(5))).As("Notes"))
                        .From(vwCustomer)
                        .CrossJoin(numbers)
                        .OrderBy(vwCustomer.CustomerId, getNum)
                )
                .Exec(context.Database);

            var count = await Select(Count(1)).From(tOrder).QueryScalar(context.Database);

            context.WriteLine("Orders are inserted: " + count);

            //Delete % 7
            await Delete(tOrder)
                .Where(tOrder.OrderId.In(Select(tOrderSub2.OrderId)
                    .From(tOrderSub2)
                    .Where(tOrderSub2.OrderId % 7 == 0)))
                .Exec(context.Database);

            count = await Select(Count(1)).From(tOrder).QueryScalar(context.Database);
            context.WriteLine("Some Orders are deleted. Current count: " + count);

            //Delete JOIN
            await Delete(tOrder)
                .From(tOrder)
                .InnerJoin(vwCustomer, on: vwCustomer.CustomerId == tOrder.CustomerId)
                .Where(tOrder.CustomerId % 7 + 1 == 1)
                .Exec(context.Database);

            //For my SQL number is different since Auto Increment is not reset on delete (ItCustomer)

            count = await Select(Count(1)).From(tOrder).QueryScalar(context.Database);
            context.WriteLine("Some Orders are deleted. Current count: " + count);

            await Update(tOrder)
                .Set(tOrder.Notes, tOrder.Notes + " (Updated 17)")
                .Where(tOrder.OrderId % 17 == 0)
                .Exec(context.Database);

            await Update(tOrder)
                .Set(tOrder.Notes, tOrder.Notes + " (Updated 19)")
                .From(tOrder)
                .Where(tOrder.OrderId % 19 == 0)
                .Exec(context.Database);

            await Update(tOrder)
                .Set(tOrder.Notes, tOrder.Notes + " (Updated 23)")
                .From(tOrder)
                .InnerJoin(vwCustomer, on: vwCustomer.CustomerId == tOrder.CustomerId)
                .Where(tOrder.OrderId % 23 == 0)
                .Exec(context.Database);
        }

19 View Source File : Server.cs
License : MIT License
Project Creator : 1ZouLTReX1

private void Start()
    {
        MaximumPlayers = ServerSettings.maxPlayerCount;
        playerIdList = Enumerable.Range(1, MaximumPlayers).Select(x => (ushort)x).ToList();

        serverLoop = new ServerLoop(playerPrefab);
        StartServer();
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Insert(StringBuilder sb, int forTime, int size) {
			var songs = Enumerable.Range(0, size).Select(a => new Song {
				Create_time = DateTime.Now,
				Is_deleted = false,
				replacedle = $"Insert_{a}",
				Url = $"Url_{a}"
			});

			//预热
			fsql.Insert(songs.First()).ExecuteAffrows();
			sugar.Insertable(songs.First()).ExecuteCommand();
			using (var db = new SongContext()) {
				//db.Configuration.AutoDetectChangesEnabled = false;
				db.Songs.AddRange(songs.First());
				db.SaveChanges();
			}
			Stopwatch sw = new Stopwatch();

			sw.Restart();
			for (var a = 0; a < forTime; a++) {
				fsql.Insert(songs).ExecuteAffrows();
			}
			sw.Stop();
			sb.AppendLine($"FreeSql Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");

			sw.Restart();
			for (var a = 0; a < forTime; a++) {
				using (var db = new FreeSongContext()) {
					db.Songs.AddRange(songs.ToArray());
					db.SaveChanges();
				}
			}
			sw.Stop();
			sb.AppendLine($"FreeSql.DbContext Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");

			sw.Restart();
			Exception sugarEx = null;
			try {
				for (var a = 0; a < forTime; a++)
					sugar.Insertable(songs.ToArray()).ExecuteCommand();
			} catch (Exception ex) {
				sugarEx = ex;
			}
			sw.Stop();
			sb.AppendLine($"SqlSugar Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : ""));

			sw.Restart();
			for (var a = 0; a < forTime; a++) {

				using (var db = new SongContext()) {
					//db.Configuration.AutoDetectChangesEnabled = false;
					db.Songs.AddRange(songs.ToArray());
					db.SaveChanges();
				}
			}
			sw.Stop();
			sb.AppendLine($"EFCore Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
		}

19 View Source File : LINQ.cs
License : MIT License
Project Creator : 71

[Fact]
        public void ShouldTransformQuery()
        {
            IEnumerable<int> items = Enumerable.Range(0, 100);

            Expression body = X.Express(() => from item in items
                                              where item > 0
                                              let cube = item * item * item
                                              from ch in cube.ToString().ToCharArray()
                                              select $"{cube}{ch}");

            QueryExpression query = X.Query(body);
        }

19 View Source File : FanChartExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private IEnumerable<VarPoint> GetVarianceData()
        {
            var dates = Enumerable.Range(0, 10).Select(i => new DateTime(2011, 01, 01).AddMonths(i)).ToArray();
            var yValues = new RandomWalkGenerator(seed: 0).GetRandomWalkSeries(10).YData;

            for (int i = 0; i < 10; i++)
            {
                double varMax = double.NaN;
                double var4 = double.NaN;
                double var3 = double.NaN;
                double var2 = double.NaN;
                double var1 = double.NaN;
                double varMin = double.NaN;

                if (i > 4)
                {
                    varMax = yValues[i] + (i - 5) * 0.3;
                    var4 = yValues[i] + (i - 5) * 0.2;
                    var3 = yValues[i] + (i - 5) * 0.1;
                    var2 = yValues[i] - (i - 5) * 0.1;
                    var1 = yValues[i] - (i - 5) * 0.2;
                    varMin = yValues[i] - (i - 5) * 0.3;
                }

                yield return new VarPoint(dates[i], yValues[i], var4, var3, var2, var1, varMin, varMax);
            }
        }

See More Examples